<template>
  <el-dialog
    v-loading="loading"
    :title="'选择商品'"
    :center="true"
    align="left"
    top="8vh"
    width="1040px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px" class="modal-form-style">
      <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="{ selection }">
          <div style="width: 100%">
            <el-row style="padding: 0 0 10px 0; margin: -5px 0 0 0">
              <el-col :span="6" style="width: 363px">
                <good-class
                  :value="parmValue.cat_id"
                  :disabled="false"
                  :size="searchSize"
                  :is-detail="false"
                  :placeholder="'分类'"
                  @handleChange="goods_class_change"
                />
              </el-col>
              <el-col :span="4" style="width: 228px; padding: 0 0 0 10px">
                <search-brand
                  :value="parmValue.brandid"
                  :disabled="false"
                  :size="'mini'"
                  :is-detail="false"
                  :names="''"
                  :placeholder="'品牌'"
                  @searchChange="brandidsearchChange"
                />
              </el-col>
              <el-col :span="4" style="width: 145px; padding: 0 0 0 10px">
                <el-select
                  v-model="parmValue.good_type"
                  filterable
                  clearable
                  :size="searchSize"
                  placeholder="是否定制"
                  style="width: 100%"
                  @change="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-option
                    v-for="item in options1"
                    :key="'good_type' + item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-col>
              <el-col :span="3" class="fr" style="width: 66px; padding: 0 0 0 10px">
                <el-button type="primary" :size="searchSize" @click="searchList">刷新</el-button>
              </el-col>
              <el-col :span="3" class="fr" style="width: 66px; padding: 0 0 0 10px">
                <el-button type="warning" :size="searchSize" @click="restSearch">重置</el-button>
              </el-col>
            </el-row>
            <el-row style="padding: 0 0 0 0">
              <el-col :span="4" style="width: 518px">
                <el-input
                  v-model="sinput"
                  :size="searchSize"
                  :maxlength="40"
                  clearable
                  placeholder="关键字"
                  @blur="
                    pageInfo.curr = 1;
                    parmValue.page = 1;
                    searchList();
                  "
                >
                  <el-select
                    slot="prepend"
                    v-model="select"
                    style="width: 135px"
                    placeholder="关键字类型"
                  >
                    <el-option label="商品编号" value="1" />
                    <el-option label="商品名称" value="2" />
                    <el-option label="业务公司名称" value="3" />
                    <el-option label="供应商名称" value="4" />
                  </el-select>
                </el-input>
              </el-col>
              <!-- <el-col :span="3" style="margin-left:10px">
                <el-select placeholder="来源" clearable size="mini" style="width:100%" v-model="parmValue.create_source" @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="3" class="fr" style="width: 66px; padding: 0 0 0 10px">
                <el-button type="success" :size="searchSize" @click="resultList(selection)">保存</el-button>
              </el-col>
            </el-row>
          </div>
        </template>

        <template #create_source="{ scope }">
        <el-tag size="mini" :type="scope.row.create_source === '1' ? 'warning' : ''">
          {{ scope.row.create_source === "1" ? "咨询成交商品" : "手动创建商品" }}
        </el-tag>
      </template>

        <template #good_thumb_img="{ scope }">
          <div
            v-if="scope.row.good_thumb_img"
            v-viewer
            style="width: 20px; height: 20px"
            class="hover"
          >
            <img
              :src="scope.row.good_thumb_img"
              style="display: inline-block; width: 100%; height: 100%"
              alt
            />
          </div>
        </template>
        <template #good_type="{ scope }">
          <el-tag
            :size="tablebtnSize"
            :type="scope.row.good_type == '0' ? 'warning' : ''"
            v-text="
              (options1.find((item) => item.id == scope.row.good_type) || {}).name || '--'
            "
          />
        </template>
      </ex-table>
    </el-card>
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/components/search-good-modal";
import resToken from "@/mixins/resToken";
import mixinPage from "@/mixins/elPaginationHandle";
import { mapGetters } from "vuex";
import columns from "./columns";
export default {
  name: "SearchGoodModal",
  mixins: [resToken, mixinPage],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"])
  },
  props: [
    "showModel",
    "once",
    "isonline",
    "is_stock",
    "isNoble",
    "isConsult",
    "checkType",
    "is_combind"
  ],

  /**
   * 属性集合
   * @param {Boolean}       showModel             : 是否弹出弹窗        必填
   * @param {Boolean}       once                  : 是否只选一条        非必填
   */
  /**
   * 事件集合
   * @resultList             : 选中值变化调用   抛出选中数据
   */
  data() {
    return {
      options1: [
        { id: "0", name: "否" },
        { id: "1", name: "是" }
      ],
      sinput: "",
      select: "1",
      options: [],
      selectLoading: false,
      searchName: "",
      supplierCode: [],
      loading: true,
      showModelThis: false,
      parmValue: {
        create_source:"",
        type_code: "", // 是否定制
        supplierNo: "", // 供应商code
        cat_id: [],
        brandid: [],
        spucode: "", // 商品编码
        good_name: "", // 商品名称
        status: "1", //
        company: "",
        supplier: "",
        isonline: "",
        is_stock: "",
        page: 1, // 页码
        size: 15 // 每页显示条数
      },
      tableData: [],
      passwordModel: false,
      passwordModelId: 0,
      isPasswordDetail: false,
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true
        // _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0
      },
      // 表格 - 列参数
      columns: columns
    };
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val;
      if (val) {
        // this.supplierCode = [];
        this.restSearch();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    }
  },

  methods: {
    // supplierChange(e) {
    //   if (e && e.length === 1) {
    //     this.parmValue.supplierNo = e[0];
    //   } else {
    //     this.parmValue.supplierNo = "";
    //   }
    //   this.parmValue.page = 1;
    //   this.searchList();
    // },
    restSearch() {
      this.sinput = "";
      this.select = "1";
      // this.supplierCode = [];
      this.parmValue = {
        create_source:"",
        type_code: "", // 是否定制
        supplierNo: "", // 供应商code
        spucode: "", // 商品编码
        cat_id: [],
        brandid: [],
        good_name: "", // 商品名称
        status: "1", //
        is_stock: "",
        company: "",
        supplier: "",
        isonline: "",
        page: 1, // 页码
        size: 15 // 每页显示条数
      };
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0
      };
      this.searchList();
    },
    async goods_class_change(e) {
      this.parmValue.cat_id = e;
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },
    async brandidsearchChange(e) {
      const { id } = e;
      this.parmValue.brandid = id ? [id] : [];
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },
    async searchList() {
      this.loading = true;
      this.parmValue.spucode = this.select === "1" ? this.sinput : "";
      this.parmValue.good_name = this.select === "2" ? this.sinput : "";
      this.parmValue.company = this.select === "3" ? this.sinput : "";
      this.parmValue.supplier = this.select === "4" ? this.sinput : "";
      this.parmValue.isonline = this.isonline || "";
      this.parmValue.is_stock = this.is_stock || "";

      console.log(this.is_combind, "---");

      if (this.is_combind) {
        this.parmValue.is_combind = this.is_combind;
      }

      const model = JSON.parse(JSON.stringify(this.parmValue));
      model.cat_id =
        model.cat_id.length > 0 ? model.cat_id[model.cat_id.length - 1] : "";
      model.brandid =
        model.brandid.length > 0 ? model.brandid[model.brandid.length - 1] : "";

      const res = await asyncRequest.list(model);
      if (res && res.code === 0 && res.data) {
        this.tableData = res.data.list;
        this.tableData.forEach(a => {
          a.cat_name = "";
          const list = a.cat_info || [];
          list.forEach((b, i) => {
            a.cat_name += i == 0 ? b.name : "/" + b.name;
          });
        });
        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 remoteMethod(query) {
      this.selectLoading = true;
      if (query !== "") {
        this.options = [];
        const formValue = {
          page: 1,
          size: 100,
          name: query,
          code: ""
        };

        const res = await asyncRequest.supplierList(formValue);
        if (res && res.code === 0 && res.data) {
          const { list } = res.data;
          this.options = list;
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } else {
        this.options = [];
      }
      this.selectLoading = false;
    },
    createWarningMessage$1(_f,_s){
      const h = this.$createElement;
        this.$message({
          message: h("p", null, [
            h("span", null, "勾选商品必须全部为"),
            h("i", { style: "color: red" }, _f),
            h("span", null, "或者全部为"),
            h( "i", { style: "color: red" },  _s)
          ]),
          type: "warning",
          dangerouslyUseHTMLString: true
        });
    },
    createWarningMessage$2(_f, _s){
      const h = this.$createElement;
      this.$message({
            message: h("p", null, [
              h("span", null, "如需添加"),
              h("i", { style: "color: red" }, _f),
              h("span", null, "请将已添加的所有"),
              h( "i",{ style: "color: red" }, _s),
              h("span", null, "删除!")
            ]),
            type: "warning",
            dangerouslyUseHTMLString: true
          });
    },
    getAllGoods(selection){
      return selection.map(({ cat_info, is_gold_price ,create_source}) => ({
          create_source,
          id: String(cat_info[0].id),
          isGoldPrice: String(is_gold_price)
        })
      );
    },
    async resultList(selection) {
        if (selection && selection.length > 1 && this.once) {
          this.$message.warning("只能选择一条商品信息！");
          return;
        }

        let isNoble = null;
        let isConsult = null;
        if (this.checkType) {
          const allGoods = this.getAllGoods(selection);
          if (allGoods.length === 0) {
          this.$message.warning("至少选择一个商品！");
          return;
        }

        if (allGoods.length > 100) {
          this.$message.warning("商品数量不能超过100！");
          return;
        }

        // 咨询成交id集合
        const consultList = allGoods.filter(({create_source}) => create_source === "1")
        // 不是全部为咨询成交商品或手动创建商品
        if(consultList.length > 0 && allGoods.length !== consultList.length){
          this.createWarningMessage$1("咨询成交商品", "手动创建商品")
          return
        }
        // 本次添加是否全部为咨询商品..
        isConsult = consultList.length > 0 && allGoods.length === consultList.length

        //本次添加全部为咨询商品,上次添加为手动创建商品
        if(isConsult && !this.isConsult && this.isConsult !== null){
          this.createWarningMessage$2("咨询成交商品", "手动创建商品")
          return;
        }

        //本次添加全部为手动创建商品,上次添加咨询商品
        if(!isConsult && this.isConsult && this.isConsult !== null){
          this.createWarningMessage$2("手动创建商品","咨询成交商品")
          return
        }
        // 到这里不是初始化就是全部为咨询商品或者全部为手动创建的商品,区分出来,手动创建商品需要判断贵金属
        if(!this.isConsult && !isConsult){
          // 手动创建商品,走是否贵金属校验...
          const nobleMetalIds = allGoods.filter(({ id, isGoldPrice }) => id === "6" && isGoldPrice === "1");
          // 当前勾选商品中有贵金属和非贵金属
          if (nobleMetalIds.length > 0 && allGoods.length !== nobleMetalIds.length ) {
            this. createWarningMessage$1("开启实时金价贵金属商品", "未开启实时金价的贵金属商品和非贵金属商品");
            return;
          }
          // 本次添加的是否全部为贵金属....
          isNoble = nobleMetalIds.length > 0 &&  allGoods.length === nobleMetalIds.length;
          //上次添加的不是贵金属商品，且本次添加的是贵金属商品
          if (isNoble && !this.isNoble && this.isNoble !== null) {
            this.createWarningMessage$2("开启实时金价贵金属商品", "未开启实时金价的贵金属商品和非贵金属商品")
            return;
          }
          //上次添加的是贵金属商品，且本次添加不是贵金属商品
          if (!isNoble && this.isNoble && this.isNoble !== null) {
            this.createWarningMessage$2("未开启实时金价的贵金属商品和非贵金属商品","开启实时金价贵金属商品")
            return;
          }
        }
      }

      this.showModelThis = false;
      //本次添加是否贵金属和是否咨询商品传递出去，下次传入作为上次添加的结果判断条件
      this.$emit("resultList", selection, {isNoble,  isConsult });
    }
  }
};
</script>

<style></style>
