<template>
  <div v-loading="loading">
    <div style="display:flex;justify-content:space-between;">
      <div style="font-size:14px;display:flex;align-items:center">
        <el-popover placement="top" trigger="hover">
          <ex-table
            size="mini"
            :columns="invColumns"
            :table="table"
            :data="invData"
            :noPagination="true"
          >
            <template #checked="{ scope }">
              <span v-if="scope.row[scope.column.property] === '--'" style="color:#909399">--</span>
              <i
                v-else-if="scope.row[scope.column.property]"
                class="el-icon-check"
                style="color:#67C23A"
              />
              <i v-else class="el-icon-close" style="color:#F56C6C" />
            </template>
          </ex-table>

          <template #reference>
            <i class="el-icon-info" style="font-size:22px; cursor:pointer; margin-right:3px" />
          </template>
        </el-popover>

        <span>点我查看 : 发票类型必填字段说明</span>
      </div>

      <div>
        <el-button
          v-if="isApproval && tableData.length > 0"
          size="mini"
          type="primary"
          @click="handleBatch"
        >批量审批发票</el-button>

        <template v-if="!readonly">
          <el-button size="mini" @click="onDownloadTemplate">下载发票模板</el-button>
          <el-button v-if="isUpload" size="mini" type="primary" @click="xlsxVisible = true">上传发票信息</el-button>
        </template>
      </div>
    </div>

    <el-table
      size="mini"
      style="margin-top: 10px"
      border
      :data="tableData"
      max-height="400px"
      @selection-change="(list) => selected = list"
    >
      <el-table-column :type="'selection'" width="45px"></el-table-column>
      <el-table-column label="序号" :type="'index'" width="45px"></el-table-column>

      <el-table-column label="发票类型" :prop="mapFields.invoiceType">
        <template
          slot-scope="scope"
        >{{invoiceTypeList.find(({value}) => value === scope.row[mapFields.invoiceType]).label}}</template>
      </el-table-column>

      <el-table-column label="状态" :prop="'status'">
        <template slot-scope="scope">
          <el-tag
            :type="(statusList.find(({id}) => id === String(scope.row.status)) || {}).type"
            size="mini"
          >{{(statusList.find(({id}) => id === String(scope.row.status)) || {}).label || '--'}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="发票代码" :prop="mapFields.invoiceCode"></el-table-column>
      <el-table-column label="发票号码" :prop="mapFields.invoiceNumber"></el-table-column>
      <el-table-column label="开票日期" :prop="'open_date'"></el-table-column>
      <el-table-column label="税前金额" :prop="'subtotal_amount'"></el-table-column>
      <el-table-column label="税后金额" :prop="'total_amount'"></el-table-column>
      <el-table-column label="校验码" :prop="'check_code'">
        <template #header>
          <span>校验码</span>
          <el-button
            v-if="!readonly && isUpload"
            style="margin-left: 10px"
            size="mini"
            type="text"
            @click="manuallyVisible = true"
          >添加</el-button>
        </template>
      </el-table-column>
    </el-table>

    <manually-upload-modal
      :visible.sync="manuallyVisible"
      :updateItem="updateItem"
      :updateIndex="updateIndex"
      :isNormalType="isNormalType"
      @change="handleModalChange"
      :loading="loading"
    />

    <excel-upload-modal
      :visible.sync="xlsxVisible"
      :isNormalType="isNormalType"
      :loading="loading"
      @change="handleUploadChange"
    />

    <invoice-modal
      :visible.sync="invVisible"
      :idArr="selected.map(({id}) => id)"
      :approvalMethod="approvalMethod"
      @ok="searchList"
    />
  </div>
</template>


<script>
import ManuallyUploadModal from "./manuallyUploadModal.vue";
import InvoiceModal from "./invoiceModal.vue";
import asyncRequest from "@/apis/components/uploadInvoice";
import { invoiceTypeList } from "@/assets/js/statusList";
import ExcelUploadModal from "./xlsxUploadModal.vue";
import { template, mapFields } from "./_template";
import { writeFile, utils } from "xlsx";

/***
 * @props
 * 发票申请编号 invoiceNo
 * 发票状态 invoiceStatus
 * 发票类型 invoiceType
 * 发票号码 invoiceNumber
 * 发票代码 invoiceCode
 * 发票名称 invoiceName
 * 开票日期 openTime
 * 税前金额 beforeTax
 * 税后金额 afterTax
 * 校验码 checkNumber
 */

export default {
  props: {
    approvalMethod: {
      type: Function
    },
    requestMethod: {
      type: Function
    },
    invType: {
      type: String,
      default: "1"
    },
    code: {
      type: String
    },
    isNormalType: {
      type: Boolean
    },
    readonly: {
      type: Boolean
    },
    isApproval: {
      type: Boolean
    },
    isUpload: {
      type: Boolean
    }
  },
  watch: {
    code: {
      handler(value) {
        if (!value) return;
        this.searchList();
      },
      immediate: true
    }
  },
  name: "UploadInvoiceNode",
  components: {
    ManuallyUploadModal,
    ExcelUploadModal,
    InvoiceModal
  },
  data() {
    return {
      mapFields,
      invoiceTypeList,
      manuallyVisible: false,
      xlsxVisible: false,
      invVisible: false,
      loading: false,
      updateIndex: -1,
      updateItem: null,
      tableData: [],
      list: [],
      selected: [],
      statusList: [
        { id: "0", label: "已驳回", type: "danger" },
        { id: "1", label: "待审核", type: "info" },
        { id: "2", label: "已通过", type: "success" }
      ],
      table: {
        stripe: true,
        border: true,
        "max-height": "800px"
      },
      invData: [
        {
          type: "发票代码",
          zNormal: true,
          zSpecal: true,
          dNormal: true,
          dSpecal: true,
          fdNormal: "--",
          fdSpecal: "--"
        },
        {
          type: "发票税前金额",
          zNormal: true,
          zSpecal: true,
          dNormal: true,
          dSpecal: true,
          fdNormal: false,
          fdSpecal: false
        },
        {
          type: "校验码",
          zNormal: true,
          zSpecal: false,
          dNormal: true,
          dSpecal: false,
          fdNormal: "--",
          fdSpecal: "--"
        }
      ],
      invColumns: [
        {
          label: "字段",
          prop: "type",
          width: "110px"
        },
        {
          prop: "zNormal",
          label: "纸质普通发票",
          _slot_: "checked",
          width: "100px"
        },
        {
          prop: "zSpecal",
          label: "纸质专用发票",
          _slot_: "checked",
          width: "100px"
        },
        {
          prop: "dNormal",
          label: "电子普通发票",
          _slot_: "checked",
          width: "100px"
        },
        {
          prop: "dSpecal",
          label: "电子专用发票",
          _slot_: "checked",
          width: "100px"
        },
        {
          prop: "fdNormal",
          label: "电子发票(增值税普通发票)",
          _slot_: "checked",
          width: "170px"
        },
        {
          prop: "fdSpecal",
          label: "电子发票(增值税专用发票)",
          _slot_: "checked",
          width: "170px"
        }
      ]
    };
  },
  methods: {
    handleBatch() {
      if (this.selected.length === 0) {
        this.$message.warning('至少选择一个状态为 "待确认" 的发票申请');
        return;
      }
      const isOK = this.selected.every(({ status }) => String(status) === "1");
      if (!isOK) {
        this.$message.warning('请选择状态为 "待确认" 的发票申请');
        return;
      }

      this.invVisible = true;
    },
    onCreateItem() {
      this.updateIndex = -1;
      this.updateItem = null;
      this.manuallyVisible = true;
    },
    onUpdateItem(index) {
      this.updateIndex = index;
      this.updateItem = this.list[index];
      this.manuallyVisible = true;
    },
    deleteItem(index) {
      this.list.splice(index, 1);
    },
    handleUploadChange(list) {
      this.list = list;
      this.onSave();
    },
    handleModalChange({ data }) {
      this.list = data;
      this.onSave();
    },
    async onSave() {
      this.loading = true;
      const { code } = await this.requestMethod(this.list);
      this.loading = false;
      if (code !== 1) return;
      this.manuallyVisible = false;
      this.xlsxVisible = false;
      this.list = [];
      this.$emit("refresh");
      this.searchList();
    },
    async searchList() {
      this.loading = true;

      const { code, data } = await asyncRequest.list({
        size: 10000,
        inv_type: this.invType,
        ...(Number(this.invType) === 1
          ? {
              invNo: this.code
            }
          : {
              settle_code: this.code
            })
      });

      this.loading = false;
      if (code !== 1) return;

      this.tableData = data.list;
    },
    onDownloadTemplate() {
      const workBook = utils.book_new();
      const workSheet = utils.json_to_sheet(template);
      utils.book_append_sheet(workBook, workSheet, "sheet");
      writeFile(workBook, "开票模板.xlsx", {
        bookType: "xlsx"
      });
    }
  }
};
</script>
