<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"
        @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: 301px; padding: 0 0 0px 0px">
                <period-date-picker
                  :start="parmValue[mapFields.createStart]"
                  :end="parmValue[mapFields.createEnd]"
                  :width="'134px'"
                  :size="searchSize"
                  placeholder="创建"
                  @timeReturned="evt => handleTime(evt,'create')"
                />
              </el-col>

              <el-col :span="3" style="margin-right:10px">
                <el-select
                  style="width:100%"
                  :size="searchSize"
                  v-model="parmValue[mapFields.status]"
                  clearable
                  placeholder="申请状态"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-option
                    v-for="item in statusList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-col>

              <el-col :span="4">
                <el-select
                  style="width:100%"
                  :size="searchSize"
                  v-model="parmValue[mapFields.demandCompany]"
                  clearable
                  placeholder="需求企业"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <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: 301px; padding: 0 0 0px 0px">
                <period-date-picker
                  :start="parmValue[mapFields.openStart]"
                  :end="parmValue[mapFields.openEnd]"
                  :width="'134px'"
                  :size="searchSize"
                  @timeReturned="evt => handleTime(evt,'open')"
                  placeholder="开票"
                />
              </el-col>

              <el-col :span="4" style="margin-right:10px">
                <el-input
                  clearable
                  :size="searchSize"
                  placeholder="开票申请编号"
                  v-model="parmValue[mapFields.openInviceNo]"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                />
              </el-col>

              <el-col :span="4" style="margin-right:10px">
                <el-input
                  clearable
                  :size="searchSize"
                  placeholder="需求订单编号"
                  v-model="parmValue[mapFields.demandOrderNo]"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                />
              </el-col>

               <el-col :span="3" style="width: 113px; 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="visible = true"
                >
                  批量审批发票
                </el-button>
              </el-col>
            </el-row>

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

              <el-col :span="4"  style="margin-right:10px">
                <el-input
                  clearable
                  :size="searchSize"
                  placeholder="发票号码"
                  v-model="parmValue[mapFields.invoiceNumber]"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                />
              </el-col>

              <el-col :span="4">
                <el-select
                  style="width:100%"
                  :size="searchSize"
                  v-model="parmValue[mapFields.invoiceType]"
                  clearable
                  placeholder="发票类型"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-option />
                </el-select>
              </el-col>
            </el-row>
          </div>
        </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 #good_name="{ scope }">
          <span>{{ scope.row.good_name }}</span>
          <span
            v-for="(si, sii) in scope.row.specinfo"
            :key="si.spec_value_id + sii"
          >
            {{ sii == 0 ? "__" : "--" }}{{ si.spec_name }}[{{
              si.spec_value_name
            }}]</span
          >
        </template>
        <template #can="{ scope }">
          <span v-for="(si, sii) in scope.row.can" :key="si.id + sii">
            <span v-if="sii !== 0">_</span>{{ si.name }}</span
          >
        </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('invoiceApplyDetail', scope.row.bargainNo )" />
          </el-tooltip>
        </template>
      </ex-table>
    </div>

    <ApprovalModal :visible.sync="visible" />
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/customerService/invoiceApproval";
import companyHelper from "@/mixins/companyHelper"
import { listCol, statusList } from "./columns";
import ApprovalModal from "./components/approvalModal.vue";
import { createEmptyStringObject } from '@/utils/static';
import { mapGetters } from "vuex";

const mapFields = {
  //创建时间开始&结束
  createStart:'createStart',
  createEnd:'createEnd',
  //开票时间开始&结束
  openStart:'openStart',
  openEnd:'openEnd',
  //需求企业
  demandCompany:'demandCompany',
  //发票号码
  invoiceNumber:'invoiceNumber',
  //发票代码
  invoiceCode:'invoiceCode',
  //发票类型
  invoiceType:'invoiceType',
  //开票申请编号
  openInviceNo:'openInviceNo',
  //需求订单编号
  demandOrderNo:'demandOrderNo',
  //申请状态
  status:'status'
}

const mapDateFields = {
  create:'创建',
  open:'开票'
}

export default {
  name: "bargainList",
  mixins: [mixinPage, resToken, companyHelper],
  components:{ApprovalModal},
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find((item) => item.menu_route == "invoiceApproval") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      mapFields,
      visible:false,
      customerCode: [], //客户公司code
      statusList,
      sitem: null,
      loading: false,
      showModel: false,
      isDetail: false,
      modelId: 0,
      parmValue: {
        ...createEmptyStringObject(mapFields),
        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.parmValue.start = start || last_start;
      // this.parmValue.end = end || last_end;

      // if(this.parmValue.customer_code.length>0){
      //     this.customerCode = [this.parmValue.customer_code] ;
      // }

       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: {
    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 = {
        bidsNo: "", // 反馈编号
        infoNo: "", // 竞价单编号
        bargainNo: "", //议价编号
        status: "", // 状态
        start: "",
        end: "",
        page: 1, // 页码
        size: 15, // 每页显示条数
        company_name:"",
      };
      // 表格 - 分页
      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 deleteById(id, status) {
      await this.$confirm("确定要删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
          const model = {
            id: id,
            status: status + '' === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.$notify.success({
              title: "删除成功",
              message: "",
            });
            this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 列表搜索
    async searchList() {
      return

      for(const field of Object.keys(mapDateFields)){
        const startField = `${field}Start`
        const endField = `${field}End`

        if (
          (this.parmValue[startField] !== "" && this.parmValue[endField] === "") ||
          (this.parmValue[startField] === "" && this.parmValue[endField] !== "")
        ) {
          this.$message.warning(`${mapDateFields[field]}时间区间不完整！`);
          return;
        }
      }

      this.loading = true;
      this.parmValue.bargainNo = this.select === "1" ? this.s_input : "";
      this.parmValue.bidsNo = this.select === "2" ? this.s_input : "";
      this.parmValue.infoNo = this.select === "3" ? this.s_input : "";
      this.parmValue.company_name = this.select === "4" ? this.s_input : "";

      const res = await asyncRequest.list({
        ...this.parmValue,
        companyNo: this.currentCompany,
        customer_code: Array.isArray(this.parmValue.customer_code) ? this.parmValue.customer_code[0] : "",
        noRelation: true
      });

      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 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,prop) {
      const startProp = `${prop}Start`
      const endProp = `${prop}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>
