<template>
  <div class="goodsResourceSelectorContainer">
    <span class="option" @click="select(item.id)" v-for="(item, index) in options" :key="index" :class="{selected: item.id == dataValue.type}">
      {{item.label}} 
    </span>
    <div v-if="dataValue.type == 'category'">
      <Button type="primary" @click="add">选择品类</Button>
    </div>
    <div v-if="dataValue.type == 'brand'">
      <Button type="primary" @click="add">选择品牌</Button>
    </div>
    <Modal v-model="showModal" :mask-closable="false" :title="modalTitle" width="600">
        <div v-if="dataValue.type == 'category'">
          <div class="search">
            <Form class="searchFormStyle" inline>
                <FormItem label="类目名称" prop="name">
                  <Input v-model="searchParams.name" placeholder="" />
                </FormItem>
                <FormItem label="类目编码" prop="name">
                  <Input v-model="searchParams.sceneId" placeholder="" />
                </FormItem>
                <Button type="primary" @click="searchList">查询</Button>
            </Form>
          </div>
          <Table
            @on-select="selectItem"
            @on-select-cancel="cancelSelectItem"
            :columns="tableColumn"
            :data="tableData"
            class="tableStyle"
            height="600"
            :loading="loading"
          />
          <Page class="page" :total="total" @on-change="changePageNo" show-total></Page>
        </div>
        <div v-if="dataValue.type == 'brand'">
          <div class="search">
            <Form class="searchFormStyle" inline>
              <FormItem label="品牌名称" prop="name">
                <Input v-model="searchParams.name" placeholder="" />
              </FormItem>
              <FormItem label="品牌编码" prop="name">
                <Input v-model="searchParams.sceneId" placeholder="" />
              </FormItem>
              <Button type="primary" @click="searchList">查询</Button>
            </Form>
          </div>
          <Table
            @on-select="selectItem"
            @on-select-cancel="cancelSelectItem"
            :columns="tableColumn"
            :data="tableData"
            class="tableStyle"
            height="600"
            :loading="loading"
          />
          <Page class="page" :total="total" @on-change="changePageNo" show-total></Page>
        </div>
        <div slot="footer">
          <Button @click="showModal = false">取消</Button>
          <Button type="primary" @click="submitSelect">确认</Button>
        </div>
     </Modal>
  </div>
</template>
<script>
import operationApi from '@api/operation.api';
const categoryCol = function() {
  return [
    {
      type: 'selection',
      width: 60,
      align: 'center'
    },
    {
      align: 'center',
      title: '类目名称',
      key: 'categoryName',
    },
    {
      align: 'center',
      title: '类目编码',
      key: 'sceneId',
      width: 180
    },
  ]
}
const brandCol = function() {
  return [
    {
      type: 'selection',
      width: 60,
      align: 'center'
    },
    {
      align: 'center',
      title: '品牌名称',
      key: 'brandName',
    },
    {
      align: 'center',
      title: '品牌编码',
      key: 'sceneId',
      width: 120
    },
    {
      align: 'center',
      title: 'logo',
      render: (h, params) => {
        const row = params.row;
        return h('div', {
          style: {
            padding: '5px 0'
          }
        }, [
            h('img', {
              attrs: {
                src: row.imgUrl,
                width: 80,
                height: 80
              },
            })
          ]
        )
      },
      width: 200
    }
  ]
}
export default {
  props: {
    value: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  computed: {
    modalTitle() {
      return this.dataValue.type === 'category' ? '选择品类' : '选择品牌'
    }
  },
  watch: {
    value(val) {
      console.log(val, '122')
      this.dataValue = val;
    },
    dataValue: {
      deep: true,
      handler(val) {
        this.$emit('input', val);  
      }
    }
  },
  methods: {
    submitSelect() {
      // 提交选择
      const targetKey = this.dataValue.type === 'category' ? 'categoryId' : 'brandId';
      this.dataValue[targetKey] = this.dataValue.type === 'category' ? this.selectCategoryCollect.join() : this.selectBrandCollect.join();
      this.dataValue.type === 'category' ? this.dataValue.brandId = '' : this.dataValue.categoryId = ''; // 清空非当前选项的id数据
      this.showModal = false;
    },
    selectItem(arr, item) {
      // 选择某一项
      if (this.dataValue.type == 'category') {
        this.selectCategoryCollect.push(String(item.sceneId));
        console.log(this.selectCategoryCollect);
      }
      if (this.dataValue.type == 'brand') {
        this.selectBrandCollect.push(String(item.sceneId));
        console.log(this.selectBrandCollect);
      }
    },
    cancelSelectItem(arr, item) {
      // 取消选择某一项
      if (this.dataValue.type == 'category') {
        this.selectCategoryCollect.splice(this.selectCategoryCollect.indexOf(item.sceneId), 1)
        console.log(this.selectCategoryCollect);
      }
      if (this.dataValue.type == 'brand') {
        this.selectBrandCollect.splice(this.selectBrandCollect.indexOf(item.sceneId), 1)
        console.log(this.selectBrandCollect);
      }
    },
    add() {
      this.showModal = true;
      this.getData();
    },
    select(type) {
      if (type == this.dataValue.type) return;
      this.dataValue = {
        type, 
        brandId: '',
        categoryId: '',
      }
      this.selectCategoryCollect = [];
      this.selectBrandCollect = [];
    },
    changePageNo(val) {
      this.searchParams.pageNo = val;
      this.getData();
    },
    searchList() {
      this.searchParams.pageNo = 1;
      this.searchParams.pageSize = 10;
      this.getData();
    },
    async getData() {
      let res;
      this.loading = true;
      this.tableData = [];
      this.tableColumn = this.dataValue.type == 'category' ? categoryCol.bind(this)() : brandCol.bind(this)();
      try {
        if (this.dataValue.type == 'category') {
          // 品类
          res = await operationApi.getCategoryAndPriority({...this.searchParams, categoryLevel: 1});
        } else {
          // 品牌
          res = await operationApi.getBrandAndPriority(this.searchParams);
        }
        this.$nextTick(() => {
          this.loading = false
          this.total = res.total || 0;
          const list = res.records || [];
          list.map(item => {
            if (this.dataValue.type == 'category') {
              if (this.selectCategoryCollect.indexOf(String(item.sceneId)) > -1) {
                item._checked = true;
              }
            }
            if (this.dataValue.type == 'brand') {
              if (this.selectBrandCollect.indexOf(String(item.sceneId)) > -1) {
                item._checked = true;
              }
            }
            return item;
          })
          this.tableData = list;
        })
      } catch (e) {
        this.loading = false;
      }
    },
  },
  data() {
    return {
      options: [
        {id: 'all', label: '全部商品'},
        {id: 'category', label: '按照品类'},
        {id: 'brand', label: '按照品牌'}
      ],
      dataValue: {},
      showModal: false,
      categoryData: [],
      tableData: [],
      tableColumn: [],
      total: 0,
      searchParams: {
        pageSize: 10,
        pageNo: 1,
        name: '',
        sceneId: ''
      },
      loading: false,
      selectCategoryCollect: [], // 选择品类集合
      selectBrandCollect: [] // 选择品牌集合
    }
  },
  created() {
    if (!Object.keys(this.value).length) {
      // 默认值
      this.dataValue = {
        type: 'all',
        brandId: '',
        categoryId: '',
      }
    } else {
      this.dataValue = this.value;
      if (this.dataValue.type == 'category') {
        this.selectCategoryCollect = this.dataValue.categoryId ? this.dataValue.categoryId.split(',') : [];
      }
      if (this.dataValue.type == 'brand') {
        this.selectBrandCollect = this.dataValue.brandId ? this.dataValue.brandId.split(',') : [];
      }
      console.log(this.selectCategoryCollect, this.selectBrandCollect)
    }
  }
}
</script>
<style lang="less" scoped>
.option{
  cursor: pointer;
  border-radius: 4px;
  line-height:normal;
  display: inline-block;
  padding: 3px 5px;
  border: 1px solid #dddee1;
  margin: 0 2px;
  user-select: none;
  &.selected, &:hover{
    border-color: #57a3f3;
    box-shadow: 0px 0px 0px 2px rgb(45 140 240 / 20%)
  }
}

.searchFormStyle {
  text-align: left;
  clear: both;
  background-color: #fff;
  padding: 4px;
  min-height: 70px;
  font-size: 0;
  display: flex;
  align-items: center;
  .btnGroupStyle{
    button{
      margin-right: 6px;
    }
  }
  /deep/ .ivu-form-item{
    margin-bottom: 0;
  }
  /deep/ .ivu-form-item-label {
    font-weight: bold;
    display: inline-block;
  }

  /deep/.ivu-form-item-content {
    display: inline-block;
  }
}
.page{
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

/deep/ th.ivu-table-column-center{
  .ivu-checkbox-wrapper{
    display: none;
  }
}
</style>