<template>
  <div class="mb-8 card shadow-sm rounded-xl overflow-hidden">
    <LTitle title="投资企业记录" type="blue-green" class="mb-4" />
    <div v-if="investCompanies.length > 0" class="space-y-3">
      <div v-for="(company, index) in investCompanies" :key="index" class="company-wrapper">
        <!-- 企业卡片 - 可点击展开 -->
        <div
          class="bg-white rounded-lg overflow-hidden shadow-sm border border-gray-200 hover:border-blue-300 hover:shadow-md transition-all duration-300 cursor-pointer relative"
          :class="{
            'border-blue-400 shadow-md': isCompanyExpanded(company.orgName, 'invest', index),
          }"
          @click="toggleCompanyExpand(company.orgName, 'invest', index)"
        >
          <!-- 企业名称 - 蓝色渐变背景 -->
          <div class="bg-gradient-to-r from-blue-50 to-blue-100 px-4 py-2 flex items-center">
            <div class="font-medium text-gray-800 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-full"
                :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>
              <span v-if="company.basicInfo && company.basicInfo.estiblishTime">
                {{ formatDate(company.basicInfo.estiblishTime) }}
              </span>
            </div>
          </div>

          <!-- 展开指示器 - 放在右下角 -->
          <div
            class="absolute right-4 bottom-2 flex items-center text-xs text-gray-500 hover:text-blue-600 transition-colors duration-300"
            :class="{
              'text-blue-600': isCompanyExpanded(company.orgName, 'invest', index),
            }"
          >
            <span class="mr-1">{{
              isCompanyExpanded(company.orgName, 'invest', index) ? '收起详情' : '查看详情'
            }}</span>
            <div
              class="w-5 h-5 rounded-full bg-gray-100 flex items-center justify-center transition-transform duration-300"
              :class="{
                'bg-blue-100 text-blue-600 rotate-180': isCompanyExpanded(company.orgName, 'invest', index),
              }"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                class="h-3 w-3"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
              </svg>
            </div>
          </div>
        </div>

        <!-- 企业详情抽屉 - 投资企业记录 -->
        <div
          class="overflow-hidden transition-all duration-500 ease-in-out"
          :class="{
            'max-h-0 opacity-0': !isCompanyExpanded(company.orgName, 'invest', index),
            'max-h-[500px] opacity-100': isCompanyExpanded(company.orgName, 'invest', index),
          }"
        >
          <div
            class="mt-1 bg-gray-50 rounded-lg overflow-hidden p-4 pb-0 border border-gray-200 transform transition-all duration-300 max-h-[500px] overflow-y-auto"
          >
            <div class="relative">
              <!-- 持股信息 - 如果有的话 -->
              <div
                v-if="company.stockHolderItem && Object.keys(company.stockHolderItem).length > 0"
                class="mb-6 relative"
              >
                <div class="flex items-center mb-3 relative z-10">
                  <div class="w-7 h-7 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                    💼
                  </div>
                  <div class="text-base font-medium text-blue-700">持股信息</div>
                </div>
                <div class="pl-10">
                  <div class="bg-blue-50 p-4 rounded-lg border border-blue-100">
                    <div class="bg-white p-3 rounded-lg shadow-sm border border-blue-100">
                      <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div>
                          <div class="text-xs text-gray-500 mb-1">股东名称</div>
                          <div class="text-sm font-medium text-gray-800">
                            {{ company.stockHolderItem.orgHolderName || '—' }}
                          </div>
                        </div>
                        <div>
                          <div class="text-xs text-gray-500 mb-1">股东类型</div>
                          <div class="text-sm text-gray-800">
                            {{ company.stockHolderItem.orgHolderType || '—' }}
                          </div>
                        </div>
                        <div>
                          <div class="text-xs text-gray-500 mb-1">出资金额</div>
                          <div class="text-sm text-gray-800">
                            {{ formatSubscriptAmt(company.stockHolderItem.subscriptAmt) }}
                          </div>
                        </div>
                        <div>
                          <div class="text-xs text-gray-500 mb-1">持股比例</div>
                          <div class="flex flex-col">
                            <div class="flex items-center">
                              <span class="text-sm font-medium text-blue-700">{{
                                formatRate(company.stockHolderItem.investRate)
                              }}</span>
                              <span
                                v-if="parseFloat(company.stockHolderItem.investRate) > 0"
                                class="ml-2 text-xs px-1.5 py-0.5 rounded-full bg-blue-50 text-blue-600"
                              >
                                {{ getInvestRateDesc(company.stockHolderItem.investRate) }}
                              </span>
                            </div>
                            <div class="mt-1.5 w-full h-2 bg-gray-100 rounded-full overflow-hidden">
                              <div
                                class="h-full rounded-full"
                                :class="getInvestRateClass(company.stockHolderItem.investRate)"
                                :style="{
                                  width: `${Math.min(parseFloat(company.stockHolderItem.investRate) || 0, 100)}%`,
                                }"
                              ></div>
                            </div>
                          </div>
                        </div>
                        <div>
                          <div class="text-xs text-gray-500 mb-1">出资时间</div>
                          <div class="text-sm text-gray-800">
                            {{ formatDate(company.stockHolderItem.investDate) }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 垂直连接线 -->
              <div class="absolute left-0 top-8 bottom-0 w-0.5 bg-gray-200 ml-3"></div>

              <!-- 分组信息展示 -->
              <div v-if="company.basicInfo" class="space-y-6">
                <div v-for="(group, groupIdx) in groupCompanyInfo(company)" :key="groupIdx" class="relative">
                  <!-- 分组标题 -->
                  <div class="flex items-center mb-3 relative z-10">
                    <div class="w-7 h-7 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                      {{ group.icon }}
                    </div>
                    <div class="text-base font-medium text-gray-700">
                      {{ group.title }}
                    </div>
                  </div>

                  <!-- 分组内容 -->
                  <div class="pl-10 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <div
                      v-for="(field, fieldIdx) in group.fields"
                      :key="fieldIdx"
                      class="bg-white rounded-lg p-3 shadow-sm"
                    >
                      <div class="text-xs text-gray-500 mb-1">
                        {{ field.label }}
                      </div>
                      <div
                        v-if="field.type === 'status'"
                        class="text-sm px-2 py-0.5 rounded-full inline-block"
                        :class="getStatusClass(field.value)"
                      >
                        {{ field.value || '—' }}
                      </div>
                      <div v-else class="text-sm font-medium text-gray-800 flex items-center">
                        <span v-if="field.icon" class="mr-1">{{ field.icon }}</span>
                        {{ field.value || '—' }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 经营范围 -->
              <div v-if="company.basicInfo && company.basicInfo.opscope" class="mt-6 relative">
                <div class="flex items-center mb-3 relative z-10">
                  <div class="w-7 h-7 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                    📝
                  </div>
                  <div class="text-base font-medium text-gray-700">经营范围</div>
                </div>
                <div class="pl-10">
                  <div class="text-sm bg-white p-4 rounded-lg shadow-sm border border-gray-100 leading-relaxed">
                    {{ company.basicInfo.opscope }}
                  </div>
                </div>
              </div>

              <!-- 主要人员 -->
              <div
                v-if="company.staffList && company.staffList.result && company.staffList.result.length > 0"
                class="mt-6 relative"
              >
                <div class="flex items-center mb-3 relative z-10">
                  <div class="w-7 h-7 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                    👥
                  </div>
                  <div class="text-base font-medium text-gray-700">主要人员</div>
                </div>
                <div class="pl-10">
                  <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                    <div
                      v-for="(staff, staffIdx) in company.staffList.result"
                      :key="staffIdx"
                      class="flex items-center bg-white p-3 rounded-lg shadow-sm border border-gray-100 hover:border-blue-200 transition-all"
                    >
                      <div
                        class="w-10 h-10 rounded-full bg-gradient-to-r from-blue-500 to-purple-500 flex items-center justify-center text-white mr-3 text-sm font-medium"
                      >
                        {{ staff.name.substring(0, 1) }}
                      </div>
                      <div>
                        <div class="text-sm font-medium text-gray-800">
                          {{ staff.name }}
                        </div>
                        <div class="flex flex-wrap gap-1 mt-1">
                          <span
                            v-for="(position, posIdx) in staff.typeJoin || []"
                            :key="posIdx"
                            class="text-xs px-2 py-0.5 bg-blue-50 text-blue-600 rounded-full"
                          >
                            {{ position }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 底部收起按钮 -->
              <div class="flex justify-center sticky bottom-0 pt-2 pb-2 bg-gradient-to-t from-gray-50 to-transparent">
                <button
                  @click.stop="toggleCompanyExpand(company.orgName, 'invest', index)"
                  class="flex items-center px-4 py-2 rounded-full bg-blue-50 text-blue-600 hover:bg-blue-100 transition-colors duration-300"
                >
                  <span class="mr-1">收起详情</span>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="h-4 w-4 transform rotate-180"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                  </svg>
                </button>
              </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>
</template>

<script setup>
const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
})

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 groupCompanyInfo = company => {
  if (!company || !company.basicInfo) return []

  const basicInfo = company.basicInfo

  return [
    {
      title: '基本信息',
      icon: '🏢',
      fields: [
        { label: '企业状态', value: basicInfo.regStatus, type: 'status' },
        { label: '统一社会信用代码', value: basicInfo.creditCode },
        { label: '注册号', value: basicInfo.regNumber },
        { label: '企业类型', value: basicInfo.entType },
        { label: '行业', value: basicInfo.industry },
        {
          label: '注册资本',
          value: formatCapital(basicInfo.regCapital, basicInfo.regCapitalCurrency),
        },
        { label: '成立日期', value: formatDate(basicInfo.estiblishTime), icon: '📅' },
        { label: '登记机关', value: basicInfo.regInstitute },
        { label: '核准日期', value: formatDate(basicInfo.approvedTime) },
      ],
    },
    {
      title: '联系方式',
      icon: '📞',
      fields: [
        { label: '电话', value: basicInfo.phone },
        { label: '邮箱', value: basicInfo.email },
        { label: '网址', value: basicInfo.website },
        { label: '注册地址', value: basicInfo.regAddress },
      ],
    },
    {
      title: '法人信息',
      icon: '👨‍⚖️',
      fields: [
        { label: '法人名称', value: basicInfo.legalPersonName },
        { label: '法人类型', value: basicInfo.legalPersonType },
      ],
    },
  ]
}

// 关系映射表
const relationshipMap = {
  sh: { text: '股东', color: 'bg-blue-100 text-blue-700', icon: '👑' },
  his_sh: { text: '曾任股东', color: 'bg-blue-50 text-blue-600', 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-green-50 text-green-600'
  } else if (status.includes('筹建') || status.includes('新设')) {
    return 'bg-blue-50 text-blue-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 ''
}
</script>

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