<template>
  <div style="width: 100%; height: 100%; overflow-y: auto">
    <template-page
      v-show="!isShowDetail && !isShowExamine && !isShowForm && !isShowReturnForm"
      ref="pageRef"
      :tableEvents="tableEvents"
      :tableAttributes="tableAttributes"
      :getList="getList"
      :exportList="exportList"
      :operation="operation()"
      :operationColumnWidth="200"
      :columnParsing="columnParsing"
      :optionsEvensGroup="optionsEvensGroup"
      :replaceOrNotMap="false"
    >
    </template-page>
    <ExamineDialog :is-show.sync="isShowExamineDialog" :examine-form.sync="examineForm" />
    <div class="app-container" v-if="isShowDetail">
      <ApplyDetail ref="refDetail" :list-item="queryItem" @backListFormDetail="backList" />
    </div>
    <div class="app-container" v-if="isShowExamine">
      <ApplyExamine :list-item="queryItem" @backListFormDetail="backList" />
    </div>
    <div class="app-container" v-if="isShowForm">
      <ApplyForm :list-item="queryItem" @backListFormDetail="backList" />
    </div>
    <div class="app-container" v-if="isShowReturnForm">
      <ApplyReturnForm :list-item="queryItem" :is-show="isShow" @backListFormDetail="backList" />
    </div>
  </div>
</template>

<script>
import { getApplyList, submitApply, deleteApply, abandonApply, examineBatchApply } from '@/api/supply/apply'
import { getCategoryList, getSalesmanList } from '@/api/common'
import ApplyDetail from '@/views/supply/apply/components/apply_detail'
import ApplyExamine from '@/views/supply/apply/components/apply_examine'
import ApplyForm from '@/views/supply/apply/components/apply_form'
import ApplyReturnForm from '@/views/supply/apply/components/apply_return_form'
import ExamineDialog from '@/components/Common/examine-dialog'
import { invoiceListRetailV2, invoiceListRetailV2Export } from '@/api/deliver_list_v2'
import TemplatePage from '@/components/template/template-page-1.vue'
let that
export default {
  components: {
    TemplatePage,
    ApplyDetail,
    ApplyExamine,
    ApplyForm,
    ApplyReturnForm,
    ExamineDialog
  },
  filters: {
    statusFilter(val) {
      const obj = that.statusList.find(o => o.value == val)
      return obj ? obj.label : ''
    },
    orderTypeFilter(val) {
      const obj = that.orderTypeList.find(o => o.value == val)
      return obj ? obj.label : ''
    }
  },
  data() {
    return {
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: null, // 列表数据
      listLoading: false, // 列表加载loading
      screenForm: {
        // 筛选表单数据
        status: '',
        orderNum: '',
        warehouse: '',
        jxsNum: '',
        jxsName: '',
        date: [],
        chName: '',
        model: '',
        salesMan: '',
        orderType: '',
        mainOrderId: '',
        k3ServiceId: '',
        serviceId: '',
        categoryId: '',
        approvalName: '',
        createBy: '',
        automaticStatus: ''
      },
      statusList: [
        { label: '已保存', value: 'SAVE' },
        { label: '待审核', value: 'WAIT' },
        { label: '审核通过', value: 'OK' },
        { label: '审核驳回', value: 'FAIL' },
        { label: '已关闭', value: 'CLOSE' }
      ],
      orderTypeList: [
        { label: '发货申请单', value: 1 },
        { label: '退货申请单', value: 2 },
        { label: '直调发货单', value: 3 }
      ],
      salesmanList: [],

      queryItem: {},
      isShowDetail: false,
      isShowExamine: false,
      isShowForm: false,
      isShowReturnForm: false,

      selectRow: [],
      multipleSelection: [],
      isShowExamineDialog: false,
      examineForm: {
        status: '',
        remark: ''
      },
      categoryList: [],
      isCustomer: JSON.parse(localStorage.getItem('supply_user')).isCustomer,
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true,
        summaryMethod: this.$getSummaries
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: []
    }
  },

  computed: {
    optionsEvensGroup() {
      return [
        [
          [
            {
              isRole: this.$checkBtnRole('add', this.$route.meta.roles),
              name: '发货申请',
              click: this.toForm
            }
          ]
        ],
        [
          [
            {
              isRole: this.$checkBtnRole('refund', this.$route.meta.roles),
              name: '退货申请',
              click: this.toReturnForm
            }
          ]
        ],
        [
          [
            {
              isRole: this.$checkBtnRole('examine', this.$route.meta.roles),
              name: '批量审批',
              click: () => {
                if (!this.multipleSelection.length) {
                  this.$message.info('请选择数据！')
                  return
                }
                this.batchExamine()
              }
            }
          ]
        ]
      ]
    },
    exParams() {
      return {
        id: this.screenForm.orderNum,
        correspondName: this.screenForm.warehouse,
        customerNumber: this.screenForm.jxsNum,
        customerName: this.screenForm.jxsName,
        productName: this.screenForm.chName,
        specification: this.screenForm.model,
        automaticStatus: this.screenForm.automaticStatus,

        startTime: this.screenForm.date ? this.screenForm.date[0] : '',
        endTime: this.screenForm.date ? this.screenForm.date[1] : '',
        examineStatus: this.screenForm.status,
        k3ServiceId: this.screenForm.k3ServiceId,
        serviceId: this.screenForm.serviceId,
        createBy: this.screenForm.createBy,
        type: this.screenForm.orderType,
        mainOrderId: this.screenForm.mainOrderId,
        categoryId: this.screenForm.categoryId,
        approvalName: this.screenForm.approvalName
      }
    }
  },

  watch: {
    multipleSelection(data) {
      // 监听选中状态
      this.selectRow = []
      if (data.length > 0) {
        data.forEach((item, index) => {
          this.selectRow.push(item.id)
        })
      }
    }
  },

  beforeCreate() {
    that = this
  },

  created() {
    this.getSalesmanList()
    // this.getList()
    this.getCategoryList()
    this.isShow = false
    if (this.$route.query && this.$route.query.isShow) {
      this.isShow = this.$route.query.isShow
      this.toReturnForm()
    }
  },
  //   activated() {
  //       this.isShow = false
  //   if (this.$route.query && this.$route.query.isShow) {
  //     this.isShow = this.$route.query.isShow

  //       this.toReturnForm()
  //   }

  // },
  methods: {
    // 列表请求函数
    getList: invoiceListRetailV2,
    // 列表导出函数
    exportList: invoiceListRetailV2Export,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.multipleSelection = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {this.$checkBtnRole('apply', this.$route.meta.roles) &&
            ((!this.isCustomer &&
              !row.automaticStatus &&
              (row.examineStatus === 'SAVE' || row.examineStatus === 'FAIL')) ||
              (this.isCustomer &&
                !row.automaticStatus &&
                (row.examineStatus === 'SAVE' || row.examineStatus === 'FAIL') &&
                row.type != 2) ||
              (!this.isCustomer &&
                row.automaticStatus &&
                (row.examineStatus === 'SAVE' || row.examineStatus === 'FAIL') &&
                row.type === 2)) ? (
              <el-popconfirm
                style="margin-right: 10px"
                title="确定申请吗？"
                onOnConfirm={() => {
                  this.handleSubmit(row.id, 'WAIT')
                }}
              >
                <el-button slot="reference" type="text">
                  申请
                </el-button>
              </el-popconfirm>
            ) : null}

            {this.$checkBtnRole('apply', this.$route.meta.roles) &&
            ((!this.isCustomer && !row.automaticStatus && row.examineStatus === 'WAIT') ||
              (this.isCustomer && !row.automaticStatus && row.examineStatus === 'WAIT' && row.type != 2) ||
              (!this.isCustomer && row.automaticStatus && row.examineStatus === 'WAIT' && row.type == 2)) ? (
              <el-popconfirm
                style="margin-right: 10px"
                title="确定撤回吗？"
                onOnConfirm={() => {
                  this.handleSubmit(row.id, 'SAVE')
                }}
              >
                <el-button slot="reference" type="text">
                  撤回
                </el-button>
              </el-popconfirm>
            ) : null}
            {this.$checkBtnRole('examine', this.$route.meta.roles) &&
            ((!this.isCustomer && !row.automaticStatus && row.examineStatus === 'OK') ||
              (this.isCustomer && !row.automaticStatus && row.examineStatus === 'OK' && row.type != 2) ||
              (!this.isCustomer && row.automaticStatus && row.examineStatus === 'OK' && row.type == 2)) ? (
              <el-popconfirm
                style="margin-right: 10px"
                title="确定弃审吗？"
                onOnConfirm={() => {
                  this.handleAbandon(row.id)
                }}
              >
                <el-button slot="reference" type="text">
                  弃审
                </el-button>
              </el-popconfirm>
            ) : null}

            {this.$checkBtnRole('edit', this.$route.meta.roles) &&
            !row.automaticStatus &&
            (row.examineStatus === 'SAVE' || row.examineStatus === 'FAIL') &&
            row.type === 1 ? (
              <el-button
                type="text"
                onClick={() => {
                  this.toForm(row)
                }}
              >
                编辑
              </el-button>
            ) : null}
            {this.$checkBtnRole('edit', this.$route.meta.roles) &&
            ((!this.isCustomer &&
              !row.automaticStatus &&
              (row.examineStatus === 'SAVE' || row.examineStatus === 'FAIL') &&
              row.type === 2) ||
              (this.isCustomer &&
                !row.automaticStatus &&
                (row.examineStatus === 'SAVE' || row.examineStatus === 'FAIL') &&
                row.type != 2 &&
                row.type !== 1) ||
              (!this.isCustomer &&
                row.automaticStatus &&
                (row.examineStatus === 'SAVE' || row.examineStatus === 'FAIL') &&
                row.type === 2)) ? (
              <el-button
                type="text"
                onClick={() => {
                  this.toReturnForm(row)
                }}
              >
                编辑
              </el-button>
            ) : null}

            {this.$checkBtnRole('examine', this.$route.meta.roles) &&
            ((!this.isCustomer && !row.automaticStatus && row.examineStatus === 'WAIT') ||
              (this.isCustomer && !row.automaticStatus && row.examineStatus !== 'WAIT' && row.type != 2) ||
              (!this.isCustomer && row.automaticStatus && row.examineStatus === 'WAIT' && row.type == 2)) ? (
              <el-button
                type="text"
                onClick={() => {
                  this.toExamine(row)
                }}
              >
                审核
              </el-button>
            ) : null}

            {this.$checkBtnRole('del', this.$route.meta.roles) &&
            ((!this.isCustomer && !row.automaticStatus && row.examineStatus !== 'OK') ||
              (this.isCustomer && !row.automaticStatus && row.examineStatus !== 'OK' && row.type != 2) ||
              (!this.isCustomer && row.automaticStatus && row.examineStatus !== 'OK' && row.type == 2)) ? (
              <el-popconfirm
                style="margin-left: 10px"
                title="确定删除吗？"
                onOnConfirm={() => {
                  this.handleDelete(row.id)
                }}
              >
                <el-button slot="reference" type="text" style="color: #f56c6c">
                  删除
                </el-button>
              </el-popconfirm>
            ) : null}
            <el-button
              type="text"
              onClick={() => {
                this.toDetail(row)
              }}
            >
              详情
            </el-button>
          </div>
        )
      }
    },
    // 获取业务员列表
    getSalesmanList() {
      getSalesmanList({
        pageNum: 1,
        pageSize: -1,
        isCustomer: 0,
        status: true
      }).then(res => {
        this.salesmanList = res.data.records
      })
    },

    // // 查询列表
    // getList() {
    //   this.listLoading = true

    //   const params = {
    //     pageNum: this.currentPage,
    //     pageSize: this.pageSize,
    //     id: this.screenForm.orderNum,
    //     correspondName: this.screenForm.warehouse,
    //     customerNumber: this.screenForm.jxsNum,
    //     createBy: this.screenForm.createBy,
    //     automaticStatus: this.screenForm.automaticStatus,
    //     customerName: this.screenForm.jxsName,
    //     productName: this.screenForm.chName,
    //     specification: this.screenForm.model,
    //     startTime: this.screenForm.date ? this.screenForm.date[0] : '',
    //     endTime: this.screenForm.date ? this.screenForm.date[1] : '',
    //     examineStatus: this.screenForm.status,
    //     serviceId: this.screenForm.serviceId,
    //     type: this.screenForm.orderType,
    //     k3ServiceId: this.screenForm.k3ServiceId,
    //     mainOrderId: this.screenForm.mainOrderId,
    //     categoryId: this.screenForm.categoryId,
    //     approvalName: this.screenForm.approvalName
    //   }
    //   getApplyList(params).then(res => {
    //     res.data.records.forEach(item => {
    //       item.sums1 = ['refundableQty', 'retiredQty']
    //       item.sums2 = ['singlePayPrice', 'payAmount', 'payRebateAmount', 'totalDiscAmount']
    //     })
    //     this.dataList = res.data.records
    //     this.listTotal = res.data.total
    //     this.listLoading = false
    //   })
    // },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1
      this.getList()
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields()
      this.currentPage = 1
      this.getList()
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getList()
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 进入表单
    toForm(item) {
      this.queryItem = item
      this.isShowForm = true
    },

    // 进入表单
    toReturnForm(item) {
      this.queryItem = item
      this.isShowReturnForm = true
    },

    // 进入审批
    toExamine(item) {
      this.queryItem = item
      this.isShowExamine = true
    },

    // 进入详情
    toDetail(item) {
      this.queryItem = item
      this.isShowDetail = true
      this.$nextTick(() => {
        this.$refs.refDetail.initPrint()
      })

      // this.$refs.refDetail.initPrint()
    },

    backList() {
      this.queryItem = {}
      this.isShowDetail = false
      this.isShowExamine = false
      this.isShowForm = false
      this.isShowReturnForm = false
    },

    handleDelete(id) {
      deleteApply({ id }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    },

    // 申请/撤回
    handleSubmit(id, examineStatus) {
      submitApply({ id, examineStatus }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    },

    // 弃审
    handleAbandon(id) {
      abandonApply({ id }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      if (val) {
        this.selections = val
      } else {
        this.selections = []
      }
    },

    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(row.id)) {
        return { 'background-color': '#ecf5ff' }
      }
    },

    // 打开 批量审批
    batchExamine() {
      this.isShowExamineDialog = true
    },

    // 提交 批量审批
    submitExamineForm() {
      let ids = this.multipleSelection.map(item => {
        return item.id
      })
      ids = Array.from(new Set(ids))
      examineBatchApply({
        ids: ids.join(','),
        examineStatus: this.examineForm.status === 'FAIL' ? 'SAVE' : 'OK',
        approvalRemark: this.examineForm.remark
      }).then(res => {
        this.isShowExamineDialog = false
        this.$refs.pageRef.refreshList()
        this.$successMsg('审批成功')
      })
    },
    // 获取存货类别列表
    getCategoryList() {
      getCategoryList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.categoryList = res.data.records
      })
    },
    /**
     * 根据条件禁用行复选框
     * 函数返回值为false则禁用选择(反之亦然)
     * @param {Object} row - 行数据
     * @param {String} index - 索引值
     * @return Boolean
     */
    selectable: function (row, index) {
      if (row.automaticStatus) {
        return false
      }
      return true
      // 函数必须有返回值且是布尔值
      // 页面刷新后该函数会执行 N 次进行判断(N 为表格行数)
      // 如果没有返回值则默认返回false(全部无法选中)
    }
  }
}
</script>

<style lang="scss" scoped></style>
