<template>
  <el-popover
    placement="bottom-start"
    width="420"
    trigger="click"
    v-model="popoverShow"
  >
    <div class="store-part-content">
      <div class="store-part-left-content">
        <div class="title">
          <span>所有自提点</span>
          <span class="group-num">{{ total }}</span>
        </div>
        <div class="search-content">
          <el-input
            placeholder="请输入自提点名称"
            v-model="search"
            clearable
            class="w-180 border-radius20"
            @keyup.enter.native="getSearchList"
            @clear="getSearchList"
          />
        </div>
        <div class="store-table-content">
          <el-table
            :data="tableData"
            :show-overflow-tooltip="true"
            :show-header="showHeader"
            ref="selectedTable"
            :row-key="getSelectList"
            @row-click="selectRow"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            v-loadmore="loadmore"
            class="scroll-table"
            height="210"
          >
            <span style="display:none">{{ refash }}</span>
            <el-table-column
              type="selection"
              width="30"
              :reserve-selection="true"
              :selectable="selectable"
            />
            <el-table-column
              prop="pickUpPointName"
              label="全部自提点"
              show-overflow-tooltip
              width="160"
            />
          </el-table>
        </div>
      </div>
      <div class="store-part-right-content">
        <div class="title">
          <p>
            已选<span class="group-num">（{{ selectLeftList.length }}个分组）</span>
          </p>
        </div>
        <div class="search-content">
          <el-input
            placeholder="请输入门店名称"
            v-model="searchValue"
            clearable
            class="w-180 border-radius20"
            @keyup.enter.native="getRightList"
            @clear="getRightList"
          />
        </div>
        <div class="list-content">
          <div v-if="selectRightList.length > 0">
            <div class="list-item" v-for="(item, index) in selectRightList" :key="index">
              <span class="storeGroup-name" :title="item.pickUpPointName">  {{ item.pickUpPointName }}</span>
              <span class="el-icon-close" @click="removeItem(item, index)" />
            </div>
          </div>
          <div v-else class="no-data-content">
            暂无数据
          </div>
        </div>
      </div>
    </div>
    <div class="store-button">
      <el-button type="text" style="color:#303133" @click="cancel">
        取消
      </el-button>
      <el-button type="text" @click="submit">
        确定
      </el-button>
    </div>
    <div slot="reference" class="group-title">
      已选择 {{ selectLeftList.length }} 个自提点
    </div>
  </el-popover>
</template>
<script>
import request from '../../service/request.js';
import qs from 'qs';
import copy from '../../utils/clone';
import utils from '../../utils/common';
export default {
  directives: {
    loadmore: {
      bind (el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-table__body-wrapper');
        SELECTWRAP_DOM.addEventListener('scroll', function () {
          /*
           * scrollHeight 获取元素内容高度(只读)
           * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见高度(只读)
           * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           *
           */
          let sign = 1; // 定义默认的向上滚于乡下滚的边界
          const CONDITION = this.scrollHeight - this.scrollTop < this.clientHeight + 1 && this.scrollTop > sign; // 注意: && this.scrollTop
          if (this.scrollTop > sign) {
            sign = this.scrollTop;
          }
          if (this.scrollTop < sign) {
            sign = this.scrollTop;
          }

          if (CONDITION) {
            binding.value();
          }
        });
      },
    },
  },
  props: {
    selectData: {
      type: Array,
      default () {
        return [];
      },
    },
  },
  data () {
    return {
      selectLeftList: [],
      selectRightList: [],
      search: '',
      total: 0,
      searchValue: '',
      pageSize: 20,
      totalPage: 1,
      currentPage: 1,
      tableData: [],
      showHeader: false,
      popoverShow: false,
      getZhLen: utils.getZhLen,
    };
  },
  mounted () {
    this.selectLeftList = this.selectData;
    this.getRightList();
    this.getList();
  },
  methods: {
    /**
     * 拉到底部加载更多
     */
    loadmore () {
      if (this.currentPage < this.totalPage) {
        this.currentPage += 1;
        this.getList();
      }
    },
    getList () {
      const params = {
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        search: this.search,
        isValid: 1,
        onlyJurisdiction: 1, // 是否是只查管辖门店范围内的 1是0否
      };
      request.post('/api-integral-mall/page-pick-up-points', qs.stringify(params)).then(res => {
        if (res.data.errorCode === 0) {
          if (this.currentPage === 1) {
            this.tableData = [];
          }
          if (res.data.result.result) {
            this.tableData = this.tableData.concat(res.data.result.result);
          }
          this.total = res.data.result.totalCount;
          this.totalPage = res.data.result.totalPage;
          console.log(this.total);
          if (this.selectLeftList.length) {
            for (const item of this.selectLeftList) {
              let obj = '';
              obj = this.tableData.find(i => {
                return i.integralMallPickUpPointId === item.integralMallPickUpPointId;
              });
              if (obj) {
                this.$refs.selectedTable.toggleRowSelection(obj, true);
              }
            }
          }
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getSearchList () {
      this.currentPage = 1;
      this.getList();
    },
    getSelectList (row) {
      return row.integralMallPickUpPointId;
    },
    // 点击正一行选中
    selectRow (row, event, column) {
      this.$refs.selectedTable.toggleRowSelection(row);
    },
    handleSelectionChange (val) {
      for (const item of val) {
        if (
          !this.selectLeftList.find(i => {
            return i.integralMallPickUpPointId === item.integralMallPickUpPointId;
          })
        ) {
          this.selectLeftList.push(item);
        }
      }
      this.selectRightList = copy(this.selectLeftList);
    },
    selectable (row, index) {
      let flag = true;
      for (const item of this.selectLeftList) {
        if (row.integralMallPickUpPointId == item.integralMallPickUpPointId) {
          flag = false;
        }
      }
      return flag;
    },
    // 移除
    removeItem (item, index) {
      this.selectRightList.splice(index, 1);
      this.selectLeftList.splice(this.selectLeftList.findIndex(i => i.integralMallPickUpPointId === item.integralMallPickUpPointId), 1);
      // 取消表格选中数据
      const obj = this.tableData.find(i => {
        return i.integralMallPickUpPointId === item.integralMallPickUpPointId;
      });
      this.$refs.selectedTable.toggleRowSelection(obj, false);
      this.searchValue = '';
    },
    // 右侧搜索
    getRightList () {
      const newData = this.selectLeftList.filter(item => {
        if (item.pickUpPointName.indexOf(this.searchValue) > -1) {
          return item;
        }
        return newData;
      });

      this.selectRightList = newData;
    },
    // 确定提交
    submit () {
      if (this.selectLeftList.length < 1) {
        this.$message.error('请至少选择一个自提点');
        return false;
      }
      // 过滤数据只保留部分有用字段
      this.selectLeftList.forEach(v => {
        delete v.storeId;
        delete v.pickUpPointAddress;
        delete v.pickUpPointPhone;
        delete v.canChooseTime;
        delete v.pickUpPointType;
        return v;
      });
      this.$emit('getSelectList', this.selectLeftList);
      this.popoverShow = false;
    },
    cancel () {
      this.selectLeftList = [];
      this.selectRightList = [];
      this.$refs.selectedTable.clearSelection();
      this.$emit('getSelectList', []);
      this.popoverShow = false;
    },
  },
};
</script>
<style scoped>
.store-part-content {
  font-size: 0px;
}
.store-part-left-content {
  width: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: inline-block;
}
.store-part-right-content {
  width: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: inline-block;
  margin-left: 15px;
  vertical-align: top;
}
.store-part-content .title {
  display: flex;
  justify-content: space-between;
  height: 40px;
  line-height: 40px;
  background: #f5f7fa;
  padding: 0 10px;
  font-size: 16px;
  color: #303133;
}
.group-num {
  font-size: 12px;
  color: #909399;
}
.search-content {
  margin: 10px;
}

.border-radius20 /deep/ input {
  border-radius: 20px;
}
.list-content {
  margin-bottom: 10px;
  height: 210px;
  overflow-y: auto;
  font-size: 14px;
}
.list-item {
  display: flex;
  justify-content: space-between;
  color: #606266;
  font-size: 14px;
  margin-bottom: 14px;
  padding: 0 10px;
  line-height: 16px;
}
.list-item .el-icon-close {
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  border-radius: 50%;
  font-size: 14px;
}
.list-item .el-icon-close:hover {
  background: #909399;
  color: #fff;
}
.storeGroup-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 150px;
}
.store-button {
  height: 22px;
  line-height: 34px;
  text-align: right;
}
.group-title {
  width: 240px;
  padding-left: 12px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-sizing: border-box;
}
.store-table-content {
  margin-bottom: 10px;
}
.store-table-content /deep/ .el-table th.is-leaf,
.store-table-content /deep/ .el-table td {
  border-bottom: none;
}
.store-table-content /deep/ .el-table .cell {
  text-overflow: clip;
}
.store-table-content /deep/ .el-table th,
.store-table-content /deep/ .el-table td {
  padding: 5px 0;
}
.no-data-content {
  color: #909399;
  font-size: 14px;
  margin: 40px auto;
  text-align: center;
}
</style>
