<template>
  <view v-if="visible" class="category-selector-mask" @click="handleMaskClick">
    <view class="category-selector-container" :style="containerStyle" @click.stop>
      <!-- 顶部标题栏 -->
      <view class="header">
        <view class="back-btn" @click="handleClose">
          <text class="back-icon"></text>
        </view>
        <text class="title">分类</text>
        <view class="search-btn">
          <text class="search-icon"></text>
        </view>
      </view>

      <!-- 主内容区域 -->
      <view class="content">
        <!-- 左侧分类列表 -->
        <scroll-view class="category-list" scroll-y="true" show-scrollbar="false">
          <view 
            v-for="(category, index) in categories" 
            :key="category.value"
            :class="['category-item', activeCategoryIndex === index ? 'category-active' : '']"
            @click="handleCategoryClick(index)"
          >
            <image 
              v-if="categoryList[index].default_icon.length > 0" 
              class="category-icon" 
              :src="categoryList[index].default_icon" 
              mode="aspectFit"
            ></image>
            <text :class="['category-text', activeCategoryIndex === index ? 'category-text-active' : '']">
              {{ category.label }}
            </text>
            <view v-if="activeCategoryIndex === index" class="category-indicator"></view>
          </view>
        </scroll-view>

        <!-- 右侧商品展示区域 -->
        <view class="product-area-wrapper">
          <!-- 标签栏 -->
          <scroll-view class="tags-container-right" scroll-x="true" show-scrollbar="false">
            <view class="tags-wrapper-right">
              <view 
                v-for="(tag, index) in tags" 
                :key="index"
                :class="['tag-item-right', activeTagIndex === index ? 'tag-active-right' : '']"
                @click="handleTagClick(index)"
              >
                <text :class="['tag-text-right', activeTagIndex === index ? 'tag-text-active-right' : '']">{{ tag }}</text>
              </view>
            </view>
          </scroll-view>

          <scroll-view class="product-area" scroll-y="true" show-scrollbar="false">
          <!-- 加载状态 -->
          <view v-if="loading" class="loading-container">
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 商品列表 -->
          <view v-else-if="currentProducts.length > 0" class="product-list">
            <view 
              v-for="(product, index) in currentProducts" 
              :key="product.value"
              class="product-item"
              @click="handleProductClick(product)"
            >
              <image class="product-image" :src="product.goods_pic" mode="aspectFit"></image>
              <view class="product-info">
                <text class="product-name">{{ product.label }}</text>
                <text class="product-price">¥{{ product.price }}</text>
              </view>
            </view>
          </view>

          <!-- 空状态 -->
          <view v-else class="empty-container">
            <text class="empty-text">暂无商品</text>
          </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, computed, watch } from 'vue'
import type { machineItems, categoryItem } from '@/types/globalData.uts'
import { getgoods, getmachines, goodscategory } from '@/utils/reques.uts'
import type { ResponseData } from '@/utils/reques.uts'

// 定义商品类型
type Product = {
  label: string
  value: number
  front_image: string
  goods_pic: string
  render_width: string
  render_height: string
  category_value: string
  design_color: string
  price: string
  machine_id: number
}

// 定义分类类型
type Category = {
  value: string
  label: string
  products: Product[]
}

// Props定义
const props = defineProps<{
  visible: boolean
}>()

// Emits定义
const emit = defineEmits<{
  close: []
  select: [product: UTSJSONObject]
}>()

// 响应式数据
const activeTagIndex = ref(0)
const activeCategoryIndex = ref(0)
const translateY = ref(100)
const loading = ref(false)

// 存储分类商品数据的Map，key为 "machineId_categoryValue"
const categoryProductsMap = ref(new Map<string, Product[]>())

// 存储设备列表数据的Map，key为 "categoryValue"
const machinesListMap = ref(new Map<string, Array<machineItems>>())

// 设备列表数据
const machinesList = ref<Array<machineItems>>([])

// 分类列表数据
const categoryList = ref<Array<categoryItem>>([])

// 获取当前选中的设备ID
const currentMachineId = computed((): number => {
  if (machinesList.value.length > 0 && activeTagIndex.value < machinesList.value.length) {
    const machineValue = machinesList.value[activeTagIndex.value].value
    // 将 value 转换为 number 类型
    if (typeof machineValue == 'number') {
      return machineValue as number
    }
  }
  return 0
})

// 获取当前选中的分类值
const currentCategoryValue = computed((): string => {
  if (categoryList.value.length > 0 && activeCategoryIndex.value < categoryList.value.length) {
    return categoryList.value[activeCategoryIndex.value].value
  }
  return ''
})

// 标签数据 - 从 machinesList 获取
const tags = computed((): string[] => {
  return machinesList.value.map((item: machineItems): string => {
    return item.label
  })
})

// 分类数据 - 从 categoryList 获取
const categories = computed((): Category[] => {
  return categoryList.value.map((item: categoryItem): Category => {
    const cacheKey = `${currentMachineId.value}_${item.value}`
    const cachedProducts = categoryProductsMap.value.get(cacheKey)
    return {
      value: item.value,
      label: item.label,
      products: cachedProducts != null ? cachedProducts : [] as Product[]
    }
  })
})

// 计算当前分类标题
const currentCategoryTitle = computed((): string => {
  const cats = categories.value
  if (cats.length > 0 && activeCategoryIndex.value < cats.length) {
    return cats[activeCategoryIndex.value].label
  }
  return ''
})

// 计算当前商品列表
const currentProducts = computed((): Product[] => {
  const cats = categories.value
  if (cats.length > 0 && activeCategoryIndex.value < cats.length) {
    return cats[activeCategoryIndex.value].products
  }
  return [] as Product[]
})

// 计算容器样式
const containerStyle = computed((): string => {
  return `transform: translateY(${translateY.value}%);`
})

// 获取设备列表 - 需要传递 category_value 参数
const fetchMachinesList = async (categoryValue: string) => {
  // 如果已有缓存数据，直接使用
  if (machinesListMap.value.has(categoryValue)) {
    const cachedMachines = machinesListMap.value.get(categoryValue)
    if (cachedMachines != null) {
      machinesList.value = cachedMachines
      // 重置为第一个设备
      activeTagIndex.value = 0
      return
    }
  }
  
  try {
    const params = {
      category_value: categoryValue
    } as UTSJSONObject
    const res = await getmachines(params) as ResponseData
    if (res.code as number == 0) {
      const dataArray = res.data as Array<any>
      const machines : Array<machineItems> = []
      for (let i = 0; i < dataArray.length; i++) {
        const item = dataArray[i] as UTSJSONObject
        const machineitems : machineItems = {
          label: item.getString('name') ?? '',
          value: item.getNumber('id') ?? 0,
        }
        machines.push(machineitems)
      }
      // 缓存设备列表数据
      machinesListMap.value.set(categoryValue, machines)
      machinesList.value = machines
      // 重置为第一个设备
      activeTagIndex.value = 0
    }
  } catch (e) {
    console.log('获取设备列表失败:', e)
  }
}

// 获取产品分类列表
const fetchCategoryList = async () => {
  try {
    const params = {} as object
    const res = await goodscategory(params) as ResponseData
    if (res.code as number == 0) {
      const dataArray = res.data as Array<any>
      const categorys : Array<categoryItem> = []
      for (let i = 0; i < dataArray.length; i++) {
        const item = dataArray[i] as UTSJSONObject
        const categoryItem : categoryItem = {
          label: item.getString('label') ?? '',
          value: item.getString('value') ?? '',
          default_icon: item.getString('default_icon') ?? ''
        }
        categorys.push(categoryItem)
      }
      categoryList.value = categorys
    }
  } catch (e) {
    console.log('获取产品分类列表失败:', e)
  }
}

// 获取商品数据
const fetchGoods = async (machineId: number, categoryValue: string) => {
  const cacheKey = `${machineId}_${categoryValue}`
  
  // 如果已有缓存数据，直接返回
  if (categoryProductsMap.value.has(cacheKey)) {
    return
  }
  
  loading.value = true
  
  try {
    const params = {
      machine_id: machineId,
      category_value: categoryValue
    } as UTSJSONObject
    
    const res = await getgoods(params) as ResponseData
    
    if (res.code == 0 && res.data != null) {
      const dataArray = res.data as Array<UTSJSONObject>
      const products = dataArray.map((item: UTSJSONObject): Product => {
        return {
          label: item.getString('name') ?? '',
          value: item.getNumber('id') ?? 0,
          front_image: item.getString('front_image') ?? '',
          goods_pic: item.getString('goods_pic') ?? '',
          render_width: item.getString('render_width') ?? '',
          render_height: item.getString('render_height') ?? '',
          category_value: categoryValue,
          design_color: item.getString('design_color') ?? '',
          price: item.getString('price') ?? '0',
          machine_id: machineId
        }
      })
      
      // 缓存数据
      categoryProductsMap.value.set(cacheKey, products)
    }
  } catch (error) {
    console.log('获取商品数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听visible变化,执行动画并加载数据
watch((): boolean => props.visible, async (newVal: boolean) => {
  if (newVal) {
    // 重置为默认选中第一个分类
    activeCategoryIndex.value = 0
    
    // 打开动画
    translateY.value = 100
    setTimeout(() => {
      translateY.value = 0
    }, 50)
    
    // 先加载分类列表
    if (categoryList.value.length == 0) {
      await fetchCategoryList()
    }
    
    // 获取当前分类值
    const categoryValue = currentCategoryValue.value
    if (categoryValue.length > 0) {
      // 根据分类获取设备列表
      await fetchMachinesList(categoryValue)
      
      // 加载当前分类的商品数据
      const machineId = currentMachineId.value
      if (machineId > 0) {
        fetchGoods(machineId, categoryValue)
      }
    }
  } else {
    // 关闭动画
    translateY.value = 100
  }
})

// 监听标签切换
watch(activeTagIndex, () => {
  const machineId = currentMachineId.value
  const categoryValue = currentCategoryValue.value
  if (machineId > 0 && categoryValue.length > 0) {
    fetchGoods(machineId, categoryValue)
  }
})

// 监听分类切换 - 需要重新获取设备列表
watch(activeCategoryIndex, async () => {
  const categoryValue = currentCategoryValue.value
  if (categoryValue.length > 0) {
    // 根据新分类获取设备列表
    await fetchMachinesList(categoryValue)
    
    // 加载当前分类的商品数据
    const machineId = currentMachineId.value
    if (machineId > 0) {
      fetchGoods(machineId, categoryValue)
    }
  }
})

// 处理关闭
const handleClose = () => {
  translateY.value = 100
  setTimeout(() => {
    emit('close')
  }, 300)
}

// 处理标签点击
const handleTagClick = (index: number) => {
  activeTagIndex.value = index
}

// 处理分类点击
const handleCategoryClick = (index: number) => {
  activeCategoryIndex.value = index
}

// 处理商品点击
const handleProductClick = (product: Product) => {
  // 将 Product 转换为 UTSJSONObject
  const productObj = {
    label: product.label,
    value: product.value,
    front_image: product.front_image,
    goods_pic: product.goods_pic,
    render_width: product.render_width,
    render_height: product.render_height,
    category_value: product.category_value,
    design_color: product.design_color,
    price: product.price,
    machine_id: product.machine_id
  } as UTSJSONObject
  emit('select', productObj)
}

// 处理遮罩点击
const handleMaskClick = () => {
  handleClose()
}
</script>

<style>
.category-selector-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.category-selector-container {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 60%;
  background-color: #f5f5f5;
  border-top-left-radius: 40rpx;
  border-top-right-radius: 40rpx;
  flex-direction: column;
  transition-property: transform;
  transition-duration: 300ms;
  transition-timing-function: ease-out;
}

.header {
  height: 88rpx;
  background-color: #ffffff;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding-left: 30rpx;
  padding-right: 30rpx;
  border-bottom-width: 2rpx;
  border-bottom-color: #eeeeee;
}

.back-btn {
  width: 80rpx;
  height: 88rpx;
  justify-content: center;
  align-items: flex-start;
}

.back-icon {
  font-size: 48rpx;
  color: #333333;
}

.title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333333;
}

.search-btn {
  width: 80rpx;
  height: 88rpx;
  justify-content: center;
  align-items: flex-end;
}

.search-icon {
  font-size: 40rpx;
  color: #333333;
}

.product-area-wrapper {
  flex: 1;
  flex-direction: column;
  background-color: #ffffff;
}

.tags-container-right {
  height: 100rpx;
  background-color: #ffffff;
  flex-direction: row;
  border-bottom-width: 2rpx;
  border-bottom-color: #eeeeee;
}

.tags-wrapper-right {
  flex-direction: row;
  align-items: center;
  padding-left: 30rpx;
  padding-right: 30rpx;
}

.tag-item-right {
  padding-left: 32rpx;
  padding-right: 32rpx;
  height: 64rpx;
  justify-content: center;
  align-items: center;
  border-radius: 32rpx;
  margin-right: 20rpx;
  background-color: #ffffff;
}

.tag-active-right {
  background-color: #ffe5e5;
  border-width: 2rpx;
  border-color: #ff4444;
}

.tag-text-right {
  font-size: 28rpx;
  color: #666666;
}

.tag-text-active-right {
  color: #ff4444;
  font-weight: bold;
}

.content {
  flex: 1;
  flex-direction: row;
}

.category-list {
  width: 240rpx;
  background-color: #f5f5f5;
  flex-direction: column;
}

.category-item {
  height: 160rpx;
  justify-content: center;
  align-items: center;
  position: relative;
  flex-direction: column;
  padding-top: 16rpx;
  padding-bottom: 16rpx;
}

.category-icon {
  width: 64rpx;
  height: 64rpx;
  margin-bottom: 8rpx;
}

.category-active {
  background-color: #ffffff;
}

.category-text {
  font-size: 28rpx;
  color: #666666;
}

.category-text-active {
  color: #333333;
  font-weight: bold;
}

.category-indicator {
  position: absolute;
  left: 0;
  width: 6rpx;
  height: 40rpx;
  background-color: #ff4444;
}

.product-area {
  flex: 1;
  flex-direction: column;
  padding-left: 30rpx;
  padding-right: 30rpx;
  padding-top: 30rpx;
}

.product-list {
  flex-direction: column;
}

.product-item {
  width: 100%;
  padding: 24rpx;
  margin-bottom: 20rpx;
  flex-direction: row;
  align-items: center;
  background-color: #ffefef;
  border-radius: 16rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
}

.product-info {
  flex: 1;
  margin-left: 24rpx;
  flex-direction: column;
  justify-content: center;
}

.product-name {
  font-size: 30rpx;
  color: #333333;
  margin-bottom: 16rpx;
}

.product-price {
  font-size: 32rpx;
  color: #ff4444;
  font-weight: bold;
}

.loading-container {
  flex: 1;
  justify-content: center;
  align-items: center;
  padding-top: 200rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
}

.empty-container {
  flex: 1;
  justify-content: center;
  align-items: center;
  padding-top: 200rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}
</style>
