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

  https://www.mall4j.com/

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

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-specification-management">
    <view
      v-if="specList.length > 0"
      class="spec"
    >
      <view
        v-for="(item, index) in specList"
        :key="index"
      >
        <!-- 有图的规格 -->
        <view
          v-if="index === 0"
          class="spec-item"
        >
          <view class="spec-name">
            <view>{{ item.name }}</view>
            <view
              v-if="!showProd"
              class="edit-icon-box"
              @tap="showEdit = true;showIndex=index"
            >
              <view
                v-for="dot in 3"
                :key="dot"
                class="edit-icon"
              />
            </view>
          </view>
          <view
            v-if="showEdit && showIndex === index"
            class="popup"
          >
            <view
              class="mask-edit"
              @tap="mask"
            />
            <view class="edit-popup">
              <view
                class="item"
                @tap.stop="edit(1, item.name, index)"
              >
                {{ $t('bianJiGuiGeMing') }}
              </view>
              <view
                class="item"
                @tap.stop="edit(2, item, index)"
              >
                {{ $t('bianJiGuiGeZhi') }}
              </view>
              <view
                class="item"
                @tap.stop="deletespec(item.name, index)"
              >
                {{ $t('shanChu') }}
              </view>
            </view>
          </view>
          <view
            v-if="item.prodPropValues.length === 0"
            class="empty-spec-vaule"
            @tap="addApec(item.propId,index)"
          >
            <view class="empty-spec-vaule-item">
              <view class="add-icon">
                +
              </view>
              {{ $t('tianJiaGuiGeZhi') }}
            </view>
          </view>
          <view v-if="item.prodPropValues.length > 0">
            <view class="spec-vaule">
              <view
                v-for="(itemValue, indexValue) in item.prodPropValues"
                :key="indexValue"
                :class="[isUpImg ? 'spec-vaule-item-img' : 'spec-vaule-item']"
              >
                <img-upload
                  v-if="isUpImg"
                  :pic="itemValue.pic"
                  :img-id="indexValue"
                  @delete-img="deleteImg"
                  @up-load-img="uploadImg"
                />
                <view class="vaule">
                  {{ itemValue.propValue }}
                </view>
              </view>
            </view>
            <view class="line" />
            <view class="spec-value-image-switch">
              <view class="title">
                <view class="big-text">
                  {{ $t('tianJiaGuiGeTuPian') }}
                </view>
                <view class="explanation-text">
                  {{ $t('jinDiYiZuGuiGeZhiKeTianJia') }}
                </view>
              </view>
              <switch
                ref="isUpImgRef"
                :checked="isUpImg"
                style="transform:scale(0.75);"
                color="#082BA6"
                :disabled="showProd"
                @change="switchChange"
              />
            </view>
          </view>
        </view>
        <!-- 有图的规格 -->

        <!-- 无图的规格 -->
        <view
          v-if="index > 0"
          class="spec-item"
        >
          <view class="spec-name">
            <view class="text">
              {{ item.name }}
            </view>
            <view
              class="edit-icon-box"
              @tap="showEdit = true;showIndex=index"
            >
              <view
                v-for="dot in 3"
                :key="dot"
                class="edit-icon"
              />
            </view>
          </view>
          <view
            v-if="showEdit && showIndex === index"
            class="popup"
          >
            <view
              class="mask-edit"
              @tap="mask"
            />
            <view class="edit-popup">
              <view
                class="item"
                @tap.stop="edit(1, item.name, index)"
              >
                {{ $t('bianJiGuiGeMing-0') }}
              </view>
              <view
                class="item"
                @tap.stop="edit(2, item, index)"
              >
                {{ $t('bianJiGuiGeZhi-0') }}
              </view>
              <view
                class="item"
                @tap.stop="deletespec(item.name, index)"
              >
                {{ $t('shanChu') }}
              </view>
            </view>
          </view>
          <view
            v-if="item.prodPropValues.length === 0"
            class="empty-spec-vaule"
            @tap="addApec(item.propId,index)"
          >
            <view class="empty-spec-vaule-item">
              <view class="add-icon">
                +
              </view>
              {{ $t('tianJiaGuiGeZhi-0') }}
            </view>
          </view>
          <view class="spec-vaule">
            <view
              v-for="(itemValue, indexValue) in item.prodPropValues"
              :key="indexValue"
              class="spec-vaule-item"
            >
              <view class="vaule">
                {{ itemValue.propValue }}
              </view>
            </view>
          </view>
        </view>
      <!-- 无图的规格 -->
      </view>
    </view>
    <empty-tips
      v-else
      :tips-list="tipsList"
    />
    <view class="specification-management-footer">
      <common-btn
        :btn-config="prodManaBtnConfig"
        @handle-click-btn="AddSku"
        @handle-click-more-btn="handleClickMoreBtn"
      />
    </view>
    <add-specification-name
      v-if="showAddSpecificationName"
      :add-title="addTitle"
      :data-list="specComList"
      :all-data="specAllNameList"
      :spec-name="specName"
      :sel-spec-values="currSelSpecValues"
      @cancal="closeAddSpecificationName"
      @search="search"
    />

    <create-popup
      v-if="showCreatePopup"
      :reg-tip="regTip"
      :input-val="createSkuName"
      :is-required="true"
      :config="createConfig"
      @cancal="closeCreatePopup"
      @submit="getSubmitData"
    />
  </view>
</template>

<script setup>
import createPopup from '@/package-prod/components/create-popup/create-popup.vue'
import AddSpecificationName from '@/package-prod/components/add-specification-name/add-specification-name.vue'

const prodStore = useProdStore()

const tipsList = [$t('ninHuanMeiYouTianJiaGuiGe'), $t('jinZhiChiWeiDiYiZuGuiGeSheZhiGuiGeZhiTuPian')]

const Data = reactive({
  prodManaBtnConfig: {
    btnText: $t('tianJiaGuiGe'),
    isPlain: false
  },
  regTip: {
    reg: /^.*[:|;|：|；].*$/,
    regTip: $t('qingWuShuRuFuHaoHe')
  },
  createSkuName: '', // 新增规格名
  // 新增规格tip
  createConfig: {
    header: $t('bianJiGuiGeMing-1'),
    placeholder: $t('qingShuRuGuiGeMing'),
    cancalText: $t('quXiao-0'),
    submitText: $t('queDing'),
    submitTip: $t('qingShuRuGuiGeMing-0'),
    maxlength: 10
  },
  showCreatePopup: false, // 显示新增/修改弹窗
  showEdit: false, // 右侧操作栏显示
  showIndex: -1, // 右侧操作栏index
  showAddSpecificationName: false, // 规格值/名编辑层显示
  isUpImg: true, // 是否上传图片
  specList: [], // 规格数据
  dataList: [], // 搜索原始名/值数据
  specComList: [], // 搜索显示名/值数据
  specAllNameList: [], // 已选规格名列表
  specAllData: {}, // 所有查询返回sku数据
  editIndex: '', // 修改index
  addTitle: 'name', // 当前新增类型（name, value）

  specData: [] // 原数据
})

const { prodManaBtnConfig, regTip, createSkuName, createConfig, showCreatePopup, showEdit, showIndex, showAddSpecificationName, isUpImg, specList, specComList, specAllNameList, addTitle } = toRefs(Data)

const specName = computed(() => {
  return Array.from(new Set([...Data.specList.map(x => x.name), ...Data.dataList.map(x => x.name)]))
})

/**
* 生命周期函数--监听页面显示
*/
onShow(() => {
  // 加载导航标题
  uni.setNavigationBarTitle({
    title: $t('shangPinGuiGe')
  })
})
const showProd = ref(false)
onLoad((options) => {
  showProd.value = options.showProd === 'true'
  Data.specData = prodStore.dataForm.skuList
  Data.specData.forEach(x => {
    x.changeStock = parseInt(x.stocks)
  })
  // 判断是否开启规格图片
  Data.isUpImg = prodStore.dataForm.skuList.some(i => i.pic)
  dealSpecData()
  getSpecData()
})

// 处理反显数据
const dealSpecData = () => {
  if (Data.specData.length > 0) {
    const data = Data.specData
    if (data[0].properties === '') {
      return
    }
    const valueObj = {}
    const skuList = {}
    const nameList = data[0].properties.split(';').map((item) => {
      const name = item.slice(0, item.indexOf(':'))
      valueObj[name] = []
      skuList[name] = []
      return name
    })
    data.forEach((item) => {
      const list = item.properties.split(';')
      for (let i = 0; i < nameList.length; i++) {
        const index = list[i].indexOf(':')
        const sku = [list[i].slice(0, index), list[i].substring(index + 1)]
        if (skuList[nameList[i]].indexOf(sku[1]) < 0) {
          skuList[nameList[i]].push(sku[1])
          valueObj[sku[0]].push({
            isSelect: true,
            name: sku[1],
            pic: (i === 0 ? item.pic : ''),
            propId: item.prodId,
            propValue: sku[1],
            propValueEn: sku[1],
            valueId: ''
          })
        }
      }
    })
    nameList.forEach((item) => {
      Data.specList.push({
        name: item,
        prodPropValues: valueObj[item]
      })
    })
    isShowBreak()
  }
}

// 获取规格数据
const getSpecData = () => {
  http.request({
    url: '/prod/spec/list',
    method: 'GET',
    data: {}
  }).then(({ data: res }) => {
    res.forEach(item => {
      Data.specAllData[item.propId] = item.prodPropValues
      item.prodPropValues = []
    })
    Data.dataList = dealList(res)
    if (Data.addTitle === 'name') {
      Data.specAllNameList = Data.dataList.map((item) => {
        return item.name
      })
      Data.specComList = Data.dataList
      if (Data.specData.length > 0) {
        const nameList = Data.specList.map((item) => {
          return item.name
        })
        const list = []
        Data.specComList.forEach((item) => {
          if (nameList.indexOf(item.name) < 0) {
            list.push(item)
          } else {
            Data.specList[nameList.indexOf(item.name)].propId = item.propId
          }
        })
        Data.specComList = list
        Data.dataList = list
      }
    }
  })
}

// 底部按钮点击
const handleClickMoreBtn = (index) => {
  if (showProd.value && index !== 3) return

  switch (index) {
    case 1:
      AddSku()
      break
    case 2:
      toBreakDown()
      break
    case 3:
      handleSubmit()
      break
  }
}

// 规格明细
const toBreakDown = () => {
  handleSubmit(true)
}

const deleteImg = (index) => {
  const data = Data.specList[0].prodPropValues[index]
  data.pic = ''
  Data.specList[0].prodPropValues.index = data
}

// 拼接保存数据
const dealSpecList = (specListData = [], isReverse = false) => {
  const specList = JSON.parse(JSON.stringify(specListData))
  if (specList.length === 0) return []
  if (isReverse) specList.reverse()
  const imgIndex = isReverse ? specList.length - 1 : 0
  const onevalueList = specList[imgIndex].prodPropValues.map((item) => {
    return item.name
  })
  const valuesList = specList.map((item) => {
    return item.prodPropValues
  })
  const specTeams = specTeam(valuesList)
  const dataForm = []
  specTeams.forEach((item) => {
    let properties = ''
    item.forEach((itemName, index) => {
      properties += specList[specList.length - 1 - index].name + ':' + itemName + (index !== (item.length - 1) ? ';' : '')
    })
    let pic = ''
    pic = onevalueList.indexOf(item[0]) > -1 ? specList[imgIndex].prodPropValues[onevalueList.indexOf(item[0])].pic : ''
    pic = pic || ''
    dataForm.push({
      name: item,
      changeStock: null,
      price: 0.01,
      stocks: 0,
      pic,
      oriPrice: 0.01,
      volume: 0,
      weight: 0.01,
      stockWarning: 0, // 库存预警
      status: 1,
      partyCode: '',
      prodName: prodStore.dataForm.prodName + ' ' + item.join(' '),
      properties,
      skuName: item.join(' '),
      isShow: true,
      isSelect: false,
      stockPointList: [{
        stock: 0,
        stockPointId: prodStore.stockPointInfo.defaultWarehouseId,
        stockPointType: 1,
        type: 0
      }]
    })
  })
  return dataForm
}

// 组合规格值（笛卡儿积）
const specTeam = (arr) => {
  let specTeams = []
  for (let i = 0; i < arr.length; i++) {
    const test = []
    for (let x = 0; x < arr[i].length; x++) {
      if (i === 0) {
        test[x] = [arr[i][x].name]
      } else {
        for (let y = 0; y < specTeams.length; y++) {
          test[test.length] = [arr[i][x].name]
          specTeams[y].forEach((item) => {
            test[test.length - 1].push(item)
          })
        }
      }
    }
    specTeams = test
  }
  return specTeams
}

// 点击新增规格
const AddSku = () => {
  if (Data.specList.length > 0 && Data.specList[Data.specList.length - 1].prodPropValues.length === 0) {
    uni.showToast({
      title: $t('qingXianWanShanYiTianJiaGuiGe'),
      mask: true,
      icon: 'none',
      duration: 1500
    })
    return
  }
  if (Data.specList.length >= 3) {
    uni.showToast({
      title: $t('zuiDuoKeTianJia_3GeGuiGe'),
      mask: true,
      icon: 'none',
      duration: 1500
    })
    return
  }
  Data.addTitle = 'name'
  Data.specComList = Data.dataList
  Data.showAddSpecificationName = true
}

// 保存
const handleSubmit = (index = false) => {
  let specListValue = dealSpecList(Data.specList, true)

  // 判断是否编辑原数据
  if (Data.specData.length > 0) {
    const propertiesList = Data.specData.map((item) => {
      return item.properties
    })
    let num = 0
    specListValue.forEach((item) => {
      const index = propertiesList.indexOf(item.properties)
      if (index > -1) {
        num++
        if (Data.specData[index].pic !== item.pic) {
          Data.specData[index].pic = item.pic
        }
      }
    })
    if (num === specListValue.length && num === Data.specData.length) {
      specListValue = Data.specData
      specListValue.forEach((item) => {
        item.changeStock = 0
      })
    }
  }
  prodStore.dataForm.skuList = specListValue
  if (index) {
    uni.navigateTo({
      url: '/package-prod/pages/specification-breakdown/specification-breakdown'
    })
  } else {
    uni.navigateTo({
      url: '/package-prod/pages/post-prod/post-prod' + '?showProd=' + showProd.value
    })
  }
}

// 规格搜索
const search = (val) => {
  if (!val) {
    Data.specComList = Data.dataList
    return
  }
  const list = []
  Data.dataList.forEach((item) => {
    if (item.name.indexOf(val) > -1) {
      list.push(item)
    }
  })
  Data.specComList = list
}

// 屏蔽层点击
const mask = () => {
  Data.showEdit = false
}

// 点击添加规格值
const addApec = (id, index) => {
  Data.addTitle = 'value'
  Data.specComList = []
  Data.editIndex = index
  // 判断数据是否存在该规格
  if (!id) {
    const tag = Data.dataList.find(el => el.name === Data.specList[index].name)
    id = tag ? tag.id : ''
  }
  if (!id) {
    Data.showAddSpecificationName = true
    return
  }
  getSpecValues(id, 2)
}

// 根据规格id获取规格（type: 1规格名; 2规格值）
const getSpecValues = (id, type, prodPropValues = []) => {
  if (Object.keys(Data.specAllData).length > 0) {
    getSpecValuesDeal(Data.specAllData[id], type, prodPropValues)
  } else {
    http.request({
      url: '/prod/spec/listSpecValue/' + id,
      method: 'GET'
    }).then(({ data }) => {
      getSpecValuesDeal(data, type, prodPropValues)
    })
  }
}

// 获取规格值处理
const currSelSpecValues = ref([])
const getSpecValuesDeal = (res, type, prodPropValues) => {
  currSelSpecValues.value = prodPropValues
  const valueList = res.length > 0 ? res : []
  if (type === 1) {
    valueList.forEach((item) => {
      item.isSelect = false
      item.name = item.propValue
    })
  } else {
    // 规格值数据
    valueList.forEach((item) => {
      item.name = item.propValue
      item.isSelect = false
      item.pic = ''
    })
  }
  Data.specComList = valueList
  Data.showAddSpecificationName = true
}

// 处理规格名数据
const dealList = (list) => {
  list.forEach((item) => {
    item.name = item.propName
    item.id = item.propId
    item.prodPropValues = item.prodPropValues ? item.prodPropValues : []
  })
  return list
}

// 编辑规格名/值（type: 1规格名; 2规格值）
const edit = (type, v, index) => {
  Data.editIndex = index
  if (type === 1) {
    mask()
    Data.showCreatePopup = true
    Data.createSkuName = v.toString()
  }
  if (type === 2) {
    mask()
    Data.addTitle = 'value'
    const list = JSON.parse(JSON.stringify(Data.specList[index].prodPropValues))
    if (!v.propId) {
      Data.specComList = Data.specList[index].prodPropValues
      Data.showAddSpecificationName = true
      return
    }
    getSpecValues(v.propId, 2, list)
  }
}

// 删除指定规格
const deletespec = (name, index) => {
  mask()
  uni.showModal({
    title: '',
    content: $t('queDingShanChuNameGuiGe').replace('[name]', name),
    cancelText: $t('quXiao-0'),
    confirmText: $t('shanChu'),
    confirmColor: '#082BA6',
    success (res) {
      if (res.confirm) {
        // 删除的规格名加入可选队列
        if (Data.specList[index].propId) {
          Data.dataList.push(Data.specList[index])
        }
        Data.specList[index].prodPropValues = []
        Data.specList.splice(index, 1)
        Data.specAllNameList = Data.specList.map((item) => {
          return item.name
        })
        isShowBreak()
        prodStore.dataForm.skuList = dealSpecList(Data.specList)
      }
    }
  })
}

// 添加规格名/值回调
const closeAddSpecificationName = (item) => {
  Data.showAddSpecificationName = false
  if (item === '') {
    return
  }
  if (Data.addTitle === 'value') {
    Data.specComList = []
    Data.specList[Data.editIndex].prodPropValues = item
    Data.editIndex = ''
  } else {
    if (Data.specComList.indexOf(item) > -1) {
      Data.specComList = Data.dataList
      Data.specComList.splice(Data.specComList.indexOf(item), 1)
      Data.dataList = Data.specComList
    }
    Data.specList.push(item)
    Data.specAllNameList = Data.specList.map((item) => {
      return item.name
    })
  }
  isShowBreak()
}

// 动态修改下方按钮
const isShowBreak = () => {
  if (Data.specList.length > 0 && Data.specList[Data.specList.length - 1].prodPropValues.length > 0) {
    Data.prodManaBtnConfig = {
      btnList: [
        {
          btnText: $t('tianJiaGuiGe-0'),
          isPlain: true
        },
        {
          btnText: $t('tianJiaGuiGeMingXi'),
          isPlain: true
        },
        {
          btnText: $t('baoCun'),
          isPlain: false
        }
      ]
    }
  } else {
    Data.prodManaBtnConfig = {
      btnText: $t('tianJiaGuiGe-1'),
      isPlain: false

    }
  }
}

// 上传图片
const uploadImg = (val) => {
  const pic = val.filePath
  const prodPropValues = Data.specList[0]
  prodPropValues.prodPropValues[val.id].pic = pic
  Data.specList[0] = prodPropValues
}

// 关闭编辑规格名
const closeCreatePopup = () => {
  Data.showCreatePopup = false
}

// 编辑规格名
const getSubmitData = (res) => {
  if (specName.value.indexOf(res) > -1) {
    uni.showToast({
      title: $t('guiGeMingResYiCunZai').replace('[res]', res),
      mask: true,
      icon: 'none',
      duration: 1500
    })
    return
  }
  Data.showCreatePopup = false
  Data.specList[Data.editIndex].name = res
  Data.editIndex = ''
}

// 是否添加图片
const switchChange = () => {
  Data.isUpImg = !Data.isUpImg
  prodStore.dataForm.isUpImg = Data.isUpImg
  Data.specList[0].prodPropValues.forEach((item) => {
    item.pic = ''
  })
}
</script>

<style lang="scss" scoped>
@use "specification-management.scss";
</style>
