<template>
  <div class="purchaseOrder pagePadding">
    <div v-if="powers.some((i) => i == '001')">
      <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="(list) => (tableSelection = list)"
        @screen-reset="
          pageInfo.curr = 1;
          parmValue.page = 1;
          searchList();
        "
        @screen-submit="
          pageInfo.curr = 1;
          parmValue.page = 1;
          searchList();
        "
        @selection="selection_change"
      >
        <template #table-header="{}">
          <div style="width: 100%">
            <el-row style="padding: 0 0 0 80px">
              <el-col :span="4" style="width: 120px">
                <el-dropdown @command="handleClick($event)" :size="searchSize">
                  <el-button :size="searchSize" style="width: 120px">
                    {{ sselect }}
                    <i class="el-icon-arrow-down el-icon--right" :size="searchSize"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="item in options"
                      :key="item"
                      :command="item"
                      >{{ item }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
              <el-col :span="4" style="width: 303px; padding: 0 0 0 10px">
                <period-date-picker
                  :type="1"
                  :width="'135px'"
                  :size="searchSize"
                  :start="timeOBJ.start"
                  :end="timeOBJ.end"
                  @timeReturned="handleTime"
                />
              </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"
                style="width: 150px; float: right"
                v-if="powers.some((i) => i == '089') && !isSupertube"
              >
                <el-button
                  type="primary"
                  @click="statusConfirm"
                  :size="searchSize"
                  class="fr"
                >
                  批量与供应商确认
                </el-button>
              </el-col>
            </el-row>
            <el-row style="padding: 10px 0 0 0">
              <el-col :span="4" style="width: 200px">
                <el-select
                  :size="searchSize"
                  v-model="parmValue.status"
                  filterable
                  clearable
                  placeholder="采购单状态"
                  style="width: 100%"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="'status' + item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="4" style="width: 151px; padding: 0 0 0 10px">
                <el-select
                  :size="searchSize"
                  v-model="parmValue.order_type"
                  filterable
                  clearable
                  placeholder="商品类型"
                  style="width: 100%"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-option
                    v-for="item in cg_order_type_options"
                    :key="'order_type' + item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-col>

              <el-col :span="4" style="width: 151px; padding: 0 0 0 10px">
                <el-select
                  :size="searchSize"
                  v-model="parmValue.order_source"
                  filterable
                  clearable
                  placeholder="订单来源"
                  style="width: 100%"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-option
                    v-for="item in cg_order_source_options"
                    :key="'order_type' + item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-col>

              <!-- <el-col :span="4">
                  <el-select style="margin-right:10px" placeholder="供应商端" clearable size="mini"  v-model="parmValue.has_account"  
                    @change="
                        pageInfo.curr = 1;
                        parmValue.page = 1;
                        searchList();
                      "
                  >
                    <el-option value="0" label="未开通" />
                    <el-option value="1" label="已开通"/>
                  </el-select>
              </el-col> -->

              <el-col :span="4" style="width: 66px; float: right">
                <el-button
                  type="warning"
                  class="fr"
                  :size="searchSize"
                  @click="restSearch"
                >
                  重置
                </el-button>
              </el-col>
              <!-- 暂时注释，下版需要导出 -->
              <el-col :span="4" style="width: 80px; float: right" v-if="!isSupertube && powers.includes('093')">
                <el-button
                  type="primary"
                  @click="handleBatchIn"
                  :size="searchSize"
                  class="fr"
                >
                  批量入库
                </el-button>
              </el-col>
            </el-row>
            <el-row style="padding: 10px 0 0 0">
              <el-col :span="4" style="width: 350px">
                <search-supplier
                  :size="'mini'"
                  :value="parmValue.supplierNo"
                  :disabled="false"
                  :placeholder="'供应商名称'"
                  :names="parmValue.supplierName"
                  :isDetail="true"
                  :noDisabled="true"
                  @searchChange="supplierChange"
                />
              </el-col>
              <el-col :span="4" style="width: 400px; padding: 0 0 0 10px">
                <el-input
                  clearable
                  placeholder="关键字"
                  v-model="input"
                  maxlength="40"
                  :size="searchSize"
                  class="input-with-select"
                  @blur="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-select
                    v-model="select"
                    style="width: 140px"
                    slot="prepend"
                    placeholder="关键字类型"
                    @change="
                      pageInfo.curr = 1;
                      parmValue.page = 1;
                      searchList();
                    "
                  >
                    <el-option label="采购单编号" value="1"></el-option>
                    <el-option label="订单编号" value="8"></el-option>
                    <!-- <el-option label="入库单编号" value="2"></el-option> -->
                    <!-- 列表未渲染备库编号，注释 -->
                    <!-- <el-option label="备库编号" value="3"></el-option> -->
                    <el-option label="商品成本编号" value="4"></el-option>
                    <el-option label="商品名称" value="5"></el-option>
                    <!-- <el-option label="供应商负责人" value="6"></el-option> -->
                    <!-- <el-option label="采购供应商编号" value="7"></el-option> -->
                    <!-- <el-option label="采购供应商名称" value="10"></el-option> -->

                    <!-- <el-option label="供应商负责人部门" value="9"></el-option> -->
                  </el-select>
                </el-input>
              </el-col>
              <el-col
                :span="4"
                style="width: 66px; float: right"
                v-if="powers.some((i) => i == '087') && !isSupertube"
              >
                <el-button
                  type="primary"
                  style="margin-left: 30px"
                  @click="download"
                  :size="searchSize"
                  class="fr"
                >
                  导出
                </el-button>
              </el-col>
            </el-row>
          </div>
        </template>

        <template #has_account="{ scope }">
          <el-tag
            :size="tablebtnSize"
            :type="scope.row.has_account == '0' ? 'warning' : ''"
            >{{ String(scope.row.has_account) === "1" ? "已开通" : "未开通" }}</el-tag
          >
        </template>

        <template #good_name="{ scope }">
          <span>{{ scope.row.good_name }}</span>
          <span v-for="(si, i) in scope.row.speclist" :key="si.spec_id + i">
            {{ i === 0 ? "__" : "--" }}{{ si.spec_name }}[{{ si.spec_value }}]
          </span>
        </template>
        <template #status="{ scope }">
          <el-tag
            :size="tablebtnSize"
            v-text="
              (statusOptions.find((item) => item.value == scope.row.status) || {})
                .label || '--'
            "
          ></el-tag>
        </template>
        <template #has_account="{ scope }">
          <el-tag
            :size="tablebtnSize"
            :type="
              (
                has_account_list.find(
                  (item) => item.code == scope.row.has_account + ''
                ) || {}
              ).type || '--'
            "
            v-text="
              (
                has_account_list.find(
                  (item) => item.code == scope.row.has_account + ''
                ) || {}
              ).name || '--'
            "
          ></el-tag>
        </template>
        <template #order_id="{ scope }">
          <el-tag
            :size="tablebtnSize"
            v-text="
              (
                cg_order_type_options.find((item) => item.id == scope.row.order_type) ||
                {}
              ).label || '--'
            "
          ></el-tag>
        </template>
        <template #order_source="{ scope }">
          <el-tag
            :size="tablebtnSize"
            v-text="
              (
                cg_order_source_options.find(
                  (item) => item.id == scope.row.order_source
                ) || {}
              ).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('purchaseOrderDetail', scope.row.cgdNo)"
            ></i>
          </el-tooltip>
        </template>
      </ex-table>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import urlConfig from "@/apis/url-config";
import asyncRequest from "@/apis/service/purchaseIn/purchaseOrder";
import { columns, statusOptions } from "./columns";
import {
  cg_order_type_options,
  cg_order_source_options,
  has_account_list,
} from "@/assets/js/statusList";
import companyHelper from "@/mixins/companyHelper";
import { mapGetters } from "vuex";

export default {
  name: "purchaseOrder",
  mixins: [mixinPage, resToken, companyHelper],
  components: {},
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size", "isSupertube"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find((item) => item.menu_route == "purchaseOrder") ||
        {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      is_stock: [
        { id: "0", name: "非库存品" },
        { id: "1", name: "库存品" },
      ],
      supplierNo: [],
      tableSelection: [],
      //入库公司
      supplierName: "",
      has_account_list,
      cg_order_type_options,
      cg_order_source_options,
      //入库仓库
      stockName: "",
      changeList: [],
      fileUrl: urlConfig.baseURL,
      sitem: null,
      select: "1",
      input: "",
      timeOBJ: {
        start: "", //起始时间
        end: "", // 结束时间
      },
      options: ["创建时间", "最晚入库时间"],
      sselect: "创建时间",
      // 状态
      statusOptions: statusOptions,
      loading: false,
      showModel: false,
      isDetail: false,
      modelId: 0,
      wsm_code: [],
      // wsm_supplierNo: [],
      parmValue: {
        supplierName:"",
        supplierNo:"",
        has_account: "",
        order_source: "",
        orderCode: "", // 订单编号
        bk_code: "", // 备库编码
        wsm_in_code: "", // 入库单号
        cgdNo: "", // 采购单编码
        apply_name: "", // 申请人
        good_name: "", // 产品名称
        good_code: "", // 产品属性编号

        status: "", //状态

        wsm_code: "", //入货仓库编码
        start: "", //新建起始时间
        end: "", // 新建结束时间
        last_start: "", //最后入库时间开始
        last_end: "", //最后入库时间结束
        page: 1, // 页码
        size: 15, // 每页显示条数
        supplierNo: "",
        company_name: "", //部门
        wsm_supplierNo: "",
      },
      tableData: [],
      passwordModel: false,
      passwordModelId: 0,
      isPasswordDetail: false,
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: columns,
    };
  },
  mounted() {
    const { back } = this.$route.query;
    if (back) {
      this.parmValue = JSON.parse(back);
      console.log(this.parmValue);
      const { page, size, start, end, last_start, last_end } = this.parmValue;
      this.timeOBJ.start = start || last_start;
      this.timeOBJ.end = end || last_end;

      this.pageInfo = {
        size: size,
        curr: page,
        total: 0,
      };
      //多选条件
      this.select = this.parmValue.select;
      this.sselect = this.parmValue.sselect;
      this.input = this.parmValue.input;

      //入库公司
      // this.supplierName = localStorage.getItem("wsm_supplierNo")
      // if(this.supplierName.length>0){

      //   this.wsm_supplierNo = [this.parmValue.wsm_supplierNo];
      //   this.stockName = localStorage.getItem("wsm_code")
      //   this.wsm_code = [this.parmValue.wsm_code]

      // }

      // console.log(this.supplierName)
    } else {
      this.select = "1";
      this.sselect = "创建时间";
    }
    this.searchList();
  },

  methods: {
    async handleBatchIn() {
      if (this.tableSelection.length === 0) {
        this.$message.warning("请选择至少一条采购单");
        return;
      }

      for (let i = 0; i < this.tableSelection.length; i++) {
        const item = this.tableSelection[i];

        if (item.status !== "1" && item.status !== "2") {
          this.$message.warning("只能选择未入库的销售订单！");
          return;
        }

        if (item.order_type === "1") {
          this.$message.warning("选择的采购单中不能包含库存品");
          return;
        }

        if (item.can && item.can[0].id === 6) {
          this.$message.warning("选择的采购单中不能包含贵金属");
          return;
        }
      }

      const cgdNo = this.tableSelection.map((item) => item.cgdNo);
      const { code, message } = await asyncRequest.orderBatchIn({ cgdNo });

      switch (code) {
        case 0:
          this.searchList();
          break;
        default:
          this.$message.warning(message);
          break;
      }
    },
    async supplierChange(e) {
      const { code, label } = e;
      this.parmValue.supplierNo = code ? [code] : [];
      this.parmValue.supplierName = label
      this.searchList();
    },
    getRouter(toRouter, queryId) {
      if (toRouter && queryId) {
        let model = {
          id: queryId,
        };

        //有多选框的条件
        this.parmValue.select = this.select;
        this.parmValue.sselect = this.sselect;
        this.parmValue.input = this.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("暂未找到相关流程！");
      }
    },
    //选中触发函数
    selection_change(e) {
      const { list } = e;
      //选中的数组集合
      this.changeList = list.length > 0 ? JSON.parse(JSON.stringify(list)) : [];
    },
    //导出文件
    async download() {
      if (this.changeList.length <= 0) {
        this.$message.warning("请选择有效数据");
        return;
      }
      let model = {
        cgdNos: [],
      };
      this.changeList.forEach((item) => {
        model.cgdNos.push(item.cgdNo);
      });

      // const res = await asyncRequest.exportcgdlist(model)

      if (!this.loading) {
        this.loading = true;
        let httpType = `aplication/zip`;
        axios({
          method: "post",
          url: this.fileUrl + "admin/exportcgdlist",
          responseType: "blob",
          data: model,
          headers: {
            // 'Content-Type': 'multipart/form-data',
            // Accept: "application/vnd.ms-excel"
            Accept: httpType,
          },
        })
          .then((res) => {
            // console.log(res)
            // console.log(this.fileUrl)
            // return;
            if (res && res.status == 200 && res.data) {
              let url = window.URL.createObjectURL(
                new Blob([res.data], {
                  // type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
                  type: httpType,
                })
              );
              let link = document.createElement("a");
              link.style.display = "none";
              link.href = url;
              let excelName = "采购单.zip";
              link.setAttribute("download", excelName);
              document.body.appendChild(link);
              link.click();
              link.remove();
              window.URL.revokeObjectURL(url); //释放掉blob对象
              this.$message.success(`${message}导出成功！`);
              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;
          });
      }
    },

    async statusConfirm() {
      if (this.changeList.length <= 0) {
        this.$message.warning("至少选择一条采购单数据！");
        return;
      }
      let isok = true,
        iss = false,
        list = [],
        errorList = [];
      this.changeList.forEach((e) => {
        if (e.status + "" !== "0") {
          isok = false;
        }
        if (
          e.has_account + "" !== "0" &&
          (e.order_type + "" === "2" ||
            e.order_type + "" === "3" ||
            e.order_type + "" === "4")
        ) {
          iss = true;
          errorList.push(e.cgdNo);
        }
        list.push(e.cgdNo);
      });
      if (!isok) {
        this.$message.warning("只能选择待与供应商确认的采购单！");
        return;
      }
      // if (iss) {
      //   let htmlList = "<ul>";
      //   errorList.forEach((v) => {
      //     console.log(v);
      //     htmlList += `<li>${v}</li>`;
      //   });
      //   htmlList += "</ul>";
      //   this.$notify({
      //     title: "以下采购单对应的供应商账号已开启，不允许在本系统操作！",
      //     dangerouslyUseHTMLString: true,
      //     message: htmlList,
      //   });
      //   return;
      // }
      await this.$confirm(`确定批量确认？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let model = {
            cgdNo: list,
            status: "1",
          };
          const { code, data, message } = await asyncRequest.status(model);
          this.loading = false;
          if (code === 0) {
            this.$notify.success({
              title: "提交成功！",
              message: "",
            });
            await this.searchList();
          } else if (code === 1003) {
            this.showal(data, message, "");
          } else if (code >= 100 && code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    showal(list, message, code) {
      let htmlList = "<ul>";
      list.forEach((v) => {
        htmlList += `<li>${code !== "" ? v[code] : v}</li>`;
      });
      htmlList += "</ul>";
      this.$notify({
        title: message,
        dangerouslyUseHTMLString: true,
        message: htmlList,
      });
    },
    restSearch() {
      this.sselect = "创建时间";
      this.select = "1";
      this.input = "";
      this.wsm_code = [];
      this.wsm_supplierNo = [];
      this.timeOBJ = {
        start: "", //起始时间
        end: "", // 结束时间
      };
      this.parmValue = {
        bk_code: "", // 备库编码
        wsm_in_code: "", // 入库单号
        cgdNo: "", // 采购单编码
        apply_name: "", // 申请人
        good_name: "", // 产品名称
        good_code: "", // 产品属性编号
        status: "", //状态
        wsm_code: "", //入货仓库编码
        start: "", //新建起始时间
        end: "", // 新建结束时间
        last_start: "", //最后入库时间开始
        last_end: "", //最后入库时间结束
        orderCode: "", //订单编号
        company_name: "", //部门
        page: 1, // 页码
        size: 15, // 每页显示条数
      };
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.searchList();
    },
    async handleClick(e) {
      this.sselect = e;
      this.parmValue.start = e === "创建时间" ? this.timeOBJ.start : "";
      this.parmValue.end = e === "创建时间" ? this.timeOBJ.end : "";
      this.parmValue.last_start = e !== "创建时间" ? this.timeOBJ.start : "";
      this.parmValue.last_end = e !== "创建时间" ? this.timeOBJ.end : "";
      if (
        !(
          (this.timeOBJ.start !== "" && this.timeOBJ.end === "") ||
          (this.timeOBJ.start === "" && this.timeOBJ.end !== "")
        )
      ) {
        this.parmValue.page = 1;
        this.pageInfo.curr = 1;
        await this.searchList();
      }
    },
    // async supplierChange(e) {
    //   if (e && e.id) {
    //     //入库公司
    //     // localStorage.setItem("wsm_supplierNo",e.label)
    //     // this.supplierName = localStorage.getItem("rkNm")
    //     this.parmValue.wsm_supplierNo = e.code;
    //     this.wsm_supplierNo = [e.code];
    //   } else {
    //     //入库公司
    //     // localStorage.setItem("wsm_supplierNo","")
    //     this.parmValue.wsm_supplierNo = "";
    //     this.wsm_supplierNo = [];
    //   }
    //   this.parmValue.wsm_code = "";
    //   this.wsm_code = [];
    //   this.parmValue.page = 1;
    //   this.pageInfo.curr = 1;
    //   await this.searchList();
    // },
    async stockChange(e) {
      if (e && e.id) {
        //入库仓库
        // localStorage.setItem("wsm_code",e.label)
        this.parmValue.wsm_code = e.code;
        this.wsm_code = [e.code];
      } else {
        //入库仓库
        // localStorage.setItem("wsm_code","")

        this.parmValue.wsm_code = "";
        this.wsm_code = [];
      }

      this.parmValue.page = 1;
      this.pageInfo.curr = 1;
      await this.searchList();
    },
    async searchList() {
      if (
        (this.timeOBJ.start !== "" && this.timeOBJ.end === "") ||
        (this.timeOBJ.start === "" && this.timeOBJ.end !== "")
      ) {
        this.$message.warning("时间区间不完整！");
        return;
      }

      this.loading = true;
      this.parmValue.cgdNo = this.select === "1" ? this.input : ""; // 采购单编码
      this.parmValue.wsm_in_code = this.select === "2" ? this.input : ""; // 入库单号
      this.parmValue.bk_code = this.select === "3" ? this.input : ""; // 备库编码
      this.parmValue.good_code = this.select === "4" ? this.input : ""; // 产品属性编号
      this.parmValue.good_name = this.select === "5" ? this.input : ""; // 产品名称
      this.parmValue.apply_name = this.select === "6" ? this.input : ""; // 申请人
      // this.parmValue.supplierNo = this.select === "7" ? this.input : ""; // 采购供应商编号
      this.parmValue.orderCode = this.select === "8" ? this.input : ""; // 采购供应商编号
      this.parmValue.company_name = this.select === "9" ? this.input : ""; // 部门
      // this.parmValue.supplier_name = this.select === "10" ? this.input : ""; // 采购供应商名称
      // this.wsm_supplierNo = [];

      const res = await asyncRequest.list({
        ...this.parmValue,
        supplierNo: Array.isArray(this.parmValue.supplierNo) ? this.parmValue.supplierNo[0] : this.parmValue.supplierNo,
        supplierName: undefined,
        needRela: 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 handleTime(e) {
      if (e.startTime !== "") {
        this.timeOBJ.start = e.startTime;
      } else {
        this.timeOBJ.start = "";
      }
      if (e.endTime !== "") {
        this.timeOBJ.end = e.endTime;
      } else {
        this.timeOBJ.end = "";
      }
      await this.handleClick(this.sselect);
    },
  },
};
</script>
<style lang="scss" scoped>
.purchaseOrder {
  // text-align: right;
}
</style>
