<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :exportList="exportList"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :fieldBeansHook="fieldBeansHook"
    :operationColumnWidth="200"
  >
    <!-- <EditDateDialog :is-show.sync="isShowEditDateDialog" :date-form.sync="dateForm" /> -->
    <Popu v-if="isShowDetail || isShowForm || isShowExamine || isShowReturn">
      <CommerceDetail :listItem="queryItem" v-if="isShowDetail" @backListFormDetail="backList" />
      <CommerceForm :listItem="queryItem" v-if="isShowForm" @backListFormDetail="backList" />
      <CommerceExamine :listItem="queryItem" v-if="isShowExamine" @backListFormDetail="backList" />
      <CommerceReturn :listItem="queryItem" v-if="isShowReturn" @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,
  applyCom,
  withdrawCom,
  deleteCom,
  editDateCom,
  abandonCom,
  v2EnginOrderTradeList,
  v2EnginOrderTradeListExport
} from '@/api/supply/engin'
import { getSalesmanList, getTypeList } from '@/api/common'
import CommerceDetail from '@/views/supply/engin/components/commerce_detail'
import CommerceForm from '@/views/supply/engin/components/commerce_form'
import CommerceExamine from '@/views/supply/engin/components/commerce_examine'
import CommerceReturn from '@/views/supply/engin/components/commerce_return'
import EditDateDialog from '@/components/Common/edit-date-dialog'
import { getNoRebateWalletList } from '@/api/policy_list'

let that
export default {
  mixins: [add_callback_mixin],
  components: {
    CommerceDetail,
    CommerceForm,
    CommerceExamine,
    CommerceReturn,
    EditDateDialog,
    TemplatePage,
    Popu
  },
  filters: {
    statusFilter(val) {
      let obj = that.statusList.find(o => o.value == val)
      return obj ? obj.label : ''
    },
    typeFilter(val) {
      const MAP = {
        TRADE: '商用',
        HOME: '家用'
      }
      return MAP[val]
    }
  },
  data() {
    return {
      // 事件组合
      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: '',
        enginName: '',
        date: [],
        saleType: '',
        createMan: '',
        examineMan: '',
        salesMan: '',
        dealer: '',
        model: '',
        isDirectTransfer: null,
        saleTypeId: '',
        customerWalletId: ''
      },
      statusList: [
        { label: '已保存', value: 'SAVE' },
        { label: '待审核', value: 'WAIT' },
        { label: '审核通过', value: 'OK' },
        //  // { label: '审核驳回', value: 'FAIL' },,
        { label: '已关闭', value: 'CLOSE' }
      ],
      salesmanList: [],
      salesTypeList: [],
      isCollapse: true,
      multipleSelection: [],
      transfer: [
        { label: '是', value: true },
        { label: '否', value: false }
      ],
      queryItem: {},
      isShowDetail: false,
      isShowForm: false,
      isShowExamine: false,
      isShowReturn: false,
      typeList: [],
      NoRebateWalletList: [],
      editId: null,
      isShowEditDateDialog: false,
      dateForm: {
        date: ''
      }
    }
  },

  computed: {
    exParams() {
      let ids = this.multipleSelection.map(item => {
        return item.enginOrderNo
      })
      return {
        examineStatus: this.screenForm.status,
        enginOrderNo: ids && ids.length ? ids.join(',') : this.screenForm.orderNum,
        refProjectNo: this.screenForm.enginNum,
        refEnginRecordNo: this.screenForm.loginNum,
        refProjectName: this.screenForm.enginName,
        startCreateTime: this.screenForm.date ? this.screenForm.date[0] : '',
        endCreateTime: this.screenForm.date ? this.screenForm.date[1] : '',
        saleTypeId: this.screenForm.saleType,
        createName: this.screenForm.createMan,
        confirmName: this.screenForm.examineMan,
        serviceId: this.screenForm.salesMan,
        customerKeyWord: this.screenForm.dealer,
        specification: this.screenForm.model,
        isDirectTransfer: this.screenForm.isDirectTransfer,

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

  beforeCreate() {
    that = this
  },

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

  methods: {
    // 列表请求函数
    getList: v2EnginOrderTradeList,
    // 列表导出函数
    exportList: v2EnginOrderTradeListExport,
    // 表格列解析渲染数据更改
    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">
            <div class="operation-btns">
              {this.$checkBtnRole('apply', this.$route.meta.roles) && row.examineStatus == '保存' ? (
                <el-popconfirm
                  onOnConfirm={async () => {
                    this.handleSubmit(row.parentId, row)
                  }}
                  title="是否确定需要申请该项内容?"
                >
                  <el-button slot="reference" size="mini" type="text">
                    申请
                  </el-button>
                </el-popconfirm>
              ) : (
                ''
              )}

              {this.$checkBtnRole('apply', this.$route.meta.roles) && 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 === '保存' ? (
                <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) ? (
                <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>
          </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

    //   let params = {
    //     pageNum: this.currentPage,
    //     pageSize: this.pageSize,
    //     examineStatus: this.screenForm.status,
    //     enginOrderNo: this.screenForm.orderNum,
    //     refProjectNo: this.screenForm.enginNum,
    //     refEnginRecordNo: this.screenForm.loginNum,
    //     refProjectName: this.screenForm.enginName,
    //     startCreateTime: this.screenForm.date ? this.screenForm.date[0] : '',
    //     endCreateTime: this.screenForm.date ? this.screenForm.date[1] : '',
    //     saleTypeId: this.screenForm.saleType,
    //     createName: this.screenForm.createMan,
    //     confirmName: this.screenForm.examineMan,
    //     customerWalletId: this.screenForm.customerWalletId,
    //     serviceId: this.screenForm.salesMan,
    //     customerKeyword: this.screenForm.dealer,
    //     isDirectTransfer: this.screenForm.isDirectTransfer,

    //     specification: this.screenForm.model,
    //     enginOrderType: 'TRADE' // TRADE=商用 HOME=家用
    //   }
    //   getOrderList(params).then(res => {
    //     res.data.records.forEach(item => {
    //       item.sums1 = ['qty', 'directTransferQty', 'hasSendQty']
    //       item.sums2 = ['price', 'payAmount', 'discAmount']
    //     })
    //     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
    },

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

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

    // 进入退订
    toReturn(item) {
      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) {
      applyCom({ id, refEnginRecordNo: row.refEnginRecordNo }).then(res => {
        this.$successMsg()
        this.getList()
      })
    },

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

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

    // 删除
    handleDelete(id) {
      deleteCom({ ids: id }).then(res => {
        this.$successMsg()
        this.getList()
      })
    },

    // 批量删除
    batchDelete() {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let ids = this.recordSelected.map(item => {
            return item.parentId
          })
          deleteCom({ 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() {
      editDateCom({
        refEnginRecordNo: this.screenForm.loginNum,
        enginOrderId: this.editId,
        orderDate: this.dateForm.date + ' 00:00:00'
      }).then(res => {
        this.isShowEditDateDialog = false
        this.getList()
        this.$successMsg('修改成功')
      })
    }
  }
}
</script>

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