<template>
  <div class="card shadow-sm rounded-xl overflow-hidden">
    <div v-if="investCompanies.length > 0" class="space-y-3">
      <div v-for="(company, index) in investCompanies" :key="index"
        class="company-wrapper bg-[#F9F9F9] rounded-lg overflow-hidden shadow-sm border border-[#EEEEEE] ">
        <!-- 企业卡片 - 可点击展开 -->
        <div class="cursor-pointer relative" @click="toggleCompanyExpand(company.orgName, 'invest', index)">
          <!-- 企业名称 - 蓝色渐变背景 -->
          <div class="px-4 py-2 flex items-center border border-[#0000000A]">
            <div class="font-medium text-[#333333] truncate">{{ company.orgName }}</div>
          </div>

          <!-- 关系标签 - 靠左排列无背景 -->
          <div class="px-4 py-1.5 flex items-center">
            <div class="flex flex-wrap gap-1">
              <span v-for="(relation, idx) in company.relationship" :key="idx" class="px-1.5 py-0.5 text-xs rounded"
                :class="getRelationshipClass(relation)">
                {{ getRelationshipText(relation) }}
              </span>
            </div>
          </div>

          <!-- 企业状态、注册资本、注册时间 -->
          <div
            class="px-4 py-2 flex flex-col sm:flex-row sm:justify-between sm:items-center gap-2 text-xs text-gray-500">
            <div class="flex items-center gap-3">
              <span v-if="company.basicInfo && company.basicInfo.regStatus"
                class="px-1.5 py-0.5 rounded-full inline-block" :class="getStatusClass(company.basicInfo.regStatus)">
                {{ company.basicInfo.regStatus }}
              </span>
              <span v-if="company.basicInfo && company.basicInfo.regCapital">
                {{ formatCapital(company.basicInfo.regCapital, company.basicInfo.regCapitalCurrency) }}
              </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': isCompanyExpanded(company.orgName, 'invest', index) }" />
          </div>
        </div>
        <!-- 企业详情抽屉 - 投资企业记录 -->
        <div class="mt-4 overflow-hidden transition-all duration-300 ease-in-out" :class="{
          'max-h-0 opacity-0': !isCompanyExpanded(company.orgName, 'invest', index),
          'max-h-none opacity-100': isCompanyExpanded(company.orgName, 'invest', index),
        }">
          <div class="mt-1 transform transition-all duration-300">
            <div class="relative">
              <!-- 持股信息 - 如果有的话 -->
              <div v-if="company.stockHolderItem && Object.keys(company.stockHolderItem).length > 0"
                class="mb-6 relative">
                <LTitle title="持股信息" />

                <div class="grid grid-cols-[max-content_1fr] gap-x-2 gap-y-3 p-4">
                  <span class="text-base text-[#666666]">股东名称：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.stockHolderItem.orgHolderName || '-'
                  }}</span>

                  <span class="text-base text-[#666666]">股东类型：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.stockHolderItem.orgHolderType || '-'
                  }}</span>

                  <span class="text-base text-[#666666]">出资金额：</span>
                  <span class="text-base font-medium text-[#333333]">{{
                    formatSubscriptAmt(company.stockHolderItem.subscriptAmt) }}</span>

                  <span class="text-base text-[#666666]">持股比例：</span>
                  <div class="flex items-center gap-2">
                    <span class="text-base font-medium text-[#333333]">{{ formatRate(company.stockHolderItem.investRate)
                    }}</span>
                    <span v-if="parseFloat(company.stockHolderItem.investRate) > 0"
                      class="text-sm px-2 py-0.5 rounded bg-primary-light text-primary">
                      {{ getInvestRateDesc(company.stockHolderItem.investRate) }}
                    </span>
                  </div>

                  <span class="text-base text-[#666666]">出资时间：</span>
                  <span class="text-base font-medium text-[#333333]">{{ formatDate(company.stockHolderItem.investDate)
                  }}</span>
                </div>

              </div>

              <!-- 基本信息 -->
              <div v-if="company.basicInfo" class="mb-6 relative">
                <LTitle title="基本信息" />

                <div class="grid grid-cols-[max-content_1fr] gap-x-2 gap-y-3 p-4">
                  <span class="text-base text-[#666666]">企业状态：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.basicInfo.regStatus || '-' }}</span>

                  <span class="text-base text-[#666666]">统一社会信用代码：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.basicInfo.creditCode || '-' }}</span>

                  <span class="text-base text-[#666666]">注册号：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.basicInfo.regNumber || '-' }}</span>

                  <span class="text-base text-[#666666]">企业类型：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.basicInfo.entType || '-' }}</span>

                  <span class="text-base text-[#666666]">行业：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.basicInfo.industry || '-' }}</span>

                  <span class="text-base text-[#666666]">注册资本：</span>
                  <span class="text-base font-medium text-[#333333]">{{ formatCapital(company.basicInfo.regCapital,
                    company.basicInfo.regCapitalCurrency) }}</span>

                  <span class="text-base text-[#666666]">成立日期：</span>
                  <span class="text-base font-medium text-[#333333]">{{ formatDate(company.basicInfo.estiblishTime)
                  }}</span>

                  <span class="text-base text-[#666666]">登记机关：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.basicInfo.regInstitute || '-' }}</span>

                  <span class="text-base text-[#666666]">核准日期：</span>
                  <span class="text-base font-medium text-[#333333]">{{ formatDate(company.basicInfo.approvedTime)
                  }}</span>
                </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>

  <!-- 温馨提示 -->
  <LRemark
    content="投资企业记录展示申请人相关企业的对外投资情况，包括投资企业名称、投资金额、投资比例和投资时间等。数据来源于工商登记信息和公开披露信息。投资组合可以反映企业的投资策略、风险偏好和资金实力。高度集中的投资或跨行业投资可能存在特定风险。建议关注投资集中度、投资表现和目标企业的经营状况。" />
</template>

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

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

const investCompanies = computed(() => props.data || [])

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

// 切换展开/收起企业详情
const toggleCompanyExpand = (companyId, listType, index) => {
  // 创建唯一标识符，包含企业名称、列表类型和索引
  const uniqueKey = `${companyId}_${listType}_${index}`
  expandedCompanies.value[uniqueKey] = !expandedCompanies.value[uniqueKey]
}

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

// 获取关系文本
const getRelationshipText = relation => {
  return relationshipMap[relation]?.text || relation
}

// 获取关系样式类
const getRelationshipClass = relation => {
  return relationshipMap[relation]?.color || ''
}


// 关系映射表
const relationshipMap = {
  sh: { text: '股东', color: 'bg-primary-light text-primary', icon: '👑' },
  his_sh: { text: '曾任股东', color: 'bg-primary-light text-primary', icon: '🕒👑' },
  lp: { text: '法人', color: 'bg-green-100 text-green-700', icon: '⚖️' },
  his_lp: { text: '曾任法人', color: 'bg-green-50 text-green-600', icon: '🕒⚖️' },
  tm: { text: '高管', color: 'bg-purple-100 text-purple-700', icon: '👔' },
  his_tm: { text: '曾任高管', color: 'bg-purple-50 text-purple-600', icon: '🕒👔' },
}

// 获取企业状态对应的样式
const getStatusClass = status => {
  if (!status) return 'bg-gray-100 text-gray-500'

  if (status.includes('注销') || status.includes('吊销')) {
    return 'bg-red-50 text-red-600'
  } else if (status.includes('存续') || status.includes('在营')) {
    return 'bg-[#2B79EE1A] text-[#2B79EE]'
  } else if (status.includes('筹建') || status.includes('新设')) {
    return 'bg-green-50 text-green-600'
  } else {
    return 'bg-yellow-50 text-yellow-600'
  }
}

// 格式化日期显示
const formatDate = dateStr => {
  if (!dateStr) return '-'
  return dateStr
}

// 格式化资本金额显示
const formatCapital = (capital, currency) => {
  if (!capital) return '-'

  // 检查是否包含"万"字或需要显示为万元
  let unit = ''
  let value = parseFloat(capital)

  // 处理原始数据中可能带有的单位
  if (typeof capital === 'string' && capital.includes('万')) {
    unit = '万'
    // 提取数字部分
    const numMatch = capital.match(/[\d.]+/)
    value = numMatch ? parseFloat(numMatch[0]) : 0
  } else if (value >= 10000) {
    // 大额数字转换为万元显示
    value = value / 10000
    unit = '万'
  }

  // 格式化数字，保留两位小数（如果有小数部分）
  const formattedValue = value.toLocaleString('zh-CN', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  })

  return `${formattedValue}${unit} ${currency || '人民币'}`
}

// 格式化占比
const formatRate = rate => {
  if (!rate) return '-'
  // 移除末尾不必要的0和小数点
  const formatted = parseFloat(rate)
    .toFixed(2)
    .replace(/\.?0+$/, '')
  return `${formatted}%`
}

// 格式化出资金额（特别处理，统一使用万元单位）
const formatSubscriptAmt = amount => {
  if (!amount) return '-'

  let value = parseFloat(amount)

  // 处理原始数据中可能带有的单位
  if (typeof amount === 'string') {
    // 提取数字部分
    const numMatch = amount.match(/[\d.]+/)
    value = numMatch ? parseFloat(numMatch[0]) : 0
  }

  // 如果数值大于等于10000，则转换为万元
  if (value >= 10000) {
    value = value / 10000
  }

  // 格式化数字，保留两位小数（如果有小数部分）
  const formattedValue = value.toLocaleString('zh-CN', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  })

  return `${formattedValue} 万元`
}

// 获取持股比例对应的颜色样式
const getInvestRateClass = rate => {
  if (!rate) return 'bg-gray-200'

  const value = parseFloat(rate)
  if (value >= 50) return 'bg-blue-500' // 控股或全资
  if (value >= 20) return 'bg-blue-400' // 重要股东
  if (value >= 10) return 'bg-blue-300' // 主要股东
  return 'bg-blue-200' // 一般股东
}

// 获取持股比例的描述
const getInvestRateDesc = rate => {
  if (!rate) return ''

  const value = parseFloat(rate)
  if (value >= 50) return '控股股东'
  if (value >= 20) return '重要股东'
  if (value >= 10) return '主要股东'
  if (value > 0) return '一般股东'
  return ''
}

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

  // 没有投资企业 -> 无风险 -> 100分
  if (companies.length === 0) {
    return 100;
  }

  // 有投资企业 -> 低风险 -> 90分
  return 90;
});

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

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

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