<template>
  <div>
    <el-descriptions v-loading="loading" :column="2">
      <el-descriptions-item label="材料名称">{{ materialsDetail?.materialsName }}</el-descriptions-item>
      <el-descriptions-item label="供应商">{{ materialsDetail?.companyVo?.companyName }}</el-descriptions-item>
      <div :key="item.value" v-for="item in materials_file_type">
        <el-descriptions-item :span="2" :label="item.label">
          <div v-if="ossIdMap?.[item.value] && ossMap?.[ossIdMap[item.value]]">
            <a :href="ossMap[ossIdMap[item.value]]?.url" target="_blank">
              {{ ossMap[ossIdMap[item.value]]?.originalName }}
            </a>
          </div>
        </el-descriptions-item>
      </div>
      <el-descriptions-item label="规格型号">{{ materialsDetail?.typeSpecificationName }}</el-descriptions-item>
      <el-descriptions-item label="使用部位">{{ materialsDetail?.usePart }}</el-descriptions-item>
      <el-descriptions-item label="计量单位">{{ materialsDetail?.weightId }}</el-descriptions-item>
      <el-descriptions-item label="预计量">{{ materialsDetail?.quantityCount }}</el-descriptions-item>
      <el-descriptions-item label="状态" v-if="materialsDetail?.status === '0'">正常</el-descriptions-item>
      <el-descriptions-item label="状态" v-if="materialsDetail?.status === '1'">停用</el-descriptions-item>
      <el-descriptions-item label="备注">{{ materialsDetail?.remark }}</el-descriptions-item>
    </el-descriptions>
  </div>
</template>

<script setup lang="ts">
import { getMaterials } from '@/api/materials/materials';
import { MaterialsVO } from '@/api/materials/materials/types';
import { listByIds } from '@/api/system/oss';
import { OssVO } from '@/api/system/oss/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { materials_file_type } = toRefs<any>(proxy?.useDict('materials_file_type'));

interface Props {
  materialsId?: string | number;
}

const props = defineProps<Props>();
const loading = ref<boolean>(false);
const materialsDetail = ref<MaterialsVO>();
const ossIdMap = ref<Record<string, string>>({});
const ossMap = ref<Record<string, OssVO>>({}); // 存储 ossId -> 对象映射
const getMaterialsDetail = async () => {
  loading.value = true;
  const res = await getMaterials(props.materialsId);
  if (res.data && res.code === 200) {
    materialsDetail.value = res.data;
    ossIdMap.value = res.data.fileOssMap;
    // 获取 value 列表
    if (res.data.fileOssMap) {
      const values = Object.values(res.data.fileOssMap);
      const ossRes = await listByIds(values);
      ossMap.value = Object.fromEntries(ossRes.data.map((item) => [item.ossId, item]));
    }
  }
  loading.value = false;
};

onMounted(() => {
  getMaterialsDetail();
});

watch(
  () => props.materialsId,
  (newId, oldId) => {
    if (newId !== oldId) {
      getMaterialsDetail();
    }
  }
);
</script>
