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

 https://www.mall4j.com/

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

 版权所有，侵权必究！
-->
<template>
  <!-- 发布商品：分类选择组件 -->
  <div class="Mall4j category-selection-component">
    <div class="category-select-box">
      <!-- 第一级 -->
      <div class="category-select-item">
        <div class="int-box">
          <input
            disabled
            class="se-int"
            :placeholder="$t('product.prodInfo.selectFirstClassification')"
          >
        </div>
        <ul class="category-list">
          <li
            v-for="(item, index) in firstCat.dataList"
            :key="item.categoryId"
            class="category-item"
            :class="item.categoryId === firstCat.id ? 'active' : ''"
            @click="selectFirstCat(item.categoryId, index)"
          >
            <div>{{ item.name }}</div>

            <el-icon
              class="el-icon-arrow-right"
            >
              <ArrowRight />
            </el-icon>
          </li>
          <li
            v-if="!initCategoryIng && !allDataList.length"
            class="category-empty-tips"
          >
            {{ $t('product.prodInfo.noSignedClassification') }}
            <span
              style="color:#155bd4;cursor:pointer"
              @click="toShopInfo"
            >{{ $t('product.prodInfo.storeInformation') }}</span>
            {{ $t('product.prodInfo.ApplyContractClassification') }}
          </li>
        </ul>
      </div>
      <!-- 第二级 -->
      <div
        v-if="firstCat.dataList.length"
        class="category-select-item"
      >
        <div class="int-box">
          <input
            disabled
            class="se-int"
            :placeholder="$t('product.prodInfo.selectSecondClassification')"
          >
        </div>
        <ul class="category-list">
          <li
            v-for="(item, index) in secondCat.dataList"
            :key="item.categoryId"
            class="category-item"
            :class="item.categoryId === secondCat.id ? 'active' : ''"
            @click="selectSecondCat(item.categoryId, index)"
          >
            <div>{{ item.name }}</div>

            <el-icon
              class="el-icon-arrow-right"
            >
              <ArrowRight />
            </el-icon>
          </li>
          <li
            v-if="!secondCat.dataList.length"
            class="cate-empty"
          >
            {{ $t('product.prodInfo.selectFirstLevelTips') }}
          </li>
        </ul>
      </div>
      <!-- 第三级 -->
      <div
        v-if="firstCat.dataList.length"
        class="category-select-item"
      >
        <div class="int-box">
          <input
            disabled
            class="se-int"
            :placeholder="$t('product.prodInfo.selectThirdClassification')"
          >
        </div>
        <ul class="category-list">
          <li
            v-for="(item, index) in threeCat.dataList"
            :key="item.categoryId"
            class="category-item"
            :class="item.categoryId === threeCat.id ? 'active' : ''"
            @click="selectThreeCat(item.categoryId, index)"
          >
            {{ item.name }}
          </li>
          <li
            v-if="!threeCat.dataList.length"
            class="cate-empty"
          >
            {{ $t('product.prodInfo.selectSecondLevelTips') }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 已选 -->
    <div class="selected-results">
      <div class="sel-con">
        {{ $t('product.prodInfo.selectedPlatformClassification') }}：
        <span class="cur-cate">{{ firstCat.name }}</span>
        <span
          v-if="secondCat.id"
          class="cur-cate"
        >&nbsp;>&nbsp;&nbsp;{{ secondCat.name }}</span>
        <span
          v-if="threeCat.id"
          class="cur-cate"
        >&nbsp;>&nbsp;&nbsp;{{ threeCat.name }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getMySigningCategoryList } from '@/api/product/category'

const props = defineProps({
  // 分类类型：platfor平台分类 store店铺分类
  categoryType: {
    default: 'platform',
    type: String
  },

  dataForm: {
    required: true,
    type: Object
  }
})

const emit = defineEmits(['close', 're-selection', 'update:dataForm'])

const setDataForm = computed({
  get () {
    return props.dataForm
  },
  Set (val) {
    emit('update:dataForm', val)
  }
})

const Data = reactive({
  isSingle: true,
  // 第一个分类
  firstCat: {
    id: 0,
    name: '',
    dataList: []
  },
  // 第二个分类
  secondCat: {
    id: 0,
    name: '',
    dataList: []
  },
  // 第三个分类
  threeCat: {
    id: 0,
    name: '',
    dataList: []
  },
  allDataList: [],
  composeType: 0, // 是否是组合商品
  initCategoryIng: true,
  isUnsignedCategories: false,
  lang: window.localStorage.getItem('cloudLang'),
  categoryId: null
})

const { firstCat, secondCat, threeCat, allDataList, initCategoryIng } = toRefs(Data)

const prodStore = useProdStore()

const selectedCategories = computed(() => {
  return prodStore.platProdCategory.threeCat
})

watch(selectedCategories, () => {
  Data.firstCat = prodStore.platProdCategory.firstCat
  Data.secondCat = prodStore.platProdCategory.secondCat
  Data.threeCat = prodStore.platProdCategory.threeCat
})

onBeforeMount(() => {
  Data.initCategoryIng = true
  clearAllCategories()
})

// 获取分类数据
// 父组件调用
const getDataList = (categoryId) => {
  Data.categoryId = categoryId
  Data.isUnsignedCategories = true
  getMySigningCategoryList().then((data) => {
    let firstCategorysList = [] // 一级分类
    let secondCategorysList = [] // 二级分类
    const threeCategorysList = [] // 三级分类
    // 筛选当前分类是否有下一级分类
    const screen = (upperArr, lowerArr) => {
      return upperArr.filter(item => {
        return lowerArr.some(el => {
          return el.parentId === item.categoryId
        })
      })
    }
    data.forEach((item) => {
      if (item.status === 1) {
        if (item.level === 0) {
          firstCategorysList.push(item)
        }
        if (item.level === 1) {
          secondCategorysList.push(item)
        }
        if (item.level === 2) {
          threeCategorysList.push(item)
        }
      }
    })
    // 筛选二级分类
    secondCategorysList = screen(secondCategorysList, threeCategorysList)
    // 筛选一级分类
    firstCategorysList = screen(firstCategorysList, secondCategorysList)
    data = [...threeCategorysList, ...secondCategorysList, ...firstCategorysList]
    Data.allDataList = data

    Data.firstCat.dataList = firstCategorysList

    Data.isUnsignedCategories = false
    if (Data.threeCat.id && !data.find(el => el.categoryId === Data.threeCat.id)) {
      clearAllCategories()
    }

    // 存在传入的categoryId且最新分类列表中包含categoryId
    if (Data.categoryId && Data.allDataList.find(el => el.categoryId === Data.categoryId)) {
      categoryBackDisplay(data)
    } else if (Data.categoryId === false) { // 无传入categoryId
      categoryBackDisplay(data)
    } else {
      // 有传入categoryId但是最新分类列表中无对应categoryId（例：已选categoryId被删除），则必须重选
      resetCategory(true)
      getMySigningCategoryList({ status: 0 }).then((data1) => {
        if (data1) {
          categoryBackDisplay(data1)
        } else {
          categoryBackDisplay(data)
        }
      })
    }
    Data.initCategoryIng = false
  })
}

// 分类数据回显
const categoryBackDisplay = (data) => {
  data.forEach(el => {
    // 根据第三级分类id回填第二级分类id（parentId）
    if (el.categoryId === Data.categoryId) {
      Data.secondCat.id = el.parentId
      Data.threeCat.name = el.name
    }
    // 根据第二级分类id回填第一级分类id（parentId）
    if (el.categoryId === Data.secondCat.id) {
      Data.firstCat.id = el.parentId
      Data.secondCat.name = el.name
    }
    // 第一级分类名称
    if (el.categoryId === Data.firstCat.id) {
      Data.firstCat.name = el.name

      selectFirstCat(Data.firstCat.id, null)
      selectSecondCat(Data.secondCat.id, null)
      selectThreeCat(Data.categoryId, null)
    }
  })
}

// 重选
const resetCategory = (isRequired) => {
  Data.threeCat = { id: 0, name: '', dataList: [] }
  // 如果点击时已存在categoryId，表示正在重选分类
  if (Data.categoryId || isRequired) {
    emit('re-selection')
  }
}

const selectFirstCat = (categoryId, index) => {
  Data.firstCat.id = categoryId
  if (index !== null && index !== undefined) {
    resetCategory()
    Data.firstCat.name = Data.firstCat.dataList[index].name
    Data.secondCat.id = 0
    Data.threeCat.id = 0
  }
  Data.secondCat.dataList = Data.allDataList.filter(item => item.parentId === categoryId)
}

const selectSecondCat = (categoryId, index) => {
  Data.secondCat.id = categoryId
  if (index !== null && index !== undefined) {
    resetCategory()
    Data.secondCat.name = Data.secondCat.dataList[index].name
    Data.threeCat.id = 0
  }
  Data.threeCat.dataList = Data.allDataList.filter(item => item.parentId === categoryId)
}

const selectThreeCat = (categoryId, index) => {
  Data.threeCat.id = categoryId
  if (index !== null && index !== undefined) {
    Data.threeCat.name = Data.threeCat.dataList[index].name
  }
  setDataForm.value.categoryId = categoryId

  prodStore.platProdCategory = {
    firstCat: JSON.parse(JSON.stringify(Data.firstCat)),
    secondCat: JSON.parse(JSON.stringify(Data.secondCat)),
    threeCat: JSON.parse(JSON.stringify(Data.threeCat)),
    composeType: Data.composeType
  }
}

const router = useRouter()

const toShopInfo = () => {
  Data.isSingle = false
  const path = router.resolve({
    path: '/shop/shop-information',
    query: {
      activeName: 3
    }
  })
  window.open(path.href, '_blank', 'noopener,noreferrer')
}

// 清空已选分类
const clearAllCategories = () => {
  Data.firstCat = {
    id: 0,
    name: '',
    dataList: []
  }
  Data.secondCat = {
    id: 0,
    name: '',
    dataList: []
  }
  Data.threeCat = {
    id: 0,
    name: '',
    dataList: []
  }
}

defineExpose({
  clearAllCategories,
  getDataList
})
</script>

<style lang="scss" scoped>

.category-selection-component {
  margin-bottom: 15px;
  ul,
  li {
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .category-select-box {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    .category-select-item:not(:last-child) {
      margin-right: 10px;
    }
    .category-select-item {
      width: 240px;
      height: auto;
      box-sizing: border-box;
      border: 1px solid #DCDCDC;
      .int-box {
        width: 100%;
        padding: 10px;
        box-sizing: border-box;
        .se-int {
          width: 100%;
          height: 30px;
          line-height: 30px;
          &::placeholder {
            font-size: 12px;
            color: #999;
            padding: 6px;
            box-sizing: border-box;
          }
        }
      }
      .category-list {
        // margin: 10px;
        height: 240px;
        overflow-y: auto;
        .category-item {
          font-size: 12px;
          color: #333;
          padding: 8px;
          box-sizing: border-box;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
          word-break:break-all;
          line-break: anywhere;
          & :deep(.el-icon-arrow-right) {
            color: #999;
          }
        }
        .category-empty-tips {
          font-size: 12px;
          color: #333;
          padding: 0 10px;
          margin-top: 45px;
        }
        .category-item:hover {
          background: rgba(245,248,255, .6);
          border-radius: 2px;
        }
        .category-item.active {
          background: #e8effa;
          border-radius: 2px;
        }
      }

      // 空
      .cate-empty {
        margin-top: 50px;
        color: #bbb;
        text-align: center;
        font-size: 12px;
        padding: 0 10px;
        box-sizing: border-box;
        line-height: 1.5em;
      }
    }
  }

  // 已选中
  .selected-results {
    margin-top: 10px;
    .sel-con {
      display: block;
      background: #f9f9f9;
      font-size: 12px;
      padding: 10px;
      margin-bottom: 20px;
      .cur-cate {
        color: #155BD4;
      }
    }
  }
}
</style>
