<template>
  <div style="width: 100%; height: 100%">
    <template-page
      v-show="showPage == 1"
      ref="pageRef"
      :operation="operation()"
      :optionsEvensGroup="optionsEvensGroup"
      :getList="getList"
      :exportList="exportList"
      :tableAttributes="tableAttributes"
      :tableEvents="tableEvents"
      :columnParsing="columnParsing"
      :replaceOrNotMap="false"
      :fieldBeansHook="fieldBeansHook"
    >
      <div slot="moreSearch">
        <div class="worker">
          <div class="worker_left">工单状态</div>
          <div class="worker_right">
            <el-button
              v-for="(item, index) in workerState"
              :key="index"
              :type="examineStatus == item.value ? 'primary' : null"
              @click="handleOrderStatusParam(item.value, index)"
              size="mini"
              >{{ item.label }}</el-button
            >
          </div>
        </div>
      </div>
    </template-page>
    <div class="app-container" v-if="showPage == 2">
      <RebateListApply
        :detailId="detailId"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div class="app-container" v-if="showPage == 3">
      <RebateListExamine
        :detailId="detailId"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div class="app-container" v-if="showPage == 4">
      <RebateListReview
        :detailId="detailId"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div class="app-container" v-if="showPage == 5">
      <RebateListDetail
        :detailId="detailId"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div class="app-container" v-if="showPage == 6">
      <RebateListConfirm
        :detailId="detailId"
        :isShow="isShow"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div class="app-container" v-if="showPage == 7">
      <RebateListEdit
        :detailId="detailId"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <ExamineDialog :isShow.sync="isShowExamineDialog" :examineForm.sync="examineForm" @submit="submitExamineForm" />
  </div>
</template>

<script>
import {
  getRebateOrderList,
  getRebateOrderApply,
  getRebateOrderBatchDel,
  getRebateOrderApplyBatch,
  getRebateOrderExamineBatch,
  getRebateOrderExamine2Batch
} from '@/api/finance/rebate_list'
import { rebateOrderList, rebateOrderListExport } from '@/api/finance/rebate_list_v2'
import RebateListApply from './components/rebate_list-apply.vue'
import RebateListExamine from './components/rebate_list-examine.vue'
import RebateListReview from './components/rebate_list-review.vue'
import RebateListDetail from './components/rebate_list-detail'
import RebateListConfirm from './components/rebate_list-confirm'
import RebateListEdit from './components/rebate_list-edit.vue'
import ExamineDialog from '@/components/Common/examine-dialog'
import TemplatePage from '@/components/template/template-page-1.vue'
export default {
  name: 'rebate_list',
  components: {
    RebateListDetail,
    RebateListApply,
    RebateListExamine,
    RebateListReview,
    RebateListConfirm,
    RebateListEdit,
    ExamineDialog,
    TemplatePage
  },
  data() {
    return {
      workerState: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '初审不通过',
          value: 'FAIL_ONE'
        },
        {
          label: '驳回',
          value: 'REJECT'
        },
        {
          label: '已确认未复核',
          value: 'OK_ONE_AND_CONFIRM'
        },
        {
          label: '弃审',
          value: 'ABANDON'
        },
        {
          label: '保存',
          value: 'SAVE'
        },
        {
          label: '关闭',
          value: 'CLOSE'
        },
        {
          label: '待审核',
          value: 'WAIT'
        },
        {
          label: '审核通过',
          value: 'OK'
        },
        {
          label: '审核不通过',
          value: 'FAIL'
        },
        {
          label: '初审通过',
          value: 'OK_ONE'
        }
      ],

      deleList: [],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [], // 列表数据
      searchForm: {
        id: '',
        customerName: '',
        walletName: '',
        customerNumber: '',
        startTime: '',
        endTime: '',
        examineStatus: '',
        isConfirm: '',
        remark1: '',
        examineBy: '',
        createBy: ''
      }, //搜索表单
      listLoading: false, // 列表加载loading
      showPage: 1,
      detailId: null,
      isCustomer: null,
      secondId: null,
      isShow: false,
      isCollapse: true,
      isShowExamineDialog: false,
      examineForm: {
        status: '',
        remark: ''
      },
      state: '',
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      examineStatus: '',
      customerIsConfirm: ''
    }
  },
  computed: {
    optionsEvensGroup() {
      return [
        [
          [
            {
              isRole: this.$checkBtnRole('del', this.$route.meta.roles),
              name: '批量删除',
              click: () => {
                if (!this.deleList.length) {
                  this.$message.info('请选择数据！')
                  return
                }
                this.$confirm('确定删除吗？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    this.deleFn()
                  })
                  .catch(() => {})
              }
            }
          ]
        ],
        [
          [
            {
              isRole: this.$checkBtnRole('apply', this.$route.meta.roles) && this.examineStatus === 'SAVE',
              name: '批量申请',
              click: () => {
                if (!this.deleList.length) {
                  this.$message.info('请选择数据！')
                  return
                }
                this.$confirm('确定执行批量申请吗？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    this.batchApplication()
                  })
                  .catch(() => {})
              }
            }
          ]
        ],
        [
          [
            {
              isRole: this.$checkBtnRole('examine', this.$route.meta.roles) && this.examineStatus === 'WAIT',
              name: '批量审核',
              click: () => {
                if (!this.deleList.length) {
                  this.$message.info('请选择数据！')

                  return
                }
                this.$confirm('确定执行批量审核吗？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    this.batchAudit('audit')
                  })
                  .catch(() => {})
              }
            }
          ]
        ],
        [
          [
            {
              isRole:
                this.$checkBtnRole('examine', this.$route.meta.roles) &&
                (this.examineStatus === 'OK_ONE_AND_CONFIRM' || this.customerIsConfirm === 'true'),
              name: '批量复核',
              click: () => {
                if (!this.deleList.length) {
                  this.$message.info('请选择数据！')
                  return
                }
                this.$confirm('确定执行批量复核吗？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                })
                  .then(() => {
                    this.batchReview('review')
                  })
                  .catch(() => {})
              }
            }
          ]
        ]
      ]
    }
    // isCustomer() {
    //   return this.$store.getters.customerId && this.$store.getters.customerNumber
    // }
  },
  watch: {
    $route() {
      if (this.$route.path === '/finance/rebate_list' && this.$route.query?.refreshList == 'true') {
        this.$refs.pageRef.refreshList()
      }
    }
  },
  created() {
    const res = JSON.parse(localStorage.getItem('supply_user'))
    this.isCustomer = res.isCustomer
    if (this.$route.query.id) {
      if (this.isCustomer) {
        this.confirmFn(this.$route.query.id, false)
      } else {
        this.examineFn(this.$route.query.id)
      }
    }
  },
  methods: {
    handleOrderStatusParam(value, index) {
      this.examineStatus = value
      this.$refs.pageRef.refreshList()
    },
    // 列表请求函数
    getList(p) {
      // var item = p.params.find(item => item.param === 'a.examine_status')
      // this.examineStatus = item?.value || ''
      var item2 = p.params.find(item => item.param === 'a.customer_is_confirm')
      this.customerIsConfirm = item2?.value || ''

      let params = {
        moduleId: p.moduleId,
        orderBy: p.orderBy,
        pageNum: p.pageNum,
        pageSize: p.pageSize,
        examineStatus: this.examineStatus,
        params: [...p.params]
      }

      return rebateOrderList(params)
    },
    // 列表导出函数
    exportList: rebateOrderListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      const res = data.map(v => v.rebateOrderId)
      this.deleList = res
    },
    fieldBeansHook(val) {
      val.map(item => {
        if (~['examine_status'].indexOf(item.colName)) {
          item.isQuery = false
        }
      })

      return val
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {!this.isCustomer &&
            this.$checkBtnRole('edit', this.$route.meta.roles) &&
            row.examineStatus != 'FAIL_ONE' ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.editFn(row.rebateOrderId)
                }}
              >
                编辑
              </el-button>
            ) : null}
            {row.examineStatus == 'SAVE' && !this.isCustomer && this.$checkBtnRole('apply', this.$route.meta.roles) ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.applyFn(row.rebateOrderId)
                }}
              >
                申请
              </el-button>
            ) : null}
            {row.examineStatus == 'WAIT' &&
            !this.isCustomer &&
            this.$checkBtnRole('examine', this.$route.meta.roles) ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.examineFn(row.rebateOrderId)
                }}
              >
                审核
              </el-button>
            ) : null}
            {(row.examineStatus == 'OK_ONE' || row.examineStatus == 'OK' || row.examineStatus == 'FAIL') &&
            !this.isCustomer &&
            this.$checkBtnRole('examine', this.$route.meta.roles) ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.reviewFn(row.rebateOrderId)
                }}
              >
                {row.examineStatus == 'OK' ? '取消复核' : '复核'}
              </el-button>
            ) : null}
            {(row.examineStatus == 'WAIT' || row.examineStatus == 'SAVE') && !this.isCustomer ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.infoFn(row.rebateOrderId)
                }}
              >
                详情
              </el-button>
            ) : null}
            {(row.examineStatus == 'OK_ONE' ||
              row.examineStatus == 'FAIL_ONE' ||
              row.examineStatus == 'FAIL' ||
              row.examineStatus == 'OK') &&
            !this.isCustomer ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.detail2(row.rebateOrderId)
                }}
              >
                详情
              </el-button>
            ) : null}
            {this.isCustomer &&
            row.withholdAmount == 0 &&
            (row.examineStatus == 'OK_ONE' || row.examineStatus == 'OK' || row.examineStatus == 'FAIL') ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.confirmFn(row.rebateOrderId, row.customerIsConfirm)
                }}
              >
                {row.customerIsConfirm == false ? '确定' : '详情'}
              </el-button>
            ) : null}
          </div>
        )
      }
    },
    // ------------------------------------
    //批量复核
    batchReview(value) {
      this.state = value
      this.isShowExamineDialog = true
    },
    //批量审核
    batchAudit(value) {
      this.state = value
      this.isShowExamineDialog = true
    },
    //提交批量审核
    async submitExamineForm() {
      let res = this.deleList.toString()
      if (this.state === 'audit') {
        await getRebateOrderExamineBatch({
          ids: res,
          examineStatus: this.examineForm.status,
          examineRemark: this.examineForm.remark
        })
        this.$message.success('批量审核成功')
      } else {
        await getRebateOrderExamine2Batch({
          ids: res,
          examineStatus: this.examineForm.status,
          examineRemark: this.examineForm.remark
        })
        this.$message.success('批量复核成功')
      }

      this.deleList = []
      this.isShowExamineDialog = false
      this.getDataList()
    },
    //批量申请
    async batchApplication() {
      let res = this.deleList.toString()
      await getRebateOrderApplyBatch({ ids: res })
      this.getDataList()
      this.$message.success('批量申请成功')
      this.deleList = []
    },
    //删除
    async deleFn() {
      let res = this.deleList.toString()
      await getRebateOrderBatchDel({ ids: res })
      this.getDataList()
      this.$message.success('删除成功')
      this.deleList = []
    },
    //获取列表数据
    async getDataList() {
      this.$refs.pageRef.refreshList()
    },
    //确认
    confirmFn(id, isShow) {
      this.isShow = isShow
      this.detailId = id
      this.showPage = 6
    },
    //复核
    reviewFn(id) {
      this.detailId = id
      this.showPage = 4
    },
    //审核
    examineFn(id) {
      this.detailId = id
      this.showPage = 3
    },
    //申请
    async applyFn(id) {
      await getRebateOrderApply({ id })
      this.getDataList()
      this.$message.success('申请成功')
    },
    //详情2
    detail2(id) {
      this.detailId = id
      this.showPage = 2
    },
    //详情
    infoFn(id) {
      this.detailId = id
      this.showPage = 5
    },
    //编辑
    editFn(id) {
      this.detailId = id
      this.showPage = 7
    }
  }
}
</script>
<style lang="scss" scoped>
.worker {
  display: flex;
  justify-content: space-between;
  .worker_left {
    font-size: 12px;
    font-weight: 400;
    text-align: left;
    color: #666;
    line-height: 28px;
    margin-right: 10px;
  }
  .worker_right {
    flex: 1;
    ::v-deep .el-button {
      margin: 0 10px 10px 0px;
    }
  }
}

.selectStyle {
  width: 100%;
}
</style>
