index.vue 11.4 KB
<!--
 * @Author: your name
 * @Date: 2022-03-07 14:32:50
 * @LastEditTime: 2025-03-11 17:12:12
 * @LastEditors: 'wangzhihui' '1733904062@qq.com'
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \scrm-micro-settings\src\views\baseInfo\editInfo.vue
-->
<template>
  <div v-loading="loading">
    <div class="select-input-box" @click="switchBrand">
      <div>
        <template v-for="(item, idx) in getCheckedArr">
          <el-tag effect="plain" type="info" :key="item.id" closable :disable-transitions="false" @close="removeItem(item, idx)" v-if="idx < 3">
            {{ item.label }}
          </el-tag>
        </template>
        <el-popover placement="top" width="600" trigger="hover" class="select-popover">
          <div class="select-popover-box">
            <p v-if="selectedLeafCount > previewTagMax" class="popover-summary">
              共已选 {{ selectedLeafCount }} 项,以下展示前 {{ previewTagMax }} 项
            </p>
            <el-tag effect="plain" class="popover-item" v-for="(item, idx) in getCheckedArr" type="info" :key="item.id" closable :disable-transitions="false" @close="removeItem(item, idx)">
              {{ item.label }}
            </el-tag>
          </div>
          <el-tag effect="plain" slot="reference" type="info" v-show="selectedLeafCount > 3">+ {{ selectedLeafCount - 3 }}</el-tag>
        </el-popover>
      </div>
      <div>
        <i v-show="!brandTree" class="el-icon-arrow-up" style="color:#909399"></i>
        <i v-show="brandTree" class="el-icon-arrow-down" style="color:#909399"></i>
      </div>
    </div>
    <div class="tree-box" v-show="brandTree">
      <el-input class="tree-input" prefix-icon="el-icon-search" placeholder="输入关键字进行过滤" v-model="filterText"
        :validate-event="false"></el-input>
      <el-tree class="filter-tree" @check="handleCheck" :data="brandListTree" :props="defaultProps" node-key="id" show-checkbox :filter-node-method="filterNode" ref="tree"></el-tree>
      <div class="tree-footer">
        <div class="tree-footer-checkbox">
          <el-checkbox v-model="checkedAll" @change="selectAll">全部</el-checkbox>
        </div>
        <div class="tree-footer-reset" @click="selectClear">重置</div>
      </div>
    </div>
  </div>
</template>

<script>
/** 后端约定 integer:车系 id、车品牌 id */
function toBrandInt(val) {
  if (val === '' || val === null || val === undefined) return undefined
  const n = parseInt(val, 10)
  return Number.isNaN(n) ? undefined : n
}

/** 勾选 key 与节点 id 可能是 number/string,统一比较 */
function checkedKeysHas(keys, id) {
  const sid = String(id)
  return (keys || []).some((k) => String(k) === sid)
}

/** 叶子 key 列表与「应选满的叶子 id 列表」是否一致(不依赖仅比 length,避免重复 id 等异常) */
function isFullLeafSelection(leafKeys, treeArr) {
  if (!treeArr || !treeArr.length) return false
  const arr = leafKeys || []
  if (arr.length !== treeArr.length) return false
  const set = new Set(arr.map((k) => String(k)))
  return treeArr.every((id) => set.has(String(id)))
}

export default {
  name: 'SelectBrand',
  data() {
    return {
      loading: false,
      /** setCheckedKeys 批量勾选时会多次触发 @check,置位期间不 emit/不跑完整 handleCheck */
      suppressBrandChangeEmit: false,
      checkedAll: false,
      /** 勾选叶子总数(展示用);getCheckedArr 最多保留 previewTagMax 条预览,避免全选时海量 DOM */
      selectedLeafCount: 0,
      previewTagMax: 50,
      filterText: '',
      treeArr: [],
      getCheckedArr: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      brandTree: false
    }
  },
  props: {
    brandListTree: {
      type: Array
    }
  },
  watch: {
    filterText(val) {
      if (this.$refs.tree) {
        this.$refs.tree.filter(val)
      }
    }
  },
  methods: {
    /**
     * 提交结构(submitVerification:merchantBrandList[].cars、merchantBrandList[].merchantBrandId[])
     * - cars:车系 id(一级)
     * - merchantBrandId:车品牌 id 数组(二级),integer[]
     */
    collectMerchantBrandIdsFromSeriesNode(car, checkedKeys) {
      const merchantBrandId = []
      if (!car.children || !car.children.length) return merchantBrandId
      car.children.forEach((item) => {
        if (checkedKeysHas(checkedKeys, item.id)) {
          const bid = toBrandInt(item.id)
          if (bid !== undefined) merchantBrandId.push(bid)
        }
      })
      return merchantBrandId
    },
    getMerchantBrandList() {
      const getCheckedKeys = this.$refs.tree.getCheckedKeys()
      const tree = this.brandListTree || []
      const rows = []
      /*
       * 仅用「顶层车系 + 勾选中的二级叶子」组装,一车系一行。
       * 原先用 half-checked 父级 + 全选父级 + 勾选叶子三套 concat,
       * 在只选部分/全部叶子时同一车系会重复多行相同 cars。
       */
      tree.forEach((series) => {
        if (!series.children || !series.children.length) {
          if (checkedKeysHas(getCheckedKeys, series.id)) {
            const cars = toBrandInt(series.id)
            if (cars !== undefined) {
              rows.push({ cars, merchantBrandId: [] })
            }
          }
          return
        }
        const merchantBrandId = this.collectMerchantBrandIdsFromSeriesNode(series, getCheckedKeys)
        if (merchantBrandId.length) {
          const cars = toBrandInt(series.id)
          if (cars !== undefined) {
            rows.push({ cars, merchantBrandId })
          }
        }
      })
      return rows
    },
    /** 大批量 setCheckedKeys 后树内部状态可能晚于单帧 nextTick,延后合并校验与 emit */
    scheduleAfterTreeStable(cb) {
      this.$nextTick(() => {
        this.$nextTick(() => {
          requestAnimationFrame(cb)
        })
      })
    },
    /**
     * 用 getCheckedKeys(true) + 遍历 brandListTree 生成预览标签,避免 getCheckedNodes(true) 全选时构建超大批节点
     */
    syncLeafDisplayFromTree() {
      const tree = this.$refs.tree
      if (!tree) return
      const leafKeys =
        typeof tree.getCheckedKeys === 'function'
          ? tree.getCheckedKeys(true)
          : tree.getCheckedKeys()
      const keys = leafKeys || []
      this.selectedLeafCount = keys.length
      if (keys.length === 0) {
        this.getCheckedArr = []
        return
      }
      const keySet = new Set(keys.map((k) => String(k)))
      const preview = []
      const max = this.previewTagMax
      const brandTree = this.brandListTree || []
      outer: for (const series of brandTree) {
        if (!series.children || !series.children.length) {
          if (keySet.has(String(series.id))) {
            preview.push({ id: series.id, label: series.label })
            if (preview.length >= max) break outer
          }
        } else {
          for (const child of series.children) {
            if (keySet.has(String(child.id))) {
              preview.push({ id: child.id, label: child.label })
              if (preview.length >= max) break outer
            }
          }
        }
      }
      this.getCheckedArr = preview
    },
    //勾选
    handleCheck() {
      if (this.suppressBrandChangeEmit) {
        return
      }
      const tree = this.$refs.tree
      if (!tree) return
      this.treeArr = this.getTreeArray()
      this.syncLeafDisplayFromTree()
      const leafKeys =
        typeof tree.getCheckedKeys === 'function'
          ? tree.getCheckedKeys(true)
          : tree.getCheckedKeys()
      if (!this.treeArr.length) {
        this.checkedAll = false
      } else {
        this.checkedAll = isFullLeafSelection(leafKeys, this.treeArr)
      }
      this.$emit('brand-change')
    },
    getCheckList(checkArr = []) {
      checkArr.forEach(item => (item = parseInt(item)))
      this.suppressBrandChangeEmit = true
      this.$refs.tree.setCheckedKeys(checkArr)
      this.scheduleAfterTreeStable(() => {
        this.suppressBrandChangeEmit = false
        this.handleCheck()
      })
    },
    //获取选择项
    getTreeArray() {
      let tree_arr = []
      this.brandListTree.forEach(k => {
        let child = k.children
        if (child && child.length > 0) {
          child.forEach(j => {
            tree_arr.push(j.id)
          })
        } else {
          tree_arr.push(k.id)
        }
      })
      return tree_arr
    },
    //全选
    selectAll() {
      const tree = this.$refs.tree
      this.treeArr = this.getTreeArray()
      const beforeKeys =
        tree && typeof tree.getCheckedKeys === 'function'
          ? tree.getCheckedKeys(true)
          : []
      const wasAll = isFullLeafSelection(beforeKeys, this.treeArr)
      this.suppressBrandChangeEmit = true
      if (wasAll) {
        tree.setCheckedKeys([])
      } else {
        this.checkedAll = true
        tree.setCheckedKeys(this.treeArr)
      }
      this.scheduleAfterTreeStable(() => {
        this.suppressBrandChangeEmit = false
        this.handleCheck()
      })
    },
    //重置
    selectClear() {
      this.suppressBrandChangeEmit = true
      this.checkedAll = false
      this.$refs.tree.setCheckedKeys([])
      this.scheduleAfterTreeStable(() => {
        this.suppressBrandChangeEmit = false
        this.handleCheck()
      })
    },
    //删除
    removeItem(checkItem) {
      this.loading = true
      const tree = this.$refs.tree
      const nodes =
        typeof tree.getCheckedNodes === 'function'
          ? tree.getCheckedNodes(true)
          : tree.getCheckedNodes()
      const leafNodes = (nodes || []).filter((n) => n.id != checkItem.id)
      this.suppressBrandChangeEmit = true
      this.$refs.tree.setCheckedNodes(leafNodes)
      this.scheduleAfterTreeStable(() => {
        this.suppressBrandChangeEmit = false
        this.loading = false
        this.handleCheck()
      })
    },
    //过滤
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 显示隐藏
    switchBrand() {
      this.brandTree = !this.brandTree
      this.$emit('clickBrand', this.brandTree)
    }
  }
}
</script>

<style lang="scss" scoped>
.select-input-box {
  width: 400px;
  // height: 38px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #e5e5e5;
  box-sizing: border-box;
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // /deep/ .el-tag {
  //   margin-right: 5px;
  //   height: 26px;
  //   line-height: 26px;
  //   box-sizing: border-box;
  // }
}
.select-popover {
  &-box {
    display: flex;
    flex-wrap: wrap;
    max-height: 500px;
    overflow-y: auto;
    .popover-summary {
      width: 100%;
      margin: 0 0 8px;
      font-size: 12px;
      color: #909399;
      line-height: 1.5;
    }
    .popover-item {
      margin-right: 5px;
      margin-bottom: 5px;
      height: 26px;
      line-height: 26px;
      box-sizing: border-box;
    }
  }
}
.tree-box {
  margin-top: 10px;
  padding: 15px 15px 0px;
  background: #ffffff;
  // box-shadow: 0px 6px 20px 0px rgba(122, 122, 122, 0.2);
  border-radius: 4px;
  .tree-input {
    margin-bottom: 10px;
  }
  .filter-tree {
    height: 300px;
    overflow-y: auto;
  }
  .tree-footer {
    border-top: 1px solid #e5e5e5;
    height: 48px;
    padding: 0px 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.tree-footer-reset {
  cursor: pointer;
}
</style>