<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :exportList="exportList"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
  >
    <ExamineDialog @submit="submitExamineForm" :isShow.sync="isShowExamineDialog" :examineForm.sync="examineForm" />

    <Popu v-if="show !== 1">
      <!-- <el-page-header slot="head" :content="content" @back="handleClose" /> -->
      <ModifyListApply v-if="show === 2 || show == 5" :cid="cid" :show="show" @back="handleClose" />
      <ModifyListApproval v-if="show === 3" :detail="detail" @back="handleClose" />
      <ModifyListDetail v-if="show === 4" :detail="detail" @back="handleClose" />
    </Popu>
  </template-page>
</template>

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

import ModifyListApply from './components/modify_list-apply.vue'
import ModifyListApproval from './components/modify_list-approval.vue'
import ModifyListDetail from './components/modify_list-detail.vue'
import ExamineDialog from '@/components/Common/examine-dialog'
// import Mixin from '@/mixin/index'
import {
  getPriceSubmit,
  getProductRricedel,
  getProductRriceDetail,
  getProductRriceList,
  getTypeList,
  examineData,
  v2ProductUpdPriceList,
  v2ProductUpdPriceListExport,
  productUpdPriceDownload,
  productUpdPriceMaterialImport
} from '@/api/basic_data/material'
// import { downloadFiles, handleImport } from '@/utils/util'
import { getCategoryList } from '@/api/common'

export default {
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      handleClose: this.addOff(() => {
        if (this.show === 2 || this.show === 5) {
          this.cid = ''
          this.show = 1
        }
        this.show = 1
        this.$refs.pageRef.refreshList()
      }),
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.addFn()
              })
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                this.hanleDeleteAll()
              },
              isRole: this.$checkBtnRole('del', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量审批',
              click: async () => {
                this.batchExamine()
              }
            }
          ]
        ],
        [
          [
            {
              name: '',
              render: this.importButton(productUpdPriceMaterialImport, '导入', {
                billType: 'GENERAL'
              })
            }
          ]
        ],
        [
          [
            {
              name: '导入模版',
              click: () => {
                productUpdPriceDownload({}, `${this.$route.meta.title}`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],

      baseURL: '',
      importFileList: [],
      show: 1,
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [
        {
          baseUnitId: '',
          batchPrice: '',
          billId: '',
          endDate: '',
          id: null,
          isPromote: '',
          isPublish: '',
          materialId: '',
          materialName: '',
          materialNumber: '',
          parentId: '',
          qty: '',
          rebateUseRate: '',
          retailPrice: '',
          saleTypeId: '',
          specification: '',
          startDate: '',
          wallets: []
        }
      ],
      screenForm: {
        materialName: '',
        materialNumber: '',
        startDate: '',
        materialOldNumber: '',
        saleTypeId: '',
        k3CategoryNumber: '',
        specification: '',
        remark: ''
      },
      liDetail: {},
      detail: {},
      obj: {
        baseUnitId: '',
        batchPrice: '',
        billId: '',
        endDate: '',
        id: null,
        isPromote: '',
        isPublish: '',
        materialId: '4',
        materialName: '',
        materialNumber: '',
        parentId: '',
        qty: '',
        rebateUseRate: '',
        retailPrice: '',
        saleTypeId: '',
        specification: '',
        startDate: '',
        wallets: []
      },
      cid: '',
      typeList: [],
      dictList: [],
      isCollapse: true,
      importLoading: false,
      isShowExamineDialog: false,
      examineForm: {
        status: 'OK',
        remark: ''
      }
    }
  },
  components: {
    ExamineDialog,
    ModifyListApply,
    ModifyListApproval,
    ModifyListDetail,
    TemplatePage,
    Popu
  },
  computed: {
    exParams() {
      return {
        materialName: this.screenForm.materialName,
        materialNumber: this.screenForm.materialNumber,
        startDate: this.screenForm.startDate,
        materialOldNumber: this.screenForm.materialOldNumber,
        saleTypeId: this.screenForm.saleTypeId,
        k3CategoryNumber: this.screenForm.k3CategoryNumber,
        specification: this.screenForm.specification,
        remark: this.screenForm.remark,
        billType: 'DIFF'
      }
    }
  },
  mounted() {
    let params = {
      pageNum: 1,
      pageSize: -1,
      saleCode: '',
      saleName: '',
      status: ''
    }
    getTypeList(params).then(res => {
      this.typeList = res.data.records
    })
    getCategoryList({ pageNum: 1, pageSize: -1 }).then(res => {
      this.dictList = res.data.records
      console.log(this.dictList, 777777)
    })
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      let params = {
        moduleId: p[0].moduleId,
        orderBy: p[0].orderBy,
        pageNum: p[0].pageNum,
        pageSize: p[0].pageSize,
        params: [...p[0].params, { param: 'a.bill_type', compare: '=', value: 'DIFF' }]
      }
      return v2ProductUpdPriceList(params)
    },
    // 列表导出函数
    // exportList: v2ProductUpdPriceListExport,
    exportList(...p) {
      let params = {
        exportFields: p[0].exportFields,
        moduleId: p[0].moduleId,
        orderBy: p[0].orderBy,
        pageNum: p[0].pageNum,
        pageSize: p[0].pageSize,
        params: [...p[0].params, { param: 'a.bill_type', compare: '=', value: 'DIFF' }]
      }
      return v2ProductUpdPriceListExport(params, p[1])
    },
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {row.examineStatus == '保存' ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.handleGetPriceSubmit(row.updPriceBillId)
                }}
                title="是否确定需要提审该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  提审
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

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

            {row.examineStatus == '保存' ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.editFn(row.updPriceBillId, row)
                }}
              >
                编辑
              </el-button>
            ) : (
              ''
            )}

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

    formatterType(row) {
      for (let i = 0; i < this.typeList.length; i++) {
        if (this.typeList[i].id == row.saleTypeId) {
          return this.typeList[i].saleName
        }
      }
    },
    addFn() {
      this.show = 2
    },

    hanleDeleteAllPromise(id) {
      return new Promise((resolve, reject) => {
        const ids = id ? [id] : this.recordSelected.map(v => v.updPriceBillId)
        if (!ids.length) {
          this.$errorMsg('请选择删除内容')
          return
        }
        resolve(ids)
      })
    },
    hanleDeleteAll(id) {
      this.hanleDeleteAllPromise(id).then(ids => {
        getProductRricedel(ids).then(res => {
          this.$successMsg('删除成功')
          // this.getList()
          this.$refs.pageRef.refreshList()
        })
      })
    },
    // 打开 批量审批
    batchExamine() {
      if (this.recordSelected.length) {
        this.isShowExamineDialog = true
        return
      }
      this.$errorMsg('请选择审核项')
    },
    // 提交 批量审批
    submitExamineForm() {
      // let ids = this.dis.map(item => {
      //   return item
      // });
      const ids = [...new Set(this.recordSelected.map(v => v.updPriceBillId))]
      examineData({
        ids: ids.join(','),
        examineStatus: this.examineForm.status,
        examineRemark: this.examineForm.remark
      }).then(res => {
        this.isShowExamineDialog = false
        this.$successMsg('修改成功')
        // this.getList()
        this.$refs.pageRef.refreshList()
      })
    },
    handleGetPriceSubmit(id) {
      // console.log(id)
      getPriceSubmit({ ids: id }).then(res => {
        this.$successMsg('已提审')
        // this.getList()
        this.$refs.pageRef.refreshList()
      })
    },
    approvalFn(id) {
      getProductRriceDetail({ id }).then(res => {
        this.detail = res.data
        this.show = 3
      })
    },
    detailFn(id) {
      getProductRriceDetail({ id }).then(res => {
        this.detail = res.data

        this.show = 4
      })
    },
    // getList() {
    //   this.listLoading = true
    //   console.log(456654)
    //   let params = {
    //     pageNum: this.currentPage,
    //     pageSize: this.pageSize,
    //     materialName: this.screenForm.materialName,
    //     materialNumber: this.screenForm.materialNumber,
    //     startDate: this.screenForm.startDate,
    //     materialOldNumber: this.screenForm.materialOldNumber,
    //     saleTypeId: this.screenForm.saleTypeId,
    //     k3CategoryNumber: this.screenForm.k3CategoryNumber,
    //     specification: this.screenForm.specification,
    //     remark: this.screenForm.remark,
    //     billType: 'DIFF'
    //   }
    //   getProductRriceList(params).then(res => {
    //     this.dataList = res.data.records
    //     this.listTotal = res.data.total
    //     this.listLoading = false
    //   })
    // },
    editFn(id, row) {
      this.cid = id
      this.show = 5

      // this.diaLogForm = {
      //   id,
      //   composeNumber: row.composeNumber,
      //   items: row.items === undefined ? [] : row.items,
      //   materialId: row.materialId,
      //   orgNumber: row.orgNumber,
      //   productModel: row.productModel,
      //   productVolume: row.productVolume,
      // };
      // this.showDialogForm = true;
    },
    hanleInfo() {
      if (this.type === 1) {
        getProductAdd(this.diaLogForm).then(res => {
          this.$successMsg('保存成功')
          console.log(params, 123)
          this.getList()
        })
      } else if (this.type === 2) {
        const params = {
          ...this.diaLogForm
        }
        console.log(params, 123)
        getProductEdit(params).then(res => {
          this.$successMsg('编辑成功')
          this.getList()
        })
        this.diaLogForm.id = null
      }
      this.showDialogForm = false
    },
    hanleDelete(id) {
      this.hanleDeleteAllPromise(id).then(ids => {
        getProductDel(ids).then(res => {
          this.$successMsg('删除成功')
        })
      })
    },
    handleExport() {
      let screenData = {
        customerName: this.screenForm.customerName,
        freeDay: this.screenForm.freeDay,
        toll: this.screenForm.toll,
        remark: this.screenForm.remark,
        billType: 'DIFF'
      }
      downloadFiles('product-compose/export', screenData)
    },
    resetInfo() {
      this.diaLogForm = {
        composeNumber: '',
        id: '',
        items: [],
        materialId: '',
        orgNumber: 0,
        productModel: '',
        productVolume: ''
      }
    },
    // 导入
    async handleImport(param) {
      this.importLoading = true
      const file = param.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('billType', 'DIFF')

      const result = await handleImport('/product-upd-price/material/import', formData)
      this.importLoading = false
      this.importFileList = []
      if (result.code === 200) {
        this.$alert('成功处理记录数：' + result.data, '导入成功', {
          confirmButtonText: '确定'
        })
        this.getList()
      } else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        })
      }
    },
    // 下载经销商模板
    hanleDownloadFiles() {
      downloadFiles('product-upd-price/download', {
        billType: 'DIFF'
      })
    },
    tableRowClassName({ row, rowIndex }) {
      // || row.examineStatus=='FAIL'
      if (this.ids.includes(row.updPriceBillId)) {
        return 'warning-row'
      }
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table .warning-row {
  background: oldlace;
}
::v-deep .el-select--small {
  width: 100%;
}
.import-btn {
  display: inline-block;
  margin: 0 10px;
}
</style>
