<template>
  <ContentWrap>
    <!-- 顶部操作栏 -->
    <div class="mb-15px">
      <el-radio-group v-model="currentTab" class="mr-15px">
        <el-radio-button
          v-for="tab in tabs"
          :key="tab.dictValue"
          :label="tab.dictValue"
        >
          <Icon :icon="getTabIcon(tab.dictValue)" class="mr-5px" />
          {{ tab.dictLabel }} ({{ tab.sum }})
        </el-radio-button>
      </el-radio-group>
      <el-button
        type="warning"
        plain
        @click="handleExport"
      >
        <Icon icon="ep:download" class="mr-5px" /> 导出
      </el-button>
    </div>

    <!-- 表格内容 -->
    <div class="table-container">
      <!-- 正常、已领用、已归还表格 -->
      <table v-show="['0', '1', '3'].includes(currentTab)">
        <thead>
        <tr>
          <th>物资类型</th>
          <th v-for="cabinet in cabinets" :key="cabinet.cabinetId">
            {{ cabinet.cabinetName }}
          </th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="materialType in materialTypes" :key="materialType.materialsTypeId">
          <td width="150">
            <UploadImg
              v-model="materialType.materialsTypeIcon"
              :limit="1"
              height="50px"
              width="50px"
            />
            <div class="mt-5px">{{ materialType.materialsTypeName }}</div>
          </td>
          <td
            v-for="cabinet in cabinets"
            :key="cabinet.cabinetId"
            class="text-center text-22px"
          >
            {{ getCellData(materialType.materialsTypeId, cabinet.cabinetId) }}
          </td>
        </tr>
        </tbody>
      </table>

      <!-- 待归还、待检查、异常表格 -->
      <table v-show="['2', '4', '5'].includes(currentTab)">
        <thead>
        <tr>
          <th>物资类型</th>
          <th v-for="cabinet in cabinets" :key="cabinet.cabinetId">
            {{ cabinet.cabinetName }}
          </th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="materialType in materialTypes" :key="materialType.materialsTypeId">
          <td width="150">
            <UploadImg
              v-model="materialType.materialsTypeIcon"
              :limit="1"
              height="50px"
              width="50px"
            />
            <div class="mt-5px">{{ materialType.materialsTypeName }}</div>
          </td>
          <td
            v-for="cabinet in cabinets"
            :key="cabinet.cabinetId"
            class="text-center text-22px"
            :class="getCellClass(materialType.materialsTypeId, cabinet.cabinetId)"
          >
            {{ getCellData(materialType.materialsTypeId, cabinet.cabinetId) }}
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </ContentWrap>
</template>

<script lang="ts" setup>

import * as StatisticApi from '@/api/material/statistics/index'
import download from '@/utils/download'
import {exportMaterialInventory} from "@/api/material/statistics/index";
defineOptions({ name: 'MaterialInventory' })

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

// 数据定义
const currentTab = ref('0') // 当前选中的Tab
const tabs = ref([]) // Tab数据
const tableData = reactive({
  '0': [], // 正常
  '1': [], // 已领用
  '2': [], // 待归还
  '3': [], // 已归还
  '4': [], // 待检查
  '5': []  // 异常
})

// 计算属性
const cabinets = computed(() => {
  return tableData[currentTab.value] || []
})

const materialTypes = computed(() => {
  if (tableData[currentTab.value]?.length > 0) {
    return tableData[currentTab.value][0].materialsTypeVOList
  }
  return []
})

/** 获取Tab图标 */
const getTabIcon = (value: string) => {
  const iconMap: Record<string, string> = {
    '0': 'ep:menu',
    '1': 'ep:folder-checked',
    '2': 'ep:sort',
    '3': 'ep:circle-check',
    '4': 'ep:question-filled',
    '5': 'ep:warning'
  }
  return iconMap[value] || 'ep:menu'
}

/** 获取单元格数据 */
const getCellData = (materialTypeId: string, cabinetId: string) => {
  const cabinet = tableData[currentTab.value].find(c => c.cabinetId === cabinetId)
  if (cabinet) {
    const materialType = cabinet.materialsTypeVOList.find(m => m.materialsTypeId === materialTypeId)
    if (materialType) {
      return materialType.number == null || materialType.number === 0 ? '' : materialType.number
    }
  }
  return ''
}

/** 获取单元格样式 */
const getCellClass = (materialTypeId: string, cabinetId: string) => {
  const number = getCellData(materialTypeId, cabinetId)
  if (!number) return ''

  if (currentTab.value === '2' && number > 0) {
    return 'bg-yellow'
  }
  if (['4', '5'].includes(currentTab.value) && number > 0) {
    return 'bg-red'
  }
  return ''
}

/** 获取列表数据 */
const getList = async () => {
  try {
    // 获取物资盘点数据
    const data = await StatisticApi.getMaterialInventory(currentTab.value)
    tableData[currentTab.value] = data

    // 获取统计数据
    const sumData = await StatisticApi.getInventorySum()
    tabs.value = sumData
  } catch (error) {
    console.error('获取数据失败:', error)
    message.error('获取数据失败')
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()

    const data = await StatisticApi.exportMaterialInventory()
    download.excel(data, '物资盘点.xls')
  } catch {
  }
}

/** 监听Tab变化 */
watch(currentTab, async (newVal) => {
  await getList()
})

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

<style lang="scss" scoped>
.table-container {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

th, td {
  border: 1px solid var(--el-border-color);
  padding: 8px;
  text-align: center;
}

th {
  background-color: var(--el-fill-color-light);
}

.text-22px {
  font-size: 22px;
}

.bg-yellow {
  background-color: var(--el-color-warning-light-9);
  color: var(--el-color-warning);
}

.bg-red {
  background-color: var(--el-color-danger-light-9);
  color: var(--el-color-danger);
}
</style>
