<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :exportList="exportList"
    :tableEvents="tableEvents"
    :tableAttributes="tableAttributes"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :columnParsing="columnParsing"
    :replaceOrNotMap="false"
  >
    <ExamineDialog :is-show.sync="isShowExamineDialog" :examine-form.sync="examineForm" @submit="submitExamineForm" />
    <Popu v-if="isShowDetail || isShowExamine || isShowReturnForm">
      <SalesDetail v-if="isShowDetail" :list-item="queryItem" :edit="edit" @close="handleClose" />
      <SalesExamine v-if="isShowExamine" :list-item="queryItem" @close="handleClose" />
      <SalesReturnForm v-if="isShowReturnForm" :list-item="queryItem" @close="handleClose" />
    </Popu>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import add_callback_mixin from '@/components/template/add_callback_mixin.js'
import Popu from '@/components/template/popu.vue'
import {
  abandonData,
  examineBatch,
  examineJudge,
  getList,
  getWarehouseList,
  getListOrderNo,
  getSaleOrderListV3,
  exportSaleOrderListV2
} from '@/api/supply/sales'
import SalesDetail from '@/views/supply/sales/components/sales_detail'
import SalesExamine from '@/views/supply/sales/components/sales_examine'
import SalesReturnForm from '@/views/supply/sales/components/sales_return_form'
import ExamineDialog from '@/components/Common/examine-dialog'
import { getCategoryList } from '@/api/common'
import { getNoRebateWalletList } from '@/api/policy_list'
export default {
  components: { TemplatePage, Popu, SalesDetail, SalesExamine, SalesReturnForm, ExamineDialog },
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      visible: false,
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '退货申请',
              click: this.toReturnForm,
              isRole: this.$checkBtnRole('refund', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量审批',
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                this.batchExamine()
              },
              isRole: this.$checkBtnRole('examine', 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: {
        // 筛选表单数据
        orderNum: '',
        jxsName: '',
        jxsNum: '',
        chName: '',
        chNum: '',
        model: '',
        warehouse: [],
        date: [],
        status: '',
        mainOrderId: '',
        approval: [],
        printTime: [],
        printDesc: null,
        syncStatus: '',
        id: '',
        categoryId: ''
      },
      statusList: [
        { label: '已保存', value: 'SAVE' },
        { label: '待审核', value: 'WAIT' },
        { label: '审核通过', value: 'OK' }
        // { label: '审核驳回', value: 'FAIL' },,
      ],
      orderTypeList: [
        { label: '商用', value: 'TRADE' },
        { label: '家用', value: 'HOME' },
        { label: '零售单', value: 'RETAIL' },
        { label: '销售政策单', value: 'RETAIL_POLICY' },
        { label: '置换单家用', value: 'PERMU_HOME' },
        { label: '置换商用', value: 'PERMU_TRADE' },
        { label: '置换零售', value: 'PERMU_RETAIL' },
        { label: '置换销售政策单', value: 'PERMU_RETAIL_POLICY' },
        { label: '调拨单零售', value: 'REQUISITION_RETAIL' },
        { label: '调拨单销售政策', value: 'REQUISITION_RETAIL_POLICY' },
        { label: '调拨单商用', value: 'REQUISITION_TRADE' },
        { label: '调拨单家用', value: 'REQUISITION_HOME' }
      ],
      warehouseList: [],
      centerDialogVisible: false,
      cid: '',
      isCollapse: true,
      queryItem: {},
      isShowDetail: false,
      isShowExamine: false,
      isShowReturnForm: false,
      value1: '',
      qty: '',
      edit: false,
      choiceDate: '',
      selectRow: [],
      categoryList: [],
      multipleSelection: [],
      isShowExamineDialog: false,
      examineForm: {
        status: '',
        remark: ''
      },
      setDisabled: {
        disabledDate: time => {
          if (this.choiceDate) {
            const res = 13 * 24 * 3600 * 1000
            const minTime = this.choiceDate - res
            const maxTime = this.choiceDate + res
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        },
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate = minDate.getTime()
          if (maxDate) this.choiceDate = ''
        }
      },
      isCustomer: JSON.parse(localStorage.getItem('supply_user')).isCustomer
    }
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      return getSaleOrderListV3(...p)
    },
    // 列表导出函数
    exportList: exportSaleOrderListV2,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            <el-button type="text" onClick={() => this.toDetail(row)}>
              详情
            </el-button>
            {row.type === 2 && row.examineStatus !== 'OK' && !this.isCustomer ? (
              <el-button
                type="text"
                onClick={() => {
                  this.toDetail(row)
                  this.edit = true
                }}
              >
                编辑
              </el-button>
            ) : null}
            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.examineStatus === 'WAIT' ? (
              <el-button type="text" onClick={() => this.toExamine(row)}>
                审批
              </el-button>
            ) : null}
            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.examineStatus === 'OK' ? (
              <el-popconfirm
                style="margin-left: 10px"
                title="确定弃审吗？"
                onConfirm={() => this.handleAbandon(row.id)}
              >
                <el-button slot="reference" type="text">
                  弃审
                </el-button>
              </el-popconfirm>
            ) : null}
          </div>
        )
      }
    },
    handleClose() {
      this.queryItem = {}
      this.edit = false
      this.addOff(() => {
        this.isShowDetail = false
        this.isShowExamine = false
        this.isShowReturnForm = false
      })()
      this.$refs.pageRef.refreshList()
    },

    // 获取仓库列表
    getWarehouseList() {
      getWarehouseList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.warehouseList = res.data.records
      })
    },
    // 获取存货类别列表
    getCategoryList() {
      getCategoryList({
        pageNum: 1,
        pageSize: -1,
        keyword: ''
      }).then(res => {
        this.categoryList = res.data.records
        console.log(this.categoryList)
      })
      // getNoRebateWalletList({
      //   walletName: ''
      // }).then(res => {
      //   console.log(res)
      //   this.NoRebateWalletList = res.data
      // })
    },
    updateReceipt() {
      if (!this.value1) {
        this.$errorMsg('请选择时间')
      }
      // updateReceipt({
      // startTime:this.value1[0],
      // endTime:this.value1[1]
      // }).then(res=>{
      //    this.$refs.pageRef.refreshList();
      //   this.$successMsg("已更新");
      //    this.value1 = ''
      // })
    },
    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1
      this.$refs.pageRef.refreshList()
      if (this.screenForm.orderNum) {
        getListOrderNo({
          orderNo: this.screenForm.orderNum.replace(/，/gi, ',')
        }).then(res => {
          if (res.data) {
            this.$confirm(res.data, '提示', {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
        })
      }
    },

    // 判断是否可以审批
    async examineJudge(item) {
      // 获取页面模版
      const result = await new Promise((resolve, reject) => {
        examineJudge({ id: item.id })
          .then(res => {
            resolve(res.code == 200)
          })
          .catch(res => {
            resolve(0)
          })
      })
      return result
    },

    // 进入表单
    toReturnForm(item) {
      this.queryItem = item
      this.isShowReturnForm = true
    },

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

    // 进入审批
    async toExamine(item) {
      const canExamine = await this.examineJudge(item)
      if (!canExamine) {
        return false
      }
      this.queryItem = item
      this.isShowExamine = true
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      if (val) {
        this.selections = val
      } else {
        this.selections = []
      }
    },

    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(row.id)) {
        return { 'background-color': '#ecf5ff' }
      }
    },

    // 打开 批量审批
    batchExamine() {
      this.isShowExamineDialog = true
    },

    // 提交 批量审批
    submitExamineForm() {
      const ids = this.recordSelected.map(item => {
        return item.id
      })
      examineBatch({
        ids: ids.join(','),
        examineStatus: this.examineForm.status,
        approvalRemark: this.examineForm.remark
      }).then(res => {
        this.isShowExamineDialog = false
        this.$refs.pageRef.refreshList()
        this.$successMsg('修改成功')
      })
    },

    // 弃审
    handleAbandon(id) {
      abandonData({ id }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    }
  }
}
</script>

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