<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="物资类型名称" prop="materialsTypeName">
        <el-input
          v-model="queryParams.materialsTypeName"
          placeholder="请输入类型名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['mes:mat:type:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
    <!-- 列表 -->
    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="typeList"
        row-key="id"
        :default-expand-all="isExpandAll"
        v-if="refreshTable"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="materialsTypeName" label="物资类型名称" :show-overflow-tooltip="true" />
        <el-table-column prop="propertyIds" label="物资规格" :show-overflow-tooltip="true">
          <template #default="scope">
        <span v-if="getPropertyDisplay(scope.row.propertyIds)">
          {{ getPropertyDisplay(scope.row.propertyIds) }}
        </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="物资类型图标" prop="materialsTypeIcon">
          <template #default="scope">
            <UploadImg
              v-if="scope.row.materialsTypeIcon"
              v-model="scope.row.materialsTypeIcon"
              :limit="1"
              height="50px"
              width="50px"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="物资类型缩略图" prop="materialsTypePicture">
          <template #default="scope">
            <UploadImg
              v-if="scope.row.materialsTypePicture"
              v-model="scope.row.materialsTypePicture"
              :limit="1"
              height="50px"
              width="50px"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row)"
              v-hasPermi="['mes:mat:type:update']"
            >
              修改
            </el-button>
            <el-button
              link
              type="primary"
              @click="openForm('create', scope.row)"
              v-hasPermi="['mes:mat:type:create']"
            >
              新增
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mes:mat:type:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>

    <!-- 表单弹窗：添加/修改 -->
    <TypeForm ref="formRef" @success="getList" />
</template>

<script lang="ts" setup>

import { handleTree } from '@/utils/tree'
import * as TypeApi from '@/api/material/type'
import TypeForm from './TypeForm.vue'
import * as PropertyApi from "@/api/material/standard/index"

defineOptions({ name: 'MaterialType' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const typeList = ref([]) // 列表的数据
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const queryFormRef=ref()
// 属性映射表
const propertyMap = ref({})
// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  materialsTypeName: undefined
})

/** 查询物资类型列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TypeApi.listType(queryParams)
    typeList.value = handleTree(data.list,'id','parentId')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}
// 获取属性映射数据
const getPropertyMap = async () => {
  try {
    const data = { pageNo: 1, pageSize: -1 }
    const response = await PropertyApi.PropertyPage(data)

    console.log('API响应:', response)

    const map = {}

    // 安全地获取数据数组
    let records = []
    if (response && typeof response === 'object') {
      records = response.records || response.list || response.data?.records || []
    }

    console.log('数据数组:', records)

    if (Array.isArray(records)) {
      records.forEach((item, index) => {
        if (item && typeof item === 'object') {
          const propertyId = item.propertyId || item.id
          const propertyName = item.propertyName || item.name

          if (propertyId && propertyName) {
            map[propertyId] = propertyName
          }
        }
      })
    }

    propertyMap.value = map
    console.log('属性映射表:', propertyMap.value)
  } catch (error) {
    console.error('获取属性映射失败:', error)
    propertyMap.value = {} // 确保有默认值
  }
}

// 安全的属性显示方法
const getPropertyDisplay = (propertyIds) => {
  if (!propertyIds) return null

  // 如果 propertyIds 是字符串，尝试分割
  if (typeof propertyIds === 'string') {
    const ids = propertyIds.split(',').map(id => id.trim())
    const names = ids.map(id => propertyMap.value[id] || id)
    return names.join(', ')
  }

  // 如果是单个值
  return propertyMap.value[propertyIds] || propertyIds
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增/修改操作 */
const formRef = ref()
const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  try {
    await message.confirm('是否确认删除所选数据项？')
    await TypeApi.deleteType(row.id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  await getPropertyMap()
})
</script>
