<!--拼音筛选-->
<template>
  <div class="out-div">
    <el-select
      :size="size"
      style="width: 100%"
      :value="value"
      filterable
      remote
      reserve-keyword
      :disabled="disabled"
      placeholder="请输入关键词首字母"
      :remote-method="remoteMethod"
      :loading="select_loading"
      @change="selectSelGoods"
      @visible-change="goodsVisibleChange"
    >
      <el-option
        v-for="(item, index) in goods_options"
        :key="index"
        :label="item.title"
        :value="item.id"
      ></el-option>
    </el-select>
    <span class="el-icon-search sel-icon" @click="openGoodsModel"></span>
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      style="text-align: left"
      title="选择属性"
      :visible.sync="spec_model"
      width="40%"
    >
      <!--       :indeterminate="is_spec_indeterminate"-->
      <el-checkbox v-model="check_all_spec" @change="checkAllSpecChange">
        全选
      </el-checkbox>
      <div
        v-for="(item, index) in spec_check_list"
        :key="index"
        style="padding: 10px; border: 1px solid #eee; margin: 10px 0"
      >
        <el-checkbox
          v-model="item.check_unit_spec"
          :indeterminate="item.is_spec_indeterminate"
          @change="checkUnitSpecChange($event, index)"
        >
          {{ item.unitName }}
        </el-checkbox>
        <div style="padding: 10px 15px 0">
          <el-checkbox-group
            v-model="item.spec_check"
            @change="specCheckChange($event, index)"
          >
            <el-checkbox
              v-for="(itemC, indexC) in item.children"
              :key="indexC"
              style="padding-bottom: 5px"
              :label="itemC.id"
            >
              <span style="font-weight: 400">{{ itemC.specGropName }}</span>
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="spec_model = false">取 消</el-button>
        <el-button type="primary" @click="specSelConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <SaleGoodsSel
      v-if="show_goods"
      :merchant-id="merchantId"
      :base-goods="type"
      :is-show="show_goods"
      :user-center-id="userCenterId"
      :is-reveal-sku="4"
      :is-eq-master="isEqMaster"
      :is-purchase="isPurchase"
      :shop-id="shopId"
      @cancel="show_goods = false"
      @confirm="selGoods"
    ></SaleGoodsSel>
  </div>
</template>

<script>
  import {
    getGoodsByCondition,
    getGoodsInfo,
    getGoodsBasicInfoById,
  } from "@/api/goods";
  import SaleGoodsSel from "@/component/goods/SaleGoodsSel.vue";
  export default {
    name: "ConditionSelGoods",
    components: {
      SaleGoodsSel,
    },
    model: {
      prop: "value",
      event: "change",
    },
    props: {
      // 商户id
      merchantId: {
        type: [Number, String],
        default: "",
      },
      type: {
        type: Boolean,
        // false 查询商品。true 查询商品资料
        default: false,
      },
      // 当前使用组件的页面是否是采购页面
      isPurchase: {
        type: Boolean,
        default: false,
      },
      // 当前使用组件的页面是否可以选择主单位
      isEqMaster: {
        type: Boolean,
        default: true,
      },
      isAddGoods: {
        type: [Number, String],
        default: 5,
      },
      userCenterId: {
        type: [Number, String],
        default: "",
      },
      shopId: {
        type: [Number, String, Array],
        default: "",
      },
      enableStatus: {
        type: [Number, String],
        default: "",
      },
      value: {
        type: String,
        default: "",
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      specCheck: {
        type: Array,
        default: () => {
          return [];
        },
      },
      // 5 只显示基本单位 4:主辅助单位都显示
      isRevealSku: {
        type: [Number, String],
        default: 4,
      },
      // 5 只显示基本单位 4:主辅助单位都显示
      size: {
        type: String,
        default: "small",
      },
    },
    data() {
      return {
        goodsName: "",
        goods_options: [],
        show_goods: false,
        select_loading: false,
        // 弹窗
        spec_model: false,
        check_all_spec: false,
        is_spec_indeterminate: false,
        spec_check: [],
        spec_check_list: [],
        now_goods_data: {},
      };
    },
    watch: {
      specCheck(Nval) {
        this.spec_check = Nval;
      },
    },
    mounted() {
      console.log(this.isPurchase);
    },
    methods: {
      openGoodsModel() {
        if (this.disabled) return;
        this.show_goods = true;
      },
      async remoteMethod(keyword) {
        if (!keyword) {
          this.goods_options = [];
          return;
        }
        let params = {
          condition: keyword,
          type: this.type,
          enableStatus: this.enableStatus,
        };
        if (this.shopId) {
          params.shopId = Array.isArray(this.shopId)
            ? this.shopId
            : [this.shopId];
        }
        if (this.merchantId) {
          params.merchantId = this.merchantId;
        }
        this.select_loading = true;
        const { data } = await getGoodsByCondition(params);
        this.select_loading = false;
        if (JSON.stringify(data) === "{}") {
          this.goods_options = [];
        } else {
          this.goods_options = data;
        }
      },
      goodsVisibleChange(val) {
        this.$emit("goodsVisibleChange", val);
      },
      selectSelGoods(val) {
        this.$emit("selectSelGoods", val);
        this.check_all_spec = false;
        if (!this.type) {
          this.getGoodsInfo(val);
        } else {
          this.getGoodsBasicInfoById(val);
        }
      },
      // 商品详情
      async getGoodsInfo(val) {
        // userCenterId: this.userCenterId
        const { data } = await getGoodsInfo(val, {
          userCenterId: this.userCenterId,
        });

        this.now_goods_data = data;
        this.spec_model = true;
        if (data.specType === 2) {
          this.spec_check_list = data.unitData.map((item) => {
            return {
              ...item,
              is_spec_indeterminate: false,
              check_unit_spec: false,
              spec_check: [],
              children: data.specMultiple
                .filter((itemF) => itemF.unitId === item.unitId)
                .map((itemP) => {
                  return {
                    ...itemP,
                    specGropName: itemP.specGroup
                      .map((itemS) => {
                        return itemS.specValueName;
                      })
                      .join("_"),
                  };
                }),
            };
          });
        } else {
          this.spec_check_list = data.specMultiple.map((itemF) => {
            return {
              ...itemF,
              is_spec_indeterminate: false,
              check_unit_spec: false,
              spec_check: [],
            };
          });
        }
        if (
          this.spec_check_list.length === 1 &&
          !this.spec_check_list[0].children
        ) {
          this.spec_model = false;
          this.$emit("specSelConfirm", {
            goodsD: [
              {
                skuId: this.spec_check_list[0].id,
                spec: this.spec_check_list[0],
              },
            ],
            spec_check_list: this.spec_check_list,
            now_goods_data: this.now_goods_data,
          });
        } else if (
          this.spec_check_list.length === 1 &&
          this.spec_check_list[0].children.length === 1
        ) {
          this.spec_model = false;
          this.$emit("specSelConfirm", {
            goodsD: [
              {
                skuId: this.spec_check_list[0].children[0].id,
                spec: this.spec_check_list[0].children[0],
              },
            ],
            spec_check_list: this.spec_check_list,
            now_goods_data: this.now_goods_data,
          });
        }
      },
      // 商品基础资料详情
      async getGoodsBasicInfoById(val) {
        const { data } = await getGoodsBasicInfoById(val, {
          isAddGoods: this.isAddGoods,
        });

        this.now_goods_data = data;
        this.spec_model = true;
        if (data.specType === 2) {
          this.spec_check_list = data.unitData.map((item) => {
            return {
              ...item,
              is_spec_indeterminate: false,
              check_unit_spec: false,
              spec_check: [],
              children: data.specMultiple
                .filter((itemF) => itemF.unitId === item.unitId)
                .map((itemP) => {
                  return {
                    ...itemP,
                    specGropName: itemP.specGroup
                      .map((itemS) => {
                        return itemS.specValueName;
                      })
                      .join("_"),
                  };
                }),
            };
          });
        } else {
          this.spec_check_list = data.specMultiple.map((itemF) => {
            return {
              ...itemF,
              is_spec_indeterminate: false,
              check_unit_spec: false,
              spec_check: [],
            };
          });
        }
        // 抄码商品 不允许采购辅助单位
        if (this.isPurchase && data.isEq === 5) {
          this.spec_check_list = this.spec_check_list.filter(
            (item) => item.isMaster === 5
          );
        }
      },
      specSelConfirm() {
        let specCheck = [];
        let goodsD = [];
        if (this.now_goods_data.specType === 2) {
          this.spec_check_list.forEach((item) => {
            if (item.spec_check && item.spec_check.length) {
              specCheck.push(item.spec_check.join(","));
            }
          });
          this.spec_check = specCheck
            .join(",")
            .split(",")
            .map((item) => {
              return parseInt(item);
            });
          goodsD = this.spec_check.map((item) => {
            let spec = {};
            for (let i in this.spec_check_list) {
              let itemS = this.spec_check_list[i];
              const specD =
                itemS.children && itemS.children.length
                  ? itemS.children.find((itemC) => itemC.id === item)
                  : "";
              if (specD) {
                spec = specD;
                break;
              }
            }
            return {
              skuId: item,
              spec: spec,
            };
          });
        } else {
          goodsD = this.spec_check_list
            .filter((item) => item.check_unit_spec)
            .map((itemM) => {
              return {
                skuId: itemM.id,
                spec: itemM,
              };
            });
        }
        this.$emit("specSelConfirm", {
          goodsD: goodsD,
          spec_check_list: this.spec_check_list,
          now_goods_data: this.now_goods_data,
        });
        this.spec_model = false;
      },
      specCheckChange(val, index) {
        const target = this.$_common.deepClone(this.spec_check_list);
        let checkedCount = val.length;
        target[index].check_unit_spec =
          checkedCount === target[index].children.length;
        target[index].is_spec_indeterminate =
          checkedCount > 0 && checkedCount < target[index].children.length;
        this.spec_check_list = target;
        this.check_all_spec = this.spec_check_list.every(
          (item) => item.check_unit_spec
        );
      },
      checkAllSpecChange(val) {
        this.spec_check_list.forEach((item) => {
          item.check_unit_spec = val;
          item.is_spec_indeterminate = false;
          item.spec_check = val
            ? item.children && item.children.length
              ? item.children.map((itemC) => itemC.id)
              : []
            : [];
        });
        this.is_spec_indeterminate = false;
      },
      checkUnitSpecChange(val, index) {
        const target = this.$_common.deepClone(this.spec_check_list);
        target[index].spec_check = val
          ? target[index].children && target[index].children.length
            ? target[index].children.map((item) => item.id)
            : []
          : [];
        target[index].is_spec_indeterminate = false;
        this.spec_check_list = target;
        this.check_all_spec = this.spec_check_list.every(
          (item) => item.check_unit_spec
        );
      },
      selGoods(val) {
        console.log(val);
        this.$emit("selGoods", val);
      },
    },
  };
</script>

<style scoped lang="scss">
  .out-div {
    position: relative;
    .sel-icon {
      position: absolute;
      display: block;
      right: 5px;
      top: 50%;
      width: 25px;
      text-align: center;
      transform: translateY(-50%);
      color: #c0c4cc;
      font-size: 13px;
      cursor: pointer;
    }
  }
</style>
