<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :exportList="exportList"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :operationColumnWidth="200"
    :fieldBeansHook="fieldBeansHook"
  >
    <EditDateDialog :is-show.sync="isShowEditDateDialog" :date-form.sync="dateForm" />
    <Popu v-if="!showPage">
      <el-page-header slot="head" :content="content" @back="handleClose" />
      <EnginDetail v-if="isShowDetail" :list-item="queryItem" @backListFormDetail="backList" />
      <EnginForm v-if="isShowForm" :list-item="queryItem" @backListFormDetail="backList" />
      <EnginExamine v-if="isShowExamine" :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 add_callback_mixin from '@/components/template/add_callback_mixin.js'

import {
  getEnginList,
  applyEngin,
  withdrawEngin,
  deleteEngin,
  editDateEngin,
  abandonEngin,
  v2EnginInfoOrderList,
  v2EnginInfoOrderListExport
} from '@/api/supply/engin'
import { getSalesmanList, getTypeList } from '@/api/common'
import EnginDetail from '@/views/supply/engin/components/engin_detail'
import EnginForm from '@/views/supply/engin/components/engin_form'
import EnginExamine from '@/views/supply/engin/components/engin_examine'
import EditDateDialog from '@/components/Common/edit-date-dialog'
import { getNoRebateWalletList } from '@/api/policy_list'

let that
export default {
  mixins: [add_callback_mixin],
  components: {
    EnginDetail,
    EnginForm,
    EnginExamine,
    EditDateDialog,
    TemplatePage,
    Popu,
    add_callback_mixin
  },
  filters: {
    statusFilter(val) {
      const obj = that.statusList.find(o => o.value == val)
      return obj ? obj.label : ''
    }
  },
  data() {
    return {
      showPage: true,
      content: '商用工程信息单',
      // 关闭新增弹窗
      handleClose: this.addOff(() => {
        this.showPage = true
        this.isShowForm = false
        this.$refs.pageRef.refreshList()
      }),
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.toForm()
              })
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],

      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: null, // 列表数据
      listLoading: false, // 列表加载loading
      screenForm: {
        // 筛选表单数据
        orderNum: '',
        enginNum: '',
        loginNum: '',
        enginName: '',
        date: [],
        dealer: '',
        company: '',
        createMan: '',
        examineMan: '',
        status: '',
        salesMan: '',
        model: '',
        orderDate: [],
        isClose: '',
        isDirectTransfer: null,
        examineStatus: ''
      },
      statusList: [
        { label: '已保存', value: 'SAVE' },
        { label: '待审核', value: 'WAIT' },
        { label: '审核通过', value: 'OK' },
        //  // { label: '审核驳回', value: 'FAIL' },,
        { label: '已关闭', value: 'CLOSE' }
      ],

      salesmanList: [],
      transfer: [
        { label: '是', value: true },
        { label: '否', value: false }
      ],
      queryItem: {},
      isShowDetail: false,
      isShowForm: false,
      isShowExamine: false,
      isCollapse: true,
      editId: null,
      NoRebateWalletList: [],
      typeList: [],
      isShowEditDateDialog: false,
      dateForm: {
        date: ''
      }
    }
  },

  computed: {
    isDealer() {
      return JSON.parse(localStorage.getItem('supply_user')).isCustomer
    }
    // exParams() {
    //   return {
    //     enginInfoNo: this.screenForm.orderNum,
    //     projectNo: this.screenForm.enginNum,
    //     enginSignType: this.screenForm.loginNum,
    //     projectName: this.screenForm.enginName,
    //     startOrderDate: this.screenForm.orderDate ? this.screenForm.orderDate[0] : '',
    //     endOrderDate: this.screenForm.orderDate ? this.screenForm.orderDate[1] : '',
    //     startContractExpireDate: this.screenForm.date ? this.screenForm.date[0] : '',
    //     endContractExpireDate: this.screenForm.date ? this.screenForm.date[1] : '',
    //     customerKeyword: this.screenForm.dealer,
    //     useUnit: this.screenForm.company,
    //     createName: this.screenForm.createMan,
    //     confirmName: this.screenForm.examineMan,
    //     examineStatus: this.screenForm.examineStatus,
    //     isClose: this.screenForm.isClose,
    //     serviceId: this.screenForm.salesMan,
    //     specification: this.screenForm.model,
    //     isDirectTransfer: this.screenForm.isDirectTransfer
    //   }
    // }
  },

  watch: {
    dataList: {
      handler(newValue, oldValue) {
        if (newValue && newValue.length) {
          newValue.forEach((item, index) => {
            this.dataList[index].compute_kdQty = this.computeAllowQty(item.qty, item.hasOrderQty)
          })
        }
      },
      immediate: true,
      deep: true
    }
  },

  beforeCreate() {
    that = this
  },

  created() {
    this.getSalesmanList()
    // this.getList()
  },

  methods: {
    // 列表请求函数
    getList: v2EnginInfoOrderList,
    // 列表导出函数
    exportList: v2EnginInfoOrderListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    fieldBeansHook(val) {
      if (this.isDealer) {
        let res = val.filter(v => v.jname !== 'powerCategory' && 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) && row.examineStatus === 'SAVE' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleSubmit(row.enginInfoId)
                }}
                title="是否确定需要申请该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  申请
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {this.$checkBtnRole('apply', this.$route.meta.roles) && row.examineStatus === 'WAIT' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleWithdraw(row.enginInfoId)
                }}
                title="是否确定需要撤回该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  撤回
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.examineStatus === 'OK' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleAbandon(row.enginInfoId)
                }}
                title="是否确定需要弃审该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  弃审
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

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

            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.examineStatus === 'WAIT' ? (
              <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) && row.examineStatus !== 'OK' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleDelete(row.enginInfoId)
                }}
                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
      })
      getNoRebateWalletList({
        walletName: ''
      }).then(res => {
        console.log(res)
        this.NoRebateWalletList = res.data
      })
      getTypeList({ pageNum: 1, pageSize: -1 }).then(res => {
        this.typeList = res.data.records
        // console.log(this.typeList)
      })
    },

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

    //   const params = {
    //     pageNum: this.currentPage,
    //     pageSize: this.pageSize,
    //     enginInfoNo: this.screenForm.orderNum,
    //     projectNo: this.screenForm.enginNum,
    //     enginSignType: this.screenForm.loginNum,
    //     projectName: this.screenForm.enginName,
    //     startOrderDate: this.screenForm.orderDate ? this.screenForm.orderDate[0] : '',
    //     endOrderDate: this.screenForm.orderDate ? this.screenForm.orderDate[1] : '',
    //     startContractExpireDate: this.screenForm.date ? this.screenForm.date[0] : '',
    //     endContractExpireDate: this.screenForm.date ? this.screenForm.date[1] : '',
    //     customerKeyword: this.screenForm.dealer,
    //     useUnit: this.screenForm.company,
    //     createName: this.screenForm.createMan,
    //     confirmName: this.screenForm.examineMan,
    //     examineStatus: this.screenForm.examineStatus,
    //     isClose: this.screenForm.isClose,

    //     serviceId: this.screenForm.salesMan,
    //     specification: this.screenForm.model,
    //     isDirectTransfer: this.screenForm.isDirectTransfer
    //   }
    //   getEnginList(params).then(res => {
    //     res.data.records.forEach(item => {
    //       item.sums1 = ['qty', 'hasOrderQty', 'compute_kdQty']
    //       item.sums2 = ['totalAmount', 'price']
    //     })
    //     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.showPage = false
      this.isShowForm = true
    },

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

    // 进入详情
    toDetail(item) {
      this.queryItem = item
      this.showPage = false
      this.isShowDetail = true
    },

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

    // 申请
    handleSubmit(id) {
      applyEngin({ id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('申请成功')
      })
    },

    // 撤回
    handleWithdraw(id) {
      withdrawEngin({ id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('撤回成功')
      })
    },

    // 弃审
    handleAbandon(id) {
      abandonEngin({ id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('弃审成功')
      })
    },

    // 删除
    handleDelete(id) {
      deleteEngin({ ids: id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('删除成功')
      })
    },

    // 打开 修改订单日期
    editDate(item) {
      this.editId = item.enginInfoId
      this.dateForm.date = item.orderDate.slice(0, 10)
      this.isShowEditDateDialog = true
    },

    // 提交 修改订单日期
    submitDateForm() {
      editDateEngin({
        enginInfoId: this.editId,
        orderDate: this.dateForm.date + ' 00:00:00'
      }).then(res => {
        this.isShowEditDateDialog = false
        this.getList()
        this.$successMsg('修改成功')
      })
    },

    computeAllowQty(qty = 0, hasOrderQty = 0) {
      const allowQty = qty - hasOrderQty
      if (allowQty < 0) {
        return 0
      }
      return allowQty
    }
  }
}
</script>

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