<template>
  <div class="box">
    <el-row>
      <el-col :span="12">
        <!--  v-model="queryParams.productName"
           @blur="handleSelectChange"
            :remote-method="searchProduct"
           -->
        <!-- <el-select
          filterable
          remote
          default-first-option
          :reserve-keyword="false"
          placeholder="类目搜索"
          clearable
          remote-show-suffix
          style="margin-bottom: 10px"
        >
          <el-option
              v-for="item in productList"
              :key="item.productBizId"
              :label="item.productName"
              :value="item.productBizId"
            />
        </el-select> -->
      </el-col>
      <el-col :span="24" v-if="categoryName">
        <div class="chooseName">
          <span style="color: rgb(0 0 0 / 55%)">已选类目：</span>{{ categoryName }}
        </div>
      </el-col>
    </el-row>
    <div class="category-container">
      <div class="tableHeader">
        <div
          class="headerItem"
          :style="{ width: `${100 / categoryList.length}%` }"
          v-for="item in categoryList"
          :key="item.level"
        >
          {{ item.title }}
        </div>
      </div>
      <div class="tableBody">
        <div
          class="bodyItem"
          v-for="(item, index) in categoryList"
          :key="item.level"
          :style="{
            width: `${100 / categoryList.length}%`,
            borderRight: categoryList.length - 1 === index ? 'none' : '1px solid #ccc'
          }"
        >
          <div
            class="categoryItem"
            v-for="(cItem, cIndex) in item.data"
            :key="cItem.id"
            @click="handleClickCategory(item, cItem, cIndex)"
            :style="{
              backgroundColor: cItem.isSelected ? 'rgb(64, 158, 255,0.1)' : null
            }"
          >
            <span> {{ cItem.name }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getCategoryTreeList } from '@/api/product/index'
import { computed } from 'vue'
import { ref } from 'vue'
const props = defineProps({
  // 类目数据,
  data: {
    type: Array,
    default: () => []
  },
  // 类型，是新增还是编辑,
  type: {
    type: String,
    default: 'add'
  }
})
const categoryList = ref([])
const level1Obj = ref([])
// 中文数字单位
const units = ['', '十', '百', '千']
const bigUnits = ['', '万', '亿', '兆', '京', '垓', '秭', '穰', '沟', '涧', '正', '载']

// 中文数字字符
const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
const categoryName = computed(() => {
  let result = []
  categoryList.value.forEach(item => {
    item.data.forEach(c => {
      if (c.isSelected) result.push(c.name)
    })
  })

  if (result.length > 0) {
    return result.join(' > ')
  } else {
    return ''
  }
})
const emit = defineEmits(['handleClickCategory'])
const handleClickCategory = (fItem, cItem, cIndex) => {
  categoryList.value.forEach(item => {
    item.data.forEach(c => {
      if (c.categoryBizId == cItem.categoryBizId && fItem.level == item.level) {
        c.isSelected = true
      } else if (fItem.level == item.level) {
        c.isSelected = false
      }
    })
  })

  getCategoryData(cItem)
}
function getCategoryData(obj) {
  // let name = query ? query.trim() : ''

  let data = {
    // name: name,
    type: 'PRODUCT',
    pid: obj.categoryBizId ? obj.categoryBizId : '0',
    pageSize: 9999,
    pageNo: 1
  }
  getCategoryTreeList(data).then(response => {
    if (response.code === 200) {
      let res = response.data.records
      res.forEach(item => {
        item.isSelected = false
      })
      if (!obj.level) {
        categoryList.value = [
          { level: 1, data: res, title: `${convertSection(1)}级类目` },
          { level: 2, data: [], title: `${convertSection(2)}级类目` },
          { level: 3, data: [], title: `${convertSection(3)}级类目` },
          { level: 4, data: [], title: `${convertSection(4)}级类目` }
        ]
      } else {
        if (res.length > 0) {
          // 先删除当前层级以后的数据
          if (categoryList.value.length > 4 && obj.level > 4) {
            categoryList.value.splice(obj.level, categoryList.value.length - obj.level)
          }

          let cIndex = categoryList.value.findIndex(item => item.level == res[0].level)
          if (cIndex > -1) {
            // 固定显示4个类目，如果超过4个类目，则删除多余的类目
            if (categoryList.value.length > 4 && obj.level < 4) {
              categoryList.value.splice(4, categoryList.value.length - 4)
            }
            categoryList.value[cIndex].data = res
            for (let i = cIndex + 1; i < categoryList.value.length; i++) {
              categoryList.value[i].data = []
            }
          } else {
            categoryList.value.push({
              level: res[0].level,
              data: res,
              title: `${convertSection(res[0].level)}级类目`
            })
          }
        }
      }
      console.log('categoryList', categoryList.value)
    } else {
      categoryList.value = []
      proxy.$modal.msgError(response.msg)
    }
  })
}

// 转换4位数字节
const convertSection = sectionNum => {
  const len = sectionNum
  let result = ''
  let hasZero = false

  for (let i = 0; i < len; i++) {
    const digit = sectionNum
    if (digit === 0) {
      hasZero = true
    } else {
      if (hasZero) {
        result += '零'
        hasZero = false
      }
      result += digits[digit]
      return result
    }
  }

  // 处理全零的情况
  if (result === '') {
    return '零'
  }

  return result
}
if (props.type == 'add') {
  getCategoryData({ categoryBizId: '0' })
} else if (props.type == 'edit') {
  console.log('props.data', props.data);

  // 先回显已经选择好的类目
  categoryList.value = JSON.parse(JSON.stringify(props.data))
  categoryList.value.forEach(item => {
    item.title = `${convertSection(item.level)}级类目`
    // 还应该把data里的数据都加上 isSelected: true
  })
}
// 暴露给父组件
defineExpose({
  categoryList,
  categoryName
})
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  box-sizing: border-box;
}
.category-container {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
  height: 100%;
}
.tableHeader {
  display: flex;
  justify-content: space-between;

  border-bottom: 1px solid #ccc;
  color: rgb(0 0 0 / 55%);
  font-size: 16px;
}
.headerItem {
  padding: 10px 20px;
  text-align: left;
}
.tableBody {
  display: flex;
  justify-content: space-between;

  color: rgb(0 0 0 / 55%);
  font-size: 14px;
  height: calc(100% - 40px);
}
.bodyItem {
  overflow-y: auto;
  padding: 10px 10px;
}
.categoryItem {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
}
.chooseName {
  padding: 10px 20px;
  background-color: #f7f7f7;
  border-radius: 5px;
  font-size: 14px;
  margin-bottom: 10px;
}
</style>
