<template>
  <div style="width: 100%; height: 100%">
    <template-page
      v-show="showPage == 1"
      ref="pageRef"
      :operation="operation()"
      :options-evens-group="optionsEvensGroup"
      :get-list="getList2"
      :export-list="exportList"
      :table-attributes="tableAttributes"
      :table-events="tableEvents"
      :column-parsing="columnParsing"
      :field-beans-hook="fieldBeansHook"
    >
      <div slot="moreSearch">
        <ul class="ulStyle">
          <li class="title">
            金额：<span class="num">{{ (Number(numSum.amountC) || 0) | numToFixed }}</span>
          </li>
          <li class="title">
            数量：<span class="num">{{ Number(numSum.totalC) || 0 }}</span>
          </li>
          <li class="title">
            项目数：<span class="num">{{ Number(numSum.totalEC) || 0 }}</span>
          </li>
          <li style="color: #f00;margin-left: 20px;">红色字为驳回单待处理</li>
        </ul>
      </div>
    </template-page>
    <div v-if="showPage == 2" class="app-container">
      <DepositListDetail
        :deposit-manage-id="depositManageId"
        :ref-engin-record-no="refEnginRecordNo"
        @updateList="updateList"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div v-else-if="showPage == 3" class="app-container">
      <DepositApplyDeduction
        :deposit-manage-id="depositManageId"
        :ref-engin-record-no="refEnginRecordNo"
        @updateList="updateList"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div v-else-if="showPage == 4" class="app-container">
      <DepositApplySurrender
        :deposit-manage-id="depositManageId"
        :ref-engin-record-no="refEnginRecordNo"
        @updateList="updateList"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
    <div v-else-if="showPage == 5" class="app-container">
      <deposit_replenish
        :deposit-manage-id="depositManageId"
        :ref-engin-record-no="refEnginRecordNo"
        @updateList="updateList"
        @setShowPage="
          val => {
            $refs.pageRef.refreshList()
            showPage = val
          }
        "
      />
    </div>
  </div>
</template>

<script>
import DepositListDetail from './components/deposit_list-detail'
import { getDepositManageDate } from '@/api/engin_deposit/refund_list'
import DepositApplyDeduction from './components/deposit-apply-deduction.vue'
import DepositApplySurrender from './components/deposit-apply-surrender.vue'
import { downloadFiles, handleImport } from '@/utils/util'
import { depositManageHomeList, depositManageHomeListExport, getCountList, updateDepositManageenginInfo } from '@/api/deposit_list_v2.js'
import TemplatePage from '@/components/template/template-page-1.vue'
import deposit_replenish from './components/deposit_replenish.vue'

export default {
  components: {
    DepositListDetail,
    DepositApplyDeduction,
    DepositApplySurrender,
    deposit_replenish,
    TemplatePage
  },
  data() {
    return {
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [], // 列表数据
      screenForm: {
        confirmName: '', // 审核人
        createName: '', // 创建人
        customerKeyword: '', // 客户编码/客户名称
        endDeliverTime: '', // 发货申请日期-结束
        enginOrderNo: '', // 工程订单编号
        enginOrderType: 'HOME', // 工程订单类型
        examineStatus: '', // 状态
        refEnginRecordNo: '', // 登录单号
        refProjectName: '', // 项目名称
        refTradeCategory: '',
        refUseUnit: '', // 使用单位
        startDeliverTime: '', // 发货申请日期-开始
        startSubmitTime: '',
        startConfirmTime: '',
        isRefundDeposit: null,
        endConfirmTime: '',
        startInstallTime: '',
        endInstallTime: '',
        specification: '',
        refFactoryNo: '',
        factoryNo: '',
        specialNo: '',
        refRegionWork: '',
        endSubmitTime: '',
        startAcceptTime: '',
        endAcceptTime: '',
        geLiInerNote: '',
        startFactoryNo: '',
        endFactoryNo: '',
        startSpecialNo: '',
        endSpecialNo: '',
        startBillNo: '',
        endBillNo: '',
        mailFactoryYear: '',
        startConfirmDate: '',
        endConfirmDate: '',
        settlementNo: '',
        startSettlementDate: '',
        endSettlementDate: '',
        startInFactoryDate: '',
        endInFactoryDate: '',
        startSettlementNo: '',
        endSettlementNo: '',
        inFactoryType: '',
        endMailFactoryDate: '',
        startMailFactoryDate: '',
        settlementStatus: '',
        mailFactoryStatus: '',
        endOrderDate: '',
        startOrderDate: ''
      }, // 搜索表单
      listLoading: false, // 列表加载loading
      deduction: '全部',
      showPage: 1,
      importFileList: [],
      selectData: [],
      baseURL: '',
      isCollapse: true,
      refundDepositArr: [
        {
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ],
      mailFactoryStatus: '',
      settlementStatus: '',
      examineStatusArr: [
        {
          label: '保存',
          value: 'SAVE'
        },
        {
          label: '待审核',
          value: 'WAIT'
        },
        {
          label: '通过',
          value: 'OK'
        },
        {
          label: '关闭',
          value: 'CLOSE'
        }
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false,
        "row-class-name":this.tableRowClassName
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      depositManageId: '',
      refEnginRecordNo: '',
      numSum: {
        totalC: 0,
        amountC: 0,
        totalEC: 0
      }
    }
  },
  computed: {
    optionsEvensGroup() {
      return [
        [
          [
            {
              name: '',
              // isRole: this.$checkBtnRole('add', this.$route.meta.roles),
              render: () => {
                return (
                  <el-popconfirm
                    title='更新工程信息吗？'
                    onConfirm={() => {
                      updateDepositManageenginInfo().then(res => {
                        this.$message.success('更新工程信息成功')
                        this.$refs.pageRef.refreshList()

                      })
                    }}
                  >
                    <span slot='reference'>更新工程信息</span>
                  </el-popconfirm>
                )
              }
            }
          ]
        ],
        [
          [
            {
              name: '',
              isRole: !this.isCustomer,
              render: () => {
                return (
                  <el-upload
                    action={this.baseURL + 'student/import'}
                    http-request={this.handleImport}
                    file-list={this.importFileList}
                    show-file-list={false}
                  >
                    <span>导入</span>
                  </el-upload>
                )
              }
            }
          ]
        ]
      ]
    },
    isCustomer() {
      return this.$store.getters.customerId && this.$store.getters.customerNumber
    }
  },
  methods: {
    updateList() {
      this.$refs.pageRef.refreshList()
    },
    fieldBeansHook(list) {
      if (this.isCustomer) {
        var newlist = [...list]
        for (var i = 0; i < newlist.length; i++) {
          if (newlist[i].jname === 'geLiInerNote') {
            newlist.splice(i, 1)
            break
          }
        }
        return newlist
      }
      return list
    },
    tableRowClassName({row, rowIndex}){
      if ( row.confirmResult === '驳回') {
          return 'red-row';
        }
        return ''
    },
    // 列表请求函数
    getList2(...p) {
      this.$refs.pageRef.showTable = false
      this.recordSelected = []
      getCountList(...p).then(res => {
        this.numSum = res.data
      })
      return depositManageHomeList(...p)
    },
    // 列表导出函数
    exportList: depositManageHomeListExport,
    // 表格列解析渲染数据更改
    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'
              class='textColor'
              size='mini'
              onClick={() => {
                this.detailFn(row)
              }}
            >
              详情
            </el-button>
            {row.examineStatus == '保存' && this.$checkBtnRole('apply', this.$route.meta.roles) ? (
              <el-button
                type='text'
                class='textColor'
                onClick={() => {
                  this.surrenderFn(row)
                }}
              >
                申请退押
              </el-button>
            ) : null}

            {((row.examineStatus == '审核通过' && row.dataState == '补充') ||
              (row.examineStatus == '审核通过' && row.dataState == '正常')) &&
            this.isCustomer ? (
                <el-button
                  type='text'
                  class='textColor'
                  onClick={() => {
                    this.replenishClick(row.depositManageId)
                  }}
                >
                补充资料
                </el-button>
              ) : null}
          </div>
        )
      }
    },
    // ------------------------------------
    replenishClick(id) {
      this.depositManageId = id
      this.showPage = 5
    },
    reexamineClick(id) {
      this.detailId = id
      this.showSurrender = 3
    },
    // 同步资料日期
    async syncDateFn() {
      await getDepositManageDate()
      this.$message.success('同步资料日期成功')
    },
    // 免扣申请
    deductionFn() {
      this.showPage = 3
    },
    // 申请退押
    surrenderFn(row) {
      this.depositManageId = row.depositManageId
      this.showPage = 4
    },
    detailFn(row) {
      this.depositManageId = row.depositManageId
      this.refEnginRecordNo = row.refEnginRecordNo
      this.showPage = 2
    },
    hanleDownloadFiles() {
      let isRefundDeposit = this.deduction === '已退押' ? true : ''
      if (this.screenForm.isRefundDeposit == true || this.screenForm.isRefundDeposit == false) {
        isRefundDeposit = this.screenForm.isRefundDeposit
      }
      downloadFiles('deposit-manage/export', {
        ...this.screenForm,
        isRefundDeposit,
        orderType: 'HOME'
      })
    },
    // 导入
    async handleImport(param) {
      this.importLoading = true
      const file = param.file
      const formData = new FormData()
      formData.append('file', file)
      const result = await handleImport('deposit-manage/import', formData)
      this.importLoading = false
      this.importFileList = []
      if (result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        })
        this.$refs.pageRef.refreshList()
      } else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        })
      }
    },
    handleSelectionAllChange(e) {
      this.selectData = e
    }
  }
}
</script>

<style lang="scss" scoped>
.ulStyle{
  list-style: none;
  padding: 0;
  li{
    display: inline-block;
    margin-right: 20px;
  }
}
::v-deep .red-row{
  color: #f00;
}
</style>
