<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.reportTitle" />
        <CommonInfoRow label="提交单位" :value="form.submitUnit" />
        <CommonInfoRow label="提交日期" :value="form.submitDate ? formatDate(form.submitDate, 'YYYY-MM-DD') : '-'" />
        <CommonInfoRow label="所属单位" :value="form.belongUnit" />
        <CommonInfoRow label="所属年度" :value="form.belongYear" />
        <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="所属团队" :value="form.belongTeam" />
        <CommonInfoRow label="学校署名" :value="form.schoolSignature === '10' ? '第一单位' : form.schoolSignature === '20' ? '非第一单位' : form.schoolSignature" />
        <CommonInfoRow label="是否被采纳" :value="form.isAdopted === 1 ? '是' : '否'" />
        <template v-if="form.isAdopted === 1">
          <CommonInfoRow label="采纳对象" :value="getDictLabel('adopt_subject', form.adoptTarget)" />
          <CommonInfoRow label="采纳单位名称" :value="form.adoptUnitName" />
        </template>
        <CommonInfoRow label="是否被批示" :value="form.isInstruction === 1 ? '是' : '否'" />
        <template v-if="form.isInstruction === 1">
          <CommonInfoRow label="批示人姓名" :value="form.instructionPersonName" />
          <CommonInfoRow label="批示领导级别" :value="getDictLabel('leader_level', form.instructionLeaderLevel)" />
          <CommonInfoRow label="批示人职务" :value="form.instructionPersonPosition" />
        </template>
        <CommonInfoRow label="总字数" :value="(form.wordCount || '0') + '万字'" />
        <CommonInfoRow label="报告电子版" isColumn>
          <view class="file-links">
            <view v-if="reportFile" class="file-item" @click="handlePreview(reportFile)">
              <text class="file-link">{{ reportFile.fileName || '-' }}</text>
            </view>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow v-if="form.isInstruction === 1" label="批示主要内容" :value="form.instructionContent" isColumn />
        <CommonInfoRow label="备注" :value="form.remark" isColumn />
      </CommonSection>

      <!-- 完成人列表 -->
      <CommonSection title="完成人列表" >
        <view class="member-list">
          <view class="member-item" v-for="(member, index) in form.memberList" :key="index">
            <view class="member-header">
              <view class="m-left">
                <text class="m-name  mr20">{{ member.memberName }}</text>
                <text class="m-type-tag blue">{{ member.memberType || '完成人' }}</text>
              </view>
              <text class="m-tag" v-if="member.contributionRate">{{ member.contributionRate }}% 贡献率</text>
            </view>
            <view class="m-body">
              <view class="m-line">
                <text class="l">单位：</text>
                <text class="v">{{ member.workUnit || '-' }}</text>
              </view>
              <view class="m-line">
                <text class="l">学历/职称：</text>
                <text class="v">{{ member.education || '-' }} / {{ member.professionalTitle || '-' }}</text>
              </view>
            </view>
          </view>
        </view>
      </CommonSection>

      <!-- 关联项目列表 -->
      <CommonSection title="关联项目列表">
        <view class="funds-list" v-if="form.projectList?.length">
          <view class="funds-item" v-for="(project, index) in form.projectList" :key="index">
            <view class="f-row">
              <text class="f-name">{{ project.projectName }}</text>
              <text class="m-type-tag" :class="project.projectType === '10' ? 'blue' : project.projectType === '20' ? 'orange' : 'green'">
                {{ getProjectType(project.projectType) }}
              </text>
            </view>
            <view class="f-grid">
              <view class="g-item highlight">
                <text class="gl">负责人</text>
                <text class="gv">{{ project.projectLeader || '-' }}</text>
              </view>
              <view class="g-item highlight">
                <text class="gl">项目状态</text>
                <text class="gv">{{ getProjectStatus(project.projectStatus) }}</text>
              </view>
            </view>
          </view>
        </view>
        <uv-empty v-else mode="data" text="暂无数据"></uv-empty>
      </CommonSection>

      <!-- 附件信息 -->
      <AttachmentList :list="mergedFileList" title="附件列表" />

      <!-- 审批记录 -->
      <CommonSection title="审批记录" v-if="form.id">
        <FlowTable :id="form.id" :businessCode="String(form.id)" defCode="sci_achievement_decision" />
      </CommonSection>
    </template>
    <uv-empty v-else mode="data" text="暂无数据"></uv-empty>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { useDict } from '@/hooks/useDict';
import { formatDate } from '@/utils/date';
import { previewFile } from '@/utils/file';
import AttachmentList from './AttachmentList.vue';
import FlowTable from '@/pages/project/components/detail/FlowTable.vue';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';
import { useDocumentApi } from '@/api/document/index';

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

const { getDictLabel } = useDict('adopt_subject', 'leader_level');
const documentApi = useDocumentApi();

const form = ref<any>(null);
const loading = ref(false);

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) return [];
  const list: any[] = [];

  // 其他附件
  if (form.value.fileList?.length) {
    form.value.fileList.forEach((f: any) => {
      list.push({
        fileName: f.adoptFileName,
        fileUrl: f.adoptFileUrl,
        fileType: f.fileType === 10 ? '采纳材料' : '批示材料'
      });
    });
  }
  
  return list;
});

const reportFile = computed(() => {
  if (form.value?.reportFileUrl) {
    return {
      fileName: form.value.reportFileName || '查看附件',
      fileUrl: form.value.reportFileUrl
    };
  }
  return null;
});

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

const getProjectType = (type: string) => {
  const map: any = { '10': '纵向', '20': '横向', '30': '内部' };
  return map[type] || type;
};

const getProjectStatus = (status: string) => {
  const map: any = { '10': '立项', '20': '在研', '30': '结题验收', '50': '临近结题' };
  return map[status] || status;
};

const fetchData = async () => {
  if (!props.code) return;
  loading.value = true;
  try {
    const res: any = await documentApi.getDecisionById(props.code);
    if (res.code == 200) {
      form.value = res.data;
    }
  } catch (error) {
    console.error('Fetch Decision error:', error);
  }
  loading.value = false;
};

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

watch(() => props.code, () => {
  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>
