<template>
  <el-button type="primary" @click="handleUpdateFile">保存文件</el-button>
  <el-row :gutter="20">
    <el-col :span="8">
      <el-menu :default-active="activeMenu" @select="handleMenuClick">
        <el-menu-item :key="item.value" v-for="item in contractor_file_type" :index="item.value">
          <el-space>
            <p>{{ item.label }}</p>
            <el-tag type="success" v-if="ossIdMap[item.value]">已上传</el-tag>
            <el-tag type="warning" v-else>未上传</el-tag>
          </el-space>
        </el-menu-item>
      </el-menu>
    </el-col>
    <el-col :span="16">
      <file-upload
        v-model="ossIdMap[activeMenu]"
        :limit="1"
        :file-size="50"
        :file-type="['pdf']"
        @update:model-value="
          (args) => {
            handleOssUpdate(args);
          }
        "
      />
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { getContractor, updateContractor } from '@/api/project/contractor';

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

interface Props {
  contractorId?: string | number;
}

const props = defineProps<Props>();
const loading = ref<boolean>(false);

// 当前选中的菜单项
const activeMenu = ref('0'); // 默认选中第一个
const ossIdMap = ref<Record<string, string>>({});
// 处理菜单点击事件
const handleMenuClick = (index: string) => {
  activeMenu.value = index;
};
// 获取公司详情
const getComponentVO = async () => {
  loading.value = true;
  const res = await getContractor(props.contractorId);
  ossIdMap.value = res.data.fileMap ?? { '0': '' };
  loading.value = false;
};

const handleOssUpdate = (ossId: string) => {
  // 判断 ossId 是否为空
  if (ossId === '' || ossId === null || ossId === undefined) {
    delete ossIdMap.value[activeMenu.value]; // 删除 key
  } else {
    ossIdMap.value[activeMenu.value] = ossId; // 直接赋值
  }
  console.log(ossIdMap.value);
};

const handleUpdateFile = async () => {
  loading.value = true;
  await updateContractor({
    id: props.contractorId,
    fileMap: ossIdMap.value
  });
  proxy?.$modal.msgSuccess('保存成功');
  loading.value = false;
};

watch(
  () => props.contractorId,
  (newId, oldId) => {
    if (newId !== oldId) {
      getComponentVO();
    }
  }
);

onMounted(() => {
  getComponentVO();
});
</script>
