<template>
  <div class="pagePadding" style="background:#f7f7f7">
    <div
      class="box"
      v-if="powers && powers.length > 0 && powers.some((item) => item == '001')"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="采购单编号: "
          prop="name"
          style="width: 500px"
          class="title"   
        >
          <el-input
            v-model="ruleForm.name"
            readonly="true"
            placeholder="请选择"
            @click.native="centerDialogVisible = true"
          ></el-input>
        </el-form-item>

        <div class="con" v-if="sitem">
              <el-collapse v-model="activeNames" style="margin: -18px 0 0 0">
              <el-collapse-item title="采购单信息" name="1">
                <show-data-table
                  :newTime="newTime"
                  v-if="newTime !== ''"
                  :sitem="sitem"
                  :columns="ShowDataTableColumns"
                >
                  <template slot="supplier_name">
                    <span>{{ sitem.supplier_name }}</span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li>
                          <span>销售方公司编号：</span
                          ><span>{{ sitem.supplierNo }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>
                  <template slot="company">
                    <span>{{ sitem.company }}</span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li>
                          <span>购买方公司编号：</span
                          ><span>{{ sitem.companyNo }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>

                  <template slot="status">
                    <el-tag
                      :size="'mini'"
                      :type="sitem.status == '0' ? 'warning' : ''"
                      v-text="
                        (
                          statusOptions.find(
                            (item) => item.value == sitem.status
                          ) || {}
                        ).label || '--'
                      "
                    ></el-tag>
                    <el-tooltip
                      class="fr"
                      v-if="
                        powers.some((item) => item == '007') &&
                        sitem.status === '0'
                      "
                      effect="dark"
                      content="已于供应商确认"
                      placement="top"
                    >
                      <i
                        class="el-icon-video-play tb-icon"
                        @click="statusConfirm()"
                      ></i>
                    </el-tooltip>
                  </template>
                  <template slot="order_type">
                    <el-tag
                      :size="'mini'"
                      v-text="
                        (
                          order_type_options.find(
                            (item) => item.value == sitem.order_type
                          ) || {}
                        ).label || '--'
                      "
                    ></el-tag>
                    <el-popover
                      placement="top"
                      width="300"
                      v-if="sitem.order_type === '1'"
                      trigger="hover"
                    >
                      <ul>
                        <li>
                          <span>备库单编号：</span><span>{{ sitem.bkcode }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>

                  <template slot="wsm">
                    <span>{{ sitem.wsm_supplier }}/{{ sitem.wsm_name }}</span>
                    <el-popover placement="top" width="300" trigger="hover">
                      <ul>
                        <li>
                          <span>仓库公司编号：</span
                          ><span>{{ sitem.wsm_supplierNo }}</span>
                        </li>
                        <li>
                          <span>仓库名称编号：</span
                          ><span>{{ sitem.wsm_code }}</span>
                        </li>
                      </ul>
                      <i class="el-icon-warning-outline fr" slot="reference"></i>
                    </el-popover>
                  </template>

                  <template slot="gold_price">
                    <div
                      v-if="
                        sitem.status == '0' &&
                        sitem.can[0].id == '6' &&
                        cost_detailArr.is_gold_price == '1'
                      "
                    >
                      {{ sitem.gold_price }}
                    </div>
                    <div v-else>----</div>
                  </template>
                </show-data-table>
              </el-collapse-item>
              <!-- <el-collapse-item title="商品信息" name="2">
                <show-goods-data-table
                  :newTime="newTime"
                  v-if="newTime !== ''"
                  :type="sitem.order_type"
                  :skucode="sitem.skuCode"
                  :spucode="sitem.spuCode"
                  :iscgd="true"
                />

                <editPrice
                  :newTime="newTime"
                  v-if="
                    newTime !== '' &&
                    sitem.status == '0' &&
                    sitem.can[0].id == '6' &&
                    cost_detailArr.is_gold_price == '1'
                  "
                  :sitem="sitem"
                  :cost_detailArr="cost_detailArr"
                  @refresh="refresh"
                >
                </editPrice>
              </el-collapse-item>
              <el-collapse-item
                title="入库单"
                name="3"
                v-if="sitem && sitem.status !== '0'"
              >
                <order-in-table
                  :newTime="newTime"
                  v-if="newTime !== ''"
                  :sitem="sitem"
                  :id="queryId"
                  @refresh="initData()"
                />
              </el-collapse-item>
              <el-collapse-item
                title="工差单"
                name="4"
                v-if="
                  sitem &&
                  sitem.order_type !== '1' &&
                  sitem.status !== '0' &&
                  sitem.purcheasediff
                "
              >
                <work-diff-table
                  :newTime="newTime"
                  v-if="newTime !== ''"
                  :sitem="sitem"
                />
              </el-collapse-item> -->
          </el-collapse>
        </div>
      </el-form>

      <el-dialog
        title="采购单详情"
        :visible.sync="centerDialogVisible"
        width="1040px"
        top="2.5vh"
        center
      >
        <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();
          "
          @selection="selection_change"
        >
          <template #table-header="{}">
            <div style="width: 100%">
              <el-row style="padding: 0 0 0 80px">
                <el-col :span="4" style="width: 150px">
                  <el-select
                    :size="searchSize"
                    v-model="parmValue.status"
                    filterable
                    clearable
                    disabled
                    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: 310px; padding: 0 0 0 10px">
                <search-supplier
                  :size="searchSize"
                  :value="wsm_supplierNo"
                  :placeholder="'入库公司名称'"
                  :disabled="false"
                  :names="supplierName"
                  :isDetail="true"
                  @searchChange="supplierChange"
                />
              </el-col>
              <el-col :span="4" style="width: 220px; padding: 0 0 0 10px">
                <search-stock
                  :size="searchSize"
                  :value="wsm_code"
                  :placeholder="'入库仓库名称'"
                  :disabled="false"
                  :names="stockName"

                  :isDetail="true"
                  :isRelation="true"
                  :companyCode="parmValue.wsm_supplierNo"
                  @searchChange="stockChange"
                />
              </el-col> -->
                <el-col :span="4" style="width: 130px; padding: 0 0 0 10px">
                  <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-row>
              <el-row style="padding: 10px 0 0 0">
                <el-col :span="6" style="width: 500px; padding: 0 0 0 0px">
                  <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: 125px"
                      slot="prepend"
                      placeholder="关键字类型"
                      @change="
                        pageInfo.curr = 1;
                        parmValue.page = 1;
                        searchList();
                      "
                    >
                      <el-option label="采购单编号" value="1"></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-select>
                  </el-input>
                </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: 66px; float: right"
                  v-if="
                    powers &&
                    powers.length > 0 &&
                    powers.some((item) => item == '087')
                  "
                >
                  <el-button
                    type="primary"
                    style="margin-left: 30px"
                    @click="submit"
                    :size="searchSize"
                    class="fr"
                  >
                    提交
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </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 #order_type="{ scope }">
            <el-tag
              :size="tablebtnSize"
              v-text="
                (
                  order_type_options.find(
                    (item) => item.value == scope.row.order_type
                  ) || {}
                ).label || '--'
              "
            ></el-tag>
          </template>
          <template #operation="{ scope }">
            <el-tooltip
              v-if="powers.some((item) => item == '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>
      </el-dialog>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>

<script>
//http
import asyncRequest from "@/apis/service/dataCorrection/cgMessage";

import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import urlConfig from "@/apis/url-config";
import { columns, order_type_options, statusOptions } from "./columns";
import { mapGetters } from "vuex";
import orderInTable from "./components/order-in-table";
import workDiffTable from "./components/work-diff-table";
import ShowDataTableColumns from "./components/ShowDataTableColumns";
import tolerance from "./components/tolerance";
import editPrice from "./components/editPrice";
export default {
  mixins: [mixinPage, resToken],
  components: {
    orderInTable,
    tolerance,
    workDiffTable,
    editPrice,
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "purchaseOrder"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  data() {
    var validate = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择采购单"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    return {
      //弹窗显隐
      centerDialogVisible: false,
      ruleForm: {
        name: "",
      },
      rules: {
        name: [{ validator: validate, required: true, trigger: "blur" }],
      },

      //入库公司
      supplierName: "",
      //入库仓库
      stockName: "",
      changeList: [],
      fileUrl: urlConfig.baseURL,
      activeNames: ["0", "1", "2", "3", "4", "5", "10"],
      sitem: null,
      select: "1",
      input: "",
      timeOBJ: {
        start: "", //起始时间
        end: "", // 结束时间
      },
      options: ["创建时间", "最晚入库时间"],
      sselect: "创建时间",
      // 状态
      statusOptions: statusOptions,
      ShowDataTableColumns: ShowDataTableColumns,
      order_type_options: order_type_options,
      cost_detailArr: [],

      loading: false,
      showModel: false,
      isDetail: false,
      modelId: 0,
      wsm_code: [],
      wsm_supplierNo: [],
      parmValue: {
        bk_code: "", // 备库编码
        wsm_in_code: "", // 入库单号
        cgdNo: "", // 采购单编码
        apply_name: "", // 申请人
        good_name: "", // 产品名称
        good_code: "", // 产品属性编号

        status: "0", //状态

        wsm_code: "", //入货仓库编码
        start: "", //新建起始时间
        end: "", // 新建结束时间
        last_start: "", //最后入库时间开始
        last_end: "", //最后入库时间结束
        page: 1, // 页码
        size: 15, // 每页显示条数
        supplierNo: "",
        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() {
   
    this.searchList();
  },

  methods: {
    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 submit() {
      if (this.changeList.length <= 0) {
        this.$message.warning("请选择有效数据");
        return;
      }

      if (this.changeList.length != 1) {
        this.$message.warning("只能同时提交一条选中数据");
        return;
      }

      let model = this.changeList[0];

        //提交成功，接口返回数据时，将选中的一行中的采购单编号赋值给页面上的input
        this.ruleForm.name = model.cgdNo;
        
        //处理成功后，关闭弹窗，渲染页面层数据
        this.centerDialogVisible = false;

        this.sitem = model;
       
    },

    async statusConfirm() {
      if (this.changeList.length <= 0) {
        this.$message.warning("至少选择一条采购单数据！");
        return;
      }
      let isok = true,
        list = [];
      this.changeList.forEach((e) => {
        if (e.status !== "0") {
          isok = false;
        }
        list.push(e.cgdNo);
      });
      if (!isok) {
        this.$message.warning("只能选择待与供应商确认的采购单！");
        return;
      }
      await this.$confirm(`确定批量确认？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let model = {
            cgdNo: list,
            status: "0",
          };
          const res = await asyncRequest.status(model);
          this.loading = false;
          if (res && res.code === 0) {
            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("取消");
        });
    },
    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: "0", //状态
        wsm_code: "", //入货仓库编码
        start: "", //新建起始时间
        end: "", // 新建结束时间
        last_start: "", //最后入库时间开始
        last_end: "", //最后入库时间结束
        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.wsm_supplierNo = [];
      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 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>
/deep/ .title {
  width: 500px;
  display: block;
  margin-top: 40px;
}
/deep/ .demo-ruleForm{
  width: 80%;
  min-width: 800px;
  padding-left: 100px;
  box-sizing: border-box;
}
.con{
  width: 100%;
  height: 60vh;
  background: #fff;
  // margin-bottom: 40px;
}
</style>