<template>
  <div style="width: 100%; height: 100%">
    <template-page
      v-if="showDetail == 1"
      ref="pageRef"
      :operation="operation()"
      :optionsEvensGroup="optionsEvensGroup"
      :getList="getList"
      :exportList="exportList"
      :tableAttributes="tableAttributes"
      :tableEvents="tableEvents"
      :columnParsing="columnParsing"
    >
    </template-page>
    <div class="app-container" v-else-if="showDetail == 2">
      <ReceiptPrint :listItem="queryItem" @backListFormDetail="backList" />
    </div>
    <div class="app-container" v-else>
      <ReceiptListDetail :detailId="detailId" />
    </div>
         <print-preview ref="preView" @initPrint="handleInitPrint" @refreshList="handleRefreshList" />

  </div>
</template>

<script>
import { disAutoConnect, hiprint } from 'vue-plugin-hiprint'
disAutoConnect()
import printPreview from './components/design/preview.vue'
import { getCompanyList } from '@/api/user'
import { getCustomerList } from '@/api/finance/wallet'
import { k3ReceiptList, k3ReceiptListExport } from '@/api/finance/receipt_list_v2'
import { getK3ReceiptList, getK3ReceiptDetail, getK3ReceiptAbandon } from '@/api/finance/receipt_list'
import ReceiptListDetail from './components/receipt_list-detail'
import ReceiptPrint from '@/views/finance/components/receipt_print.vue'
import importButton from '@/components/Common/import-button.vue'
import { changeNumberMoneyToChinese, dateFormat } from '@/utils/util'
import { numToFixed } from '@/filters'
import TemplatePage from '@/components/template/template-page-1.vue'
export default {
  components: {
    ReceiptPrint,
    printPreview,
    importButton,
    ReceiptListDetail,
    TemplatePage
  },
  data() {
    return {
      customerList: [],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [], // 列表数据
      searchForm: {
        billType: '',
        billNo: '',
        wlCompanyType: '',
        customerName: '',
        settleType: '',
        startTime: '',
        endTime: '',
        websitNumber: ''
      }, //搜索表单
      listLoading: false, // 列表加载loading
      showDetail: 1,
      detailId: null,
      queryItem: {},
      tableSelection: [],
      company: '',
      panel: '',
      isCollapse: true,
      hiprintTemplate: '',
      orage: [
        {
          value: 'GZ',
          label: '广州'
        },
        {
          value: 'FS',
          label: '佛山'
        }
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: []
    }
  },
  computed: {
    optionsEvensGroup() {
      return [
        [
          [
            {
              name: '打印发货单',
              click: () => {
                if (!this.tableSelection.length) {
                  this.$message.info('请选择数据！')
                  return
                }
                this.toPrint()
              },
              isRole: this.$checkBtnRole('print', this.$route.meta.roles)
            }
          ]
        ]
      ]
    },
    exParams() {
      return {
        ...this.searchForm
      }
    }
  },
  created() {
    this.getDataList()
    this.getCustomerDataList()
    this.getCompanyList()
  },
  mounted() {},
  methods: {
    // 列表请求函数
    getList: k3ReceiptList,
    // 列表导出函数
    exportList: k3ReceiptListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.tableSelection = data
    },
    
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {this.$checkBtnRole('examine', this.$route.meta.roles) && row.status == 'C' ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.NoExamineFn(row.id)
                }}
              >
                弃审
              </el-button>
            ) : null}
            <el-button
              type="text"
              class="textColor"
              onClick={() => {
                this.seeFn(row.id)
              }}
            >
              查看
            </el-button>
            {this.$checkBtnRole('print', this.$route.meta.roles) ? (
              <el-button
                type="text"
                class="textColor"
                onClick={() => {
                  this.toPrint(row, 2)
                }}
              >
                打印
              </el-button>
            ) : null}
          </div>
        )
      }
    },
    // ------------------------------------
    //获取经销商列表
    async getCustomerDataList() {
      let res = await getCustomerList({
        pageNum: 1,
        pageSize: -1
      })
      this.customerList = res.data.records
    },
    //合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        }

        if (index === 8) {
          let arr = []
          data.forEach(v => {
            if (v.billType == 2 || v.billType == 3) {
              arr.push(-v.amount)
            } else {
              arr.push(v.amount)
            }
          })

          let a = arr.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = numToFixed(a)
          sums[11] = numToFixed(a)
        }
      })
      return sums
    },
    //弃审
    async NoExamineFn(id) {
      await getK3ReceiptAbandon({ id })
      this.$message.success('弃审成功')
      this.getDataList({ pageSize: this.pageSize, pageNum: this.currentPage })
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getDataList()
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getDataList()
    },
    //清空
    cancelFn() {
      this.$refs.searchForm.resetFields()
    },
    //搜索
    searchFn() {
      this.getDataList()
    },
    async getDataList() {
      let params = {
        billType: this.searchForm.billType,
        billNo: this.searchForm.billNo,
        wlCompanyType: this.searchForm.wlCompanyType,
        customerName: this.searchForm.customerName,
        settleType: this.searchForm.settleType,
        startTime: this.searchForm.startTime,
        endTime: this.searchForm.endTime,
        websitNumber: this.searchForm.websitNumber,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      const res = await getK3ReceiptList(params)
      // console.log(res);
      // res.data.records.forEach((item) => {
      //   item.sums1 = [];
      //   item.sums2 = ["amount"];
      // });
      this.dataList = res.data.records
      this.listTotal = res.data.total
    },
    seeFn(id) {
      this.detailId = id
      this.showDetail = 3
    },
    handleSelect(selection, row) {
      this.$refs.table.toggleRowSelection(row)
      this.dataList.forEach(item => {
        if (item.id === row.id) {
          this.$refs.table.toggleRowSelection(item)
        }
      })
      this.tableSelection = this.$refs.table.selection
    },

    handleSelectAll(selection) {
      this.tableSelection = this.$refs.table.selection
    },
    backList() {
      this.queryItem = {}
      this.isShowPrint = false
    },
    // 获取当前时间
    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
    },
    // 点击打印
    async toPrint(row, type) {
      // 初始化模板，否则生成的模板叠加
      hiprint.init()
      this.hiprintTemplate = new hiprint.PrintTemplate()
      // 兼容批量打印
      let params = !type ? this.tableSelection : [row.id]
      let len = params.length
      let loadingLen = len
      // 使用 i-- 提升for效率
      this.$startLoading()
      for (let i = len; i > 0; i--) {
        try {
          const { data } = await getK3ReceiptDetail({
            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) {
          this.$endLoading()
          return
        }
      }
      if (loadingLen === 0) {
        this.$endLoading()
      }
      // 预览打印内容
      this.$refs.preView.show(this.hiprintTemplate, this.panel)
    },
    getCompanyList() {
      getCompanyList().then(res => {
        this.company = res.data ? res.data[0].companyName : ''
      })
    },
    // 收款单打印模板
    setTableDom(data) {
      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.billNo}</td>
                  <td>业务日期</td>
                  <td>${data.theTime}</td>
                  <td>打印日期</td>
                  <td>${this.nowDate()}</td>
                </tr>
                <tr>
                  <td>付款单位</td>
                  <td colspan="5">${data.customerName}</td>
                </tr>
                <tr>
                  <td>钱包</td>
                  <td>${data.walletName}</td>
                  <td>实收金额</td>
                  <td style="text-align:right">${numToFixed(data.amount)}</td>
                  <td colspan="2">${changeNumberMoneyToChinese(data.amount)}</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>
      `
    },

    handleRefreshList(){
      this.recordSelected = []
      this.$refs.pageRef.refreshList()

    },
    handleInitPrint(){
      this.$nextTick(() => {
      this.initPrint()
    })
    }
  }
}
</script>

<style lang="scss" scoped>
.selectStyle {
  width: 100%;
}
.improt {
  display: flex;
}
</style>
