<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :exportList="exportList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :replaceOrNotMap="false"
  >
    <Popu v-if="showPage !== 1">
      <ReceivableListAdd v-if="showPage == 2" @close="handleClose" />
      <ReceivableListApproval :approvalId="approvalId" v-if="showPage == 3" @close="handleClose" />
      <ReceivableListDetail :approvalId="approvalId" :czType="czType" v-if="showPage == 4" @close="handleClose" />
    </Popu>
    <print-preview ref="preView" @initPrint="handleInitPrint" @refreshList="handleRefreshList"  />
  </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 { getCustomerList } from '@/api/finance/wallet'
import {
  getFinanceOtherReceList,
  getFinanceOtherReceListV2,
  exportFinanceOtherReceListV2,
  getFinanceOtherReceDelete,
  getFinanceOtherReceDetail,
  getFinanceOtherReceApply,
  getFinanceOtherReceAbandon
} from '@/api/finance/receivable_list'
import ReceivableListAdd from './components/receivable_list-add'
import ReceivableListApproval from './components/receivable_list-approval'
import ReceivableListDetail from './components/receivable_list-detail'
import { disAutoConnect, hiprint } from 'vue-plugin-hiprint'

disAutoConnect()
import printPreview from './components/design/preview.vue'

import { getCompanyList } from '@/api/user'
import { numToFixed } from '@/filters'
import { changeNumberMoneyToChinese } from '@/utils/util'

export default {
  components: { TemplatePage, Popu, ReceivableListAdd, ReceivableListApproval, ReceivableListDetail, printPreview },
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      visible: false,
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '打印发货单',
              click: () => {
                if (!this.recordSelected.length) {
                  this.$message.info('请选择数据！')
                  return
                }
                this.toPrint()
              },
              isRole: this.$checkBtnRole('print', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.addFn()
              }),
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                let ids = this.recordSelected.map(v => {
                  return v.itemId
                })
                let params = { ids: ids.toString() }
                await getFinanceOtherReceDelete(params)
                this.$refs.pageRef.refreshList()
                this.$message.success('批量删除成功')
              },
              isRole: this.$checkBtnRole('del', this.$route.meta.roles)
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      }, // 关闭新增弹窗

      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      customerList: [],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [], // 列表数据
      searchForm: {
        source: '',
        code: '',
        userName: '',
        startTime: '',
        endTime: '',
        examineBy: ''
      }, //搜索表单
      listLoading: false, // 列表加载loading
      examine: '',
      showPage: 1,
      approvalId: null,
      czType: '',
      isCollapse: true,
      deleList: [],
      hiprintTemplate: '',
      company: '',
      tableSelection: []
    }
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      return getFinanceOtherReceListV2(...p)
    },
    // 列表导出函数
    exportList: exportFinanceOtherReceListV2,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {this.$checkBtnRole('print', this.$route.meta.roles) ? (
              <el-button type="text" class="textColor" onClick={() => this.toPrint(row, 2)}>
                打印
              </el-button>
            ) : null}
            {(row.examineStatus == 'WAIT' || row.examineStatus == 'FAIL') &&
            this.$checkBtnRole('examine', this.$route.meta.roles) ? (
              <el-button type="text" onClick={() => this.approvalFn(row.id)}>
                审批
              </el-button>
            ) : null}
            {row.examineStatus == 'SAVE' ? (
              <el-button type="text" onClick={() => this.bringFn(row.id)}>
                提审
              </el-button>
            ) : null}
            {row.examineStatus == 'OK' || row.examineStatus == 'FAIL' ? (
              <el-button type="text" onClick={() => this.unApprovalFn(row.id)}>
                弃审
              </el-button>
            ) : null}
            {row.examineStatus == 'SAVE' ? (
              <el-button type="text" onClick={() => this.detailFn(row.id, 'edit')}>
                编辑
              </el-button>
            ) : null}
            {
              <el-button type="text" onClick={() => this.detailFn(row.id, 'detail')}>
                详情
              </el-button>
            }
          </div>
        )
      }
    },
    handleClose() {
      this.addOff(() => {
        this.showPage = 1
      })()
      this.$refs.pageRef.refreshList()
    },
    //获取经销商列表
    async getCustomerDataList() {
      let res = await getCustomerList({
        pageNum: 1,
        pageSize: -1
      })
      this.customerList = res.data.records
    },
    //提审
    async bringFn(id) {
      await getFinanceOtherReceApply({ id })
      this.$message.success('提审成功')
      this.$refs.pageRef.refreshList()
      // this.getDataList({
      //   pageNum: this.currentPage,
      //   pageSize: this.pageSize,
      //   examineStatus: this.examine
      // })
    },
    //弃审
    async unApprovalFn(id) {
      await getFinanceOtherReceAbandon({ id })
      this.$message.success('弃审成功')
      this.$refs.pageRef.refreshList()
      // this.getDataList({
      //   pageNum: this.currentPage,
      //   pageSize: this.pageSize,
      //   examineStatus: this.examine
      // })
    },
    handleSelectAll(selection) {
      this.tableSelection = this.$refs.table.selection
    },
    //radio切换'
    changeRadioGroupFn(v) {
      this.getDataList({
        pageSize: this.pageSize,
        pageNum: this.currentPage,
        examineStatus: v
      })
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getDataList({
        pageNum: 1,
        pageSize: this.pageSize,
        examineStatus: this.examine
      })
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getDataList({
        pageNum: val,
        pageSize: 10,
        examineStatus: this.examine
      })
    },
    //清除
    async clearFn() {
      await this.$refs.searchForm.resetFields()
      this.examine = ''
    },
    //搜索
    searchFn() {
      this.getDataList({
        ...this.searchForm,
        // examineStatus: this.examine,
        pageSize: this.pageSize,
        pageNum: this.currentPage
      })
    },
    //删除
    async deleFn() {
      let res = this.deleList.toString()
      console.log(res)
      await getFinanceOtherReceDelete({ ids: res })
      this.getDataList({ pageSize: this.pageSize, pageNum: this.currentPage })
      this.$message.success('删除成功')
      this.deleList = []
    },
    selectionChangeFn(value) {
      // console.log(value);
      const res = value.map(v => v.itemId)
      // console.log(res);
      this.deleList = res
    },
    //新建后更新列表
    updateList() {
      this.getDataList({ pageSize: this.pageSize, pageNum: this.currentPage })
    },
    //获取来列表数据
    async getDataList(data) {
      let res = await getFinanceOtherReceList(data)
      // console.log(res);
      res.data.records.forEach(item => {
        item.sums2 = ['itemAmount']
        item.sums1 = ['itemAmount']
      })
      this.dataList = res.data.records
      this.listTotal = res.data.total
    },
    //详情
    detailFn(id, type) {
      this.czType = type
      this.approvalId = id
      this.showPage = 4
    },
    //审批
    approvalFn(id) {
      this.approvalId = id
      this.showPage = 3
    },
    //新建
    addFn() {
      this.showPage = 2
    },
    // 点击打印
    async toPrint(row, type) {
      // 初始化模板，否则生成的模板叠加
      hiprint.init()
      this.hiprintTemplate = new hiprint.PrintTemplate()
      // 兼容批量打印
      let params = !type ? this.recordSelected : [row.id]
      let len = params.length
      let loadingLen = len
      // 使用 i-- 提升for效率
      this.$startLoading()
      for (let i = len; i > 0; i--) {
        try {
          const { data } = await getFinanceOtherReceDetail({
            id: params[i - 1].id || params[i - 1]
          })
          // 模板基础配置
          this.panel = this.hiprintTemplate.addPrintPanel({
            height: 140,
            width: 241,
            fontFamily: '黑体',
            fontSize: 13,
            paperFooter: 340,
            paperHeader: 10,
            paperNumberDisabled: true
          })

          // 获取收款单模板和基础配置
          this.panel.addPrintHtml({
            options: {
              width: 633,
              top: 30,
              left: 20,
              fontFamily: '黑体',
              fontSize: 13,
              content: this.setTableDom(data)
            }
          })

          loadingLen--
        } catch (error) {
          console.log(999)
          this.$endLoading()
          return
        }
      }
      if (loadingLen === 0) {
        this.$endLoading()
      }
      console.log(333)
      // 预览打印内容
      this.$refs.preView.show(this.hiprintTemplate, this.panel)
    },
    getCompanyList() {
      getCompanyList().then(res => {
        this.company = res.data ? res.data[0].companyName : ''
      })
    },
    // 收款单打印模板
    setTableDom(data) {
      console.log(this.company, this.nowDate())
      return `
       <div style="font-family:'黑体';">
          <h1 style="text-align:center">${this.company}其他应收单</h1>
          <div >
            <table border=".5" cellspacing="0" width="856" height="250"
             style="border-color: rgb(0,0,0);
              border-collapse: collapse;
              border-style: none;
              border: 1px solid rgb(0,0,0);
              font-weight: normal;
              direction: ltr;
              padding-bottom: 0pt;
              padding-left: 4pt;
              padding-right: 4pt;
              padding-top: 0pt;
              text-decoration: none;
              vertical-align: middle;
              box-sizing: border-box;
              word-wrap: break-word;
              word-break: break-all;">
                <tr>
                  <td>单据编号</td>
                  <td>${data.code}</td>
                  <td>业务日期</td>
                  <td>${data.createTime}</td>
                  <td>打印日期</td>
                <td>${this.nowDate()}</td>
                </tr>
                <tr>
                  <td>付款单位</td>
                  <td colspan="5">${data.items[0].customerName}</td>
                </tr>
                <tr>
                  <td>钱包</td>
                  <td>${data.items[0].customerWalletName}</td>
                  <td>实收金额</td>
                  <td style="text-align:right">${numToFixed(data.totalAmount)}</td>
                  <td colspan="2">${changeNumberMoneyToChinese(data.totalAmount)}</td>
                </tr>
                <tr>
                  <td>备注</td>
                  <td colspan="5">${data.remark}</td>
                </tr>
            </table>
          </div>
          <div style="margin:100px 0 0 0">
            <div></div>
          </div>
       </div>
      `
    },
    // 获取当前时间
    nowDate() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      console.log(currentdate)
      return currentdate
    },
    handleRefreshList() {
      this.recordSelected = []
      this.$refs.pageRef.refreshList()
    },
    handleInitPrint() {
      this.$nextTick(() => {
        this.initPrint()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.selectStyle {
  width: 100%;
}

.dateStyle {
  width: 100%;
}

.delClass {
  margin-left: 10px;
}
</style>
