<template>
  <div class="orderBatchBilling pagePadding">
    <ex-table
      v-loading="loading"
      v-if="powers && powers.length > 0 && powers.some((item) => item == '001')"
      :table="table"
      :data="tableData"
      :columns="columns"
      :page="pageInfo"
      :size="size"
      @page-curr-change="handlePageChange"
      @page-size-change="handleSizeChange"
      @screen-reset="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
      @screen-submit="
        pageInfo.curr = 1;
        parmValue.page = 1;
        searchList();
      "
    >
      <template #table-header="{ selection }">
        <div style="width: 100%">
          <el-row style="padding: 0 0 10px 80px">
            <el-col :span="24">
              <el-col :span="6" style="width: 296px; padding: 0">
                <period-date-picker
                  :start="parmValue.starttime"
                  :end="parmValue.endtime"
                  :type="1"
                  :width="'135px'"
                  :size="searchSize"
                  @timeReturned="timeReturned($event)"
                ></period-date-picker>
              </el-col>

              <el-col
                :span="4"
                style="width: 153px"
                class="fr"
                v-if="powers.some((item) => item == '046')"
              >
                <el-button
                  type="primary"
                  class="fr"
                  icon="el-icon-download"
                  :size="searchSize"
                  @click="batchExport(selection)"
                  >批量导出开票信息</el-button
                ></el-col
              >
              <el-col :span="4" style="width: 153px" class="fr">
                <el-button
                  type="primary"
                  class="fr"
                  :disabled="downLoading"
                  @click="showModel = true"
                  icon="el-icon-upload2"
                  :size="searchSize"
                  >批量导入开票信息</el-button
                >
              </el-col>
              <el-col
                :span="4"
                style="width: 140px"
                class="fr"
                v-if="powers.some((item) => item == '023')"
              >
                <el-button
                  type="primary"
                  class="fr"
                  icon="el-icon-download"
                  :size="searchSize"
                  :disabled="downLoading"
                  @click="dlTemplate"
                  >下载导入模板</el-button
                >
              </el-col>
            </el-col>
          </el-row>
          <el-row style="padding: 0">
            <el-col :span="12" style="width: 460px">
              <el-select
                v-model="code"
                multiple
                filterable
                remote
                :multiple-limit="1"
                reserve-keyword
                :size="searchSize"
                style="width: 100%"
                placeholder="公司名称"
                :remote-method="remoteMethod"
                :loading="selectLoading"
                @change="selectChange"
              >
                <el-option
                  v-for="item in activeOptions"
                  :key="item.companyNo"
                  :label="item.companyName"
                  :value="item.companyNo"
                />
              </el-select>
            </el-col>

            <el-col
              :span="4"
              style="width: 66px"
              class="fr"
              v-if="powers.some((item) => item == '002')"
            >
              <el-button
                :size="searchSize"
                type="primary"
                style="float: right"
                @click="searchList"
              >
                刷新
              </el-button>
            </el-col>
            <el-col
              :span="4"
              class="fr"
              style="width: 66px"
              v-if="powers.some((item) => item == '024')"
            >
              <el-button
                type="warning"
                class="fr"
                :size="searchSize"
                @click="restSearch"
              >
                重置
              </el-button>
            </el-col>

            <el-col :span="4" class="fr" style="width: 54px">
              <el-button
                :size="searchSize"
                type="primary"
                class="fr"
                icon="el-icon-search"
                @click="searchList"
            /></el-col>
          </el-row>
        </div>
      </template>
      <template #status="{ scope }">
        <el-tag
          :type="
            scope.row.status == '0'
              ? 'info'
              : scope.row.status == '5'
              ? 'success'
              : scope.row.status == '2'
              ? 'danger'
              : ''
          "
          size="mini"
          v-text="
            (statusOptions.find((item) => item.id == scope.row.status) || {})
              .label || '--'
          "
        ></el-tag>
      </template>
      <template #type_check="{ scope }">
        <el-tag
          size="mini"
          v-text="
            (billType.find((item) => item.code == scope.row.type_check) || {})
              .name || '--'
          "
        />
      </template>
    </ex-table>
    <no-auth v-else></no-auth>
    <!-- 弹窗 批量导入开票信息-->
    <add-edit
      :show-model="showModel"
      @refresh="searchList()"
      @cancel="showModel = false"
    />
  </div>
</template>
<script>
import ExTable from "@/components/ExTableNew.vue";
import addEdit from "./addEdit";
import asyncRequest from "@/apis/service/InvoiceSales/orderBatchBilling";
import mixinPage from "@/mixins/elPaginationHandle";
import PeriodDatePicker from "@/components/PeriodDatePicker";
import { mapGetters } from "vuex";
import resToken from "@/mixins/resToken";
import urlConfig from "@/apis/url-config";
import { timestampToTime } from "@/utils/validate";
export default {
  name: "orderBatchBilling",
  mixins: [mixinPage, resToken],
  components: {
    ExTable,
    addEdit,
    PeriodDatePicker,
  },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "orderBatchBilling"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      showModel: false,
      isDetail: false,
      selection: [],
      invNo: "0",
      status: "0",
      modelId: 0,
      selectLoading: false,
      billType: [
        {
          code: "1",
          name: "确认单开票",
        },
        {
          code: "2",
          name: "资金开票-资金未认领",
        },
        {
          code: "3",
          name: "资金开票-资金已认领",
        },
      ],
      activeOptions: [],
      // 状态
      statusOptions: [
        { id: 0, label: "待发起审核" },
        { id: 1, label: "待财务审核" },
        { id: 2, label: "审核驳回" },
        { id: 3, label: "待财务开票" },
        { id: 4, label: "待填写物流" },
        { id: 5, label: "开票已完成" },
      ],

      name: "",
      downLoading: false,
      code: [],
      loading: true,

      formValue: {
        company: "", // 账户
        page: 1, // 页码
        size: 100, // 每页显示条数
      },
      fileUrl:
        urlConfig.baseURL +
        "%E5%8F%91%E7%A5%A8%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls",
      parmValue: {
        companyNo: "",
        status: "3",
        type_check: "1",
        starttime: "",
        endtime: "",
        page: 1, // 页码
        size: 15, // 每页显示条数
      },
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: [
        { type: "selection", fixed: "left", _noset_: true, width: "50" },
        {
          prop: "invNo",
          label: "发票编号",
          width: "180px",
          fixed: "left",
        },
        {
          prop: "inv_in",
          label: "客户企业编码",
          width: "130px",
        },
        {
          prop: "company",
          label: "客户企业名称",
          "min-width": "180px",
        },
        {
          prop: "kp_company",
          label: "销售方开票公司名称",
          "min-width": "180px",
        },
        {
          prop: "inv_value",
          label: "发票额度",
          width: "120px",
        },
        // {
        //   prop: "contactor",
        //   label: "客户联系人",
        //   width: "85px",
        // },
        {
          prop: "type_check",
          label: "开票类型",
          _slot_: "type_check",
          width: "150px",
        },
        {
          prop: "apply_name",
          label: "申请人",
          width: "85px",
        },
        {
          prop: "status",
          label: "状态",
          _slot_: "status",
          width: "120px",
        },
        {
          prop: "addtime",
          label: "申请时间",
          sortable: true,
          width: "150px",
        },
      ],
    };
  },
  mounted() {
    this.searchList();
  },
  methods: {
    async selectChange() {
      let arr = JSON.parse(JSON.stringify(this.code));
      this.parmValue.companyNo = arr.join(",");
      this.parmValue.page = 1;
      await this.searchList();
    },
    restSearch() {
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.parmValue = {
        companyNo: "",
        status: "3",
        type_check: "1",
        starttime: "",
        endtime: "",
        page: 1, // 页码
        size: 15, // 每页显示条数
      };
      this.searchList();
    },
    async timeReturned(e) {
      if (e.startTime !== "") {
        this.parmValue.starttime = e.startTime;
      } else {
        this.parmValue.starttime = "";
      }

      if (e.endTime !== "") {
        this.parmValue.endtime = e.endTime;
      } else {
        this.parmValue.endtime = "";
      }
      if (this.parmValue.starttime !== "" && this.parmValue.endtime !== "") {
        this.parmValue.page = 1;
        await this.searchList();
      }
    },

    /**
     * 批量导出开票信息
     * * @param {Array} selection //选中的对账编码
     */
    async batchExport(selection) {
      if (!this.downLoading) {
        if (selection && selection.length === 0) {
          this.$message.warning("至少选择一条数据！");
          return;
        }
        let list = [];
        selection.forEach((v1) => {
          list.push(v1.id);
        });
        this.downLoading = true;
        const model = {
          invid: list.join(","),
        };

        let httpType = `application/vnd.ms-excel`;
        axios({
          method: "post",
          url: urlConfig.baseURL + "Admin/receiptexport",
          responseType: "blob",
          data: model,
          headers: {
            Accept: httpType,
          },
        })
          .then((res) => {
            if (res && res.status == 200 && res.data) {
              let blob = new Blob([res.data], {
                type: httpType,
              });
              let url = window.URL.createObjectURL(blob);
              let aLink = document.createElement("a");
              aLink.style.display = "none";
              aLink.href = url;
              aLink.setAttribute("download", `确认单开票信息导出.xls`);
              document.body.appendChild(aLink);
              aLink.click();
              document.body.removeChild(aLink); //下载完成移除元素
              window.URL.revokeObjectURL(url); //释放掉blob对象

              this.$message.success(`确认单开票信息导出成功！`);
              setTimeout(() => {
                this.downLoading = false;
              }, 500);
            } else {
              this.$message.error(res.data.message);
              setTimeout(() => {
                this.downLoading = false;
              }, 500);
            }
          })
          .catch((error) => {
            this.downLoading = false;
          });
      }
    },
    // 刷新表格
    async searchList() {
      if (this.parmValue.starttime !== "" && this.parmValue.endtime === "") {
        this.$message.error("结束时间不能为空！");
        return;
      }
      if (this.parmValue.starttime === "" && this.parmValue.endtime !== "") {
        this.$message.error("开始时间不能为空！");
        return;
      }
      this.loading = true;
      const res = await asyncRequest.list(this.parmValue);
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data.list;
        this.pageInfo.total = Number(res.data.count);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
    async remoteMethod(query) {
      this.selectLoading = true;
      if (query !== "") {
        this.activeOptions = [];
        this.formValue.company = query;
        const res = await asyncRequest.clist(this.formValue);
        if (res && res.code === 0 && res.data && res.data.list) {
          this.activeOptions = res.data.list;
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } else {
        this.activeOptions = [];
      }
      this.selectLoading = false;
    },

    async dlTemplate() {
      if (!this.downLoading) {
        this.downLoading = true;
        let elemIF = document.createElement("iframe");
        elemIF.src =
          this.fileUrl + "?time=" + timestampToTime(new Date().valueOf());
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
        this.$message.success(`导入模板下载成功！`);
        setTimeout(() => {
          this.downLoading = false;
        }, 500);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
