<template>
  <div class="pagePadding">
    <div class="tableBox" v-if="powers.some((i) => i == '001')">
      <ex-table
        ref="multipleTable"
        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 class="searchBox" style="width: 100%">
            <el-row style="margin: 0 0 0 80px; padding: 0 0 10px 0">
              <el-col :span="4" style="width: 150px">
                <el-select
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                  clearable
                  :size="searchSize"
                  v-model="parmValue.status"
                  style="width: 100%"
                  placeholder="状态筛选"
                >
                  <el-option
                    v-for="item in statusArr"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-col>

              <el-col :span="7" style="width: 352px; padding: 0 0 0 10px">
                <periodDatePickerActive
                  :start="parmValue.platform_time_start"
                  :end="parmValue.platform_time_end"
                  :placeholder="'下单'"
                  :width="'160px'"
                  :size="searchSize"
                  @timeReturned="platformTime"
                />
              </el-col>

              <el-col :span="2" class="fr" style="width: 66px; padding: 0 0 0 10px">
                <el-button size="mini" type="primary" class="btn" @click="resetF5"
                  >刷新</el-button
                >
              </el-col>

              <el-col
                :span="2"
                class="fr"
                style="width: 130px; padding: 0 0 0 10px"
                v-if="powers.some((i) => i == '013')"
              >
                <el-button type="primary" icon="el-icon-download" class="btn" size="mini"
                  ><a href="./static/C端订单导入模板.xlsx">下载导入模板</a></el-button
                >
              </el-col>
            </el-row>
            <el-row style="padding: 0 0 10px 0">
              <el-col :span="6" style="width: 230px">
                <search-terrace
                  :value="parmValue.platform_id"
                  :disabled="false"
                  :size="'mini'"
                  :isDetail="false"
                  :is_show="'0'"
                  :placeholder="'导入目标平台'"
                  @searchChange="platform_codesearchChange"
              /></el-col>
              <el-col :span="8" style="width: 352px; padding: 0 0 0 10px">
                <periodDatePickerActive
                  :start="parmValue.addtime_start"
                  :end="parmValue.addtime_end"
                  :placeholder="'导入'"
                  :width="'160px'"
                  :size="searchSize"
                  @timeReturned="addtime"
                />
              </el-col>
              <el-col :span="2" class="fr" style="width: 66px; padding: 0 0 0 10px">
                <el-button type="warning" class="btn" @click="reset" size="mini"
                  >重置</el-button
                >
              </el-col>
              <el-col
                :span="2"
                class="fr"
                style="width: 130px; padding: 0 0 0 10px"
                v-if="powers.some((i) => i == '085')"
              >
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-share"
                  class="btn"
                  @click="selectStock"
                  >批量关联库存</el-button
                >
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10" style="width: 400px">
                <el-input
                  v-model="inputValue"
                  :size="searchSize"
                  @blur="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                  placeholder="关键字"
                >
                  <el-select
                    style="width: 120px"
                    @change="
                      pageInfo.curr = 1;
                      parmValue.page = 1;
                      searchList();
                    "
                    slot="prepend"
                    :size="searchSize"
                    v-model="selectValue"
                  >
                    <el-option
                      v-for="item in selectValueArr"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-input>
              </el-col>
              <el-col
                :span="2"
                class="fr"
                style="width: 66px; padding: 0 0 0 10px"
                v-if="powers.some((i) => i == '006')"
              >
                <el-button size="mini" type="danger" class="btn" @click="batchDel"
                  >删除</el-button
                >
              </el-col>

              <el-col
                :span="2"
                class="fr"
                style="width: 130px; padding: 0 0 0 10px"
                v-if="powers.some((i) => i == '086')"
              >
                <el-button
                  class="btn entry"
                  @click="entry"
                  size="mini"
                  icon="el-icon-upload"
                  type="success"
                  >平台订单导入</el-button
                >
              </el-col>
            </el-row>
          </div>
        </template>
        <template #statusTxt="{ scope }">
          <el-tag
            :size="'mini'"
            :type="statusActiveTag(scope.row.status)"
            style="margin: auto"
            >{{ statusActive(scope.row.status) }}</el-tag
          >
        </template>
        <template #operation="{ scope }">
          <el-tooltip
            effect="dark"
            content="详情"
            placement="top"
            v-if="powers.some((i) => i == '007') && scope.row.status !== '5'"
          >
            <i
              class="el-icon-view tb-icon"
              @click="getRouter('orderConfirm', scope.row.id, scope.row.status)"
            ></i>
          </el-tooltip>
          <el-tooltip
            v-if="
              powers.some((i) => i == '006') &&
              (scope.row.status === '2' || scope.row.status === '4')
            "
            effect="dark"
            content="删除"
            placement="top"
          >
            <i class="el-icon-delete tb-icon" @click="deleteItem([scope.row.id])"></i>
          </el-tooltip>
        </template>
      </ex-table>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>

<script>
import { listCol } from "./columns";
import { mapGetters } from "vuex";
import asyncRequest from "@/apis/service/orderEntry/orderEnter";
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import periodDatePickerActive from "./period-date-picker/main.vue";
export default {
  mixins: [mixinPage, resToken],
  components: {
    periodDatePickerActive,
  },
  data() {
    return {
      // centerDialogVisible: false,
      loading: true,
      //竞价类型
      statusArr: [
        { value: "1", label: "系统验证数据中" },
        { value: "2", label: "待确认订单信息" },
        { value: "3", label: "待处理(待扣减库存)" },
        { value: "4", label: "库存不足" },
        { value: "5", label: "订单录入成功" },
      ],
      //多筛选select
      selectValueArr: [
        { value: "1", label: "平台订单号" },
        { value: "2", label: "平台商品编号" },
        { value: "3", label: "PO编号" },
        { value: "4", label: "录入订单编号" },
        { value: "5", label: "导入人部门" },
      ],
      parmValue: {
        status: "",
        platform_code: "",
        platform_id: "",
        // cs3: "",
        po_code: "",
        plat_code: "",
        // cs6: "",
        platform_time_end: "",
        platform_time_start: "",
        addtime_end: "",
        addtime_start: "",
        orderCode: "",
        page: 1,
        size: 15,
        company_name: "", //导入人部门
      },
      changeList: [],
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      tableData: [],
      columns: listCol,

      //多前置输入框值
      inputValue: "",
      //多筛选
      selectValue: "1",
    };
  },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find((item) => item.menu_route == "orderEnter") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    statusActive() {
      return function (status) {
        let active = "";
        switch (status) {
          case "1":
            active = "系统验证数据中";
            break;
          case "2":
            active = "待确认订单信息";
            break;
          case "3":
            active = "待处理(待扣减库存)";
            break;
          case "4":
            active = "库存不足";
            break;
          case "5":
            active = "订单录入成功";
            break;
        }
        return active;
      };
    },
    statusActiveTag() {
      return function (status) {
        let active = "";
        switch (status) {
          case "1":
            active = "";
            break;
          case "2":
            active = "info";
            break;
          case "3":
            active = "warning";
            break;
          case "4":
            active = "danger";
            break;
          case "5":
            active = "success";
            break;
        }
        return active;
      };
    },
  },
  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.brandid.length>0){
      //   this.brandid = [this.parmValue.brandid] ;
      // }

      this.pageInfo = {
        size: size,
        curr: page,
        total: 0,
      };
      //多选条件
      this.select = this.parmValue.select;
      // this.sselect = this.parmValue.sselect;
      this.inputValue = this.parmValue.inputValue;
    } else {
      this.select = "1";
      //  this.sselect = "创建时间"
      this.tableData = [];
    }
    this.select = "1";
    this.searchList();
  },
  methods: {
    async platform_codesearchChange(e) {
      const { id } = e;
      this.parmValue.platform_id = id || "";
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },
    getRouter(toRouter, queryId, status) {
      if (status === "1") {
        this.$message.warning(`脚本验证中的数据能查看详情！`);
        return;
      }
      if (toRouter && queryId) {
        let model = {
          id: queryId,
          type: "view",
        };

        //有多选框的条件
        this.parmValue.select = this.select;
        // this.parmValue.sselect = this.sselect ;
        this.parmValue.inputValue = this.inputValue;
        //
        console.log(this.parmValue);
        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("暂未找到相关流程！");
      }
    },
    //初始化请求
    async searchList() {
      if (
        (this.parmValue.platform_time_start !== "" &&
          this.parmValue.platform_time_end === "") ||
        (this.parmValue.platform_time_start === "" &&
          this.parmValue.platform_time_end !== "")
      ) {
        this.$message.warning("平台下单时间区间不完整！");
        return;
      }
      if (
        (this.parmValue.addtime_start !== "" && this.parmValue.addtime_end === "") ||
        (this.parmValue.addtime_start === "" && this.parmValue.addtime_end !== "")
      ) {
        this.$message.warning("导入时间区间不完整！");
        return;
      }

      this.parmValue.platform_code = this.selectValue == "1" ? this.inputValue : "";
      this.parmValue.plat_code = this.selectValue == "2" ? this.inputValue : "";
      this.parmValue.po_code = this.selectValue == "3" ? this.inputValue : "";
      this.parmValue.orderCode = this.selectValue == "4" ? this.inputValue : "";
      this.parmValue.company_name = this.selectValue == "5" ? this.inputValue : "";

      this.loading = true;
      let res = await asyncRequest.orderimportlist(this.parmValue);
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data.list;
        console.log(this.tableData);
        this.pageInfo.total = Number(res.data.count);
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
    //点击批量删除按钮
    batchDel() {
      if (this.changeList.length === 0) {
        this.$message.warning(`请勾选有效数据后在进行删除`);
        return;
      }
      let isok = true,
        ids = [];
      this.changeList.forEach((item) => {
        console.log(item);
        if (item.status === "2" || item.status === "4") {
          ids.push(item.id);
        } else {
          isok = false;
        }
      });
      if (!isok) {
        this.$message.warning(`只能删除待确认和库存不足的订单!`);
        return;
      }
      this.deleteItem(ids);
    },
    //删除
    async deleteItem(ids) {
      await this.$confirm("确定要删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const model = {
            ids,
          };
          const res = await asyncRequest.delimportorder(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 addtime(e) {
      this.parmValue.addtime_start = e.startTime || "";
      this.parmValue.addtime_end = e.endTime || "";
      await this.searchList();
    },
    //平台时间
    async platformTime(e) {
      this.parmValue.platform_time_start = e.startTime || "";
      this.parmValue.platform_time_end = e.endTime || "";
      await this.searchList();
    },

    //批量关联库存规则判断
    selectStockIf() {
      if (this.changeList.length <= 0) {
        this.$message.warning(`请勾选需要关联的商品`);
        return;
      }
      let flag = false;
      try {
        this.changeList.forEach((item, index) => {
          if (item.status == "4") {
            if (item.plat_code == this.changeList[0].plat_code) {
            } else {
              this.$message.warning(`选中的商品平台商品编号不一致`);
              flag = false;
              throw new Error("End Loop");
            }
          } else {
            this.$message.warning(`选中第${index + 1}行状态不是库存不足品`);
            flag = false;
            throw new Error("End Loop");
          }
          flag = true;
        });
      } catch {}
      console.log("判断函数", flag);
      return flag;
    },

    //批量关联库存
    async selectStock() {
      if (!this.selectStockIf()) {
        return;
      }

      let ids = [];
      let plat_code = this.changeList[0].plat_code;
      this.changeList.forEach((item) => {
        ids.push(item.id);
      });
      let model = {
        ids,
        plat_code,
      };
      let res = await asyncRequest.relationstockbatch(model);
      if (res && res.code === 0) {
        console.log(res);
        this.$message.success(res.message);
        this.searchList();
        //成功展示弹窗
        // this.centerDialogVisible = true;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    //重置按钮
    reset() {
      this.select = "1";
      this.inputValue = "";
      this.parmValue = {
        status: "",
        platform_code: "",
        // cs3: "",
        po_code: "",
        plat_code: "",
        // cs6: "",
        platform_time_end: "",
        platform_time_start: "",
        addtime_end: "",
        addtime_start: "",
        company_name: "", //导入人部门
        orderCode: "",
        page: 1,
        size: 15,
      };
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.selectValue = "1";
      this.searchList();
    },
    //刷新按钮
    resetF5() {
      this.searchList();
    },

    //订单导入入口
    entry() {
      this.$router.push("/orderEntry/orderImport");
    },

    //选中触发函数
    selection_change(e) {
      console.log(e);
      const { list } = e;
      //选中的数组集合
      this.changeList = list.length > 0 ? JSON.parse(JSON.stringify(list)) : [];
    },
  },
};
</script>

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