<template>
  <template-page
    ref="pageRef"
    :get-list="getList"
    :operation="operation()"
    :options-evens-group="optionsEvensGroup"
    :export-list="exportList"
    :column-parsing="columnParsing"
    :table-attributes="tableAttributes"
    :table-events="tableEvents"
    :field-beans-hook="fieldBeansHook"
    :operation-column-width="200"
  >
    <div slot="moreSearch">
      <ul class="ulStyle">
        <li class="title">
          金额：<span class="num">{{ (Number(numSum.amountC) || 0) | numToFixed }}</span>
        </li>
        <li class="title">
          数量：<span class="num">{{ Number(numSum.totalC) || 0 }}</span>
        </li>
        <li class="title">
          项目数：<span class="num">{{ Number(numSum.totalEC) || 0 }}</span>
        </li>
      </ul>

      <div class="worker">
        <div class="worker_left">工单状态</div>
        <div class="worker_right">
          <el-button
            v-for="(item, index) in workerState"
            :key="index"
            :type="orderStatusParam == item.value ? 'primary' : null"
            size="mini"
            @click="handleOrderStatusParam(item.value, index)"
            >{{ item.label }}</el-button
          >
        </div>
      </div>
    </div>
    <!-- <EditDateDialog :is-show.sync="isShowEditDateDialog" :date-form.sync="dateForm" /> -->
    <Popu v-if="isShowDetail || isShowForm || isShowExamine || isShowReturn">
      <HomeDetail v-if="isShowDetail" :list-item="queryItem" @backListFormDetail="backList" />
      <HomeForm v-if="isShowForm" :list-item="queryItem" @backListFormDetail="backList" />
      <HomeExamine v-if="isShowExamine" :list-item="queryItem" @backListFormDetail="backList" />
      <HomeReturn v-if="isShowReturn" :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 {
  getOrderList,
  applyHome,
  withdrawHome,
  deleteHome,
  editDateHome,
  abandonHome,
  getEnginCountList,
  v2EnginOrderHomeList,
  v2EnginOrderHomeCountList,
  v2EnginOrderHomeListExport
} from '@/api/supply/engin'
import { getSalesmanList, getTypeList } from '@/api/common'
import HomeDetail from '@/views/supply/engin/components/home_detail'
import HomeForm from '@/views/supply/engin/components/home_form'
import HomeExamine from '@/views/supply/engin/components/home_examine'
import HomeReturn from '@/views/supply/engin/components/home_return'
import EditDateDialog from '@/components/Common/edit-date-dialog'
import { getNoRebateWalletList } from '@/api/policy_list'

let that
export default {
  components: {
    HomeDetail,
    HomeForm,
    HomeExamine,
    HomeReturn,
    EditDateDialog,
    TemplatePage,
    Popu
  },
  filters: {
    statusFilter(val) {
      const obj = that.statusList.find(o => o.value === val)
      return obj ? obj.label : ''
    },
    typeFilter(val) {
      const MAP = {
        TRADE: '商用',
        HOME: '家用'
      }
      return MAP[val]
    }
  },
  mixins: [add_callback_mixin],
  data() {
    return {
      orderStatusParam: '',
      workerState: [
        {
          label: '全部',
          value: ''
        },
        // {
        //   label: '初审不通过',
        //   value: 'FAIL_ONE'
        // },
        // {
        //   label: '驳回',
        //   value: 'REJECT'
        // },
        // {
        //   label: '已确认未复核',
        //   value: 'OK_ONE_AND_CONFIRM'
        // },
        // {
        //   label: '弃审',
        //   value: 'ABANDON'
        // },
        {
          label: '保存',
          value: 'SAVE'
        },
        // {
        //   label: '关闭',
        //   value: 'CLOSE'
        // },
        {
          label: '待审核',
          value: 'WAIT'
        },
        {
          label: '审核通过',
          value: 'OK'
        }
        // {
        //   label: '初审不通过',
        //   value: 'FAIL'
        // },
        // {
        //   label: '初审通过',
        //   value: 'OK_ONE'
        // }
      ],
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.toForm()
              }),
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                this.batchDelete()
              },
              isRole: this.$checkBtnRole('del', 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: '',
        enginNum: '',
        loginNum: '',
        refTradeCategory: '',
        date: [],
        saleType: '',
        createMan: '',
        examineMan: '',
        salesMan: '',
        refUseUnit: '',
        materialOldNumber: '',
        specification: '',
        customerKeyword: '',
        refRegionWork: '',
        remark: '',
        geLiInerNote: '',
        refFactoryNo: '',
        refBuyUnitName: '',
        refPromiseProvide: '',
        isDirectTransfer: null,
        orderTime: [],
        saleTypeId: '',
        customerWalletId: ''
      },
      statusList: [
        { label: '已保存', value: 'SAVE' },
        { label: '待审核', value: 'WAIT' },
        { label: '审核通过', value: 'OK' }
        //  // { label: '审核驳回', value: 'FAIL' },,
        // { label: '已关闭', value: 'CLOSE' },
      ],
      salesmanList: [],
      transfer: [
        { label: '是', value: true },
        { label: '否', value: false }
      ],
      multipleSelection: [],

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

      editId: null,
      isShowEditDateDialog: false,
      dateForm: {
        date: ''
      },
      isCollapse: true,
      salesTypeList: [],
      NoRebateWalletList: [],
      typeList: [],
      numSum: {
        totalC: 0,
        amountC: 0,
        totalEC: 0
      }
    }
  },

  computed: {
    exParams() {
      const ids = this.multipleSelection.map(item => {
        return item.enginOrderNo
      })
      return {
        examineStatus: this.screenForm.status.join(','),
        enginOrderNo: ids && ids.length ? ids.join(',') : this.screenForm.orderNum,
        refProjectNo: this.screenForm.enginNum,
        refEnginRecordNo: this.screenForm.loginNum,
        refTradeCategory: this.screenForm.refTradeCategory,
        startCreateTime: this.screenForm.date ? this.screenForm.date[0] : '',
        endCreateTime: this.screenForm.date ? this.screenForm.date[1] : '',
        startOrderTime: this.screenForm.orderTime ? this.screenForm.orderTime[0] : '',
        endOrderTime: this.screenForm.orderTime ? this.screenForm.orderTime[1] : '',
        saleTypeId: this.screenForm.saleType,
        createName: this.screenForm.createMan,
        confirmName: this.screenForm.examineMan,
        serviceId: this.screenForm.salesMan,
        refUseUnit: this.screenForm.refUseUnit,
        materialOldNumber: this.screenForm.materialOldNumber,
        specification: this.screenForm.specification,
        customerKeyword: this.screenForm.customerKeyword,
        refRegionWork: this.screenForm.refRegionWork,
        remark: this.screenForm.remark,
        geLiInerNote: this.screenForm.geLiInerNote,
        refFactoryNo: this.screenForm.refFactoryNo,
        refBuyUnitName: this.screenForm.refBuyUnitName,
        refPromiseProvide: this.screenForm.refPromiseProvide,
        isDirectTransfer: this.screenForm.isDirectTransfer,

        enginOrderType: 'HOME' // TRADE=商用 HOME=家用
      }
    },
    isCustomer() {
      return this.$store.getters.customerId && this.$store.getters.customerNumber
    }
  },

  beforeCreate() {
    that = this
  },

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

  methods: {
    handleOrderStatusParam(value, index) {
      this.orderStatusParam = value
      this.$refs.pageRef.refreshList()
    },
    // 列表请求函数
    // getList: v2EnginOrderHomeList,
    async getList(...p) {
      this.$refs.pageRef.showTable = false
      let params = {}

      if (this.orderStatusParam === '') {
        params = {
          moduleId: p[0].moduleId,
          orderBy: p[0].orderBy,
          pageNum: p[0].pageNum,
          pageSize: p[0].pageSize,
          params: [...p[0].params]
        }
      } else {
        params = {
          moduleId: p[0].moduleId,
          orderBy: p[0].orderBy,
          pageNum: p[0].pageNum,
          pageSize: p[0].pageSize,
          params: [{ param: 'a.examine_status', compare: '=', value: this.orderStatusParam }, ...p[0].params]
        }
      }
      try {
        let res = await v2EnginOrderHomeCountList(params)
        this.numSum.totalC = res.data.totalC
        this.numSum.amountC = res.data.amountC
        this.numSum.totalEC = res.data.totalEC
      } catch (error) {
        // console.log(error)
      }

      return v2EnginOrderHomeList(params)
    },
    // 列表导出函数
    exportList: v2EnginOrderHomeListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    fieldBeansHook(val) {
      val.map(item => {
        if (~['examine_status'].indexOf(item.colName)) {
          item.isQuery = false
        }
      })
      if (this.isCustomer !== '') {
        const 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">
            {row.examineStatus == '保存' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleSubmit(row.parentId, row)
                }}
                title="是否确定需要申请该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  申请
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {row.examineStatus == '待审核' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleWithdraw(row.parentId, row)
                }}
                title="是否确定需要撤回该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  撤回
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

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

            {this.$checkBtnRole('edit', this.$route.meta.roles) &&
            (row.examineStatus === '保存' || row.examineStatus === '审核不通过') ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.toForm(row)
                }}
              >
                编辑
              </el-button>
            ) : (
              ''
            )}

            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.examineStatus === '待审核' ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.toExamine(row)
                }}
              >
                审批
              </el-button>
            ) : (
              ''
            )}

            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.examineStatus !== '审核不通过' ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.toReturn(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 !== '审核通过' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleDelete(row.parentId, row)
                }}
                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
        console.log(this.NoRebateWalletList)
      })
      getTypeList({ pageNum: 1, pageSize: -1 }).then(res => {
        this.typeList = res.data.records
        console.log(this.typeList)
      })
    },

    // 获取销售类型列表
    getSalesTypeList() {
      getTypeList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.salesTypeList = res.data.records
      })
    },

    // 查询列表
    // getList() {
    //   this.listLoading = true
    //   const params = {
    //     pageNum: this.currentPage,
    //     pageSize: this.pageSize,
    //     examineStatus: this.screenForm.status.join(','),
    //     enginOrderNo: this.screenForm.orderNum,
    //     refProjectNo: this.screenForm.enginNum,
    //     refEnginRecordNo: this.screenForm.loginNum,
    //     refTradeCategory: this.screenForm.refTradeCategory,
    //     startCreateTime: this.screenForm.date ? this.screenForm.date[0] : '',
    //     endCreateTime: this.screenForm.date ? this.screenForm.date[1] : '',
    //     startOrderTime: this.screenForm.orderTime ? this.screenForm.orderTime[0] : '',
    //     endOrderTime: this.screenForm.orderTime ? this.screenForm.orderTime[1] : '',
    //     createName: this.screenForm.createMan,
    //     confirmName: this.screenForm.examineMan,
    //     serviceId: this.screenForm.salesMan,
    //     refUseUnit: this.screenForm.refUseUnit,
    //     materialOldNumber: this.screenForm.materialOldNumber,
    //     specification: this.screenForm.specification,
    //     customerKeyword: this.screenForm.customerKeyword,
    //     refRegionWork: this.screenForm.refRegionWork,
    //     remark: this.screenForm.remark,
    //     geLiInerNote: this.screenForm.geLiInerNote,
    //     saleTypeId: this.screenForm.saleTypeId,
    //     customerWalletId: this.screenForm.customerWalletId,
    //     refFactoryNo: this.screenForm.refFactoryNo,
    //     refBuyUnitName: this.screenForm.refBuyUnitName,
    //     isDirectTransfer: this.screenForm.isDirectTransfer,

    //     refPromiseProvide: this.screenForm.refPromiseProvide,
    //     enginOrderType: 'HOME' // TRADE=商用 HOME=家用
    //   }

    //   getOrderList(params).then(res => {
    //     res.data.records.forEach(item => {
    //       item.sums1 = ['qty', 'directTransferQty', 'hasSendQty']
    //       item.sums2 = ['price', 'totalAmount', 'payAmount', 'discAmount']
    //     })
    //     this.dataList = res.data.records
    //     this.listTotal = res.data.total
    //     this.listLoading = false
    //   })

    //   getEnginCountList({
    //     examineStatus: this.screenForm.status.join(','),
    //     enginOrderNo: this.screenForm.orderNum,
    //     refProjectNo: this.screenForm.enginNum,
    //     refEnginRecordNo: this.screenForm.loginNum,
    //     refTradeCategory: this.screenForm.refTradeCategory,
    //     startCreateTime: this.screenForm.date ? this.screenForm.date[0] : '',
    //     endCreateTime: this.screenForm.date ? this.screenForm.date[1] : '',
    //     startOrderTime: this.screenForm.orderTime ? this.screenForm.orderTime[0] : '',
    //     endOrderTime: this.screenForm.orderTime ? this.screenForm.orderTime[1] : '',
    //     createName: this.screenForm.createMan,
    //     confirmName: this.screenForm.examineMan,
    //     serviceId: this.screenForm.salesMan,
    //     refUseUnit: this.screenForm.refUseUnit,
    //     materialOldNumber: this.screenForm.materialOldNumber,
    //     specification: this.screenForm.specification,
    //     customerKeyword: this.screenForm.customerKeyword,
    //     refRegionWork: this.screenForm.refRegionWork,
    //     remark: this.screenForm.remark,
    //     geLiInerNote: this.screenForm.geLiInerNote,
    //     saleTypeId: this.screenForm.saleTypeId,
    //     customerWalletId: this.screenForm.customerWalletId,
    //     refFactoryNo: this.screenForm.refFactoryNo,
    //     refBuyUnitName: this.screenForm.refBuyUnitName,
    //     isDirectTransfer: this.screenForm.isDirectTransfer,

    //     refPromiseProvide: this.screenForm.refPromiseProvide,
    //     enginOrderType: 'HOME' // TRADE=商用 HOME=家用
    //   }).then(res => {
    //     if (res.data) {
    //       this.numSum = res.data
    //     }
    //   })
    // },

    // 提交筛选表单
    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
    },

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

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

    // 进入退订
    toReturn(item) {
      if (item.refundableQty <= 0) {
        return this.$errorMsg('可退数量为0')
      }
      this.queryItem = item
      this.isShowReturn = true
    },

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

    // 申请
    handleSubmit(id, row) {
      this.$confirm('发货时将暂扣工程押金，请确保钱包余额充足', '温馨提示').then(() => {
        applyHome({ id, refEnginRecordNo: row.refEnginRecordNo }).then(res => {
          this.$successMsg()
          // this.getList()
          this.$refs.pageRef.refreshList()
        })
      })
    },

    // 撤回
    handleWithdraw(id, row) {
      withdrawHome({ id, refEnginRecordNo: row.refEnginRecordNo }).then(res => {
        this.$successMsg()
        // this.getList()
        this.$refs.pageRef.refreshList()
      })
    },

    // 弃审
    handleAbandon(id, row) {
      abandonHome({ id, refEnginRecordNo: row.refEnginRecordNo }).then(res => {
        this.$successMsg()
        // this.getList()
        this.$refs.pageRef.refreshList()
      })
    },

    // 删除
    handleDelete(id, row) {
      deleteHome({ ids: id }).then(res => {
        this.$successMsg()
        // this.getList()
        this.$refs.pageRef.refreshList()
      })
    },

    // 批量删除
    batchDelete() {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const ids = this.recordSelected.map(item => {
            return item.parentId
          })
          deleteHome({ ids: ids.join(',') }).then(res => {
            this.$successMsg()
            // this.getList()
            this.$refs.pageRef.refreshList()
          })
        })
        .catch(() => {})
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

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

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

<style lang="scss" scoped>
.worker {
  display: flex;
  justify-content: space-between;
  .worker_left {
    font-size: 12px;
    font-weight: 400;
    text-align: left;
    color: #666;
    line-height: 28px;
    margin-right: 10px;
  }
  .worker_right {
    flex: 1;
    ::v-deep .el-button {
      margin: 0 10px 10px 0px;
    }
  }
}

.ulStyle {
  list-style: none;
  margin: 0;
  padding: 10px 0;
  background-color: #ffffff;
  z-index: 1;
}
.title {
  display: inline-block;
  font-weight: 700;
  margin-right: 20px;
}
.num {
  padding-left: 6px;
  font-weight: 400;
}
</style>
