<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :exportList="exportList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :columnParsing="columnParsing"
    :tableEvents="tableEvents"
    :tableAttributes="tableAttributes"
    :operationColumnWidth="200"
  >
    <ExamineDialog :isShow.sync="isShowExamineDialog" :examineForm.sync="examineForm" @submit="submitExamineForm" />
    <EditDateDialog :is-show.sync="isShowEditDateDialog" :date-form.sync="dateForm" @submit="submitDateForm" />

    <Popu v-if="isShowDetail || isShowForm || isShowExamine || isShowReturn">
      <RetailDetail v-if="isShowDetail" :list-item="queryItem" @backListFormDetail="backList" />
      <RetailForm v-if="isShowForm" :list-item="queryItem" @backListFormDetail="backList" />
      <RetailExamine v-if="isShowExamine" :list-item="queryItem" @backListFormDetail="backList" />
      <RetailReturn v-if="isShowReturn" :list-item="queryItem" @backListFormDetail="backList" />
    </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,
  closeData,
  deleteList,
  editData,
  examineData,
  getList,
  submitCancel,
  submitData,
  getRetailListV2,
  exportRetailListV2
} from '@/api/supply/policy'
import RetailDetail from './components/retail_detail'
import RetailForm from './components/retail_form'
import RetailExamine from './components/retail_examine'
import RetailReturn from './components/retail_return'
import EditDateDialog from '@/components/Common/edit-date-dialog'
import ExamineDialog from '@/components/Common/examine-dialog'
import { getSalesmanList, getCategoryList, getTypeList } from '@/api/common'
import { getNoRebateWalletList } from '@/api/policy_list'

export default {
  components: {
    TemplatePage,
    Popu,
    RetailDetail,
    RetailForm,
    RetailExamine,
    RetailReturn,
    EditDateDialog,
    ExamineDialog
  },
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      visible: false,
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.toForm()
              }),
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量审批',
              click: () => {
                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: '',
        policyCode: '',
        policyRemark: '',
        jxsName: '',
        date: [],
        zbMan: '',
        shMan: '',
        status: '',
        salesMan: '',
        isDirectTransfer: null,
        specification: '',
        k3ServiceId: '',
        serviceId: '',
        categoryNumber: '',
        saleTypeId: '',
        customerWalletId: ''
      },
      transfer: [
        { label: '是', value: true },
        { label: '否', value: false }
      ],
      statusList: [
        { label: '已保存', value: 'SAVE' },
        { label: '待审核', value: 'WAIT' },
        { label: '审核通过', value: 'OK' }
        // { label: '审核驳回', value: 'FAIL' },
      ],
      queryItem: {},
      isShowDetail: false,
      isShowForm: false,
      isShowExamine: false,
      isShowReturn: false,
      isShowEditDateDialog: false,
      dateForm: {
        date: ''
      },
      salesmanList: [],
      selectRow: [],
      recordSelected: [],
      isShowExamineDialog: false,
      examineForm: {
        status: 'OK',
        remark: ''
      },
      categoryList: [],
      isCollapse: true,
      NoRebateWalletList: [],
      typeList: []
    }
  },
  watch: {
    recordSelected(data) {
      // 监听选中状态
      this.selectRow = []
      if (data.length > 0) {
        data.forEach((item, index) => {
          this.selectRow.push(item.id)
        })
      }
    }
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      return getRetailListV2(...p)
    },
    // 列表导出函数
    exportList: exportRetailListV2,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      if (item.colName === 'the_time') {
        defaultData.render = (h, { row, index, column }) => {
          return (
            <div class="dateClass">
              <span>{row.theTime}</span>
              {this.$checkBtnRole('date', this.$route.meta.roles) ? (
                <el-button
                  type="text"
                  icon="el-icon-edit"
                  style="padding: 0; margin-left: 6px"
                  onClick={() => this.editDate(row)}
                />
              ) : (
                ''
              )}
            </div>
          )
        }
      }

      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        const statusData = row.selectMapData.examineStatus
        return (
          <div class="operation-btns">
            {row.examineStatus === statusData['SAVE'] ? (
              <el-popconfirm title="确定提审？" onConfirm={() => this.handleSubmit(row.id)}>
                <el-button slot="reference" size="mini" type="text">
                  提审
                </el-button>
              </el-popconfirm>
            ) : null}
            {row.examineStatus == statusData['WAIT'] && this.$checkBtnRole('examine', this.$route.meta.roles) ? (
              <el-button type="text" size="mini" onClick={() => this.toExamine(row)}>
                审核
              </el-button>
            ) : null}
            {this.$checkBtnRole('del', this.$route.meta.roles) && row.examineStatus === statusData['SAVE'] ? (
              <el-popconfirm title="确定删除吗？" onConfirm={() => this.handleDelete(row.id)}>
                <el-button slot="reference" size="mini" type="text">
                  删除
                </el-button>
              </el-popconfirm>
            ) : null}
            {row.examineStatus === statusData['SAVE'] && this.$checkBtnRole('edit', this.$route.meta.roles) ? (
              <el-button type="text" size="mini" onClick={() => this.toForm(row)}>
                编辑
              </el-button>
            ) : null}
            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.examineStatus === statusData['OK'] ? (
              <el-popconfirm title="确定弃审吗？" onConfirm={() => this.handleAbandon(row.id)}>
                <el-button slot="reference" size="mini" type="text">
                  弃审
                </el-button>
              </el-popconfirm>
            ) : null}
            {row.examineStatus == statusData['WAIT'] && this.$checkBtnRole('apply', this.$route.meta.roles) ? (
              <el-popconfirm title="确定撤回？" onConfirm={() => this.handleCancel(row.id)}>
                <el-button slot="reference" size="mini" type="text">
                  撤回
                </el-button>
              </el-popconfirm>
            ) : null}
            <el-button type="text" size="mini" onClick={() => this.toDetail(row)}>
              详情
            </el-button>

            {row.examineStatus === statusData['OK'] && this.$checkBtnRole('examine', this.$route.meta.roles) ? (
              <el-button type="text" size="mini" onClick={() => this.toReturn(row)}>
                退订
              </el-button>
            ) : null}
            {row.examineStatus === statusData['SAVE'] && this.$checkBtnRole('examine', this.$route.meta.roles) ? (
              <el-popconfirm title="确定关闭吗？" onConfirm={() => this.handleClose(row.id)}>
                <el-button slot="reference" type="text" size="mini">
                  关闭
                </el-button>
              </el-popconfirm>
            ) : null}
          </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)
      })
    },
    handleSelectionAllChange(e) {
      this.recordSelected = e
      if (e) {
        this.selections = e
      } else {
        this.selections = []
      }
    },

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

    // 打开 批量审批
    batchExamine() {
      if (this.recordSelected.length) {
        this.isShowExamineDialog = true
        return
      }
      this.$errorMsg('请选择审核项')
    },
    // 提交 批量审批
    submitExamineForm() {
      let ids = this.recordSelected.map(item => {
        return item.id
      })
      ids = [...new Set(ids)]
      examineData({
        id: ids.join(','),
        examineStatus: this.examineForm.status,
        examineRemark: this.examineForm.remark,
        serviceId: ''
      }).then(res => {
        this.isShowExamineDialog = false
        this.$successMsg('修改成功')
        this.$refs.pageRef.refreshList()
      })
    },
    // 查询按钮权限
    checkBtnRole(value) {
      // let btnRole = this.$route.meta.roles;
      // if(!btnRole) {return true}
      // let index = btnRole.indexOf(value);
      // return index >= 0;
      return true
    },
    handleDelete(id) {
      deleteList({ id }).then(res => {
        this.$successMsg('删除成功')
        this.$refs.pageRef.refreshList()
      })
    },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1
      this.$refs.pageRef.refreshList()
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields()
      this.currentPage = 1
      this.$refs.pageRef.refreshList()
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.$refs.pageRef.refreshList()
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.$refs.pageRef.refreshList()
    },

    // 进入表单
    toForm(item) {
      this.queryItem = item

      this.isShowForm = true
    },

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

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

    // 进入退订
    toReturn(item) {
      this.queryItem = item
      this.isShowReturn = true
    },
    // 弃审
    handleAbandon(id) {
      abandonData({ id }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    },
    backList() {
      this.queryItem = {}

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

    // 关闭
    handleClose(id) {
      closeData({ id }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    },

    // 提审
    handleSubmit(id) {
      submitData({ id }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    },
    // 撤回
    handleCancel(id) {
      submitCancel({ id }).then(res => {
        this.$successMsg()
        this.$refs.pageRef.refreshList()
      })
    },
    // 打开 修改订单日期
    editDate(item) {
      this.editId = item.id
      this.dateForm.date = item.theTime.slice(0, 10)
      this.isShowEditDateDialog = true
    },

    // 提交 修改订单日期
    submitDateForm() {
      editData({
        id: this.editId,
        theTime: this.dateForm.date + ' 00:00:00'
      }).then(res => {
        this.isShowEditDateDialog = false
        this.$refs.pageRef.refreshList()
        this.$successMsg('修改成功')
      })
    },
    // 获取存货类别列表
    getCategoryList() {
      getCategoryList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.categoryList = res.data.records
      })
    }
  }
}
</script>

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