<template>
  <!-- 高管任职记录 -->
  <div class="card shadow-sm rounded-xl overflow-hidden">
    <div v-if="managerPositions.length > 0" class="space-y-3">
      <div v-for="(company, index) in managerPositions" :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, 'manager', 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, 'manager', 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, 'manager', index),
          'max-h-none opacity-100': isCompanyExpanded(company.orgName, 'manager', index),
        }">
          <div class="mt-1 transform transition-all duration-300">
            <div class="relative">
              <!-- 任职信息 -->
              <div v-if="company.relationship && company.relationship.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]">{{ getManagerPositionDesc(company.relationship)
                  }}</span>

                  <template v-if="company.staffList && company.staffList.result && company.staffList.result.length > 0">
                    <span class="text-base text-[#666666]">公司职位：</span>
                    <div class="flex flex-wrap gap-1">
                      <template v-for="(staff, staffIdx) in company.staffList.result" :key="staffIdx">
                        <template v-if="staff.typeJoin && staff.typeJoin.length > 0">
                          <span v-for="(position, posIdx) in staff.typeJoin" :key="posIdx"
                            class="text-sm px-2 py-0.5 rounded bg-primary-light text-primary">
                            {{ position }}
                          </span>
                        </template>
                      </template>
                    </div>
                  </template>
                </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 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.phone || '-' }}</span>

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

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

                  <span class="text-base text-[#666666]">注册地址：</span>
                  <span class="text-base font-medium text-[#333333]">{{ company.basicInfo.regAddress || '-' }}</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 LTitle from '@/components/LTitle.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 managerPositions = computed(() => {
  return props.data || []
})
onMounted(() => {
  setTimeout(() => {
  }, 1000)
})
// 用于跟踪展开的企业卡片
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 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 getRelationshipText = relation => {
  return relationshipMap[relation]?.text || relation
}

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

// 高管类关系
const managerRelations = ['tm', 'his_tm']

// 获取企业状态对应的样式
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 getManagerPositionDesc = relations => {
  if (!relations || relations.length === 0) return '-'

  const positions = []
  relations.forEach(relation => {
    if (managerRelations.includes(relation)) {
      positions.push(getRelationshipText(relation))
    }
  })

  return positions.length > 0 ? positions.join('、') : '-'
}

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

  // 没有高管任职记录 -> 无风险 -> 100分
  if (positions.length === 0) {
    return 100;
  }

  // 有高管任职记录 -> 低风险 -> 90分
  return 90;
});

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

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

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