relateStoreTable.vue 13.1 KB
<template>
  <div class="store-table">
    <el-form :model="merchantForm" class="store-form" ref="relateStoreTable">
      <el-form-item label="" prop="selectedMerchantList" :rules="[{ required: true, message: '请选择门店', trigger: ['blur', 'change'] }]">
        <el-table
          :data="merchantForm.selectedMerchantList"
          style="width: 100%"
          :header-row-style="headerRowStyle"
          header-cell-class-name="header-cell-class-name">
          <el-table-column
            align="center"
            width="60px"
            label="序号"
            type="index" />
          <el-table-column
            prop="merchantName"
            label="分配门店" min-width="200"/>
          <el-table-column
            prop="merchantId"
            label="商户号" min-width="100" />
          <el-table-column label="应用到具体商品" min-width="600" v-if="formData.sceneType == 0 && formData.hireType == 2">
            <template slot-scope="scope">
              <el-form-item :prop="`selectedMerchantList[${scope.$index}].goodsData`" :rules="[{ required: true, message: '请选择商品', trigger: ['blur', 'change'] }]">
                <div :ref="`tagContainer_${scope.$index}`" style="display: flex; align-items: center;height: 26px;">
                  <span class="add_btn" @click="addTag(scope.row, scope.$index)"><i class="el-icon-plus"></i></span>
                  <div :class="['tag_item', item.merchantGoodsStatus != 1 ? 'disabled' : '']" v-for="(item, index) in visibleTags(scope.row.goodsData, scope.$index)" :key="index">
                    <span>{{ item.upgradeGoodsName }}</span>
                    <span class="del_icon" @click="removeTag(scope.$index, index)"><i class="el-icon-close"></i></span>
                  </div>
                  <el-popover
                    v-if="hiddenTags(scope.row.goodsData, scope.$index).length"
                    placement="top"
                    width="fit-content"
                    trigger="click"
                  >
                    <div class="tab_content">
                      <div :class="['tag_item', item.merchantGoodsStatus != 1 ? 'disabled' : '']" v-for="(item, index) in hiddenTags(scope.row.goodsData, scope.$index)" :key="index">
                        <span>{{ item.upgradeGoodsName }}</span>
                        <span class="del_icon" @click="removeHiddenTag(scope.$index, index)"><i class="el-icon-close"></i></span>
                      </div>
                    </div>
                    <span class="tag_item hidden_btn" slot="reference" type="text">
                      ···{{ hiddenTags(scope.row.goodsData, scope.$index).length}}
                    </span>
                  </el-popover>
                </div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="90">
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="addOrEdit == 'edit'"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-btn"><el-button size="small" icon="el-icon-plus" :disabled="addOrEdit == 'edit'" @click="addRow">新增门店</el-button></div>
      </el-form-item>
    </el-form>
    <relate-store-dialog v-if="relateStoreVisible" ref="formRelateStore" :relate-store-visible="relateStoreVisible"
                         :store-api="getDistributeStoreListApi"
                         :store-search-form="storeSearchForm" :store-selected="storeSelected"
                         @handleRelateStoreConfirm="handleRelateStoreConfirm" :form-data="formData" @handleRelateStoreClose="handleRelateStoreClose">
      <el-row slot>
        <el-form :model="storeSearchForm" ref="relate" :inline="true">
          <el-form-item label="门店名称:">
            <el-input v-model.trim="storeSearchForm.merchantName" placeholder="门店名称" @keydown.native="handleStoreInput"
                      clearable />
          </el-form-item>
          <el-form-item label="商户号:">
            <el-input v-model.trim="storeSearchForm.merchantId" placeholder="商户号" @keydown.native="handleStoreInput"
                      clearable />
          </el-form-item>
          <el-button type="primary" @click="handleSearchStore">搜索</el-button>
        </el-form>
      </el-row>
    </relate-store-dialog>
    <!-- 应用商品 -->
     <applied-goods-dialog v-if="appliedGoodsVisible" ref="formAppliedGoods" :applied-goods-visible="appliedGoodsVisible"
                          :goods-api="getAppGoodsApi" :goods-search-form="goodsSearchForm" :add-goods-row="addGoodsRow"
                          @handleAppliedGoodsConfirm="handleAppliedGoodsConfirm" @handleAppliedGoodsClose="handleAppliedGoodsClose" title="选择商品">
      <el-row slot>
        <el-form :model="goodsSearchForm" ref="relate" :inline="true">
          <el-form-item label="商品名称:">
            <el-input v-model.trim="goodsSearchForm.upgradeGoodsName" placeholder="商品名称" @keydown.native="handleGoodsInput"
                      clearable />
          </el-form-item>
          <el-button type="primary" @click="handleSearchGoods">搜索</el-button>
        </el-form>
      </el-row>
     </applied-goods-dialog>
  </div>
</template>
<script>
import { deepClone } from '@/common/util'
import RelateStoreDialog from './relateStoreDialog.vue'
import appliedGoodsDialog from './appliedGoodsDialog.vue'
import { getDistributeStoreListApi, getAppGoodsApi } from '@api/resident'
export default {
  name: 'RelateProTable',
  components: {
    RelateStoreDialog,
    appliedGoodsDialog
  },
  props: {
    merchantGoodsRefList: {
      type: Array,
      default: () => {}
    },
    formData: {
      type: Object,
      default: () => {}
    },
    addOrEdit: {
      type: String,
      default: () => ''
    }
  },
  watch: {
    merchantGoodsRefList: {
      handler(newVal) {
        this.merchantForm.selectedMerchantList = deepClone(newVal)
      },
      deep: true
    }
  },
  data() {
    return {
      getDistributeStoreListApi,
      getAppGoodsApi,
      merchantForm: {
        selectedMerchantList: []
      },
      storeSelected: [],
      relateStoreVisible: false,
      storeSearchForm: {
        merchantName: '',
        merchantId: ''
      },
      goodsSearchForm: {
        upgradeGoodsName: ''
      },
      appliedGoodsVisible: false
    }
  },
  methods: {
    // 新增门店
    addRow() {
      const _this = this
      if (((this.formData.sceneType ?? '') === '')) return this.$message.warning('请先选择所属业务')
      if (!this.formData.hireType) return this.$message.warning('请先选择适用招聘类型')
      _this.storeSelected = deepClone(_this.merchantForm.selectedMerchantList)
      // 将搜索条件清空
      this.storeSearchForm = {
        merchantName: '',
        merchantId: ''
      }
      _this.relateStoreVisible = true
    },
    handleRelateStoreConfirm(selectedData) {
      if (!selectedData.length) {
        this.$message({
          message: '请选择关联门店',
          type: 'warning',
          showClose: true
        })
        return true
      }
      if (selectedData?.length > 20) {
        return this.$message({
          message: '关联门店最多20个',
          type: 'warning',
          showClose: true
        })
      }
      selectedData.forEach(item => {
        if (!item.goodsData?.length) item.goodsData = []
      })
      this.$set(this.merchantForm, 'selectedMerchantList', deepClone(selectedData))
      this.relateStoreVisible = false
      this.$nextTick(() => {
        this.$refs.relateStoreTable?.clearValidate()
      })
    },
    arrayUnique(arr, name) {
      var hash = {}
      return arr.reduce(function (acc, cru, index) {
        if (!hash[cru[name]]) {
          hash[cru[name]] = { index: index }
          acc.push(cru)
        } else {
          acc.splice(hash[cru[name]]["index"], 1, cru)
        }
        return acc
      }, [])
    },
    handleRelateStoreClose() {
      this.relateStoreVisible = false
    },
    handleStoreInput(e) {
      (e.keyCode === 13) && this.handleSearchStore()
    },
    // 门店搜索
    handleSearchStore() {
      this.$refs.formRelateStore.handleCurrentChange(1)
    },
    handleDelete(item) {
      const filterArr = this.merchantForm.selectedMerchantList.filter(i => i.merchantId !== item.merchantId)
      this.$set(this.merchantForm, 'selectedMerchantList', filterArr)
    },
    headerRowStyle() {
      return {
        height: '40px',
        background: '#F2F4F7',
        color: '#333333',
        fontSize: '14px',
        fontWeight: 'bold'
      }
    },
    validateCustomForm() {
      return new Promise((resolve, reject) => {
        this.$refs.relateStoreTable.validate((valid) => {
          if (valid) {
            let arr = this.merchantForm.selectedMerchantList?.map(item => {
              return {
                merchantId: item.merchantId,
                merchantName: item.merchantName,
                goodsData: item.goodsData
              }
            })
            resolve(arr)
          } else {
            reject()
          }
        })
      })
    },
    // 添加商品
    addTag(row, rowIndex) {
      let _this = this
      _this.addGoodsRow = deepClone({ ...row, rowIndex })
      // 清除筛选条件
      this.goodsSearchForm = {
        upgradeGoodsName: ''
      }
      _this.appliedGoodsVisible = true 
    },
    handleAppliedGoodsConfirm(selectedData) {
      if (!selectedData.length) {
        this.$message({
          message: '请选择商品',
          type: 'warning',
          showClose: true
        })
        return true
      }
      this.$set(this.merchantForm.selectedMerchantList[this.addGoodsRow.rowIndex], 'goodsData', deepClone(selectedData))
      this.appliedGoodsVisible = false
      this.$nextTick(() => {
        this.$refs.relateStoreTable?.clearValidate()
      })
    },
    handleAppliedGoodsClose() {
      this.appliedGoodsVisible = false
    },
    handleGoodsInput(e) {
      (e.keyCode === 13) && this.handleSearchStore()
    },
    // 商品搜索
    handleSearchGoods() {
      this.$refs.formAppliedGoods.handleCurrentChange(1)
    },
    // table显示出的商品标签
    visibleTags(tags, rowIndex) {
      const container = this.$refs['tagContainer_' + rowIndex]
      if (!container) return tags
      const containerWidth = container.clientWidth
      let totalWidth = 0
      const visibleTags = []
      for (const tag of tags) {
        // 根据每个商品标签的宽度动态计算
        const tagWidth = this.measureTagWidth(tag)
        if (totalWidth + tagWidth + 70 > containerWidth) break // 70是预留隐藏tag按钮的宽度
        visibleTags.push(tag)
        totalWidth += tagWidth
      }
      return visibleTags
    },
    hiddenTags(tags, rowIndex) {
      const visibleCount = this.visibleTags(tags, rowIndex).length
      return tags.slice(visibleCount)
    },
    // 创建虚拟不会显示在页面的dom来获取每个商品标签的宽度
    measureTagWidth(tag) {
      const div = document.createElement('div')
      div.style.position = 'absolute'
      div.style.visibility = 'hidden'
      div.style.width = 'auto'
      div.style.padding = '0 8px'
      div.style.border = '1px solid #E8E8EA'
      div.style.borderRadius = '4px'
      div.style.display = 'inline-block'
      div.style.whiteSpace = 'nowrap'
      div.textContent = tag?.upgradeGoodsName
      document.body.appendChild(div)
      const width = div.clientWidth
      document.body.removeChild(div)
      return width + 26 // 26是删除图标和tag右边距的宽度
    },
    // 删除显示在table的标签
    removeTag(rowIndex, tagIndex) {
      this.merchantForm.selectedMerchantList[rowIndex].goodsData.splice(tagIndex, 1)
    },
    // 删除气泡框中的商品标签
    removeHiddenTag(rowIndex, tagIndex) {
      const visibleCount = this.visibleTags(this.merchantForm.selectedMerchantList[rowIndex].goodsData, rowIndex).length
      this.merchantForm.selectedMerchantList[rowIndex].goodsData.splice(tagIndex + visibleCount, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
.store-form{
  ::v-deep .header-cell-class-name{
    height: 30px;
    background: #F2F4F7;
  }
  ::v-deep .el-table th .cell {
    padding: 0;
  }
  ::v-deep .el-table__body-wrapper tr td{
    padding: 0 !important;
  }
  ::v-deep .el-table__row .cell {
    padding: 16px 0;
  }
}
.add-btn{
  margin-top: 10px;
}
.add_btn{
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border: 1px dashed #DCDCDC;
  border-radius: 3px;
  margin-right: 8px;
  cursor: pointer;
}
.tab_content{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  max-width: 550px;
  .tag_item{
    margin-bottom: 8px;
  }
}
.tag_item{
  flex-shrink: 0;
  display: inline-block;
  height: 26px;
  line-height: 26px;
  padding: 0 8px;
  background: #FAFBFE;
  border: 1px solid #E8E8EA;
  border-radius: 4px;
  margin-right: 8px;
  box-sizing: border-box;
  &.disabled {
    color: #66666642;
  }
  cursor: pointer;
  .del_icon{
    color: #666666;
    margin-left: 4px;
  }
}
</style>