<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-02-08 10:27:21
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-26 09:57:39
 -->
<!--
  选择门店分组组件：
  <gic-select-store
  :selectData="selectData"
  @returnStores="returnStores">
  </gic-select-store>

  import gicSelectStore from '@/components/common/gic-select-store.vue';

  returnStores: function(nodes) {
    const that = this;
    that.conditionObj.groupIds = nodes;
  },
 -->
<template>
  <el-popover placement="bottom" title="" width="350" trigger="click" v-model="storeVisible">
    <div class="daily-store-select">
      <div class="select-search">
        <el-input placeholder="请输入门店名称" maxlength="50" v-model="searchSelect" style="width: 100%;" clearable @keyup.native="value => toInput(value, searchSelect)" @clear="clearSearch"> <i slot="prefix" class="el-input__icon el-icon-search"></i> </el-input>
      </div>
      <div class="checkbox border-box" style="padding: 15px 20px;">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      </div>
      <div class="el-scrollbar define-search-select">
        <div class="el-select-dropdown__wrap el-scrollbar__wrap" style="margin-bottom: -5px; margin-right: -5px;">
          <el-checkbox-group v-model="dailyRuleForm.stores" @change="handleStoresChange">
            <ul class="el-scrollbar__view el-select-dropdown__list">
              <li :class="['el-select-dropdown__item', item.select ? 'selected hover' : '']" v-for="item in stores" :key="item.storeId">
                <!-- @click="checkStore(item)" -->
                <!--  <span>{{ item.storeName }}</span> -->
                <el-checkbox :label="item.storeId">{{ item.storeName }}</el-checkbox>
              </li>
              <li v-if="!stores.length" class="text-center"><span>暂无数据</span></li>
            </ul>
          </el-checkbox-group>
        </div>
        <div class="el-scrollbar__bar is-horizontal"><div class="el-scrollbar__thumb" style="transform: translateX(0%);"></div></div>
        <div class="el-scrollbar__bar is-vertical"><div class="el-scrollbar__thumb" style="transform: translateY(0%);"></div></div>
      </div>
    </div>
    <div class="show-select-num cursor-pointer w-250" slot="reference" @click="changeVisible">
      已经选择{{ dailyRuleForm.stores.length }}家门店
      <span class="el-input__suffix"
        ><span class="el-input__suffix-inner"><i :class="['el-select__caret el-input__icon el-icon-arrow-up', storeVisible ? 'is-reverse' : '']"></i></span
      ></span>
    </div>
  </el-popover>
</template>
<script>
import { getRequest } from '@/api/api';
import errMsg from '@/common/js/error';
import { _debounce } from '@/common/js/public';
export default {
  name: 'gic-select-store',
  props: {
    width: {
      type: String,
      default() {
        return '357px';
      }
    },
    selectData: {
      type: [Object, Array],
      default() {
        return [];
      }
    },
    brandId: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    return {
      projectName: '', // 当前项目名
      enterpriseId: this.brandId,
      checkAll: false,
      isIndeterminate: false,
      searchSelect: '',
      storeVisible: false,
      stores: [],
      storesCopy: [],
      dailyRuleForm: {
        stores: []
      },
      pageNum: 1,
      pageSize: 200
    };
  },

  methods: {
    /**
     * 全选
     */
    handleCheckAllChange(val) {
      const that = this;
      that.dailyRuleForm.stores = val ? that.stores.map(item => item.storeId) : [];
      that.isIndeterminate = false;
      that.$emit('returnStores', that.dailyRuleForm.stores);
    },
    handleStoresChange(value) {
      const that = this;
      let checkedCount = value.length;
      that.checkAll = checkedCount === that.stores.length;
      that.isIndeterminate = checkedCount > 0 && checkedCount < that.stores.length;
      that.$emit('returnStores', that.dailyRuleForm.stores);
    },

    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      if (that.searchSelect != '') {
        that.stores = [];
        that.pageNum = 1;
        that.getStoreData();
      }
      /* if (!that.storesCopy.length) {
        return false;
      }
      if (value == '') {
        that.stores = JSON.parse(JSON.stringify(that.storesCopy));
      }
      let filterData = JSON.parse(JSON.stringify(that.storesCopy)).filter(ele => {
        return ele.storeName.includes(value);
      });
      that.stores = filterData; */
    }, 500),

    /**
     * 显示或隐藏门店列表
     */
    /* eslint-disable */
    changeVisible() {
      // const that = this;
      // that.storeVisible = !that.storeVisible;
    },

    /**
     * 选择门店
     */
    checkStore(item) {
      const that = this;
      if (item.select) {
        item.select = false;
        const index = that.dailyRuleForm.stores.indexOf(item.storeId);
        that.dailyRuleForm.stores.splice(index, 1);
      } else {
        item.select = true;
        that.dailyRuleForm.stores.push(item.storeId);
      }
      that.storesCopy.forEach(ele => {
        if (that.dailyRuleForm.stores.includes(ele.storeId)) {
          ele.select = true;
        }
      });
    },

    /**
     * 清空
     */
    clearSearch() {
      const that = this;
      that.stores = [];
      that.pageNum = 1;
      that.getStoreData();
      // that.stores = JSON.parse(JSON.stringify(that.storesCopy));
    },

    /**
     * 获取门店
     */
    getStoreData() {
      let that = this;
      let para = {
        searchName: that.searchSelect,
        gicEnterpriseId: that.brandId,
        pageNum: that.pageNum,
        pageSize: that.pageSize
      };
      getRequest('/haoban-app-customer-web/cardCoupon/get-store-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            if (resData.result.result) {
              resData.result.result.forEach(ele => {
                ele.select = false;
                if (that.selectData.includes(ele.storeId)) {
                  ele.select = true;
                }
              });
            }
            if (that.pageNum == 1) {
              that.stores = JSON.parse(JSON.stringify(resData.result.result)) || [];
              that.storesCopy = JSON.parse(JSON.stringify(resData.result.result)) || [];
            }else {
              resData.result.result.forEach(ele => {
                that.stores.push(ele);
                that.storesCopy.push(ele);
              })
            }
            if (that.pageNum*that.pageSize < resData.result.totalCount) {
              that.pageNum ++;
              that.$nextTick(()=>{
                that.getStoreData();
              })
            }
            // console.log('that.stores:',that.stores)
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    brandId(val) {
      const that = this;
      if (val) {
        that.checkAll = false;
        that.isIndeterminate = false;
        that.stores = [];
        that.storesCopy = [];
        that.searchSelect = '';
        that.getStoreData();
      }
    },
    selectData: function(newData, oldData) {
      let that = this;
      if (!!newData.length) {
        that.dailyRuleForm.stores = JSON.parse(JSON.stringify(newData));
      }else {
        that.dailyRuleForm.stores = [];
      }
    },
  },
  mounted() {
    const that = this;
    // 对否有默认选中数据
    if (!!that.brandId) {
      that.stores = [];
      that.storesCopy = [];
      that.getStoreData();
    }
    if (!!that.selectData.length) {
      that.dailyRuleForm.stores = JSON.parse(JSON.stringify(that.selectData));
    }else {
      that.dailyRuleForm.stores = [];
    }
  }
};
</script>
<style lang="scss" scoped>
.depart-item-content {
  width: 213px;
  height: 32px;
  overflow: hidden;
  white-space: nowrap;
  border-radius: 2px;
  border: 1px solid #c4c6cf;
  cursor: pointer;
  box-sizing: border-box;
}

.select-tree-wrap {
  max-height: 300px;
  overflow-y: auto;
}

.item-cell-select {
  >>> .el-select__tags {
    white-space: nowrap;
    overflow: hidden;
  }
  .el-select {
    .el-tag {
      border-radius: 2px;
      border: 1px solid rgba(220, 223, 230, 1);
      background-color: #fff;
      .el-tag__close {
        top: 1px;
        color: #909399;
        &:hover {
          background-color: transparent;
        }
      }
    }
  }
}
.w-250 {
    width: 250px;
  }
.show-select-num {
    position: relative;
    display: inline-block;
    font-size: inherit;
    height: 32px;
    line-height: 32px;
    padding-left: 10px;
    -webkit-appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #606266;
    .el-select__caret {
      color: #c0c4cc;
      font-size: 14px;
      transition: transform 0.3s;
      transform: rotate(180deg);
      cursor: pointer;
      &.is-reverse {
        transform: rotate(0deg);
      }
    }
  }
.daily-store-select {
  position: relative;
}
</style>
