<template>
  <div class="app-container">
    <div v-if="showDetail == 1">
      <!-- 筛选条件 -->
      <div>
        <el-form
          ref="searchForm"
          :model="searchForm"
          label-width="100px"
          size="mini"
          label-position="left"
        >
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="单据类型" prop="billType">
                <!-- <el-input v-model="searchForm.billType" placeholder="请输入"></el-input> -->
                <el-select
                  v-model="searchForm.billType"
                  class="selectStyle"
                  placeholder="请选择"
                  filterable
                >
                  <el-option label="收款单" value="1"> </el-option>
                  <el-option label="付款单" value="3"> </el-option>
                  <el-option label="退款单" value="2"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="单据编号" prop="billNo">
                <el-input
                  v-model="searchForm.billNo"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="往来单位" prop="wlCompanyType">
                <!-- <el-input v-model="searchForm.wlCompanyType" placeholder="请输入"></el-input> -->
                <el-select
                  class="selectStyle"
                  v-model="searchForm.wlCompanyType"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="(v, i) in customerList"
                    :key="i"
                    :label="v.name"
                    :value="v.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="付款单位" prop="customerName">
                <!-- <el-input v-model="searchForm.customerName" placeholder="请输入"></el-input> -->
                <el-select
                  class="selectStyle"
                  v-model="searchForm.customerName"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    v-for="(v, i) in customerList"
                    :key="i"
                    :label="v.name"
                    :value="v.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="结算方式" prop="settleType">
                <el-input
                  v-model="searchForm.settleType"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="收款用途" prop="">
                <el-input v-model="searchForm." placeholder="请输入"></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  class="selectStyle"
                  v-model="searchForm.startTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  default-time="00:00:00"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  class="selectStyle"
                  v-model="searchForm.endTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  default-time="00:00:00"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="" class="fr">
                <el-button size="mini" @click="cancelFn">清空</el-button>
                <el-button size="mini" type="primary" @click="searchFn"
                  >搜索</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 按钮 -->
      <div class="btn-group clearfix">
        <div class="fl">
          <!-- <el-button
            type="primary"
            size="mini"
            v-if="$checkBtnRole('print', $route.meta.roles)"
            @click="toPrint"
            :disabled="tableSelection.length < 1"
            >打印发货单
          </el-button> -->
        </div>
        <div class="fr">
          <!-- <ExportButton :exUrl="'/k3/receipt/export'" :exParams="exParams" class="exportClass" /> -->
        </div>
      </div>
      <!-- 列表 -->
      <div class="mymain-container">
        <div class="table">
          <el-table
            ref="table"
            v-loading="listLoading"
            :data="dataList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
            show-summary
            :summary-method="getSummaries"
            @select="handleSelect"
            @select-all="handleSelectAll"
          >
            <el-table-column
              align="center"
              type="selection"
              width="55"
            ></el-table-column>

            <el-table-column
              align="left"
              label="单据类型"
              prop="billType"
              min-width="160"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{
                  scope.row.billType == 1
                    ? "收款单"
                    : scope.row.billType == 2
                    ? "退款单"
                    : scope.row.billType == 3
                    ? "付款单"
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="单据编码"
              prop="billNo"
              min-width="160"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <CopyButton :copyText="scope.row.billNo" />
                <span>{{ scope.row.billNo }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="业务日期"
              prop="theTime"
              min-width="160"
              show-overflow-tooltip
            >
            </el-table-column>
            <!-- <el-table-column
              align="left"
              label="币别"
              prop="bibie"
              min-width="160"
              show-overflow-tooltip
            ></el-table-column> -->
            <el-table-column
              align="left"
              label="单据状态"
              prop="status"
              min-width="160"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-tag size="mini" v-show="scope.row.status == 'A'"
                  >保存</el-tag
                >
                <el-tag size="mini" v-show="scope.row.status == 'B'" type="info"
                  >审核中</el-tag
                >
                <el-tag
                  size="mini"
                  v-show="scope.row.status == 'C'"
                  type="success"
                  >已审核</el-tag
                >
                <el-tag
                  size="mini"
                  v-show="scope.row.status == 'D'"
                  type="warning"
                  >重新审核</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="钱包"
              prop="walletName"
              min-width="160"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              align="right"
              label="表头·应收金额"
              prop=""
              min-width="160"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              align="left"
              label="往来单位"
              prop="wlCompanyName"
              min-width="260"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <CopyButton :copyText="scope.row.wlCompanyName" />
                <span>{{ scope.row.wlCompanyName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="right"
              label="表头·实收金额"
              prop="amount"
              min-width="160"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{
                  scope.row.billType == 3 || scope.row.billType == 2
                    ? -scope.row.amount
                    : scope.row.amount | numToFixed
                }}
              </template>
            </el-table-column>
            <el-table-column
              align="right"
              label="收款金额"
              prop=""
              min-width="160"
              show-overflow-tooltip
            ></el-table-column>
            <!-- <el-table-column
              align="center"
              label="结算方式"
              prop="settleType"
              min-width="160"
              show-overflow-tooltip
            ></el-table-column> -->
            <!-- <el-table-column
              align="center"
              label="收款用途"
              prop=""
              min-width="160"
              show-overflow-tooltip
            ></el-table-column> -->
            <el-table-column
              align="left"
              label="付款单位"
              prop="customerName"
              min-width="260"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <CopyButton :copyText="scope.row.customerName" />
                <span>{{ scope.row.customerName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="right"
              label="表体·实收金额"
              prop="amount"
              min-width="160"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{
                  scope.row.billType == 3 || scope.row.billType == 2
                    ? -scope.row.amount
                    : scope.row.amount | numToFixed
                }}
              </template>
            </el-table-column>
            <el-table-column
              align="left"
              label="勾对"
              prop=""
              min-width="160"
              show-overflow-tooltip
            ></el-table-column>

            <el-table-column
              align="left"
              label="备注"
              prop="remark"
              min-width="160"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              align="center"
              label="操作"
              min-width="160"
              show-overflow-tooltip
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  class="textColor"
                  v-if="
                    $checkBtnRole('examine', $route.meta.roles) &&
                    scope.row.status == 'C'
                  "
                  @click="NoExamineFn(scope.row.id)"
                  >弃审</el-button
                >
                <el-button
                  type="text"
                  class="textColor"
                  @click="seeFn(scope.row.id)"
                  >查看</el-button
                >
                <!-- <el-button
                  type="text"
                  class="textColor"
                  v-if="$checkBtnRole('print', $route.meta.roles)"
                  @click="toPrint(scope.row, 2)"
                  >打印</el-button
                > -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50,500]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <ReceiptPrint
      :listItem="queryItem"
      v-else-if="showDetail == 2"
      @backListFormDetail="backList"
    />
    <ReceiptListDetail :detailId="detailId" v-else />
    <print-preview ref="preView" />
  </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 {
  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 { changeNumberMoneyToChinese,dateFormat } from "@/utils/util";
import { numToFixed } from "@/filters";
export default {
  components: {
    ReceiptPrint,
    printPreview,
    ReceiptListDetail,
  },
  data() {
    return {
      customerList: [],
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      dataList: [], // 列表数据
      searchForm: {
        billType: "",
        billNo: "",
        wlCompanyType: "",
        customerName: "",
        settleType: "",
        startTime: "",
        endTime: "",
      }, //搜索表单
      listLoading: false, // 列表加载loading
      showDetail: 1,
      detailId: null,
      queryItem: {},
      tableSelection: [],
      company: "",
      panel: "",
      hiprintTemplate: "",
    };
  },
  computed: {
    exParams() {
      return {
        ...this.searchForm,
      };
    },
  },
  created() {
    this.getDataList({ pageSize: this.pageSize, pageNum: this.currentPage });
    this.getCustomerDataList();
    this.getCompanyList();
  },
  mounted() {},
  methods: {
    //获取经销商列表
    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({ pageNum: this.currentPage, pageSize: this.pageSize });
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDataList({ pageNum: this.currentPage, pageSize: this.pageSize });
    },
    //清空
    cancelFn() {
      this.$refs.searchForm.resetFields();
    },
    //搜索
    searchFn() {
      this.getDataList({
        ...this.searchForm,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      });
    },
    async getDataList(data) {
      const res = await getK3ReceiptList(data);
      // 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>
      `;
    },
  },
};
</script>

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