<!--选择店铺商品-->
<template>
  <div>
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      title="商品列表"
      :visible="isShow"
      width="60%"
      @close="cancel"
    >
      <div class="clearfix" style="padding-bottom: 10px">
        <el-input
          v-model="keyword"
          style="width: 240px"
          size="mini"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="pageChange(1)"
          @clear="pageChange(1)"
        >
          <el-button slot="append" @click="pageChange(1)">
            <i class="el-icon-search"></i>
          </el-button>
        </el-input>
      </div>
      <el-table
        ref="goodsTable"
        border
        height="500"
        :data="goods_list"
        size="small"
        @selection-change="selectionChange"
        @row-dblclick="selGoods"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="title" label="商品名称"></el-table-column>
        <el-table-column prop="code" label="商品编码"></el-table-column>
        <el-table-column
          prop="categoryTitle"
          label="商品分类"
        ></el-table-column>
        <el-table-column prop="categoryTitle" label="规格">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              width="300"
              trigger="click"
              @show="showSkuChange(scope.row.id, scope.$index)"
            >
              <div class="sku-view">
                <el-checkbox
                  v-model="scope.row.check_all_spec"
                  @change="checkAllSpecChange($event, scope.$index)"
                >
                  全选
                </el-checkbox>
                <div
                  v-for="(item, index) in scope.row.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, scope.$index)"
                  >
                    {{ item.unitName }}
                  </el-checkbox>
                  <div v-if="item.children" style="padding: 10px 15px 0">
                    <el-checkbox-group
                      v-model="item.spec_check"
                      @change="specCheckChange($event, index, scope.$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>
              </div>
              <el-button slot="reference" size="mini">选择规格</el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="选择商品">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-check"
              @click="selGoods(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <FooterPage
        :page-size="pre_page"
        :total-page.sync="total"
        :current-page.sync="page"
        @pageChange="pageChange"
        @sizeChange="sizeChange"
      ></FooterPage>
      <div
        slot="footer"
        style="width: 100%; border-top: 1px solid #eee; padding-top: 10px"
      >
        <el-button size="small" type="primary" @click="confirm">确定</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getGoodsBasicInfoById,
    getAllGoodsBasic,
    searchBasic,
  } from "@/api/goods";
  export default {
    name: "SelBaseGoods",
    props: {
      isShow: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        keyword: "",
        choose_data: [],
        spec_check_list: [],
        goods_list: [],
        loading: false,
        total: 0,
        pre_page: 10,
        page: 1,
        pageLayout: "total, prev, pager, next",
      };
    },
    created() {
      this.getList();
    },
    methods: {
      // 全选选中切换
      checkAllSpecChange(val, tindex) {
        // console.log(this.goods_list[tindex])
        this.goods_list[tindex].spec_check_list.forEach((item) => {
          item.check_unit_spec = val;
          item.spec_check = val
            ? item.children && item.children.length
              ? item.children.map((itemC) => itemC.id)
              : []
            : [];
        });
      },
      // 单位选择切换
      checkUnitSpecChange(val, index, tindex) {
        const goodsList = this.$_common.deepClone(this.goods_list);
        const target = goodsList[tindex].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;
        goodsList[tindex].check_all_spec = target.every(
          (item) => item.check_unit_spec
        );
        this.goods_list = goodsList;
        this.$refs.goodsTable.toggleRowSelection(this.goods_list[tindex], true);
      },
      // 属性单位切换
      specCheckChange(val, index, tindex) {
        const goodsList = this.$_common.deepClone(this.goods_list);
        const target = goodsList[tindex].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;
        goodsList[tindex].check_all_spec = target.every(
          (item) => item.check_unit_spec
        );
        this.goods_list = goodsList;
        this.$refs.goodsTable.toggleRowSelection(this.goods_list[tindex], true);
      },
      getList() {
        if (this.keyword) {
          this.searchBasic();
        } else {
          this.getAllGoodsBasic();
        }
      },
      async showSkuChange(id, index) {
        if (this.goods_list[index].spec_check_list) {
          return;
        }
        const { data } = await getGoodsBasicInfoById(id, {
          isAddGoods: 5,
        });

        let specCheckList = [];
        if (data.specType === 2) {
          specCheckList = data.unitData.map((item) => {
            return {
              ...item,
              check_all_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 {
          specCheckList = data.specMultiple.map((itemF) => {
            return {
              ...itemF,
              check_all_spec: false,
              spec_check: [],
            };
          });
        }
        this.goods_list[index].spec_check_list = specCheckList;
        this.goods_list[index].specMultiple = data.specMultiple;
        // this.goods_list[index].spec_check = []
        if (this.choose_data.findIndex((item) => item.id === data.id) > -1) {
          this.$refs.goodsTable.toggleRowSelection(
            this.goods_list[index],
            false
          );
          setTimeout(() => {
            this.$refs.goodsTable.toggleRowSelection(
              this.goods_list[index],
              true
            );
          }, 10);
        } else {
          this.$refs.goodsTable.toggleRowSelection(
            this.goods_list[index],
            true
          );
        }
      },
      // 获取列表
      async getAllGoodsBasic() {
        const { data, pageTotal } = await getAllGoodsBasic({
          page: this.page,
          pageSize: this.pageSize,
        });

        for (let i = 0; i < data.length; i++) {
          const isTrue = this.choose_data.find((itemF) => {
            return itemF.id === data[i].id;
          });
          if (isTrue) {
            this.$nextTick(() => {
              data[i] = isTrue;
              this.$refs.goodsTable.toggleRowSelection(data[i], true);
            });
          }
        }
        this.goods_list = data;
        this.total = pageTotal;
      },
      // 搜索引擎 列表
      async searchBasic() {
        const { data, pageTotal } = await searchBasic({
          keyword: this.keyword,
          page: this.page,
          pageSize: this.pageSize,
        });

        for (let i = 0; i < data.length; i++) {
          const isTrue = this.choose_data.find((itemF) => {
            return itemF.id === data[i].id;
          });
          if (isTrue) {
            this.$nextTick(() => {
              this.$refs.goodsTable.toggleRowSelection(data[i], true);
            });
          }
        }
        this.goods_list = data;
        this.total = pageTotal;
      },
      pageChange(page) {
        this.page = page;
        this.getList();
      },
      sizeChange(size) {
        this.pre_page = size;
        this.pageChange(1);
      },
      selectionChange(val) {
        if (!this.choose_data.length) {
          this.choose_data = val;
        } else {
          this.choose_data = this.$_common.unique(
            this.choose_data.concat(val),
            ["id"]
          );
        }
      },
      // 关闭弹窗
      cancel() {
        this.$emit("cancel");
      },
      // 关闭弹窗
      confirm() {
        let isReturn = true;
        for (let i = 0; i < this.choose_data.length; i++) {
          let item = this.choose_data[i];
          if (!item.spec_check_list) {
            this.$message.warning("【" + item.title + "】未选择规格");
            isReturn = false;
            break;
          }
          if (item.specType === 2) {
            let specCheck = [];
            item.spec_check_list.forEach((itemS) => {
              if (itemS.spec_check && itemS.spec_check.length) {
                specCheck.push(itemS.spec_check.join(","));
              }
            });
            if (specCheck.length) {
              item.spec_check = specCheck
                .join(",")
                .split(",")
                .map((itemD) => {
                  return parseInt(itemD);
                });
            } else {
              item.spec_check = [];
            }

            item.skuD = item.spec_check.map((itemD) => {
              let spec = {};
              for (let i in item.spec_check_list) {
                let itemS = item.spec_check_list[i];
                const specD =
                  itemS.children && itemS.children.length
                    ? itemS.children.find((itemC) => itemC.id === itemD)
                    : "";
                if (specD) {
                  spec = specD;
                  break;
                }
              }
              return {
                skuId: itemD,
                spec: spec,
              };
            });
          } else {
            item.skuD = item.spec_check_list
              .filter((itemS) => itemS.check_unit_spec)
              .map((itemM) => {
                return {
                  skuId: itemM.id,
                  spec: itemM,
                };
              });
          }
        }
        if (!isReturn) {
          return;
        }
        this.cancel();
        this.$emit("confirm", this.choose_data);
      },
      selGoods(row) {
        this.cancel();
        this.$emit("confirm", [row]);
      },
    },
  };
</script>

<style scoped></style>
