<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.awardName || '-'" />
        <CommonInfoRow label="编号" :value="form.awardCode || '-'" />
        <CommonInfoRow label="所在部门" :value="form.deptName" />
        <CommonInfoRow label="奖项所属年度" :value="form.awardYear ? formatDate(form.awardYear, 'YYYY') : '-'" />
        <CommonInfoRow label="获奖类别" :value="awardTypeText" />
        <CommonInfoRow label="获奖等级" :value="getDictLabel('sci_awards_grade', form.awardGrade)" />
        <CommonInfoRow label="获奖级别" :value="getDictLabel('sci_awards_level', form.awardLevel)" />
        <CommonInfoRow label="获奖人（备案人）" :value="form.members || showMembers(form.memberList)" />
        <CommonInfoRow label="完成单位" :value="form.completionUnit" />
        <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.remark || '-'" isColumn />
      </CommonSection>

      <!-- 授权信息 -->
      <CommonSection title="授权信息">
        <CommonInfoRow label="批文年月日" :value="formatDate(form.awardDate)" />
        <CommonInfoRow label="颁奖机构" :value="form.awardIssueAuthority || '-'" />
        <CommonInfoRow label="获奖金额（万元）" :value="formatAmountInTenThousand(form.awardAmount)" />
      </CommonSection>

      <!-- 附件 -->
      <CommonSection title="附件">
        <CommonInfoRow label="获奖批文" isColumn>
          <view class="file-links">
            <template v-if="awardIssueAuthorityProofList.length">
              <view class="file-item" v-for="(item, index) in awardIssueAuthorityProofList" :key="'award-proof-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.fileName || item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="获奖证书" isColumn>
          <view class="file-links">
            <template v-if="awardCertificateList.length">
              <view class="file-item" v-for="(item, index) in awardCertificateList" :key="'award-certificate-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.fileName || item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
        <CommonInfoRow label="获奖金额证明" isColumn>
          <view class="file-links">
            <template v-if="awardAmountProofList.length">
              <view class="file-item" v-for="(item, index) in awardAmountProofList" :key="'award-amount-proof-' + index" @click="handlePreview(item)">
                <text class="file-link">{{ item.fileName || item.name || '-' }}</text>
              </view>
            </template>
            <text v-else>-</text>
          </view>
        </CommonInfoRow>
      </CommonSection>

      <!-- 关联项目 -->
      <CommonSection title="关联项目">
        <view class="related-list" v-if="relatedProjectList.length">
          <view class="related-item" v-for="(item, index) in relatedProjectList" :key="item.id || item.projectSource || index">
            <text class="related-index">{{ Number(index) + 1 }}</text>
            <view class="related-content">
              <view class="related-top">
                <text class="related-type-tag" :class="{ subject: item.sourceType === '20' }">
                  {{ item.sourceType === '10' ? '项目' : item.sourceType === '20' ? '学科' : '-' }}
                </text>
              </view>
              <text class="related-name">{{ item.projectSource || '-' }}</text>
            </view>
          </view>
        </view>
        <text v-else>-</text>
      </CommonSection>

      <!-- 审批信息 -->
      <CommonSection title="审批信息" v-if="form.id">
        <FlowTable :id="form.id" :businessCode="'奖项荣誉-' + String(form.awardCode)" defCode="sci_academic_achievement" />
      </CommonSection>

      <!-- 授权审核进度 -->
      <CommonSection title="授权审核进度" v-if="form.id">
        <FlowTable :id="form.id" :businessCode="'奖项荣誉授权-' + String(form.awardCode)" defCode="sci_academic_achievement_reward_auth" />
      </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 { useDocumentApi } from '@/api/document';
import { formatDate } from '@/utils/date';
import { previewFile } from '@/utils/file';
import to from 'await-to-js';
import FlowTable from '@/pages/project/components/detail/FlowTable.vue';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';

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

const { getDictLabel } = useDict('sci_awards_grade', 'sci_awards_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 parseFileList = (fileStr: string) => {
  if (!fileStr) return [];
  try {
    const files = JSON.parse(fileStr);
    return Array.isArray(files) ? files : [files];
  } catch (e) {
    return [];
  }
};

const awardIssueAuthorityProofList = computed(() => parseFileList(form.value?.awardIssueAuthorityProof));
const awardCertificateList = computed(() => parseFileList(form.value?.awardCertificate));
const awardAmountProofList = computed(() => parseFileList(form.value?.awardAmountProof));
const relatedProjectList = computed(() => Array.isArray(form.value?.projList) ? form.value.projList : []);
const awardTypeText = computed(() => {
  if (form.value?.awardType === '10') return '教学成果';
  if (form.value?.awardType === '20') return '科研奖项';
  return '-';
});

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 awardCode = props.code.includes('-') ? props.code.split('-')[1] : props.code;
  const [err, res] = await to(documentApi.getAwardsByCode(awardCode));
  if (!err && res?.data) {
    form.value = res.data;
  }
  loading.value = false;
};

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

watch(() => props.code, () => {
  fetchData();
});

const showMembers = (list: any[]) => {
  return list?.map(m => m.memberName).join(', ') || '-';
};

const formatAmountInTenThousand = (amount: number | string) => {
  const num = Number(amount);
  if (Number.isNaN(num)) return '-';
  return num.toFixed(2);
};
</script>

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

.platform-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  gap: 8rpx;
  
  .platform-tag {
    font-size: 20rpx;
    padding: 2rpx 12rpx;
    background-color: #f6f8fa;
    color: #64748b;
    border-radius: 4rpx;
    border: 1rpx solid #e2e8f0;
  }
}

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

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

.related-list {
  width: 100%;
}

.related-item {
  display: flex;
  align-items: flex-start;
  padding: 16rpx 18rpx;
  border-radius: 12rpx;
  background: #f8fafc;
  border: 1rpx solid #e2e8f0;
  margin-bottom: 12rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.related-index {
  min-width: 36rpx;
  height: 36rpx;
  line-height: 36rpx;
  text-align: center;
  border-radius: 50%;
  background: #e0f2fe;
  color: #0284c7;
  font-size: 22rpx;
  font-weight: 700;
  margin-right: 12rpx;
}

.related-content {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  flex: 1;
  min-width: 0;
}

.related-top {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.related-label {
  font-size: 22rpx;
  color: #64748b;
}

.related-type-tag {
  font-size: 20rpx;
  color: #2563eb;
  background: #dbeafe;
  border: 1rpx solid #bfdbfe;
  border-radius: 100rpx;
  padding: 2rpx 12rpx;

  &.subject {
    color: #7c3aed;
    background: #ede9fe;
    border-color: #ddd6fe;
  }
}

.related-name {
  font-size: 24rpx;
  color: #1e293b;
  line-height: 1.5;
  word-break: break-all;
}
</style>
