<template>
  <view class="document-form">
    <uv-loading-icon v-if="loading" mode="circle" text="正在加载活动详情..."></uv-loading-icon>
    <template v-else-if="form">
      <!-- 基本信息 -->
      <CommonSection title="基本信息" :isFirst="true">
        <CommonInfoRow label="活动名称" :value="form.activityName" />
        <CommonInfoRow label="申请人" :value="form.applicantBy" />
        <CommonInfoRow label="所属部门" :value="deptName" />
        <CommonInfoRow label="所属年度" :value="form.belongYear" />
        <CommonInfoRow label="活动类型" :value="activityTypeLabel" />
        <CommonInfoRow label="活动地点" :value="form.activityPlace" />
        <CommonInfoRow label="展览类别" :value="exhibitionCategoryLabel" />
        <CommonInfoRow label="开始日期" :value="formatDate(form.activityStartTime)" />
        <CommonInfoRow label="结束日期" :value="formatDate(form.activityEndTime)" />
        <CommonInfoRow label="活动规模" :value="form.activityScale" />
        <CommonInfoRow label="产出成果" :value="form.outputAchievement" />
        <CommonInfoRow label="所属平台" isColumn>
          <view class="platform-tags">
            <template v-if="platformList.length > 0">
              <uv-tags v-for="(p, index) in platformList" :key="index" :text="p.platformName === '其他' ? '其他' : (p.platformType ? p.platformName + ' (' + p.platformType + ')' : p.platformName)" type="primary" plain size="mini" class="mr5"></uv-tags>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="佐证材料" isColumn>
          <view class="file-links">
            <template v-if="mergedFileList.length">
              <view class="file-item" v-for="(item, index) in mergedFileList" :key="'evidence-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="备注" :value="form.remark" isColumn />
      </CommonSection>

      <!-- 审核信息 -->
      <CommonSection title="审核信息" v-if="showAuditOpinion">
        <CommonInfoRow label="审核意见" :value="form.auditOpinion" isColumn />
      </CommonSection>

    </template>
    <uv-empty v-else mode="data" text="暂无数据"></uv-empty>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useAchievementApi } from '@/api/achievement/index';
import { useDeptApi } from '@/api/system/index';
import { formatDate } from '@/utils/date';
import { previewFile } from '@/utils/file';
import to from 'await-to-js';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';

const props = defineProps<{
  code: string | number; // 接收 ID
}>();

const achievementApi = useAchievementApi();
const deptApi = useDeptApi();

const form = ref<any>(null);
const loading = ref(false);
const unitList = ref<any[]>([]);
const activityTypeDict = ref<any[]>([]);
const exhibitionCategoryDict = ref<any[]>([]);

const deptName = computed(() => {
  if (!form.value?.belongDeptId) return '-';
  const findNode = (nodes: any[]): string | null => {
    for (const node of nodes) {
      if (node.id === form.value.belongDeptId) return node.deptName;
      if (node.children?.length) {
        const name = findNode(node.children);
        if (name) return name;
      }
    }
    return null;
  };
  return findNode(unitList.value) || form.value.deptName || '-';
});

const activityTypeLabel = computed(() => {
  const item = activityTypeDict.value.find(d => d.dictValue === form.value?.activityType);
  return item ? item.dictLabel : (form.value?.activityType || '-');
});

const exhibitionCategoryLabel = computed(() => {
  const item = exhibitionCategoryDict.value.find(d => d.dictValue === form.value?.exhibitionCategory);
  return item ? item.dictLabel : (form.value?.exhibitionCategory || '-');
});

const platformNames = computed(() => {
  return form.value?.platformInfo?.map((item: any) => item.platformName).join('、') || '-';
});

const showAuditOpinion = computed(() => {
  if (!form.value) return false;
  // 参考 PC 逻辑: 驳回(1) 或 审核通过(3) 时展示
  return form.value.auditOpinion && (form.value.auditStatus === 1 || form.value.auditStatus === 3);
});

const platformList = computed(() => {
  if (form.value?.belongPlatform) {
    try {
      const data = JSON.parse(form.value.belongPlatform);
      return Array.isArray(data) ? data : [];
    } catch (e) {
      if (form.value.belongPlatform === '其他') return [{ platformName: '其他' }];
      return [{ platformName: form.value.belongPlatform }];
    }
  }
  return [];
});

const mergedFileList = computed(() => {
  if (!form.value?.evidenceMaterials) return [];
  let rawFiles: string[] = [];
  try {
    rawFiles = typeof form.value.evidenceMaterials === 'string' 
      ? JSON.parse(form.value.evidenceMaterials) 
      : form.value.evidenceMaterials;
    if (!Array.isArray(rawFiles)) rawFiles = [rawFiles];
  } catch (e) {
    return [];
  }

  return rawFiles.map(fileData => {
    if (!fileData) return null;
    const name = fileData.split('/').pop() || '文件';
    const startIndex = fileData.indexOf('/');
    const url = import.meta.env.VITE_SCIENTIFIC_FILE_URL + fileData.slice(startIndex + 1);
    return { name, url };
  }).filter((item): item is { name: string; url: string } => Boolean(item));
});

const handlePreview = (file: any) => {
  const url = file.fileUrl || file.url;
  const name = file.fileName || file.name;
  if (url) {
    previewFile(url, name);
  }
};

const fetchData = async () => {
  if (!props.code) return;
  loading.value = true;

  // 并行获取详情、部门树、字典
  const [
    [err, res],
    [deptErr, deptRes],
    [typeDictErr, typeDictRes],
    [categoryDictErr, categoryDictRes]
  ] = await Promise.all([
    to(achievementApi.getSpecialActivityDetail(props.code)),
    to(deptApi.getDeptTree()),
    to(achievementApi.getDictData('cxy_research_special_activity_type')),
    to(achievementApi.getDictData('cxy_research_special_exhibition_category'))
  ]);

  if (!err && res?.data) {
    form.value = res.data;
  }
  if (!deptErr && deptRes?.data) {
    unitList.value = deptRes.data || [];
  }
  if (!typeDictErr && typeDictRes?.data) {
    activityTypeDict.value = Array.isArray(typeDictRes.data) ? typeDictRes.data : [];
  }
  if (!categoryDictErr && categoryDictRes?.data) {
    exhibitionCategoryDict.value = Array.isArray(categoryDictRes.data) ? categoryDictRes.data : [];
  }

  loading.value = false;
};

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

<style lang="scss" scoped>
@import "./common.scss";

.file-links {
  .file-item {
    padding: 6rpx 0;
  }

  .file-link {
    color: #2979ff;
    text-decoration: underline;
    word-break: break-all;
  }
}
</style>
