<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <div style="display: flex; justify-content: flex-end;">
      <el-button type="primary" @click="openAddDialog">
        <Icon icon="ep:plus" class="mr-5px" /> 新增
      </el-button>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="盘点类型" align="center" width="120">
        <template #default="scope">
          {{ scope.row.label }}
        </template>
      </el-table-column>
      <el-table-column label="盘点数据" align="center" min-width="300">
        <template #default="scope">
          <div style="display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">
            <el-button
              v-for="data in scope.row.dataArray"
              :key="data.code"
              type="success"
              size="small"
              plain
              @click="openEditDataDialog(scope.row, data)"
            >
              {{ data.name }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            @click="openEditEnableDialog(scope.row)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            link
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="list.length === 0" description="暂无数据" />
  </ContentWrap>

  <!-- 新增/编辑盘点类型对话框 -->
  <el-dialog v-model="addDialogVisible" :title="dialogTitle" width="600px">
    <el-form :model="formData" label-width="120px">
      <el-form-item label="盘点类型名称">
        <el-input v-model="formData.label" placeholder="请输入盘点类型名称" />
      </el-form-item>
      <el-form-item label="盘点数据">
        <el-checkbox-group v-model="selectedCodes">
          <el-checkbox
            v-for="item in availableItems"
            :key="item.code"
            :label="item.code"
          >
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="formData.sort" :min="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">确定</el-button>
    </template>
  </el-dialog>

  <!-- 编辑盘点数据对话框 -->
  <el-dialog v-model="editDialogVisible" title="编辑盘点数据" width="600px">
    <el-form :model="editForm" label-width="120px">
      <el-form-item label="盘点数据字符">
        <el-input v-model="editForm.code" placeholder="请输入盘点数据字符" />
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="editForm.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="盘点类型名称">
        <el-select
          v-model="editForm.typeCode"
          placeholder="请选择盘点类型名称"
          @change="handleTypeChange"
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleEdit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import * as DictDataApi from '@/api/system/dict/dict.data'

defineOptions({ name: 'LogisticsStockType' })

const message = useMessage()

const loading = ref(true)
const list = ref<any[]>([])
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const dialogTitle = ref('新增盘点类型')
const selectedCodes = ref<string[]>([])
const availableItems = ref<any[]>([])
const typeList = ref<any[]>([])

// 表单数据
const formData = ref({
  id: undefined,
  label: '',
  sort: 1
})

// 编辑表单
const editForm = ref({
  id: undefined,
  code: '',
  name: '',
  typeCode: '',
  typeName: '',
  parentId: undefined,
  scanConfId: undefined
})

// 获取 scan_enable 字典数据（盘点信号）
const getScanEnableData = async () => {
  const data = await DictDataApi.getTypeList('scan_enable')
  return data.map((item: any) => ({
    id: item.id,
    label: item.label, // 盘点类型名称，如"E1", "E2"
    value: item.value, // 逗号分隔的盘点数据，如"trayCode,itemCode"
    dataArray: item.value ? item.value.split(',').map((code: string) => ({
      code: code.trim()
    })) : []
  }))
}

// 获取 scan_conf_name 字典数据（可选的盘点数据）
const getScanConfNameData = async () => {
  const data = await DictDataApi.getTypeList('scan_conf_name')
  return data.map((item: any) => ({
    label: item.value, // 显示名称，如"货物码"
    value: item.label, // 字段名，如"code"
    name: item.value,
    code: item.label
  }))
}

// 获取 scan_code_type 字典数据（盘点类型）
const getScanCodeTypeData = async () => {
  const data = await DictDataApi.getTypeList('scan_code_type')
  return data.map((item: any) => ({
    id: item.id,
    label: item.label, // 显示名称，如 "scanning_gun"
    value: item.value  // 盘点类型代码，如 "10"
  }))
}

// 获取 scan_conf 字典数据
const getScanConfData = async () => {
  const data = await DictDataApi.getTypeList('scan_conf')
  return data.map((item: any) => ({
    id: item.id,
    label: item.label,  // 字段名，如"itemCode"
    value: item.value   // 值，如"10"
  }))
}

// 根据 scan_code_type 获取盘点类型名称
const getTypeName = (typeCode: string) => {
  const item = typeList.value.find((t: any) => t.value === typeCode)
  return item ? item.label : ''
}



// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const rawData = await getScanEnableData()

    // 获取每个盘点数据字符对应的详细信息
    const scanConfData = await getScanConfNameData()

    list.value = rawData.map((item: any) => {
      // 为每个 code 补充详细信息
      const dataArray = item.dataArray.map((d: any) => {
        const confItem = scanConfData.find((s: any) => s.code === d.code)
        return {
          code: d.code,
          name: confItem ? confItem.name : d.code,
          typeCode: confItem ? confItem.typeCode || '' : ''
        }
      })

      return {
        ...item,
        dataArray
      }
    })
  } finally {
    loading.value = false
  }
}

// 打开新增对话框
const openAddDialog = async () => {
  availableItems.value = await getScanConfNameData()
  selectedCodes.value = []
  formData.value = {
    id: undefined,
    label: '',
    sort: 1
  }
  dialogTitle.value = '新增盘点类型'
  addDialogVisible.value = true
}

// 打开编辑 enable 对话框（编辑盘点类型）
const openEditEnableDialog = async (item: any) => {
  availableItems.value = await getScanConfNameData()
  selectedCodes.value = item.dataArray.map((d: any) => d.code)
  formData.value = {
    id: item.id,
    label: item.label,
    sort: item.sort || 1
  }
  dialogTitle.value = '编辑盘点类型'
  addDialogVisible.value = true
}

// 打开编辑盘点数据对话框
const openEditDataDialog = async (item: any, data: any) => {
  // 从 scan_conf 字典表获取当前的类型值
  // 判断盘点数据字符是 itemCode 的 label（不是 value）
  const scanConfData = await getScanConfData()
  const currentTypeItem = scanConfData.find((s: any) => s.label === data.code)

  editForm.value = {
    id: item.id,
    code: data.code,
    name: data.name,
    typeCode: currentTypeItem ? currentTypeItem.value : '', // 使用 scan_conf 的 value
    typeName: '',
    parentId: item.id,
    scanConfId: currentTypeItem ? currentTypeItem.id : undefined // 保存 scan_conf 的 id
  }

  // 获取盘点类型列表
  typeList.value = await getScanCodeTypeData()

  // 设置盘点类型名称
  editForm.value.typeName = getTypeName(editForm.value.typeCode)

  editDialogVisible.value = true
}

// 保存盘点类型
const handleSave = async () => {
  if (!formData.value.label) {
    message.warning('请输入盘点类型名称')
    return
  }

  if (selectedCodes.value.length === 0) {
    message.warning('请至少选择一项盘点数据')
    return
  }

  try {
    const newValue = selectedCodes.value.join(',')

    if (formData.value.id) {
      // 更新现有的盘点类型
      await DictDataApi.updateDictData({
        id: formData.value.id,
        label: formData.value.label,
        value: newValue,
        dictType: 'scan_enable',
        sort: formData.value.sort || 1,
        status: 0,
        colorType: '',
        cssClass: '',
        remark: '',
        createTime: new Date()
      } as any)
      message.success('修改成功')
    } else {
      // 创建新的盘点类型，默认排序为 1
      await DictDataApi.createDictData({
        label: formData.value.label,
        value: newValue,
        dictType: 'scan_enable',
        sort: 1,
        status: 0,
        colorType: '',
        cssClass: '',
        remark: '',
        createTime: new Date()
      } as any)
      message.success('新增成功')
    }

    addDialogVisible.value = false
    await getList()
  } catch (error) {
    message.error('保存失败')
  }
}

// 处理盘点类型变更
const handleTypeChange = () => {
  editForm.value.typeName = getTypeName(editForm.value.typeCode)
}

// 处理编辑盘点数据
const handleEdit = async () => {
  if (!editForm.value.code || !editForm.value.name) {
    message.warning('请填写完整信息')
    return
  }

  try {
    // 更新 scan_conf 的 value
    if (editForm.value.scanConfId) {
      // 更新现有的 scan_conf
      await DictDataApi.updateDictData({
        id: editForm.value.scanConfId,
        label: editForm.value.code,
        value: editForm.value.typeCode,
        dictType: 'scan_conf',
        sort: 1,
        status: 0,
        colorType: '',
        cssClass: '',
        remark: '',
        createTime: new Date()
      } as any)
    }

    // 同时更新 scan_conf_name 的名称
    const scanConfNameData = await DictDataApi.getTypeList('scan_conf_name')
    const existingNameItem = scanConfNameData.find((item: any) => item.label === editForm.value.code)

    if (existingNameItem) {
      // 更新 scan_conf_name
      await DictDataApi.updateDictData({
        id: existingNameItem.id,
        label: editForm.value.code,
        value: editForm.value.name,
        dictType: 'scan_conf_name',
        sort: 1,
        status: 0,
        colorType: existingNameItem.colorType || '',
        cssClass: existingNameItem.cssClass || '',
        remark: existingNameItem.remark || '',
        createTime: existingNameItem.createTime || new Date()
      } as any)
    } else {
      // 创建新的 scan_conf_name
      await DictDataApi.createDictData({
        label: editForm.value.code,
        value: editForm.value.name,
        dictType: 'scan_conf_name',
        sort: 1,
        status: 0,
        colorType: '',
        cssClass: '',
        remark: '',
        createTime: new Date()
      } as any)
    }

    message.success('修改成功')
    editDialogVisible.value = false
    await getList()
  } catch (error) {
    message.error('修改失败')
  }
}

// 处理删除
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await DictDataApi.deleteDictData(id)
    message.success('删除成功')
    await getList()
  } catch {}
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
</style>
