<template>
  <uv-popup ref="popupRef" mode="bottom" round="20" :safeAreaInsetBottom="true">
    <view class="popup-container">
      <view class="popup-header">
        <text class="title">变更详情</text>
        <uv-icon name="close" size="36rpx" color="#999" @click="close"></uv-icon>
      </view>

      <scroll-view class="popup-content" scroll-y v-if="!projectStore.fetchChangeDetailLoading">

        <uv-tabs :list="tabList" :current="currentTab" @click="handleTabClick" lineColor="#1c9bfd" activeColor="#1c9bfd" inactiveColor="#666"></uv-tabs>

        <view class="tab-pane" v-show="tabList[currentTab]?.name === '基本信息'">
          <!-- 基本信息 -->
          <CommonSection title="基本信息">
            <CommonInfoRow label="变更类型" :value="getDictLabel(changeTypeOptions, projectStore.changeDetailData.changeType)" />
            
            <template v-if="projectStore.changeDetailData.projectType == '10' || projectStore.changeDetailData.projectType == '30'">
              <CommonInfoRow 
                label="项目分类" 
                :value="projectStore.projectBaseData.projectClazzName" 
              />
            </template>

            <template v-if="projectStore.changeDetailData.projectType == '20'">
              <CommonInfoRow 
                label="研究类型" 
                :value="sysDict.getDictLabel('sci_pjt_type', projectStore.projectBaseData.isClinicalTrial)" 
              />
            </template>

            <CommonInfoRow 
              v-if="projectStore.changeDetailData.changeType == '50'"
              label="中止时间" 
              :value="projectStore.changeDetailData.abortDate ? dayjs(projectStore.changeDetailData.abortDate).format('YYYY-MM-DD') : '--'" 
              noBorder
            />

            <CommonInfoRow 
              v-if="projectStore.changeDetailData.changeType == '60'"
              label="经费卡余额" 
              :value="projectStore.projectBaseData.cardBalanceAmount !== undefined && projectStore.projectBaseData.cardBalanceAmount !== null ? String(projectStore.projectBaseData.cardBalanceAmount) : '--'" 
              noBorder
            />

            <view 
              class="ui-info-row no-border" 
              v-if="projectStore.changeDetailData.evidence"
              style="padding: 24rpx 0; font-size: 28rpx; display: flex; justify-content: space-between;"
            >
              <view class="item-label" style="color: #343a3f; width: 200rpx; flex-shrink: 0; margin-right: 20rpx;">证明材料</view>
              <view class="item-value" style="flex: 1; text-align: right;">
                <text style="color: #1c9bfd;" @click="previewFile(projectStore.changeDetailData.evidence)">查看附件</text>
              </view>
            </view>
          </CommonSection>
        </view>

        <view class="tab-pane" v-show="tabList[currentTab]?.name === '变更前信息'">
          <!-- 变更前信息 -->
          <CommonSection title="变更前信息" v-if="projectStore.changeDetailData.changeType != '50'">
            <!-- 10: 成员变更 -->
            <template v-if="projectStore.changeDetailData.changeType == '10'">
              <view class="member-list">
                <view class="member-card" v-for="(row, idx) in projectStore.changePreData" :key="idx">
                  <view class="m-header">
                    <text class="m-name">{{ row.memberName }}</text>
                    <text class="m-role">{{ getProjectRoleName(row.projectRole) }}</text>
                  </view>
                  <view class="m-body">
                    <CommonInfoRow label="学位" :value="getDegreeName(row.degree)" />
                    <CommonInfoRow label="成员类型" :value="getMemberTypeName(row.memberType)" />
                    <CommonInfoRow label="科室" :value="row.deptName" />
                    <CommonInfoRow label="负责内容" :value="row.responsibleContent" noBorder />
                  </view>
                </view>
                <uv-empty v-if="!projectStore.changePreData || projectStore.changePreData.length === 0" mode="data" text="暂无数据"></uv-empty>
              </view>
            </template>

            <!-- 30: 延期变更 -->
            <template v-if="projectStore.changeDetailData.changeType == '30'">
              <CommonInfoRow label="开始日期" :value="projectStore.changePreData && projectStore.changePreData[0] ? dayjs(projectStore.changePreData[0]).format('YYYY-MM-DD') : '--'" />
              <CommonInfoRow label="结束日期" :value="projectStore.changePreData && projectStore.changePreData[1] ? dayjs(projectStore.changePreData[1]).format('YYYY-MM-DD') : '--'" noBorder />
            </template>

            <!-- 40: 经费变更 -->
            <template v-if="projectStore.changeDetailData.changeType == '40'">
              <CommonInfoRow 
                :label="projectStore.projectBaseData.isClinicalTrial === '10' ? '科研经费（万元）' : '合同经费（万元）'" 
                :value="amountUnitTransfer(projectStore.changePreData)" 
                isAmount 
                noBorder 
              />
            </template>

            <!-- 60: 经费调剂 -->
            <template v-if="projectStore.changeDetailData.changeType == '60'">
              <view class="member-list">
                <view class="member-card" v-for="(row, idx) in projectStore.changePreData" :key="idx">
                  <view class="m-header">
                    <text class="m-name">{{ row.subjName }}</text>
                  </view>
                  <view class="m-body">
                    <CommonInfoRow label="科目编号" :value="row.subjCode" />
                    <CommonInfoRow label="剩余金额(元)" :value="row.balanceAmount !== undefined && row.balanceAmount !== null ? String(row.balanceAmount) : '0'" noBorder />
                  </view>
                </view>
                <uv-empty v-if="!projectStore.changePreData || projectStore.changePreData.length === 0" mode="data" text="暂无数据"></uv-empty>
              </view>
            </template>
          </CommonSection>
          <uv-empty v-else mode="data" text="此变更类型无变更前信息"></uv-empty>
        </view>

        <view class="tab-pane" v-show="tabList[currentTab]?.name === '变更后信息'">
          <!-- 变更后信息 -->
          <CommonSection title="变更后信息" v-if="projectStore.changeDetailData.changeType != '50'">
            <!-- 10: 成员变更 -->
            <template v-if="projectStore.changeDetailData.changeType == '10'">
              <view class="member-list">
                <view class="member-card is-new" v-for="(row, idx) in projectStore.changeAfterData" :key="idx">
                  <view class="m-header">
                    <text class="m-name">{{ row.memberName }}</text>
                    <text class="m-role">{{ getProjectRoleName(row.projectRole) }}</text>
                  </view>
                  <view class="m-body">
                    <CommonInfoRow label="学位" :value="getDegreeName(row.degree)" />
                    <CommonInfoRow label="成员类型" :value="getMemberTypeName(row.memberType)" />
                    <CommonInfoRow label="科室" :value="row.deptName" />
                    <CommonInfoRow label="负责内容" :value="row.responsibleContent" noBorder />
                  </view>
                </view>
                <uv-empty v-if="!projectStore.changeAfterData || projectStore.changeAfterData.length === 0" mode="data" text="暂无数据"></uv-empty>
              </view>
            </template>

            <!-- 30: 延期变更 -->
            <template v-if="projectStore.changeDetailData.changeType == '30'">
              <CommonInfoRow label="开始日期" :value="projectStore.changeAfterData && projectStore.changeAfterData[0] ? dayjs(projectStore.changeAfterData[0]).format('YYYY-MM-DD') : '--'" />
              <CommonInfoRow label="结束日期" :value="projectStore.changeAfterData && projectStore.changeAfterData[1] ? dayjs(projectStore.changeAfterData[1]).format('YYYY-MM-DD') : '--'" noBorder />
            </template>

            <!-- 40: 经费变更 -->
            <template v-if="projectStore.changeDetailData.changeType == '40'">
              <CommonInfoRow 
                :label="projectStore.projectBaseData.isClinicalTrial === '10' ? '科研经费（万元）' : '合同经费（万元）'" 
                :value="amountUnitTransfer(projectStore.changeAfterData)" 
                isAmount 
                noBorder 
              />
            </template>

            <!-- 60: 经费调剂 -->
            <template v-if="projectStore.changeDetailData.changeType == '60'">
              <view class="member-list">
                <view class="member-card is-new" v-for="(row, idx) in projectStore.changeAfterData" :key="idx">
                  <view class="m-header">
                    <text class="m-name">{{ row.subjName }}</text>
                  </view>
                  <view class="m-body">
                    <CommonInfoRow label="科目编号" :value="row.subjCode" />
                    <CommonInfoRow label="剩余金额(元)" :value="row.balanceAmount !== undefined && row.balanceAmount !== null ? String(row.balanceAmount) : '0'" noBorder />
                  </view>
                </view>
                <uv-empty v-if="!projectStore.changeAfterData || projectStore.changeAfterData.length === 0" mode="data" text="暂无数据"></uv-empty>
              </view>
            </template>
          </CommonSection>
          <uv-empty v-else mode="data" text="此变更类型无变更后信息"></uv-empty>
        </view>

        <view class="tab-pane" v-show="tabList[currentTab]?.name === '审批信息'">
          <!-- 审批信息 -->
          <CommonSection title="审批信息">
            <FlowTable :id="projectStore.changeDetailData.id" :businessCode="String(projectStore.changeDetailData.id)"
              defCode="sci_project_change" />
          </CommonSection>
        </view>

      </scroll-view>

      <view class="loading-wrap" v-else>
        <uv-loading-icon text="数据加载中..." :vertical="true"></uv-loading-icon>
      </view>

    </view>
  </uv-popup>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useProjectStore } from '@/store/modules/project';
import { useDict } from '@/hooks/useDict';
import { changeTypeOptions } from '@/constants';
import FlowTable from './FlowTable.vue';
import dayjs from 'dayjs';
import CommonSection from '@/components/ui/CommonSection.vue';
import CommonInfoRow from '@/components/ui/CommonInfoRow.vue';
import { previewFile } from '@/utils/file';

const projectStore = useProjectStore();
const popupRef = ref<any>(null);

const sysDict = useDict('sci_pjt_level', 'sci_pjt_type', 'sci_academic_degree');

/** Tab 页标题配置 */
const tabList = computed(() => {
  const tabs = [{ name: '基本信息' }];

  if (projectStore.changeDetailData.changeType != '50') {
    tabs.push({ name: '变更前信息' });
    tabs.push({ name: '变更后信息' });
  }

  if (projectStore.changeDetailData.approvalStatus > 10) {
    tabs.push({ name: '审批信息' });
  }

  return tabs;
});

// 当前激活的 tab index
const currentTab = ref(0);

/**
 * 切换 Tab 页
 */
const handleTabClick = (item: any) => {
  currentTab.value = item.index;
};

/**
 * 外部调用开启详情弹窗
 * @param row 原始数据
 * @param projectType 项目类型
 * @param projectId 项目对应的原记录ID
 */
const open = (row: any, projectType: string, projectId: number) => {
  popupRef.value?.open();
  // Call mapped store action, keeping all logic decoupled
  projectStore.fetchProjectChangeDetail(row.id || row.changeId, projectType, projectId);
};

const close = () => {
  popupRef.value?.close();
  // 关闭时重置 tab 索引
  setTimeout(() => {
    currentTab.value = 0;
  }, 300);
};

// Utils strictly mapped locally for UI
const getDictLabel = (options: any[], value: string | number) => {
  const opt = options.find((item: any) => item.dictValue == value);
  return opt ? opt.dictLabel : value;
};

const getDegreeName = (val: string) => {
  return sysDict.getDictLabel('sci_academic_degree', val) || '--';
};

const getMemberTypeName = (val: string) => {
  const map: Record<string, string> = { '10': '本院人员', '20': '非本院人员', '30': '研究生' };
  return map[val] || val || '--';
};

const getProjectRoleName = (val: string) => {
  const map: Record<string, string> = { '10': '负责人', '20': '主要参与人', '30': '一般参与人' };
  return map[val] || val || '--';
};

const amountUnitTransfer = (val: any) => {
  if (val === null || val === undefined) return '0.00';
  const num = Number(val);
  if (isNaN(num)) return '0.00';
  const formatted = (num / 10000).toFixed(2);
  const parts = formatted.split('.');
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return parts.join('.');
};

defineExpose({ open, close });
</script>

<style lang="scss" scoped>
.popup-container {
  height: 85vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.popup-header {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  background-color: #fff;
  border-bottom: 2rpx solid #eee;

  .title {
    font-size: 34rpx;
    font-weight: bold;
    color: #343A3F;
  }
}

.loading-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-content {
  flex: 1;
  overflow: hidden;
  background-color: #f7f8fa;
}

.tab-pane {
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #343A3F;
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;

    .icon {
      width: 8rpx;
      height: 30rpx;
      background-color: #1c9bfd;
      border-radius: 4rpx;
      margin-right: 16rpx;
    }
  }
}

.info-list {
  display: flex;
  flex-direction: column;

  .info-item {
    display: flex;
    padding: 16rpx 0;
    border-bottom: 2rpx dashed #f5f5f5;
    font-size: 28rpx;
    line-height: 1.5;

    &:last-child {
      border-bottom: none;
    }

    .label {
      color: #343A3F;
      width: 180rpx;
      flex-shrink: 0;
    }

    .value {
      flex: 1;
      color: #585858;
      word-break: break-all;
      text-align: right;
    }
  }
}

.member-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;

  .member-card {
    background-color: #f8f9fb;
    border-radius: 12rpx;
    padding: 24rpx;
    border-left: 6rpx solid #b3d8ff;

    &.is-new {
      border-left-color: #67c23a;
    }

    .m-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .m-name {
        font-size: 30rpx;
        font-weight: bold;
        color: #343A3F;
      }

      .m-role {
        font-size: 24rpx;
        background-color: #e6f1fc;
        color: #1c9bfd;
        padding: 4rpx 12rpx;
        border-radius: 8rpx;
      }
    }
    
    .m-body {
      background-color: #fff;
      padding: 10rpx 20rpx;
      border-radius: 8rpx;
    }
  }
}

.text-red {
  color: #ff4d4f;
}

.font-num {
  font-family: din;
  font-weight: bold;
}
</style>
