<template>
  <div class="bargainList pagePadding">
    <div>
      <ex-table
        v-loading="loading"
        :table="table"
        :data="tableData"
        :columns="columns"
        :page="pageInfo"
        :size="size"
        @page-curr-change="handlePageChange"
        @page-size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @screen-reset="
          pageInfo.curr = 1;
          parmValue.page = 1;
          searchList();
        "
        @screen-submit="
          pageInfo.curr = 1;
          parmValue.page = 1;
          searchList();
        "
      >
        <template #table-header="{}">
          <div style="width: 100%">
            <el-row style="padding: 0 0 0 80px">
              <el-col :span="4" style="width: 360px; padding: 0 10px 0 0px">
                <period-date-picker
                  :start="parmValue.create_start"
                  :end="parmValue.create_end"
                  :width="'164px'"
                  :size="searchSize"
                  @timeReturned="handleTime"
                  placeholder="创建"
                />
              </el-col>

              <el-col :span="3" style="margin-right:10px">
                <el-input v-model="parmValue.reqCode" size="mini" placeholder="需求订单编号" style="width:100%"
                       @change="pageInfo.curr = 1;
                                parmValue.page = 1;
                                searchList();"
                />
              </el-col>

              <el-col :span="4" style="width: 150px;margin-right:10px">
                <el-select
                  :size="searchSize"
                  v-model="parmValue.invoiceStatus"
                  clearable
                  placeholder="开票状态"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-option
                    v-for="item in statusList"
                    :key="item.ids"
                    :label="item.label"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-col>

              <el-col :span="3" style="width: 66px; float: right">
                <el-button
                  :size="searchSize"
                  type="primary"
                  style="float: right; margin-left: 5px"
                  @click="searchList"
                >
                  刷新
                </el-button>
              </el-col>
              <el-col :span="4" class="fr" style="width: 66px">
                <el-button
                  type="warning"
                  class="fr"
                  :size="searchSize"
                  @click="restSearch"
                >
                  重置
                </el-button>
              </el-col>
            </el-row>

            <el-row style="margin-top:10px">
              <el-col :span="4" style="width: 360px; padding: 0 10px 0 0px">
                <period-date-picker
                  :start="parmValue.open_start"
                  :end="parmValue.open_end"
                  :width="'164px'"
                  :size="searchSize"
                  @timeReturned="() => handleTime(true)"
                  placeholder="开票"
                />
              </el-col>

              <el-col :span="4" style="margin-right:10px">
                <el-input size="mini" placeholder="发票代码" v-model="parmValue.invoiceCode"
                  @change="pageInfo.curr = 1;
                           parmValue.page = 1;
                          searchList();"  />
              </el-col>

              <el-col :span="4">
                <el-input size="mini" placeholder="发票号码" v-model="parmValue.invoiceNum"
                  @change="pageInfo.curr = 1;
                           parmValue.page = 1;
                          searchList();"
                 />
              </el-col>

              <el-col :span="3" style="width:115px;float: right">
                <el-button
                  :size="searchSize"
                  type="primary"
                  style="float: right; margin-left: 5px"
                  @click="download"
                >
                  下载发票数据
                </el-button>
              </el-col>
              <el-col :span="4" class="fr" style="width: 66px">
                <el-button
                  type="warning"
                  class="fr"
                  :size="searchSize"
                  @click="onBatchApprovalInvoice"
                >
                  批量审核发票
                </el-button>
              </el-col>
            </el-row>

            <el-row style="margin-top:10px">
              <el-col :span="4" style="margin-right:10px">
                <el-select v-model="parmValue.invoice_type" size="mini" placeholder="发票类型" style="width:100%"
                  @change="pageInfo.curr = 1;
                           parmValue.page = 1;
                           searchList();"
                  >
                    <el-option
                      v-for="type in invoiceTypeList"
                      :key="type.value"
                      :value="type.value"
                      :label="type.label"
                     />
                  </el-select>
              </el-col>

              <el-col :span="4">
                <el-input size="mini" placeholder="发票申请编号" v-model="parmValue.invNo"
                  @change=" pageInfo.curr = 1;
                           parmValue.page = 1;
                          searchList();"
                 />
              </el-col>
            </el-row>
          </div>
        </template>

        <template #invoiceType="{ scope }">
          <el-tag size="mini">
            {{(invoiceTypeList.find(({value}) => value === scope.row.invoiceType) || {}).label || '--'}}
          </el-tag>
        </template>

        <template #demandOrder={scope}>{{
            (scope.row.orderinvoice || {}).reqCode || '--'
          }}</template>

        <template #status="{ scope }">
          <el-tag
            :size="tablebtnSize"
            :type="
              (statusList.find((item) => item.id == scope.row.status) || {})
                .type || ''
            "
            v-text="
              (statusList.find((item) => item.id == scope.row.status) || {})
                .label || '--'
            "
          ></el-tag>
        </template>

        <template #operation="{ scope }">
          <el-tooltip
            v-if="powers.some((i) => i == '007')"
            effect="dark"
            content="详情"
            placement="top"
          >
            <i
              class="el-icon-view tb-icon"

               @click="getRouter('bargainListDetail', scope.row.bargainNo )"
            ></i>
          </el-tooltip>
        </template>
      </ex-table>

      <invoice-modal :visible.sync="visible" @confirm="handleBatchApprovalInvoice" />
    </div>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/platformService/invoice";
import companyHelper from "@/mixins/companyHelper"
import { listCol, statusList } from "./columns";
import { mapGetters } from "vuex";
import { invoiceTypeList } from '@/assets/js/statusList';
import InvoiceModal from "./components/invoice-modal.vue"
import urlConfig from "@/apis/url-config";



/**
 * @props
    create_start 创建开始时间
    create_end 创建结束时间
    open_start 开票开始时间
    open_end 开票结束时间
    supplier 供应商企业
    reqCode 需求订单编号
    invoiceStatus 发票状态
    invoiceCode 发票代码,
    invoiceNum 发票号码,
    invoice_type 发票类型
    invNo 发票申请编号
*/


export default {
  name: "bargainList",
  mixins: [mixinPage, resToken, companyHelper],
  components:{InvoiceModal},
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "invoice"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      selected:[],
      select: "1",
      s_input: "",
      invoiceTypeList,
      customerCode: [], //客户公司code
      statusList,
      sitem: null,
      loading: false,
      visible: false,
      isDetail: false,
      modelId: 0,
            //全局url
      fileUrl: urlConfig.baseURL,
      parmValue: {
        create_start:"", // 创建开始时间
        create_end:"", // 创建结束时间
        open_start:"", // 开票开始时间
        open_end:"", // 开票结束时间
        supplier:"", // 供应商企业
        reqCode:"", // 需求订单编号
        invoiceStatus:"", // 发票状态
        invoiceCode:"", // 发票代码,
        invoiceNum:"", // 发票号码,
        invoice_type:"", // 发票类型
        invNo:"", // 发票申请编号
        page: 1, // 页码
        size: 15, // 每页显示条数
      },
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: listCol,
      resultValue: "", //处理结果
    };
  },
  mounted() {
    const { back } = this.$route.query;
    if (back) {
      this.parmValue = JSON.parse(back);
      console.log(this.parmValue)
      const {page,size}=this.parmValue;
       this.pageInfo= {
        size: size,
        curr: page,
        total: 0,
      }
      //多选条件
    this.select = this.parmValue.select;
    // this.sselect = this.parmValue.sselect;
    this.s_input = this.parmValue.s_input

    }else{
       this.select = "1";
      //  this.sselect = "创建时间"
    }
    this.searchList();
  },
  methods: {
    async handleBatchApprovalInvoice(data){
      const { code } = await asyncRequest.batch({
        idArr:this.selected.map(({id}) => id),
        ...data
      })

      if(code !== 1) return
      this.visible = false
      this.searchList()
    },
    async download() {
      let model = JSON.parse(JSON.stringify(this.parmValue));
      if (!this.loading) {
        this.loading = true;
        let httpType = `aplication/zip`;
        axios({
          method: "post",
          url: this.fileUrl + "admin/invoiceInfo/invoiceDown",
          responseType: "blob",
          data: model,
          headers: {
            // 'Content-Type': 'multipart/form-data',
            // Accept: "application/vnd.ms-excel"
            Accept: httpType,
          },
        })
          .then((res) => {
            if (res && res.status == 200 && res.data) {
              let url = window.URL.createObjectURL(
                new Blob([res.data], {
                  type: httpType,
                })
              );
              let link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              let excelName = "发票数据.xlsx";
              link.setAttribute("download", excelName);
              document.body.appendChild(link);
              link.click();
              link.remove();
              window.URL.revokeObjectURL(url); //释放掉blob对象
              this.$message.success(`导出成功！`);
              setTimeout(() => {
                this.loading = false;
              }, 500);
            } else {
              this.$message.error(res.data.message);
              setTimeout(() => {
                this.loading = false;
              }, 500);
            }
          })
          .catch((error) => {
            console.log(error);
            this.loading = false;
          });
      }
    },
    onBatchApprovalInvoice(){
      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.visible = true
      // console.log(this.selected)
    },
    handleSelectionChange(list) {
      console.log(list)
      this.selected = list
    },
    getRouter(toRouter, queryId){
      if (toRouter && queryId) {
        let model = {
          id: queryId,
          type: 'view',
        };

        //有多选框的条件
        this.parmValue.select = this.select ;
        // this.parmValue.sselect = this.sselect ;
        this.parmValue.s_input= this.s_input;
        //
         let routerModel = {
          options: JSON.parse(JSON.stringify(this.parmValue)),
          router: this.$route.path,
        };
        model.preModel = JSON.stringify(routerModel);

        this.routeGoto(toRouter, model);
      } else {
        this.$message.warning("暂未找到相关流程！");
      }
    },
    restSearch() {
      this.customerCode = [];
      this.select = "1";
      this.s_input = "";
      this.parmValue = {
        create_start:"", // 创建开始时间
        create_end:"", // 创建结束时间
        open_start:"", // 开票开始时间
        open_end:"", // 开票结束时间
        supplier:"", // 供应商企业
        reqCode:"", // 需求订单编号
        invoiceStatus:"", // 发票状态
        invoiceCode:"", // 发票代码,
        invoiceNum:"", // 发票号码,
        invoice_type:"", // 发票类型
        invNo:"", // 发票申请编号
        page: 1, // 页码
        size: 15, // 每页显示条数
      }
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.searchList();
    },

    openModal(id, isDetail, sitem) {
      this.showModel = true;
      this.modelId = id;
      this.isDetail = isDetail;
      this.sitem = sitem;
    },
    // 列表搜索
    async searchList() {
      this.loading = true;
      const res = await asyncRequest.list({
        ...this.parmValue,
        inv_type: "1"
      });

      if (res && res.code === 1 && res.data) {
        this.tableData = res.data.list;
        this.pageInfo.total = Number(res.data.count);
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },

    async statusConfirm(id, status) {
      let str = status + '' === "1" ? "禁用" : "启用";
      await this.$confirm("确定要改为" + str + "?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.loading = true;
          const model = {
            id: id,
            status: status + '' === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.loading = false;
            this.$notify.success({
              title: "状态修改成功！",
              message: "",
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 时间选择事件
    async handleTime(e,isOpen = false) {
      const startProp = isOpen ? "open_start" :"create_start"
      const endProp = isOpen ? "open_end" : "create_end"

      if (e.startTime !== "") {
        this.parmValue[startProp] = e.startTime;
      } else {
        this.parmValue[startProp] = "";
      }
      if (e.endTime !== "") {
        this.parmValue[endProp] = e.endTime;
      } else {
        this.parmValue[endProp] = "";
      }
      if (this.parmValue[startProp] !== "" && this.parmValue[endProp] !== "") {
        this.pageInfo.curr = 1;
        this.parmValue.page = 1;
        await this.searchList();
      }
    },
    async customerChange(e) {
      const { code } = e;
      this.parmValue.customer_code = code ? [code] : [];
      this.parmValue.supplierName = e.label;
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },
  },
};
</script>
   <style lang="scss" scoped>
.bargainList {
}
</style>
