<!--  -->
<template>
  <div>
    <save-form
      :inline="true"
      class="searchForm"
      ref="searchForm"
      @submit="onSearch"
      @reset="onReset"
      :model="searchForm"
      save-key="subShopGoods"
    >
      <el-form-item prop="keyword">
        <el-input
          v-model.trim="searchForm.keyword"
          clearable
          placeholder="商品名称"
        ></el-input>
      </el-form-item>
      <el-form-item prop="productSn">
        <el-input
          v-model.trim="searchForm.productSn"
          clearable
          placeholder="商品货号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="productCategoryId">
        <!-- <el-select
          v-model.trim="searchForm.productCategoryId"
          clearable
          placeholder="商品分类"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
        <el-cascader
          v-model.trim="searchForm.productCategoryId"
          :options="categoryList"
          placeholder="商品分类"
          :props="{ expandTrigger: 'hover' }"
        ></el-cascader>
        <!-- checkStrictly: true, -->
      </el-form-item>
      <el-form-item prop="brandId">
        <el-select
          v-model.trim="searchForm.brandId"
          clearable
          placeholder="商品品牌"
        >
          <el-option
            v-for="(item, index) in goodsBrand"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="publishStatus">
        <el-select
          v-model.trim="searchForm.publishStatus"
          clearable
          placeholder="上架状态"
        >
          <el-option label="上架" :value="1"></el-option>
          <el-option label="下架" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" native-type="submit">搜索</el-button>
        <el-button type="primary" native-type="reset">重置</el-button>
      </el-form-item>
    </save-form>
    <div class="tableWrap">
      <el-table
        :data="tableList"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        @selection-change="handleSelectionChange"
        @select="onTableSelect"
        ref="multipleSelection"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="onSelectable"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="商品名称"
          width="200px"
        >
          <template slot-scope="scope">
            <tooltip :content="scope.row.name" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productSn" label="商品货号">
        </el-table-column>
        <el-table-column align="center" prop="brandName" label="品牌">
        </el-table-column>
        <el-table-column align="center" prop="skuCode" label="sku编号">
        </el-table-column>
        <el-table-column align="center" prop="price" label="销售价格">
        </el-table-column>
        <el-table-column align="center" prop="stock" label="剩余库存">
        </el-table-column>
        <!-- <el-table-column align="center" prop="price" label="采购价">
        </el-table-column> -->
        <el-table-column align="center" prop="publishStatus" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.publishStatus == 1 ? '' : 'danger'">
              {{ scope.row.publishStatus ? "上架" : "下架" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        sync
        save-key="subShopGoods"
        :total.sync="pageInfo.total"
        :page.sync="pageInfo.page"
        :limit.sync="pageInfo.limit"
        :page-sizes="pageInfo.page_size"
        @pagination="getList"
      />
    </div>
    <div class="dialog-footer">
      <el-button @click="onClose()">取 消</el-button>
      <el-button type="primary" @click="onSubmit()">确 定</el-button>
    </div>
  </div>
</template>

<script>
import pagination from "@/components/Pagination/index";
import {
  api_queryGoodsSubByPage,
  api_queryGoodsCategoryList
} from "@/api/businessManager";
export default {
  props: ["disabledIds", "goodsBrand"],
  components: {
    pagination
  },
  data() {
    return {
      categoryList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      searchForm: {
        keyword: null,
        productSn: null,
        publishStatus: null,
        productCategoryId: null,
        brandId: null
      },
      tableList: [],
      isNewPage: false,
      selectList: []
    };
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.__init();
    this.getList();
  },
  methods: {
    async __init() {
      let params = {
        delFlag: 0,
        rows: 9999
      };
      try {
        const { data } = await api_queryGoodsCategoryList(params);
        const result = data || [];
        let tempArray = [];
        result.forEach(row => {
          let children = [];
          if (row.children && row.children.length > 0) {
            row.children.forEach(child => {
              children.push({
                label: child.name,
                value: child.id
              });
            });
          }
          tempArray.push({
            label: row.name,
            value: row.id,
            children
          });
        });
        this.categoryList = tempArray;
      } catch {}
    },
    getList() {
      let params = Object.assign({}, this.searchForm);
      // params.organId = this.organId;
      params.rows = this.pageInfo.limit;
      params.page = this.pageInfo.page;
      params.productCategoryId = params.productCategoryId
        ? params.productCategoryId[params.productCategoryId.length - 1]
        : null;
      api_queryGoodsSubByPage(params).then(res => {
        if (res.code == 200 && res.data) {
          this.tableList = res.data.rows;
          this.pageInfo.total = res.data.total;

          let idList = this.selectList.map(group => {
            return group.skuStockId;
          });
          this.isNewPage = true;
          this.$nextTick(() => {
            this.tableList.forEach(course => {
              if (idList.indexOf(course.skuStockId) != -1) {
                this.$refs.multipleSelection.toggleRowSelection(course, true);
              }
            });
            this.isNewPage = false;
          });
        }
      });
    },
    onSearch() {
      this.pageInfo.page = 1;
      this.getList();
    },
    onReset() {
      // 重置
      this.$refs.searchForm.resetFields();
      this.getList();
    },
    onClose() {
      this.$listeners.close();
    },
    onSubmit() {
      this.$listeners.comfirm(this.selectList);
      this.onClose();
    },
    onSelectable(row) {
      return !this.disabledIds.includes(row.skuStockId);
    },
    handleSelectionChange(arr) {
      if (arr.length > 0) {
        // 有可能加 有可能减
        this.selectList = this.selectList.concat(arr);
        // 去重
        this.selectList = this.$helpers.lodash.uniqBy(
          this.selectList,
          "skuStockId"
        );
      }
      // else if(){}
      else {
        if (this.isNewPage) return;
        // 有2种 1是新页
        // 2是点击反选
        let idList = this.selectList.map(course => {
          return course.skuStockId;
        });
        this.$nextTick(() => {
          let tableIdList = [];
          this.tableList.forEach(course => {
            tableIdList.push(course.skuStockId);
            if (idList.indexOf(course.skuStockId) != -1) {
              this.$refs.tableList.toggleRowSelection(course, false);
              // 删除这个元素
            }
          });
          this.selectList = this.$helpers.lodash.remove(
            this.selectList,
            function(item) {
              return tableIdList.indexOf(item.skuStockId) == -1;
            }
          );
          if (this.selectList.length <= 0) {
            this.clearCom();
          }
        });
      }
    },
    onTableSelect(rows, row) {
      let idList = this.selectList.map(course => {
        return course.skuStockId;
      });
      if (idList.indexOf(row.skuStockId) != -1) {
        this.selectList.splice(idList.indexOf(row.skuStockId), 1);
        if (this.selectList.length <= 0) {
          this.clearCom();
        }
      }
    },
    clearCom() {
      // this.selectList = [];
      // this.$refs.multipleSelection.clearSelection();
    }
  }
};
</script>
<style lang="less" scoped>
.dialog-footer {
  padding-top: 20px;
  width: 100%;
  text-align: center;
}
</style>
