<template>
  <div class="purchaseOrder pagePadding">
    <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" :gutter="10">
            <el-col :span="4" style="width: 303px; padding: 0 0 0 10px">
              <period-date-picker
                :type="1"
                :width="'135px'"
                :size="searchSize"
                :start_date="timeOBJ.start_date"
                :end_date="timeOBJ.end_date"
                @timeReturned="handleTime"
              />
            </el-col>

            <el-col :span="4">
              <el-input
                size="mini"
                placeholder="报备单号"
                v-model="parmValue.filingCode"
                @blur="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                "
              />
            </el-col>

            <el-col :span="4">
              <el-input
                size="mini"
                placeholder="商品名称"
                v-model="parmValue.good_name"
                @blur="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                "
              />
            </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: 66px; float: right">
              <el-button type="warning" class="fr" :size="searchSize" @click="restSearch">重置</el-button>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="3" class="fr" style="width: 66px; margin-top: 10px">
              <el-button
                v-if="!isSupertube && powers.includes('003')"
                :size="searchSize"
                type="success"
                style="float: right"
                @click="
                  routeGoto('/sellOut/filingDetail', {
                    id: 'add',
                    type: 'add',
                  })
                "
              >添加</el-button>
            </el-col>
            <el-col :span="4" style="margin-top: 15px">
              <search-customer
                size="mini"
                :names="khName"
                :is-detail="type !== 'add'"
                :value="parmValue.companyCode"
                placeholder="客户公司"
                @searchChange="handleCustomerChange"
              />
            </el-col>

            <el-col :span="4" style="margin-top: 15px;margin-left:10px">
              <search-supplier
                :size="'mini'"
                :value="parmValue.supplierNo"
                :disabled="false"
                :placeholder="'供应商名称'"
                :names="parmValue.supplierName"
                :is-detail="true"
                :no-disabled="true"
                @searchChange="supplierChange"
              />
            </el-col>

            <el-col :span="4" style="margin-top: 15px; margin-left: 10px">
              <el-select
                clearable
                size="mini"
                placeholder="状态"
                v-model="parmValue.status"
                @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                "
              >
                <el-option
                  v-for="status in statusOptions"
                  :key="status.value"
                  :value="status.value"
                  :label="status.label"
                />
              </el-select>
            </el-col>
          </el-row>
        </div>
      </template>

      <template #good_img="{ scope }">
        <div v-if="scope.row.good_img" style="width: 20px; height: 20px" class="hover" v-viewer>
          <img
            :src="scope.row.good_img"
            style="display: inline-block; width: 100%; height: 100%"
            alt
          />
        </div>
      </template>

      <template #wsm_has_account="{ scope }">
        <el-tag size="mini">{{Number(scope.row.wsm_has_account) === 1 ? '开通' :'未开通'}}</el-tag>
      </template>

      <template #company="{scope}">
        <div style="display:flex;align-items:center">
          <el-tooltip :content="'企业客户编码 : ' + (scope.row.companyCode || '--')" placement="top">
            <i
              v-if="scope.row.companyName"
              class="el-icon-warning-outline"
              style="margin-right:2px;cursor:pointer"
            />
          </el-tooltip>
          {{scope.row.companyName}}
        </div>
      </template>

      <template #customer="{scope}">
        <div style="display:flex;align-items:center">
          <el-tooltip :content="'业务公司编码 : ' + (scope.row.customerCode || '--')" placement="top">
            <i class="el-icon-warning-outline" style="margin-right:2px;cursor:pointer" />
          </el-tooltip>
          {{scope.row.customerName}}
        </div>
      </template>

      <template #supplier="{scope}">
        <div style="display:flex; align-items:center">
          <el-tooltip :content="'供应商公司编码 : ' + (scope.row.supplierNo || '--')" placement="top">
            <i class="el-icon-warning-outline" style="margin-right:2px;cursor:pointer" />
          </el-tooltip>
          {{scope.row.supplierName}}
        </div>
      </template>

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

      <template #operation="{ scope }">
        <el-tooltip effect="dark" content="详情" placement="top">
          <i class="el-icon-view tb-icon" @click="getRouter('/sellOut/filingDetail', scope.row.id)"></i>
        </el-tooltip>

        <el-tooltip effect="dark" content="修改" placement="top">
          <i
            v-if="String(scope.row.status) === '1' && !isSupertube && powers.includes('005') && Number(scope.row.wsm_has_account) === 0"
            class="el-icon-edit tb-icon"
            @click="getRouter('/sellOut/filingDetail', scope.row.id, 'edit')"
          />
        </el-tooltip>

        <el-tooltip effect="dark" content="取消转单" placement="top">
          <i
            v-if="
              String(scope.row.status) !== '4' 
              && String(scope.row.status) !== '5' 
              && Number(scope.row.wsm_has_account) === 0
              && powers.includes('005')
            "
            class="el-icon-refresh-right tb-icon"
            @click="handleCancel(scope.row.id)"
          ></i>
        </el-tooltip>
      </template>
    </ex-table>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import urlConfig from "@/apis/url-config";
import asyncRequest from "@/apis/service/sellOut/filing";
import { columns, statusOptions } from "./config/columns";
import { cg_order_type_options } from "@/assets/js/statusList";
import { mapGetters } from "vuex";
import companyHelper from "@/mixins/companyHelper";

export default {
  name: "purchaseOrder",
  mixins: [mixinPage, resToken, companyHelper],
  components: {},
  computed: {
    ...mapGetters([
      "business_companyNo",
      "tablebtnSize",
      "isSupertube",
      "searchSize",
      "size"
    ]),
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find(item => item.menu_route == "filing") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    _process() {
      const { roleProcess } = this.$store.getters;
      const tran = roleProcess.find(i => i.process_type === "BBD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    maxNo() {
      return this.business_companyNo;
    }
  },

  watch: {
    maxNo(val, oldval) {
      this.restSearch();
    }
  },
  data() {
    return {
      //入库公司
      supplierName: "",
      cg_order_type_options,
      //入库仓库
      stockName: "",
      changeList: [],
      fileUrl: urlConfig.baseURL,
      sitem: null,
      select: "1",
      input: "",
      timeOBJ: {
        start_date: "", //起始时间
        end_date: "" // 结束时间
      },
      // 状态
      statusOptions: statusOptions,
      loading: false,
      showModel: false,
      isDetail: false,
      modelId: 0,
      wsm_code: [],
      wsm_supplierNo: [],
      parmValue: {
        supplierNo: [],
        companyCode: [],
        start_date: "", //新建起始时间
        end_date: "" // 新建结束时间
      },
      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_date, end_date } = this.parmValue;

      this.pageInfo = {
        size: this.pageInfo.size,
        curr: page,
        total: 0
      };
      //多选条件
      this.select = this.parmValue.select;
    } else {
      this.select = "1";
    }
    this.searchList();
  },

  methods: {
    async handleCancel(id) {
      const { code, message } = await asyncRequest.cancel({ id });
      if (Number(code) === 0) {
        this.searchList();
      } else {
        this.$message.warning(message);
      }
    },
    async supplierChange(e) {
      const { code, label } = e;
      this.parmValue.supplierNo = code ? [code] : [];
      this.searchList();
    },
    getRouter(toRouter, queryId, type) {
      console.log(toRouter, queryId);
      if (toRouter && queryId) {
        let model = {
          id: queryId,
          type
        };

        //有多选框的条件
        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("暂未找到相关流程！");
      }
    },
    async handleCancel(id) {
      const { code, message } = await asyncRequest.cancel({ id });
      if (Number(code) === 0) {
        this.searchList();
      } else {
        this.$message.warning(message);
      }
    },
    //选中触发函数
    selection_change(e) {
      const { list } = e;
      //选中的数组集合
      this.changeList = list.length > 0 ? JSON.parse(JSON.stringify(list)) : [];
    },
    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.select = "1";
      this.input = "";
      this.wsm_code = [];
      this.wsm_supplierNo = [];
      this.timeOBJ = {
        start_date: "", //起始时间
        end_date: "" // 结束时间
      };
      this.parmValue = {
        filingCode: "", // 报备单编码
        wsm_in_code: "", // 入库单号
        cgdNo: "", // 销售订单编码
        apply_name: "", // 申请人
        good_name: "", // 产品名称
        good_code: "", // 产品属性编号
        status: "", //状态
        wsm_code: "", //入货仓库编码
        start_date: "", //新建起始时间
        end_date: "", // 新建结束时间
        last_start_date: "", //最后入库时间开始
        last_end_date: "", //最后入库时间结束
        orderCode: "", //订单编号
        company_name: "", //部门
        page: 1, // 页码
        size: 15 // 每页显示条数
      };
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0
      };
      this.searchList();
    },
    handleCustomerChange(e) {
      this.parmValue.companyCode = e.code ? [e.code] : "";
      this.customerName = e.label;
      this.searchList();
    },
    async searchList() {
      if (this.loading) return;

      if (
        (this.timeOBJ.start_date !== "" && this.timeOBJ.end_date === "") ||
        (this.timeOBJ.start_date === "" && this.timeOBJ.end_date !== "")
      ) {
        this.$message.warning("时间区间不完整！");
        return;
      }

      this.loading = true;

      const res = await asyncRequest.list({
        ...this.parmValue,
        ...this.timeOBJ,
        ...this.pageInfo,
        customerCode: this.currentCompany,
        supplierNo: Array.isArray(this.parmValue.supplierNo)
          ? this.parmValue.supplierNo[0]
          : this.parmValue.supplierNo,
        companyCode: Array.isArray(this.parmValue.companyCode)
          ? this.parmValue.companyCode[0]
          : this.parmValue.companyCode,
        noRelation: true
      });
      const { code, data } = await this.useResHandle(res);
      if (code === 0) {
        const { list, count } = data;
        this.tableData = list;
        this.pageInfo.total = Number(count);
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
    // 时间
    async handleTime(e) {
      this.timeOBJ.start_date = e?.startTime ?? "";
      this.timeOBJ.end_date = e?.endTime ?? "";

      if (e.startTime && e.endTime) {
        this.pageInfo.curr = 1;
        this.parmValue.page = 1;
        this.searchList();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.purchaseOrder {
  // text-align: right;
}
</style>
