<template>
  <div>
    <el-dialog :visible="visible" v-if="visible" title="选择成员" width="1030px" append-to-body @close="onCancel">
      <div class="select-clerk" v-loading="loading">
        <!-- 选择导购 -->
        <div class="clerk-list">
          <!-- 筛选条件 -->
          <div class="search-bar">
            <!-- <el-select clearable style="width: 182px"></el-select> -->
            <gic-select-group class="select-group" :brandId="enterpriseId" :selectData="params.storeGroup" @checkGroupIds="onCheckGroupIds"> </gic-select-group>
            <el-input v-model="params.storeSearchParams" @change="onSearch" placeholder="请输入门店名称/code" prefix-icon="el-icon-search" clearable style="margin-left: 10px; width: 210px"></el-input>
            <el-input v-model="params.clerkSearchParams" @change="onSearch" placeholder="请输入导购名称/手机号/code" prefix-icon="el-icon-search" clearable style="margin-left: 10px; width: 250px"></el-input>
          </div>
          <!-- 导购列表的表头 -->
          <el-table :class="['clerk-list-header', { 'hide-empty': storeClerkList.length > 0 }]">
            <el-table-column min-width="67px">
              <template #header>
                <el-checkbox v-if="multiple" v-model="selectAll.selected" @change="onSelectAll" :indeterminate="selectAll.indeterminate" :disabled="selectAll.disabled"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="导购" min-width="230px"></el-table-column>
            <el-table-column label="手机号码" min-width="155px"></el-table-column>
            <el-table-column label="备注" min-width="161px"></el-table-column>
          </el-table>
          <!-- 导购列表 -->
          <div v-if="storeClerkList.length > 0" ref="clerkList" class="clerk-list-body">
            <div v-for="(el, index) in storeClerkList" :key="el.storeId" class="clerk-list-cell">
              <!-- 门店信息 -->
              <el-table :data="[{}]" class="clerk-store-info" :show-header="false">
                <el-table-column min-width="67px">
                  <el-checkbox v-if="multiple" v-model="el.selected" @change="onSelectStore(el)" :indeterminate="el.indeterminate" :disabled="el.disabled"></el-checkbox>
                </el-table-column>
                <el-table-column min-width="546px">
                  <div class="clerk-store-name">{{ el.storeName }}</div>
                  <div class="clerk-store-code">code：{{ el.storeCode }}</div>
                </el-table-column>
              </el-table>
              <!-- 门店下的导购 -->
              <el-table :data="el.clerkList" class="clerk-list-table" :show-header="false">
                <el-table-column min-width="67px">
                  <template slot-scope="{ row }">
                    <el-checkbox v-if="multiple" v-model="row.selected" @change="onSelectClerk(row, index)" :disabled="row.disabled"></el-checkbox>
                    <!-- 为了实现单选框选中状态时再次点击能切换到未选中状态，所以使用一个复选框盖在单选框上 -->
                    <div v-else class="radio-wrapper">
                      <el-checkbox class="radio-handler" v-if="!row.disabled" v-model="row.selected" @change="onSelectClerk(row, index)"></el-checkbox>
                      <el-radio class="radio-content" :value="row.selected" :label="true" :disabled="row.disabled"></el-radio>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="导购" min-width="230px">
                  <template slot-scope="{ row }">
                    <div class="clerk-name">{{ row.clerkName }}</div>
                    <div class="clerk-code">code：{{ row.clerkCode }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="手机号码" prop="phoneNumber" min-width="155px"></el-table-column>
                <el-table-column label="备注" min-width="161px">
                  <div slot-scope="{ row }">{{ formatRemark(row.hmStatus) }}</div>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <el-pagination v-if="params.total > 0" @current-change="onCurrentChange" :total="params.total" :page-size="params.pageSize" :current-page="params.pageNum" layout="prev, pager, next" style="margin-bottom: 0;text-align: right"></el-pagination>
        </div>
        <!-- 选中的导购 -->
        <div class="selected-clerk">
          <div class="selected-clerk-title">
            <span>{{ `已选导购（${selected.length}）` }}</span>
            <el-button v-if="multiple" type="text" @click="onDelAll">全部清除</el-button>
          </div>
          <!-- 选中的导购列表 -->
          <div class="selected-clerk-list">
            <div v-for="(el, index) in selected" :key="el.clerkId" class="clerk-item">
              <div class="clerk-info">
                <div class="clerk-name">{{ el.clerkName }}</div>
                <div class="clerk-code">code：{{ el.clerkCode }}</div>
              </div>
              <div class="del-btn" @click="onDel(index)">
                <i class="iconfont-hb3 iconclose1 del-btn-icon"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template slot="footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import GicSelectGroup from '@/components/common/gic-select-group.vue';
import { getRequest } from '@/api/api.js';
export default {
  name: 'SelectClerk',
  components: { GicSelectGroup },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array,
      default: () => []
    },
    // 是否批量选择导购
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否单人活码
    isSimple: {
      type: Boolean,
      default: false
    },
    max: {
      type: Number,
      default: 100
    }
  },
  watch: {
    visible(flag) {
      if (flag) {
        this.selected = JSON.parse(JSON.stringify(this.data));
        this.getStoreClerkList();
      }
    }
  },
  data() {
    return {
      params: {
        storeGroup: [],
        storeGroupId: '', // 分组ID
        storeSearchParams: '', // 门店条件
        clerkSearchParams: '', // 导购条件
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      enterpriseId: '',
      loading: false,
      // 门店-导购列表
      storeClerkList: [],
      selectAll: {
        // 全选的选中状态
        selected: false,
        // 全选的半选状态
        indeterminate: false,
        // 全选的禁用状态
        disabled: false
      },
      // 选中的导购
      selected: []
    };
  },
  created() {
    this.enterpriseId = JSON.parse(sessionStorage.getItem('userInfos') || '{}').enterpriseId;
  },
  methods: {
    getStoreClerkList() {
      const { storeGroupId, storeSearchParams, clerkSearchParams, pageNum, pageSize } = this.params;
      const params = {
        storeGroupId: storeGroupId || undefined,
        storeSearchParams: storeSearchParams || undefined,
        clerkSearchParams: clerkSearchParams || undefined,
        pageNum,
        pageSize
      };
      this.loading = true;

      getRequest('/haoban-manage3-web/hm/store-clerk-list', params)
        .then(res => {
          const { code, message, result } = res.data || {};
          if (code != 0) {
            return this.$message.error(message);
          }
          result.result = Array.isArray(result.result) ? result.result : [];
          this.params.total = result.totalCount;
          this.storeClerkList = result.result.map(el => {
            el.clerkList = Array.isArray(el.clerkList) ? el.clerkList : [];
            // 设置导购的禁用状态和选中状态
            el.clerkList = el.clerkList.map(item => {
              item.disabled = this.isSimple ? item.hmStatus == 1 || item.hmStatus == 2 || item.hmStatus == 3 : item.hmStatus == 1 || item.hmStatus == 2;
              item.selected = this.selected.some(clerk => clerk.clerkId == item.clerkId);
              return item;
            });
            this.selected = this.selected.map(item => {
              const clerk = el.clerkList.find(cell => cell.clerkId == item.clerkId);
              return clerk ? clerk : item;
            });
            // 设置门店禁用状态、选中状态和半选状态
            el.disabled = el.clerkList.length == 0 || el.clerkList.every(el => el.disabled);
            el.selected = el.clerkList.length > 0 && el.clerkList.every(el => !el.disabled && el.selected);
            el.indeterminate = !el.selected && el.clerkList.some(el => el.selected);
            return el;
          });
          this.selectAll.disabled = this.storeClerkList.length == 0 || this.storeClerkList.every(el => el.disabled);
          this.selectAll.selected = this.storeClerkList > 0 && this.storeClerkList.every(el => !el.disabled && el.selected);
          this.selectAll.indeterminate = !this.selectAll.selected && this.storeClerkList.some(el => el.selected || el.indeterminate);
          this.$refs.clerkList.scrollTop = 0;
        })
        .finally(() => (this.loading = false));
    },
    onCheckGroupIds(nodes) {
      this.params.storeGroup = nodes;
      this.params.storeGroupId = nodes.map(el => el.storeGroupId).join(',');
      this.onSearch();
    },
    onSearch() {
      this.onCurrentChange(1);
    },
    onCurrentChange(currentPage) {
      this.params.pageNum = currentPage;
      this.getStoreClerkList();
    },
    // 解析备注
    formatRemark(status) {
      // 1未关联企微 2关联的企微号未配置客户联系功能  3已有单人活码（单人活码不能创建 多人活码可以）  4无单人活码(可以创建)
      let result;
      switch (Number(status)) {
        case 1:
          result = '未关联企微号';
          break;
        case 2:
          result = '关联的企微号未配置客户联系功能';
          break;
        case 3:
          result = '已有单人活码';
          break;
        // case 4:
        //   result = '';
        //   break;
      }
      return result;
    },
    // 更新全选的复选框样式
    updateAllState() {
      // 计算全选的选中状态，计算半选的选中状态
      this.selectAll.selected = this.storeClerkList.every(el => !el.disabled && el.selected);
      this.selectAll.indeterminate = !this.selectAll.selected && this.storeClerkList.some(el => el.selected || el.indeterminate);
    },
    // 更新门店全选的复选框样式
    updateStoreState(store) {
      // 计算门店的选中状态，计算门店的半选状态
      store.selected = store.clerkList.every(el => !el.disabled && el.selected);
      store.indeterminate = !store.selected && store.clerkList.some(el => el.selected);
    },
    // 全选所有导购
    onSelectAll() {
      // 只能全选本页，或者取消本页的全选
      const storeClerkList = this.storeClerkList.filter(el => !el.disabled);
      if (storeClerkList.length > 0) {
        const isSelectedAll = storeClerkList.every(el => el.selected) || this.selected.length >= this.max;
        if (isSelectedAll) {
          storeClerkList.forEach(el => {
            el.selected = false;
            el.indeterminate = false;
          });
          this.selected.forEach(el => (el.selected = false));
          this.selected = [];
        } else {
          storeClerkList.forEach(el => {
            if (this.selected.length < this.max && !el.selected) {
              el.selected = true;
              this.onSelectStore(el, true);
            }
          });
        }
      }
      this.updateAllState();
    },
    // 全选门店下的导购
    onSelectStore(store, isAll) {
      const clerkList = store.clerkList.filter(el => !el.disabled);
      if (clerkList.length > 0) {
        let isSelectedAll = clerkList.every(el => el.selected) || this.selected.length >= this.max;
        clerkList.forEach((el, index) => {
          if (isSelectedAll) {
            el.selected = false;
            this.onSelectClerk(el, index, true);
          } else {
            if (this.selected.length < this.max && !el.selected) {
              el.selected = true;
              this.onSelectClerk(el, index, true);
            }
          }
        });
        this.updateStoreState(store);
        if (!isAll) {
          this.updateAllState();
        }
      }
    },
    // 选择单个导购
    onSelectClerk(clerk, index, isAll) {
      // 单选时只能选一个导购，不需要更新全选所有的复选框的样式，也不需要更新门店全选的复选框的样式
      if (!this.multiple) {
        if (this.selected.length > 0) {
          this.selected[0].selected = false;
          if (clerk.clerkId == this.selected[0].clerkId) {
            this.selected = [];
          } else {
            this.selected.splice(0, 1, clerk);
          }
        } else {
          this.selected.push(clerk);
        }
        return;
      }

      // 选择单个导购时
      if (clerk.selected) {
        // 计算有没有超过上限
        if (this.selected.length < this.max) {
          this.selected.push(clerk);
        } else {
          clerk.selected = false;
          this.$message.warning(`最多只能选择 ${this.max} 个导购`);
        }
      } else {
        const index = this.selected.findIndex(el => el.clerkId == clerk.clerkId);
        if (index >= 0) {
          this.selected.splice(index, 1);
        }
      }
      if (!isAll) {
        this.updateStoreState(this.storeClerkList[index]);
        this.updateAllState();
      }
    },
    onDelAll() {
      if (this.selected.length > 0) {
        this.selectAll.selected = false;
        this.selected.length = this.max;
        this.onSelectAll();
      }
    },
    onDel(index) {
      const clerk = this.selected[index];
      clerk.selected = false;
      this.onSelectClerk(
        clerk,
        this.storeClerkList.findIndex(el => el.clerkList.some(item => item.clerkId == clerk.clerkId))
      );
    },
    onCancel() {
      this.selectAll.selected = false;
      this.selectAll.indeterminate = false;
      this.selectAll.disabled = false;
      this.selected = [];
      this.params.storeGroup = [];
      this.params.storeGroupId = '';
      this.params.storeSearchParams = '';
      this.params.clerkSearchParams = '';
      this.params.pageNum = 1;
      this.$emit('update:visible', false);
    },
    onSave() {
      this.$emit('save', JSON.parse(JSON.stringify(this.selected)));
      this.$emit('update:visible', false);
    }
  }
};
</script>

<style lang="scss" scoped>
.select-clerk {
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
  height: 55vh;
  .clerk-list,
  .selected-clerk {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
  }
  .clerk-list {
    padding: 10px 16px;
    width: 694px;
    box-sizing: border-box;
    .hide-empty {
      >>> .el-table__empty-block {
        display: none;
      }
    }
    .search-bar {
      font-size: 0;
      .select-group {
        >>> .el-select {
          width: 180px !important;
        }
      }
    }
    .clerk-list-header {
      margin-top: 10px;
      >>> .el-table__header th {
        height: 32px !important;
        background-color: #f2f3f5;
        border-bottom: none;
      }
    }
    .clerk-list-body {
      height: calc(100% - 120px);
      overflow-y: auto;
      .clerk-list-cell {
        margin-top: 10px;
        border: 1px solid #e4e7ed;
        border-bottom: none;
        >>> .el-table {
          &::before {
            background-color: #e4e7ed !important;
          }
          .cell {
            padding-left: 10px;
            padding-right: 0;
          }
        }
        .clerk-store-info {
          background: #f7f8fa;
          >>> .el-table__body {
            tr,
            tr:hover > td.el-table__cell {
              background-color: transparent;
            }
            td {
              padding-top: 5px;
              padding-bottom: 5px;
              border: none;
              .cell:empty::before {
                content: '';
              }
            }
          }
          .clerk-store-name {
            font-size: 14px;
            font-weight: 400;
            color: #303133;
            line-height: 20px;
          }
          .clerk-store-code {
            font-size: 12px;
            font-weight: 400;
            color: #606266;
            line-height: 17px;
          }
        }
        .clerk-list-table {
          >>> .el-table__row {
            + .el-table__row {
              border-top: 1px solid #e4e7ed;
            }
            td {
              padding-top: 6px;
              padding-bottom: 6px;
              border-bottom: none;
            }
          }
          >>> .el-table__empty-block {
            min-height: 120px !important;
            height: 120px !important;
            .el-table__empty-text::before {
              width: 60px;
              height: 60px;
            }
          }
          .clerk-name {
            font-size: 14px;
            font-weight: 400;
            color: #303133;
            line-height: 20px;
          }
          .clerk-code {
            font-size: 12px;
            font-weight: 400;
            color: #606266;
            line-height: 17px;
          }
          .radio-wrapper {
            position: relative;
            .radio-handler {
              position: absolute;
              top: 0;
              left: 0;
              z-index: 1;
              opacity: 0;
            }
            .radio-content {
              >>> .el-radio__label {
                display: none;
              }
            }
          }
        }
      }
    }
  }
  .selected-clerk {
    margin-left: 12px;
    width: 274px;
    .selected-clerk-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 12px 16px 16px;
      font-size: 14px;
      font-weight: 400;
      color: #303133;
      line-height: 20px;
    }
    .selected-clerk-list {
      max-height: calc(100% - 56px);
      overflow-y: auto;
      .clerk-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px 8px 16px;
        &:hover {
          background: #f7f8fa;
        }
        .clerk-info {
          width: calc(100% - 30px);
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          line-height: 20px;
          .clerk-name {
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .clerk-code {
            margin-top: 2px;
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-weight: 400;
          }
        }
        .del-btn {
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 20px;
          border-radius: 10px;
          cursor: pointer;
          &:hover {
            background: #e5e6eb;
          }
          .del-btn-icon {
            font-size: 16px;
            color: #606266;
          }
        }
      }
    }
  }
}
</style>
