<script setup lang="ts">
import { ref, watch } from 'vue'
import { getAllCabinetsWithCells, AllCabinetDataDTO } from '@/api/cabinet/smart-cabinet'
import { ElMessage } from "element-plus";

import type { GoodsDTO } from '@/api/shop/goods'
import { configureGoodsCells } from '@/api/cabinet/cabinet-cell';

const props = defineProps<{
  visible: boolean
  rowData: GoodsDTO
}>()

const emit = defineEmits(['update:visible', 'refresh'])

const loading = ref(false)
const treeData = ref<Array<any>>([])
const selectedCell = ref<number | null>(null)

// 转换柜机格口数据结构
const transformCabinetData = (data: AllCabinetDataDTO) => {
  return data.smartCabinetList.map(cabinet => ({
    id: cabinet.cabinetId,
    label: cabinet.cabinetName,
    disabled: true,
    children: data.cells
      .filter(cell => cell.cabinetId === cabinet.cabinetId)
      .map(cell => ({
        id: cell.cellId,
        label: `格口${cell.cellNo}`,
        disabled: cell.availableStatus !== 1
      }))
  }))
}

// 获取柜机格口数据
const fetchCabinetData = async () => {
  try {
    loading.value = true
    const { data } = await getAllCabinetsWithCells()
    treeData.value = transformCabinetData(data)
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
fetchCabinetData()

const handleSubmit = async () => {
  try {
    await configureGoodsCells(selectedCell.value, props.rowData.goodsId)
    ElMessage.success('配置成功')
    emit('update:visible', false)
    emit('refresh')
  } catch (error) {
    console.error('配置失败', error)
  }
}
const handleNodeClick = (data: { id: number; disabled: boolean }) => {
  if (!data.disabled) {
    selectedCell.value = data.id
  }
}

watch(() => props.visible, (newVal) => {
  if (newVal) {
    selectedCell.value = null
    fetchCabinetData()
  }
})
</script>

<template>
  <el-dialog :model-value="visible" title="柜机格口配置" width="600px" @close="emit('update:visible', false)">
    <el-scrollbar height="400px">
      <el-tree :data="treeData" highlight-current node-key="id" :props="{
        label: 'label',
        children: 'children'
      }" v-model:current-node-key="selectedCell" :default-expand-all="true" @node-click="handleNodeClick"
        class="p-4" />
    </el-scrollbar>

    <template #footer>
      <el-button @click="emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="!selectedCell">确定</el-button>
    </template>
  </el-dialog>
</template>