<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <div class="sku-tag-components">
    <el-form-item
      :label="$t('product.productSpecifi')"
      :label-width="'120px'"
    >
      <div class="sku-border">
        <!-- 新增的商品sku tag -->
        <div
          v-for="(tag, index) in prodStore.skuTags"
          :key="tag.tagName"
          class="tagTree"
        >
          <div class="tag">
            <!-- 规格名 -->
            <div class="sku-background spec-name-box">
              <div class="spec-name">
                <div class="tag-item-tit">
                  {{ $t('product.prodInfo.seq') }}
                </div>
                <div>
                  <div>
                    <el-select
                      :model-value="tag.tagName"
                      filterable
                      allow-create
                      default-first-option
                      :placeholder="$t('product.prodInfo.select')"
                      @change="changeTagName($event, index)"
                    >
                      <el-option
                        v-for="item in unUseTags"
                        :key="item.attrId"
                        :label="item.attrLangList[0].name"
                        :value="item.attrLangList[0].name"
                      />
                    </el-select>
                    <!-- 提示 -->
                    <span class="tips-word">
                      <el-tooltip
                        placement="top"
                        effect="light"
                        :content="$t('product.prodInfo.supportManual')"
                      >
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </span>
                    <!-- 添加图片 -->
                    <span
                      v-if="index === 0"
                      class="add-img"
                    >
                      <el-checkbox
                        v-model="addImgchecked"
                        @change="handleAddImgchecked(index)"
                      >{{ $t('product.prodInfo.addSeqPic') }}</el-checkbox>
                    </span>
                    <div class="del-spec-btn">
                      <el-icon
                        class="el-icon-error"
                        @click="removeTag(index)"
                      >
                        <CircleClose />
                      </el-icon>
                    </div>
                  </div>

                  <div
                    v-if="index === 0"
                    class="first-tag-tips"
                  >
                    {{ $t('product.prodInfo.seqTips') }}
                  </div>
                </div>
              </div>
            </div>
            <!-- 规格值 -->
            <div
              v-if="tag.tagName"
              class="spec-val"
            >
              <div class="tag-item-tit">
                {{ $t('product.prodInfo.seqValue') }}
              </div>
              <div class="tag-item-box">
                <div
                  class="item-list"
                  :class="{ 'ft-spec-val': index === 0 }"
                >
                  <div
                    v-for="(tagItem, tagItemIndex) in tag.tagItems"
                    :key="tagItemIndex"
                    class="spec-val-item"
                    :class="{ 'ft-spec-val-item': index === 0 && !tagItem.creating && addImgchecked }"
                  >
                    <div class="item2">
                      <div class="prop-value">
                        <div class="text-hid">
                          {{ tagItem.propValue }}
                        </div>
                        <!-- 第一个规格允许上传图片 -->
                        <div
                          v-if="index === 0 && !tagItem.creating && addImgchecked"
                          class="up-box"
                        >
                          <div class="img-upload">
                            <img-upload
                              v-model="tagItem.pic"
                              @input="changeTagItemPic($event, tagItem, index, tagItemIndex)"
                            />
                          </div>
                          <div
                            v-if="tagItem.pic"
                            class="text-btn"
                            @click="delTagItemPic(index, tagItemIndex)"
                          >
                            {{ $t('table.delete') }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="del-btn"
                        @click="handleTagClose(index, tagItemIndex)"
                      >
                        <el-icon class="el-icon-close">
                          <Close />
                        </el-icon>
                      </div>
                    </div>
                  </div>
                  <!-- 添加规格值 -->
                  <div class="add-item">
                    <el-select
                      v-if="tagItemInputs[index] && tagItemInputs[index].visible"
                      :ref="saveTagInputRef"
                      v-model="tagItemInputs[index].value"
                      filterable
                      allow-create
                      default-first-option
                      value-key="valueId"
                      :placeholder="$t('product.prodInfo.select')"
                      class="input-new-tag"
                      @visible-change="addSkuTagItem($event, index)"
                    >
                      <el-option
                        v-for="item in getTagValues(tag.tagName,tag.tagItems)"
                        :key="item.attrValueId"
                        :label="item.values[0].value"
                        :value="item.values[0].value"
                      />
                    </el-select>

                    <el-icon
                      v-else
                      class="add-btn"
                      :class="{'disable': !tag.showAddTagBtn}"
                      @click="showTagInput(index)"
                    >
                      <CirclePlus />
                    </el-icon>
                  </div>
                  <!-- 添加规格值 / -->
                </div>
                <div
                  v-if="index === 0"
                  class="img-tips"
                >
                  {{ $t('product.prodInfo.supportSeqPicTips') }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 添加商品规格按钮 -->
        <div class="sku-background">
          <div
            class="default-btn add-sku-btn"
            @click="addskuTag()"
          >
            {{ $t('product.prodInfo.addShopSeq') }}
          </div>
          <span class="tips">({{ $t('product.prodInfo.maxGruop') }})</span>
        </div>
      </div>
    </el-form-item>
  </div>
</template>

<script setup>
import * as api from '@/api/product/category'
import { validNoEmptySpace } from '@/utils/validate'
import { ElMessage } from 'element-plus'
import { watch } from 'vue'

const { proxy } = getCurrentInstance()

const props = defineProps({
  skuList: {
    type: Array,
    default () {
      return []
    }
  }
})

const emit = defineEmits(['update:skuList', 'change', 'hasSkuImgChange', 'clearSkuImg', 'changeSkuImg'])

const Data = reactive({
  isShowTagInput: false,
  addTagInput: {
    propName: '',
    propNameEn: '',
    propNameObj: null,
    selectValues: []
  },
  type: 0,
  tagIndex: '',
  tagItemName: '',
  tagName: '',
  tagItemNameEn: '',
  tagNameEn: '',
  tagNameIndex: 0,
  tagItemInputs: [],
  // sku的标记
  // tags: [],
  // 数据库中的规格
  dbTags: [],
  skuTagsStatus: [
    {
      showAddIcon: false
    }
  ],
  // 根据选定的规格所查询出来的规格值
  dbTagValues: [],
  dbTagValuesMap: {},
  specs: [], // 使用的规格
  maxValueId: 0, // 规格值id最大
  maxPropId: 0, // 规格id 最大
  initing: false,

  addImgchecked: true,
  propValue: [],
  tagPic: '',

  changeImg: false,

  // 最大规格组合数量
  maxNumOfCombo: 100
})

const { tagItemInputs, addImgchecked } = toRefs(Data)

const prodStore = useProdStore()

const unUseTags = computed(() => {
  const res = []
  for (let i = 0; i < Data.dbTags.length; i++) {
    const dbTag = Data.dbTags[i]
    let specIndex = prodStore.skuTags.findIndex(tag => tag.tagName === dbTag.attrLangList[0].name)
    if ($t('language') === 'English') {
      specIndex = prodStore.skuTags.findIndex(tag => tag.tagNameEn === (dbTag.attrLangList.length > 1 ? dbTag.attrLangList[1].name : dbTag.attrLangList[0].name))
    }
    if (specIndex === -1) {
      res.push(dbTag)
    }
  }
  return res
})

// 计算规格组合数量
const countSkuTagCombo = computed(() => {
  // 计算当前规格组合数量
  const skuTags = prodStore.skuTags.filter(el => el.tagItems && el.tagItems.length)
  return skuTags.length ? skuTags.map(tag => (tag.tagItems && tag.tagItems.length)).reduce((a, b) => a * b) : 0
})

watch(() => prodStore.skuTags, (val) => {
  handlerTagLength(val)
  if (Data.initing) {
    Data.initing = false
    return
  }
  let skuList = []
  if (Data.type === 4) {
    // 删除规格值
    props.skuList.forEach((sku) => {
      const propertiesArray = sku.properties.split(';')
      if (propertiesArray[Data.tagNameIndex] && Data.tagItemName !== propertiesArray[Data.tagNameIndex].substring(propertiesArray[Data.tagNameIndex].indexOf(':') + 1)) {
        skuList.push(sku)
      }
    })
  } else if (Data.type === 2) {
    // 添加规格值
    const properties = Data.tagName + ':' + Data.tagItemName
    const propertiesEn = Data.tagNameEn + ':' + Data.tagItemNameEn
    // 增加或删除规格
    let tempSkuList = []
    val.forEach(tag => {
      if (skuList.length === 0) {
        if (Data.tagName === tag.tagName) {
          const sku = Object.assign({}, prodStore.defalutSku)
          sku.properties = properties // 销售属性组合字符串
          sku.propertiesEn = propertiesEn // 销售属性组合字符串
          skuList.push(sku)
        } else {
          tag.tagItems.forEach(tagItem => {
            const sku = Object.assign({}, prodStore.defalutSku)
            sku.properties = `${tag.tagName}:${tagItem.propValue}` // 销售属性组合字符串
            sku.propertiesEn = `${tag.tagNameEn}:${tagItem.propValueEn}` // 销售属性组合字符串
            skuList.push(sku)
          })
        }
        if (val.length === 1) {
          skuList = props.skuList.concat(skuList)
        }
      } else {
        tempSkuList = []
        if (Data.tagName === tag.tagName) {
          skuList.forEach(sku => {
            if (!slidingCheckTagName(sku.properties, Data.tagName)) {
              const newSku = Object.assign({}, sku)
              newSku.properties = `${sku.properties};${properties}`
              newSku.propertiesEn = `${sku.propertiesEn};${propertiesEn}`
              tempSkuList.push(newSku)
            }
          })
        } else {
          tag.tagItems.forEach(tagItem => {
            skuList.forEach(sku => {
              if (!slidingCheckTagName(sku.properties, tag.tagName)) {
                const newSku = Object.assign({}, sku)
                newSku.properties = `${sku.properties};${tag.tagName}:${tagItem.propValue}`
                newSku.propertiesEn = `${sku.propertiesEn};${tag.tagNameEn}:${tagItem.propValueEn}`
                tempSkuList.push(newSku)
              }
            })
          })
        }
        skuList = props.skuList.concat(tempSkuList)
      }
    })
  } else if (Data.type === 5) {
    // 新增/更改/删除图片
    return
  } else {
    // 增加或删除规格
    let tempSkuList = []
    val.forEach(tag => {
      if (skuList.length === 0) {
        tag.tagItems.forEach(tagItem => {
          const sku = Object.assign({}, prodStore.defalutSku)
          sku.properties = `${tag.tagName}:${tagItem.propValue}` // 销售属性组合字符串
          sku.propertiesEn = `${tag.tagNameEn}:${tagItem.propValueEn}` // 销售属性组合字符串
          if (tagItem.pic) {
            sku.pic = tagItem.pic
          }
          skuList.push(sku)
        })
      } else {
        tempSkuList = []
        skuList.forEach(sku => {
          tag.tagItems.forEach(tagItem => {
            const newSku = Object.assign({}, sku)
            newSku.properties = `${sku.properties};${tag.tagName}:${tagItem.propValue}`
            newSku.propertiesEn = `${sku.propertiesEn};${tag.tagNameEn}:${tagItem.propValueEn}`
            if (tagItem.pic) {
              newSku.pic = tagItem.pic
            }
            tempSkuList.push(newSku)
          })
        })
        skuList = tempSkuList
      }
    })
  }
  if (!skuList.length) {
    skuList.push(Object.assign({}, prodStore.defalutSku))
  }
  emit('change', skuList, val, Data.type)
}, {
  deep: true
})

watch(() => Data.addImgchecked, (newVal) => {
  const val = newVal ? 1 : 0
  emit('hasSkuImgChange', val)
})

onBeforeMount(() => {
  prodStore.skuTags = []
  api.getShopAttrs().then(data => {
    Data.dbTags = data
  })
})

onBeforeUnmount(() => {
  prodStore.skuTags = []
})

const init = (dataForm) => {
  Data.addImgchecked = dataForm.hasSkuImg === 1
  const skuTags = []
  dataForm.skus.forEach((item, index) => {
    if (index === 0) {
      // 确定有多少层添加第一个数据
      item.spuSkuAttrValues.forEach((el, i) => {
        skuTags.push({
          tagId: el.attrId,
          tagName: el.attrName,
          tagNameEn: el.attrName,
          tagItems: [{
            attrId: el.attrValueId,
            pic: i === 0 ? item.imgUrl : null,
            propValue: el.attrValueName,
            propValueEn: el.attrValueName
          }]
        })
      })
    } else {
      item.spuSkuAttrValues.forEach((el, i) => {
        // 根据attrValueId查找有没有重复的规格
        // const flag = skuTags[i].tagItems.some(item => item.attrId === el.attrValueId)
        // 根据attrValueName查找有没有重复的规格
        const flag = skuTags[i].tagItems.some(item => item.propValue === el.attrValueName)
        // 没有重复就添加
        if (!flag) {
          skuTags[i].tagItems.push({
            attrId: el.attrValueId,
            pic: i === 0 ? item.imgUrl : null,
            propValue: el.attrValueName,
            propValueEn: el.attrValueName
          })
        }
      })
    }
  })
  prodStore.skuTags = skuTags
}

// 计算规格组合数量，判断是否允许新增
const handlerTagLength = (val) => {
  const skuTags = val.filter(el => el.tagItems && el.tagItems.length)
  val.forEach((tag, idx) => {
    const ln = skuTags.length ? skuTags.map(tag => (tag.tagItems && tag.tagItems.length)) : []
    ln[idx] = ln[idx] ? ln[idx] + 1 : ''
    const count = ln.length ? ln.reduce((a, b) => a * b) : 0
    tag.showAddTagBtn = count <= Data.maxNumOfCombo
  })
}

// 从properties属性中查找是否存在名称为参数tagName的规格名
const slidingCheckTagName = (properties, tagName) => {
  if (tagName === '' && (properties.indexOf(';:') !== -1)) {
    return true
  }
  if (!tagName || tagName === '' || !properties || properties === '') {
    return false
  }
  let leftIndex = 0
  for (let i = 0; i < properties.length; i++) {
    leftIndex = i
    while (i < properties.length && properties.charAt(i) !== ':' && properties.charAt(i) !== ';') {
      ++i
    }
    if (properties.charAt(i) === ';' || (i - leftIndex) !== tagName.length || i >= properties.length) {
      continue
    }
    let j = 0
    while (properties.charAt(leftIndex++) === tagName.charAt(j)) {
      if (j + 1 === tagName.length) {
        return true
      }
      ++j
    }
  }
  return false
}

const handleAddImgchecked = (tagIndex) => {
  if (!Data.addImgchecked) {
    // 不添加规格图片时把图片属性置空
    if (prodStore.skuTags[tagIndex] && prodStore.skuTags[tagIndex].tagItems) {
      for (let i = 0; i < prodStore.skuTags[tagIndex].tagItems.length; i++) {
        const newSkuTagItem = {
          ...prodStore.skuTags[tagIndex].tagItems[i],
          pic: ''
        }
        if (newSkuTagItem) {
          prodStore.skuTags[tagIndex].tagItems.splice(i, 1, newSkuTagItem)
        }
      }
      for (let i = 0; i < props.skuList.length; i++) {
        this.skuList[i].pic = ''
      }
      Data.changeImg = true

      proxy.$forceUpdate()
      Data.type = 5
      emit('change', props.skuList, prodStore.skuTags, Data.type)
      emit('clearSkuImg')
    }
  }
}

// 添加规格名
const addskuTag = () => {
  if (prodStore.skuTags.find(tag => !tag.tagName ||
          !tag.tagItems.length ||
            tag.tagItems.find(tagItem => !tagItem.propValue))) {
    ElMessage({
      message: $t('product.prodInfo.completeTheAddedSpec'),
      type: 'error',
      duration: 1000
    })
    return
  }
  prodStore.skuTags.push({
    tagName: '',
    tagNameEn: '',
    tagItems: [
    ]
  })
  Data.type = 1
}

// 修改规格名
const changeTagName = (selVal, index) => {
  let useTag = unUseTags.value.find(el => selVal === el.attrLangList[0].name || selVal === el.propNameEn)
  const is = Object.prototype.toString.call(useTag) === '[object Object]'
  const reg = /[\\;\\:\\；\\：]/g
  // 纯空格校验
  if (validNoEmptySpace(selVal)) {
    ElMessage.error('内容不能只有空格')
    return
  }
  if (reg.test(selVal)) {
    ElMessage.error($t('product.specName') + $t('product.specialWordSymbolTips') + ':;')
    return
  }
  // 替换:;字符
  // selVal = selVal.replace(/[\\;\\:]/g, '')
  // 判断规格名是否超长
  if (selVal.length > 10) {
    ElMessage.error($t('product.postProductTips'))
    return
  }
  // 判断规格名是否重复
  if (prodStore.skuTags.find(el => el.tagName === selVal)) {
    ElMessage.error($t('group.skuName') + '\'' + selVal + '\' ' + $t('product.isExistsPleaReEn'))
    return
  }
  if (!is) {
    useTag = {
      attrLangList: [
        {
          attrId: '',
          name: selVal,
          lang: 1
        },
        {
          attrId: '',
          name: selVal,
          lang: 2
        }
      ]
    }
  }
  const oldSkuTag = prodStore.skuTags[index]
  const oldValue = $t('language') === 'English' && oldSkuTag.tagNameEn !== '' ? oldSkuTag.tagNameEn : oldSkuTag.tagName
  if (selVal !== oldValue) {
    // 规格发生变化
    Data.type = 3
  }
  if (useTag && oldSkuTag) {
    const newSkuTag = {
      tagId: useTag.attrId,
      tagName: useTag.attrLangList[0].name,
      tagNameEn: useTag.attrLangList.length > 1 ? useTag.attrLangList[1].name : useTag.attrLangList[0].name,
      tagItems: [
      ]
    }

    prodStore.skuTags.splice(parseInt(index), 1, newSkuTag)
  }
}

// 添加规格值
const addSkuTagItem = (event, tagIndex) => {
  Data.tagIndex = tagIndex
  const reg = /[\\;\\；]/g
  const itemValue = Data.tagItemInputs[tagIndex].value
  if (!event && itemValue) {
    let tagItem = {}
    Data.tagName = prodStore.skuTags[tagIndex].tagName
    Data.tagNameEn = prodStore.skuTags[tagIndex].tagNameEn
    // 纯空格校验
    if (validNoEmptySpace(itemValue)) {
      ElMessage.error('内容不能只有空格')
      Data.tagItemInputs[tagIndex].value = ''
      Data.tagItemInputs[tagIndex].visible = true
      return
    }
    if (reg.test(itemValue)) {
      ElMessage.error($t('product.specValue') + $t('product.specialWordSymbolTips') + ';')
      Data.tagItemInputs[tagIndex].value = ''
      Data.tagItemInputs[tagIndex].visible = true
      return
    }
    // 替换:;字符
    // itemValue = itemValue.replace(/[\\;\\:]/g, '')
    // 规格值是否超长
    if (itemValue.length > 20) {
      ElMessage.error($t('product.specValueCharacterLength'))
      Data.tagItemInputs[tagIndex].value = ''
      Data.tagItemInputs[tagIndex].visible = true
      return
    }
    // 校验规格值是否重复
    if (checkTagItem(prodStore.skuTags[tagIndex], tagIndex)) {
      Data.tagItemInputs[tagIndex].value = ''
      Data.tagItemInputs[tagIndex].visible = true
      return
    }
    Data.tagItemName = itemValue
    Data.tagItemNameEn = itemValue
    const dbTags = Data.dbTags.filter(item => item.attrLangList[0].name === prodStore.skuTags[tagIndex].tagName)
    let attrId = ''
    let propValueEn = itemValue
    if (dbTags.length !== 0) {
      const propIndex = dbTags[0].attrValues.findIndex(item => item.values[0].value === itemValue)
      if (propIndex !== -1) {
        attrId = getTagValues(prodStore.skuTags[tagIndex].tagName)[propIndex].attrValueId
        propValueEn = dbTags[0].attrValues[propIndex].values.length > 1 ? dbTags[0].attrValues[propIndex].values[1].value : itemValue
      }
    }
    tagItem = {
      attrId,
      propValue: itemValue,
      propValueEn
      // valueId: index === -1 ? 0 : maxValue ? (maxValue + 1) : getUUID()
    }
    if (tagItem) {
      prodStore.skuTags[tagIndex].tagItems.push(tagItem)
      Data.tagItemInputs[tagIndex].visible = false
      Data.tagItemInputs[tagIndex].value = ''
      Data.type = 2
    }
  }
  if (!event && !itemValue && Data.tagItemInputs[tagIndex].visible) {
    Data.tagItemInputs[tagIndex].visible = false
    Data.tagItemInputs[tagIndex].value = ''
    proxy.$forceUpdate()
  }
}

// 修改图片
const changeTagItemPic = (value, skuTagItem, tagIndex, tagItemIndex) => {
  const skuTag = prodStore.skuTags[tagIndex]
  if (skuTag && skuTagItem) {
    const newSkuTagItem = {
      ...skuTagItem,
      pic: value
    }

    prodStore.skuTags[tagIndex].tagItems.splice(tagItemIndex, 1, newSkuTagItem)

    Data.changeImg = true
    proxy.$forceUpdate()
    Data.type = 5
    // 把对应的sku图片修改
    for (let i = 0; i < props.skuList.length; i++) {
      if (!props.skuList[i].properties) {
        continue
      }
      const index = (props.skuList[i].properties.split(';'))[0].indexOf(':')
      const properties = (props.skuList[i].properties.split(';'))[0].substring(index + 1)
      if (properties === skuTagItem.propValue) {
        this.skuList[i].pic = value
      }
    }
    emit('changeSkuImg', skuTagItem.propValue, value)
  }
}

const delTagItemPic = (tagIndex, tagItemIndex) => {
  const skuTagItem = Object.assign({}, prodStore.skuTags[tagIndex].tagItems[tagItemIndex])
  skuTagItem.pic = ''
  changeTagItemPic('', skuTagItem, tagIndex, tagItemIndex)
  Data.changeImg = true
  Data.type = 5
}

// 获取对应规格名下的规格值列表
const getTagValues = (key, tagItems = null) => {
  const index = Data.dbTags.findIndex(item => {
    return item.attrLangList[0].name === key
  })
  // 去除已选择的规格值
  if (tagItems) {
    const attrIds = tagItems.map(el => el.attrId)
    return index === -1 ? [] : Data.dbTags[index].attrValues.filter(el => !attrIds.includes(el.attrValueId))
  }
  return index === -1 ? [] : Data.dbTags[index].attrValues
}

// 关闭标签 --删除
const handleTagClose = (tagIndex, tagItemIndex) => {
  Data.tagName = prodStore.skuTags[tagIndex].tagName
  Data.tagNameEn = prodStore.skuTags[tagIndex].tagNameEn
  Data.tagNameIndex = tagIndex
  Data.tagItemName = prodStore.skuTags[tagIndex].tagItems[tagItemIndex].propValue
  Data.tagItemNameEn = prodStore.skuTags[tagIndex].tagItems[tagItemIndex].propValueEn
  Data.type = 4

  prodStore.skuTags[tagIndex].tagItems.splice(tagItemIndex, 1)
}

const saveTagInputs = []

const saveTagInputRef = (el) => {
  if (el) saveTagInputs.push(el)
}

// 显示标签输入框
const showTagInput = (tagIndex) => {
  // 判断是否允许添加
  if (!prodStore.skuTags[tagIndex].showAddTagBtn) {
    ElMessage.error(
          `${'当前已添加' +
          countSkuTagCombo.value +
          '组商品规格'}（${'最多可添加' +
          Data.maxNumOfCombo +
          '组'}），该规格名下不可添加`
    )
    return
  }
  Data.tagItemInputs.push({ visible: false, value: '' })
  Data.tagItemInputs[tagIndex] = { visible: true, value: '' }
}

// 删除 规格
const removeTag = (tagIndex) => {
  Data.type = 3
  prodStore.skuTags.splice(tagIndex, 1)
}

// 新增规格值时，判断是否存在同名的规格值
const checkTagItem = (tag, tagIndex) => {
  const tagItem = Data.tagItemInputs[tagIndex].value
  if (!tagItem) {
    Data.tagItemInputs[tagIndex].visible = false
    Data.tagItemInputs[tagIndex].value = ''
    return true
  }
  let isSame = false
  const arr = tag.tagItems.map((item) => {
    return $t('language') === 'English' ? item.propValueEn : item.propValue
  })
  if (arr.indexOf(tagItem) !== -1) {
    isSame = true
    ElMessage.error($t('product.specificationValue') + '\'' + tagItem + '\' ' + $t('product.isExistsPleaReEn'))
  }
  return isSame
}

// 校验规格列表
const vaildSkuTag = () => {
  let isValid = true
  if (countSkuTagCombo.value > Data.maxNumOfCombo) {
    ElMessage.error(
          `${$t('product.currentlyAdded') +
          countSkuTagCombo.value +
          $t('product.productSpecCount')}（${$t('product.mostAdd') +
          Data.maxNumOfCombo +
          $t('product.groups')}），${$t('product.cannotAddUnderThisSpec')}`
    )
    return false
  }
  if (prodStore.skuTags && prodStore.skuTags.length) {
    prodStore.skuTags.some(sku => {
      if (!sku.tagName) {
        // 规格名不能为空
        ElMessage({
          message: $t('product.specNameNotNull'),
          type: 'error',
          duration: 1000
        })
        isValid = false
        // 终止遍历
        return true
      }
      if (sku.tagName && (!sku.tagItems.length || (sku.tagItems.length && sku.tagItems.find(item => !item.propValue)))) {
        // 规格值不能为空
        ElMessage({
          message: $t('product.specValueCannotBeEmpty'),
          type: 'error',
          duration: 1000
        })
        isValid = false
        // 终止遍历
        return true
      }
      return false
    })
  }
  return isValid
}

defineExpose({
  vaildSkuTag,
  init
})

</script>

<style lang="scss" scoped>
.sku-tag-components {
  .input-new-tag {
    width: 150px;
    margin-bottom: 10px;
    // margin-left: 10px;
    // vertical-align: bottom;
  }
  .text-btn {
    display: inline-block;
    margin-left: 5px;
    cursor: pointer;
    color: #155bd4;
  }
}

.sku-tag-components {
  & :deep(img) {
    vertical-align: top;
  }
  // 新增规格外部边框
  .sku-border{
    border: 1px solid #DCDCDC;
    // padding-bottom: 10px;
    // width:70%
  }
  & :deep(.sku-background){
    background-color: #f8f8f8;
    margin: 10px;
    padding: 7px 10px;
    .el-button{
      margin-left: 10px;
      span{
        color:#000 !important;
      }
    }
    .el-form-item__label{
      padding:0 24px 0 0
    }
    .add-sku-btn {
      height: 28px;
      line-height: 28px;
      // margin-left: 10px;
    }
    .tips {
      font-size: 12px;
      color: #999999;
      margin-left: 10px;
    }
  }
  .tag-item-tit {
    min-width: 45px;
    margin-right: 10px;
  }
  // 规格名
  .sku-background.spec-name-box {
    .spec-name {
      display: flex;
      position: relative;
      .first-tag-tips {
        color: #999;
        font-size: 12px;
        height: 1em;
        line-height: 1em;
        margin: 5px 0;
      }
    }
    // 提示
    .tips-word {
      margin-left: 10px;
      margin-right: 10px;
      & :deep(.el-icon-question::before) {
        color: #999;
      }
    }
    & :deep(.el-input__inner) {
      width: 150px;
    }
    .del-spec-btn {
      display: inline-block;
      font-size: 20px;
      // line-height: 47px;
      position: absolute;
      right: 10px;
      top: 0;
      bottom: 0;
      vertical-align: middle;
      color: #BFBFBF;
      cursor: pointer;
      & :deep(.el-icon-error) {
        vertical-align: middle;
      }
    }
    .add-img {
      margin-left: 10px;
    }
  }
  // 规格值
  .spec-val {
    display: flex;
    margin: 0 10px;
    padding: 0 10px;
    .tag-item-tit {
      margin-right: 12px;
    }
    .spec-val-item {
      margin-bottom: 10px;
      & :deep(.el-input__inner) {
        width: 100%;
        padding-left: 0!important;
        padding-right: 5px;
        border: 0;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
      }
      & :deep(.el-input__suffix) {
        display: none;
      }
      position: relative;
      display: inline-block;
      width: 150px;
      line-height: 1.5em;
      padding: 0 10px;
      box-sizing: border-box;
      border: 1px solid #DCDCDC;
      .item2 {
        display: flex;
        justify-content: space-between;
        .prop-value {
          width: 90%;
          .text-hid {
            display: block;
            width: 100%;
            height: 32px;
            line-height: 32px;
            overflow: hidden;
            text-overflow:ellipsis;
            white-space: nowrap;
          }
          .up-box {
            display: flex;
            align-items: flex-end;
            height: 80px;
            .img-upload {
              width:80px;
              height: 80px;
              :deep(.el-upload) {
                width:80px;
                height: 80px;
              }
              & :deep(.plugin-images),
              & :deep(.plugin-images .el-upload--picture-card),
              & :deep(.el-upload-list),
              & :deep(.el-upload-list__item.is-success) {
                width: 80px;
                line-height: 80px;
                border-radius: 0;
              }
              & :deep(.plugin-images .el-upload--picture-card) {
                border: 1px dashed #155BD4;
                background: transparent;
                & i {
                  font-size: 18px;
                  font-weight: bold;
                  color: #155BD4;
                }
              }
            }
            .text-btn {
              height: 20px;
              line-height: 20px;
            }
          }
        }
        .del-btn {
          font-size: 12px;
          line-height: 32px;
          color: #999;
          cursor: pointer;
        }
      }
      // &:not(:last-child) {
      //   margin-right: 5px;
      // }
    }
    .spec-val-item:not(:last-child) {
      margin-right: 10px;
    }
    .add-btn {
      font-size: 20px;
      line-height: 32px;
      vertical-align: middle;
      color: #155bd4;
      cursor: pointer;
    }
    .add-btn.disable {
      color: #DCDCDC;
    }

    // 第一个规格值
    .spec-val-item.ft-spec-val-item {
      padding: 0 10px 10px 10px;
      & :deep(.el-input__inner) {
        padding-left: 5px;
        padding-right: 5px;
        border: 0;
        height: 24px;
        line-height: 24px;
        margin-bottom: 5px;
      }
    }
    .tag-item-box {
      .item-list {
        display: flex;
        align-items: flex-start;
        flex-wrap: wrap;
      }
      .img-tips {
        height: 1em;
        line-height: 1em;
        margin-bottom: 10px;
        color: #999999;
        font-size: 12px;
      }
    }
  }

  .ft-spec-val {
    .add-btn {
      vertical-align: top;
    }
  }

.default-btn {
  height: 32px;
  line-height: 32px;
  padding: 0 15px;
  font-size: 13px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
  cursor: pointer;
  display: inline-block;
}
.default-btn:hover {
  color: #155bd4;
  border-color: #155bd4;
}
}
</style>
