<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :exportList="exportList"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :operationColumnWidth="200"
    :replaceOrNotMap="false"
  >
    <ExamineDialog :is-show.sync="isShowExamineDialog" :examine-form.sync="examineForm" @submit="submitExamineForm" />

    <Popu v-if="isShowDetail || isShowForm || isShowExamine || isShowReturnForm">
      <EnginDetail v-if="isShowDetail" ref="refDetail" :list-item="queryItem" @backListFormDetail="backList" />
      <EnginExamine v-if="isShowExamine" :list-item="queryItem" @backListFormDetail="backList" />
      <EnginForm v-if="isShowForm" :list-item="queryItem" @backListFormDetail="backList" />
      <EnginReturnForm v-if="isShowReturnForm" :isShow="isShow" :list-item="queryItem" @backListFormDetail="backList" />
    </Popu>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import Popu from '@/components/template/popu.vue'

import { invoiceListProjectV2, invoiceListProjectV2Export } from '@/api/supply/deliver'
import { getEnginList, submitEngin, deleteEngin, abandonEngin, examineBatchEngin } from '@/api/supply/apply'
import { getCategoryList, getSalesmanList } from '@/api/common'
import EnginDetail from '@/views/supply/apply/components/engin_detail'
import EnginExamine from '@/views/supply/apply/components/engin_examine'
import EnginForm from '@/views/supply/apply/components/engin_form'
import EnginReturnForm from '@/views/supply/apply/components/engin_return_form'
import ExamineDialog from '@/components/Common/examine-dialog'

let that
export default {
  components: {
    EnginDetail,
    EnginExamine,
    EnginForm,
    EnginReturnForm,
    ExamineDialog,
    TemplatePage,
    Popu
  },
  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 {
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '发货申请',
              click: () => {
                this.toForm()
              },
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '退货申请',
              click: () => {
                this.toReturnForm()
              },
              isRole: this.$checkBtnRole('refund', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量审批',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要批量审批的数据')
                  return
                }
                this.batchExamine()
              },
              isRole: this.$checkBtnRole('examine', this.$route.meta.roles)
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],

      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: null, // 列表数据
      listLoading: false, // 列表加载loading
      screenForm: {
        // 筛选表单数据
        status: '',
        orderNum: '',
        warehouse: '',
        jxsNum: '',
        jxsName: '',
        date: [],
        chName: '',
        model: '',
        salesMan: '',
        orderType: '',
        mainOrderId: '',
        refEnginRecordNo: '',
        refUseUnit: '',
        k3ServiceId: '',
        categoryId: '',
        approvalName: '',
        refRegionWork: '',
        automaticStatus: '',
        createBy: ''
      },
      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: ''
      },
      isShow: false,
      categoryList: [],
      isCustomer: JSON.parse(localStorage.getItem('supply_user')).isCustomer
    }
  },

  computed: {
    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,
        serviceId: this.screenForm.salesMan,
        k3ServiceId: this.screenForm.k3ServiceId,
        type: this.screenForm.orderType,
        mainOrderId: this.screenForm.mainOrderId,
        createBy: this.screenForm.createBy,
        refEnginRecordNo: this.screenForm.refEnginRecordNo,
        refUseUnit: this.screenForm.refUseUnit,
        categoryId: this.screenForm.categoryId,
        approvalName: this.screenForm.approvalName,
        refRegionWork: this.screenForm.refRegionWork
      }
    }
  },

  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() {
  //   // keepAlice  activated 主要是从发货单汇总调用退货申请按钮
  //   this.isShow = false
  //   if(this.$route.query && this.$route.query.isShow){
  //     this.isShow = this.$route.query.isShow
  //       this.toReturnForm()
  //   }
  // },
  methods: {
    // 列表请求函数
    getList(...p) {
      let params = {
        ...p[0]
      }
      return invoiceListProjectV2(params)
    },
    // 列表导出函数
    exportList: invoiceListProjectV2Export,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    fieldBeansHook(val) {
      if (this.isCustomer !== '') {
        let res = val.filter(
          v => v.jname !== 'refPowerCategory' && v.jname !== 'geLiInerNote' && v.jname !== 'geLiNote'
        )
        return res
      } else {
        return val
      }
    },
    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
                onOnConfirm={async () => {
                  this.handleSubmit(row.id, 'WAIT')
                }}
                title="是否确定需要申请该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  申请
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {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
                onOnConfirm={async () => {
                  this.handleSubmit(row.id, 'SAVE')
                }}
                title="是否确定需要撤回该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  撤回
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {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
                onOnConfirm={async () => {
                  this.handleAbandon(row.id)
                }}
                title="是否确定需要弃审该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  弃审
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

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

            {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
                size="mini"
                type="text"
                onClick={async () => {
                  this.toReturnForm(row)
                }}
              >
                编辑
              </el-button>
            ) : (
              ''
            )}

            {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
                size="mini"
                type="text"
                onClick={async () => {
                  this.toExamine(row)
                }}
              >
                审核
              </el-button>
            ) : (
              ''
            )}

            <el-button
              size="mini"
              type="text"
              onClick={async () => {
                this.toDetail(row)
              }}
            >
              详情
            </el-button>

            {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
                onOnConfirm={async () => {
                  this.handleDelete(row.id)
                }}
                title="是否确定需要删除该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  删除
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}
          </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,
    //     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,
    //     createBy: this.screenForm.createBy,
    //     automaticStatus: this.screenForm.automaticStatus,

    //     serviceId: this.screenForm.salesMan,
    //     k3ServiceId: this.screenForm.k3ServiceId,
    //     type: this.screenForm.orderType,
    //     mainOrderId: this.screenForm.mainOrderId,
    //     refEnginRecordNo: this.screenForm.refEnginRecordNo,
    //     refUseUnit: this.screenForm.refUseUnit,
    //     categoryId: this.screenForm.categoryId,
    //     approvalName: this.screenForm.approvalName,
    //     refRegionWork: this.screenForm.refRegionWork
    //   }
    //   getEnginList(params).then(res => {
    //     res.data.records.forEach(item => {
    //       item.sums1 = ['refundableQty']
    //       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()
      })
    },

    backList() {
      this.queryItem = {}
      this.isShowDetail = false
      this.isShowExamine = false
      this.isShowForm = false
      this.isShowReturnForm = false
      this.$refs.pageRef.refreshList()
    },

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

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

    // 弃审
    handleAbandon(id) {
      abandonEngin({ id }).then(res => {
        this.$successMsg()
        // this.getList()
        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.recordSelected.map(item => {
        return item.id
      })
      ids = Array.from(new Set(ids))

      examineBatchEngin({
        ids: ids.join(','),
        examineStatus: this.examineForm.status === 'FAIL' ? 'SAVE' : 'OK',
        approvalRemark: this.examineForm.remark
      }).then(res => {
        this.isShowExamineDialog = false
        // this.getList()
        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>
