<template>
  <div class="card shadow-sm rounded-xl overflow-hidden p-4">
    <div class="border border-[#EEEEEE] p-4 rounded-xl">
      <div class="flex items-center mb-3">
        <div class="w-8 h-8 flex items-center justify-center mr-2">
          <img src="@/assets/images/report/rzls.png" alt="融资历史" class="w-8 h-8 object-contain" />
        </div>
        <span class="font-bold text-gray-800">融资历史</span>
      </div>

      <!-- 按融资企业分组显示 -->
      <div v-if="groupedFinancing.length > 0" class="space-y-4">
        <div v-for="(group, groupIndex) in groupedFinancing" :key="groupIndex" class="financing-group">
          <!-- 融资企业容器 -->
          <div class="bg-[#F5F5F5] rounded-lg p-3">
            <!-- 融资企业标题 -->
            <div class="mb-3">
              <div class="flex items-center border-b border-[#0000000A] pb-2">
                <div class="text-[#333333] font-medium">{{ group.companyName }}</div>
              </div>
              <div class="flex items-center justify-between pt-2">
                <span class="text-sm text-gray-600">融资企业</span>
                <span class="text-sm text-gray-600">融资轮次: <span class="ml-1 font-medium text-[#333333]">{{
                  group.totalFinancings }}</span></span>
              </div>
            </div>

            <!-- 融资记录列表 -->
            <div class="space-y-3">
              <div v-for="(financing, index) in group.financings" :key="index"
                class="financing-wrapper bg-white rounded-lg overflow-hidden shadow-sm border border-[#EEEEEE]">
                <!-- 融资卡片 - 可点击展开 -->
                <div class="cursor-pointer relative"
                  @click="toggleFinancingExpand(financing.companyName, 'financingHistory', index)">
                  <!-- 企业名称和轮次 -->
                  <div class="px-4 py-2 border-b border-[#0000000A] flex items-center justify-between">
                    <div class="font-medium text-[#333333] flex-1 truncate">{{ financing.companyName }}</div>
                    <span v-if="financing.round"
                      class="px-2 py-1 text-xs rounded font-medium flex-shrink-0 ml-2 bg-blue-50 text-blue-600">
                      {{ financing.round }}
                    </span>
                  </div>

                  <!-- 融资信息 -->
                  <div class="px-4 py-2">
                    <!-- 投资方 -->
                    <div class="text-sm text-gray-600 mb-2">
                      <span>投资方：</span>
                      <span>{{ financing.investorName || '—' }}</span>
                    </div>

                    <!-- 披露时间 -->
                    <div class="text-sm text-gray-600 mb-2">
                      <span>披露：</span>
                      <span>{{ formatDate(financing.pubTime) }}</span>
                    </div>

                    <!-- 融资金额 -->
                    <div class="text-sm mb-2">
                      <span class="text-gray-600">融资金额：</span>
                      <span class="font-bold text-primary">{{ financing.money || '—' }}</span>
                    </div>

                    <!-- 底部标签行 -->
                    <div class="flex items-center gap-2 flex-wrap">
                      <!-- 估值 -->
                      <span v-if="financing.value" class="text-xs bg-primary-light rounded py-1 px-2 text-primary">
                        估值: {{ financing.value }}
                      </span>

                      <!-- 股权 -->
                      <span v-if="financing.share" class="text-xs bg-primary-light rounded py-1 px-2 text-primary">
                        股权: {{ financing.share }}
                      </span>

                      <!-- 有新闻标签 -->
                      <span v-if="financing.newsTitle" class="text-xs bg-primary-light rounded py-1 px-2 text-primary">
                        有新闻
                      </span>
                    </div>
                  </div>

                  <!-- 展开指示器 -->
                  <div class="absolute right-4 bottom-2 flex items-center text-xs text-gray-500">
                    <img src="@/assets/images/report/zk.png" alt="展开" class="w-4 h-4 container"
                      :class="{ 'rotate-180': isFinancingExpanded(financing.companyName, 'financingHistory', index) }" />
                  </div>
                </div>

                <!-- 融资详情抽屉 -->
                <div class="mt-4 overflow-hidden transition-all duration-300 ease-in-out" :class="{
                  'max-h-0 opacity-0': !isFinancingExpanded(financing.companyName, 'financingHistory', index),
                  'max-h-none opacity-100': isFinancingExpanded(financing.companyName, 'financingHistory', index),
                }">
                  <div class="mt-1 transform transition-all duration-300">
                    <div class="grid grid-cols-[max-content_1fr] gap-y-3 p-4">
                      <!-- 轮次 -->
                      <span class="text-base text-[#666666] flex-shrink-0">轮次：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{ financing.round || '-' }}</span>

                      <!-- 投资方 -->
                      <span class="text-base text-[#666666] flex-shrink-0">投资方：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{ financing.investorName || '-'
                      }}</span>

                      <!-- 披露时间 -->
                      <span class="text-base text-[#666666] flex-shrink-0">披露时间：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{ formatDate(financing.pubTime)
                      }}</span>

                      <!-- 融资金额 -->
                      <span class="text-base text-[#666666] flex-shrink-0">融资金额：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{ financing.money || '-' }}</span>

                      <!-- 企业估值 -->
                      <template v-if="financing.value">
                        <span class="text-base text-[#666666] flex-shrink-0">估值：</span>
                        <span class="text-base font-medium text-[#333333] break-words">{{ financing.value }}</span>
                      </template>

                      <!-- 股权 -->
                      <template v-if="financing.share">
                        <span class="text-base text-[#666666] flex-shrink-0">股权：</span>
                        <span class="text-base font-medium text-[#333333] break-words">{{ financing.share }}</span>
                      </template>

                      <!-- 新闻标题 -->
                      <template v-if="financing.newsTitle">
                        <span class="text-base text-[#666666] flex-shrink-0">新闻标题：</span>
                        <span class="text-base font-medium text-[#333333] break-words">{{ financing.newsTitle }}</span>
                      </template>

                      <!-- 新闻链接 -->
                      <template v-if="financing.newsUrl">
                        <span class="text-base text-[#666666] flex-shrink-0">新闻链接：</span>
                        <a :href="financing.newsUrl" target="_blank" rel="noopener noreferrer"
                          class="text-base font-medium text-blue-500 hover:underline break-words">
                          查看原文
                        </a>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无融资历史时的空状态展示 -->
      <div v-else class="text-gray-500 py-10 text-center bg-gray-50 rounded-lg mx-4 mb-4">
        <div class="text-gray-300 text-3xl mb-2">📈</div>
        暂无融资历史记录
      </div>
    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="融资历史展示申请人相关企业的融资情况，包括融资轮次、融资金额、投资机构和融资时间等信息。数据来源于公开的融资信息和投资机构披露。融资历史可以反映企业的成长轨迹、资金实力和市场认可度。一般而言，有多轮融资经历的企业风险相对较低。建议关注融资阶段、投资机构的知名度和融资间隔时间。" />
</template>

<script setup>
import { ref, computed } from 'vue'
import LTitle from '@/components/LTitle.vue'
import LRemark from '@/components/LRemark.vue'
import { useRiskNotifier } from '@/composables/useRiskNotifier'

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => ({ items: [], total: 0 }),
  },
  apiId: {
    type: String,
    default: '',
  },
  index: {
    type: Number,
    default: 0,
  },
  notifyRiskStatus: {
    type: Function,
    default: () => { },
  },
})

const financingHistory = computed(() => props.data?.items || [])

// 按融资企业分组
const groupedFinancing = computed(() => {
  const groups = {}

  financingHistory.value.forEach(financing => {
    const companyName = financing.companyName || '未知企业'

    if (!groups[companyName]) {
      groups[companyName] = {
        companyName,
        financings: [],
        totalFinancings: 0
      }
    }

    groups[companyName].financings.push(financing)
    groups[companyName].totalFinancings++
  })

  return Object.values(groups)
})

// 用于跟踪展开的企业卡片
const expandedFinancing = ref({})

// 切换展开/收起企业详情
const toggleFinancingExpand = (companyId, listType, index) => {
  const uniqueKey = `${companyId}_${listType}_${index}`
  expandedFinancing.value[uniqueKey] = !expandedFinancing.value[uniqueKey]
}

// 检查企业是否展开
const isFinancingExpanded = (companyId, listType, index) => {
  const uniqueKey = `${companyId}_${listType}_${index}`
  return !!expandedFinancing.value[uniqueKey]
}

// 格式化日期显示 (处理时间戳和日期字符串)
const formatDate = (dateInput) => {
  if (!dateInput) return '—'
  // 如果是时间戳（毫秒），转换为日期字符串
  if (typeof dateInput === 'number' && dateInput > 1000000000000) {
    return new Date(dateInput).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
  }
  // 如果已经是日期字符串，直接返回
  return dateInput
}

// 计算风险评分（0-100分，分数越高越安全）
const riskScore = computed(() => {
  const history = financingHistory.value || [];

  // 没有融资历史 -> 无风险 -> 100分
  if (history.length === 0) {
    return 100;
  }

  // 有融资历史 -> 低风险 -> 90分
  return 90;
});

// 使用 composable 通知父组件风险评分
useRiskNotifier(props, riskScore);

// 暴露给父组件
defineExpose({
  riskScore
});
</script>

<style lang="scss" scoped></style>