<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"
    :replace-or-not-map="false"
    :operation-column-width="200"
    :field-beans-hook="fieldBeansHook"
  >
    <popu v-if="isShow !== 1">
      <el-page-header slot="head" :content="content" @back="handleClose" />
      <add-policy
        v-if="isShow === 2"
        :is-show="isShow"
        :is-flag="isFlag"
        @close="handleClose"
        @upDataIsFlag="upDataIsFlag"
      />
      <edit-policy
        v-if="isShow === 3"
        :id="id"
        :is-show="isShow"
        :is-flag="isFlag"
        @close="handleClose"
        @upDataIsFlag="upDataIsFlag"
      />
      <Details v-if="isShow === 4" :id="id" :is-show="isShow" @close="handleClose" />
      <examine v-if="isShow === 5" :id="id" :is-show="isShow" @close="handleClose" />
    </popu>
    <el-dialog
      title="批量修改机型"
      :visible.sync="replaceVisible"
      width="80%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <replace-record-form v-if="replaceVisible" :record-selected="recordSelected" @close="handleDialogClose" />
    </el-dialog>
    <el-dialog
      title="批量修改延期"
      :visible.sync="delayVisible"
      width="80%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <delay-record-form v-if="delayVisible" :record-selected="recordSelected" @close="handleDialogClose" />
    </el-dialog>
    <el-dialog
      title="批量作废机型"
      :visible.sync="cancalVisible"
      width="80%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <Cancal v-if="cancalVisible" :record-selected="recordSelected" @close="handleDialogClose" />
    </el-dialog>
  </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 DelayRecordForm from './components/delayRecordForm.vue'
import ReplaceRecordForm from './components/replaceRecordForm.vue'
import Cancal from './components/cancal.vue'
import {
  cancelPolicy,
  cloneList,
  deletePolicy,
  getCrList,
  getId,
  getpolicySubmit,
  toExamine,
  setAbandon,
  policyListV2,
  policyListV2Export
} from '@/api/policy_list'
import { downloadFiles, handleImport } from '@/utils/util'
import AddPolicy from './components/AddPolicy'
import EditPolicy from './components/editPolicy'
import Details from './components/details.vue'
import Examine from './components/Examine'
import { mapState } from 'vuex'

export default {
  mixins: [add_callback_mixin],
  data() {
    return {
      replaceVisible: false,
      delayVisible: false,
      cancalVisible: false,
      showPage: true,
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.hanlenewInfo()
              })
            }
          ]
        ],
        [
          [
            {
              name: '批量修改机型',
              isRole: this.$checkBtnRole('xiugai', this.$route.meta.roles),

              click: () => {
                this.replaceVisible = true
              }
            }
          ]
        ],
        [
          [
            {
              name: '批量作废机型',
              isRole: this.$checkBtnRole('zuofei', this.$route.meta.roles),

              click: () => {
                if (!this.recordSelected.length) {
                  this.$errorMsg('请选择内容')
                  return
                }
                this.cancalVisible = true
              }
            }
          ]
        ],
        [
          [
            {
              name: '批量修改延期',
              isRole: this.$checkBtnRole('yanqi', this.$route.meta.roles),
              click: () => {
                if (!this.recordSelected.length) {
                  this.$errorMsg('请选择内容')
                  return
                }
                for (let i = 0; i < this.recordSelected.length; i++) {
                  if (this.recordSelected[i].examineStatus !== 'OK') {
                    this.$errorMsg('请选择审核通过的政策')
                    return
                  }
                }
                this.delayVisible = true
              }
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],

      //
      id: '',
      code: '',
      codeId: '',
      listLoading: false,
      policyId: '',
      CrList: [],
      isShow: 1,
      dataList: [],
      screenForm: {
        code: '',
        createBy: '',
        endCreateTime: '',
        endTime1: '',
        endTime2: '',
        examineBy: '',
        remark: '',
        startCreateTime: '',
        startTime1: '',
        startTime2: '',
        status: '',
        title: '',
        type: '',
        customerId: '',
        specification: '',
        customerNumber: ''
      },
      fileList: [],
      statusOptions: [
        {
          value: true,
          label: '已生效'
        },
        {
          value: false,
          label: '未生效'
        }
      ],
      typeOptions: [
        {
          vlaue: 'PROVISION',
          label: '配提'
        },
        {
          value: 'LIMIT',
          label: '限量'
        }
      ],
      typeList: [],
      value: '',
      imageUrl: '',
      baseURL: '',
      isFlag: '',
      isCollapse: true
    }
  },
  created() {
    const customerParams = {
      pageNum: 1,
      pageSize: -1,
      keyword: '',
      region: ''
    }
    // 获取经销商列表
    getCrList(customerParams).then(res => {
      this.CrList = res.data.records
    })
  },
  computed: mapState({
    comCode: state => state.sales.code,
    content() {
      const textArr = ['新增', '编辑', '详情', '审核']
      return textArr[this.isShow - 2]
    }
  }),
  methods: {
    handleDialogClose() {
      this.replaceVisible = false
      this.delayVisible = false
      this.cancalVisible = false
      this.$refs.pageRef.refreshList()
    },
    fieldBeansHook(list) {
      return [
        ...list,
        {
          adminUserId: null,
          colName: 'specification',
          enumMap: '{}',
          frontCode: '',
          hide: false,
          isCopy: false,
          isQuery: true,
          isShow: false,
          isTotal: false,
          jname: 'specification',
          label: '机型规格',
          multiple: false,
          pk: false,
          sortNum: 0,
          tbName: '',
          type: 'input',
          noUse: true
        },
        {
          adminUserId: null,
          colName: 'specification2',
          enumMap: '{}',
          frontCode: '',
          hide: false,
          isCopy: false,
          isQuery: true,
          isShow: false,
          isTotal: false,
          jname: 'specification2',
          label: '已作废机型',
          multiple: false,
          pk: false,
          sortNum: 0,
          tbName: '',
          type: 'input',
          noUse: true
        },
        {
          adminUserId: null,
          colName: 'customer_id',
          enumMap: '{}',
          frontCode: 'CUSTOMER',
          hide: false,
          isCopy: false,
          isQuery: true,
          isShow: false,
          isTotal: false,
          jname: 'customerId',
          label: '经销商',
          multiple: false,
          pk: false,
          sortNum: 0,
          tbName: '',
          type: 'select',
          noUse: true
        }
      ]
    },
    // 列表请求函数
    getList(p, cb) {
      var pm = JSON.parse(JSON.stringify(p))
      var specification, customerId, specification2

      for (let i = 0; i < pm.params.length; i++) {
        if (pm.params[i].param === 'specification') {
          specification = pm.params[i].value
          pm.params.splice(i, 1)
        }
      }
      for (let i = 0; i < pm.params.length; i++) {
        if (pm.params[i].param === 'customer_id') {
          customerId = pm.params[i].value
          pm.params.splice(i, 1)
        }
      }
      for (let i = 0; i < pm.params.length; i++) {
        if (pm.params[i].param === 'specification2') {
          specification2 = pm.params[i].value
          pm.params.splice(i, 1)
        }
      }

      cb?.({ ...pm, specification, customerId, specification2 })
      return policyListV2({ ...pm, specification, customerId, specification2 })
    },
    // 列表导出函数
    exportList: policyListV2Export,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    upDataIsFlag() {
      this.isFlag = 1
    },
    handleClose() {
      this.addOff(() => {
        this.isShow = 1
        this.showPage = true
        this.$refs.pageRef.refreshList()
      })()
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {row.examineStatus == 'SAVE' ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.isShow = 3
                  this.id = row.id
                }}
              >
                编辑
              </el-button>
            ) : (
              ''
            )}

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

            {row.examineStatus == 'WAIT' && this.$checkBtnRole('examine', this.$route.meta.roles) ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.isShow = 5
                  this.id = row.id
                  this.code = row.code
                  this.policyId = row.policyId
                }}
              >
                审核
              </el-button>
            ) : (
              ''
            )}

            {row.examineStatus == 'SAVE' ? (
              <el-popconfirm
                onConfirm={async () => {
                  this.handlesubmit(row)
                }}
                title="是否确定需要提审该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  提审
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {row.examineStatus == 'OK' && row.status ? (
              <el-popconfirm
                onConfirm={async () => {
                  this.handleNullify(row)
                }}
                title="是否确定需要作废该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  作废
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {
              <el-popconfirm
                onConfirm={async () => {
                  this.handleClone(row)
                }}
                title="是否确定需要克隆该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  克隆
                </el-button>
              </el-popconfirm>
            }

            {row.examineStatus != 'OK' ? (
              <el-popconfirm
                onConfirm={async () => {
                  this.hanleDelete(row.id)
                }}
                title="是否确定需要删除该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  删除
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {row.examineStatus == 'OK' ? (
              <el-popconfirm
                onConfirm={async () => {
                  this.hanleAbandon(row.id)
                }}
                title="是否确定需要弃审该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  弃审
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}
          </div>
        )
      }
    },

    tableRowClassName({ row, rowIndex }) {
      // || row.examineStatus=='FAIL'
      if (row.status == 0) {
        return 'warning-row'
      }
      return ''
    },
    hanlenewInfo() {
      console.log()
      getId().then(res => {
        this.$store.commit('sales/setId', res.data)
        this.isShow = 2
      })
    },
    handleClone(row) {
      cloneList({ policyId: row.id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('克隆成功')
      })
    },
    // getList() {
    //   this.listLoading = true
    //   const params = {
    //     pageNum: this.currentPage,
    //     pageSize: this.pageSize,
    //     code: this.screenForm.code,
    //     type: this.screenForm.type,
    //     createBy: this.screenForm.createBy,
    //     endCreateTime: this.screenForm.endCreateTime,
    //     endTime1: this.screenForm.endTime1,
    //     endTime2: this.screenForm.endTime2,
    //     examineBy: this.screenForm.examineBy,
    //     remark: this.screenForm.remark,
    //     startCreateTime: this.screenForm.startCreateTime,
    //     startTime1: this.screenForm.startTime1,
    //     startTime2: this.screenForm.startTime2,
    //     status: this.screenForm.status,
    //     title: this.screenForm.title,
    //     customerId: this.screenForm.customerId,
    //     customerNumber: this.screenForm.customerNumber,
    //     specification: this.screenForm.specification
    //   }
    //   getList(params).then(res => {
    //     this.dataList = res.data.records
    //     console.log(this.dataList)
    //     this.listTotal = res.data.total
    //     this.listLoading = false
    //   })
    //   // 产品类型
    //   // const paramsType = {
    //   //   pageNum: 1,
    //   //   pageSize: 10,
    //   //   saleCdoe: '',
    //   //   saleName: '',
    //   //   stauts: ''
    //   // }
    //   // getTypeList(paramsType).then(res => {
    //   //   this.typeList = res.data.records
    //   // })
    // },
    hanleAbandon(id) {
      setAbandon({ policyId: id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('弃审成功')
      })
    },
    hanleDelete(id) {
      this.hanleDeleteAllPromise(id).then(ids => {
        deletePolicy({
          id: ids[0]
        }).then(res => {
          this.$refs.pageRef.refreshList()
          this.$message.success('删除成功')
        })
      })
    },
    hanleDeleteAllPromise(id) {
      return new Promise((resolve, reject) => {
        const ids = id ? [id] : this.ids
        if (!ids.length) {
          this.$errorMsg('请选择删除内容')
          return
        }
        resolve(ids)
      })
    },
    // 作废
    handleNullify(row) {
      cancelPolicy({ id: row.id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('作废成功')
      })
    },
    // 导出文档
    handleExport() {
      const screenData = {
        customerTel: this.diaLogForm.customerTel,
        logisticsCompany: this.diaLogForm.logisticsCompany
      }
      downloadFiles('policy/export', screenData)
    },

    // 导入
    async handleImport(param) {
      this.importLoading = true
      const file = param.file
      console.log(file, 123)
      const formData = new FormData()
      formData.append('file', file)
      const result = await handleImport('/policy/material/import', formData)
      this.importLoading = false
      this.importFileList = []
      if (result.code == 200) {
        this.$alert('导入成功', '导入成功', {
          confirmButtonText: '确定'
        })
        this.getList()
      } else {
        this.$alert('导入失败', '导入失败', {
          confirmButtonText: '确定'
        })
      }
    },
    handlesubmit(e) {
      getpolicySubmit({ policyId: e.id }).then(res => {
        this.$refs.pageRef.refreshList()
        this.$message.success('提审成功')
      })
    },
    hanleExamine(e) {
      if (e.examineStatus == 'WAIT') {
        toExamine({
          examineRemark: e.id,
          examineStatus: 'WAIT',
          policyId: e.id
        }).then(res => {
          this.$successMsg('已提交')
        })
      } else {
        this.$errorMsg('未满足条件')
      }
    }
  },
  // eslint-disable-next-line vue/order-in-components
  components: {
    TemplatePage,
    Popu,
    Cancal,
    Examine,
    Details,
    AddPolicy,
    EditPolicy,
    DelayRecordForm,
    ReplaceRecordForm
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table .warning-row {
  background: oldlace;
}
// ::v-deep  .el-table .success-row {
//   background: #f0f9eb;
// }
.btn {
  width: 80px;
}

.mpd {
  padding: 20px 0 0 0;
}

.select_height {
  width: 100%;
}
.import-btn {
  margin: 0 10px;
}
.header {
  display: flex;
  height: 50px;
  align-items: center;
}
.fr {
  margin: 20px 0;
}
</style>
