<template>
  <div class="bg-white rounded-xl shadow-sm p-6">
    <LTitle title="法院风险信息" type="red" />

    <div class="mt-4">
      <!-- 法院风险概览 -->
      <div class="bg-gradient-to-r from-[#F9ECEC] to-[#FCE8E8] rounded-lg p-4 mb-4">
        <h3 class="text-lg font-semibold text-[#333333] mb-3 flex items-center">
          <span class="w-2 h-2 bg-[#EB3C3C] rounded-full mr-2"></span>
          法院风险概览
        </h3>
        <div class="grid grid-cols-2 gap-4">
          <div class="text-center">
            <div class="text-2xl font-bold" :class="courtRiskInfos?.length > 0 ? 'text-[#EB3C3C]' : 'text-green-600'">
              {{ courtRiskInfos?.length || 0 }}
            </div>
            <div class="text-sm text-[#666666]">法院案件数</div>
          </div>
          <div class="text-center">
            <div class="text-2xl font-bold" :class="courtRiskInfos?.length > 0 ? 'text-[#EB3C3C]' : 'text-green-600'">
              {{ courtRiskInfos?.length > 0 ? '有风险' : '无风险' }}
            </div>
            <div class="text-sm text-[#666666]">风险状态</div>
          </div>
        </div>
      </div>

      <!-- 案件类型统计 -->
      <div v-if="courtRiskInfos && courtRiskInfos.length > 0" class="mb-4">
        <div class="bg-white rounded-xl border border-[#DDDDDD] p-4">
          <div class="flex items-center justify-between mb-3">
            <div class="flex items-center">
              <div class="w-8 h-8 flex items-center justify-center mr-2">
                <img src="@/assets/images/report/ajlxfb.png" alt="案件类型分布" class="w-8 h-8 object-contain" />
              </div>
              <span class="font-bold text-[#333333]">案件类型分布</span>
            </div>
          </div>

          <!-- 案件类型统计 -->
          <div class="grid grid-cols-3 md:grid-cols-6 gap-2">
            <div v-for="(typeInfo, type) in caseTypeStats" :key="type" class="text-center p-2 rounded-lg border"
              :class="typeInfo.count > 0 ? 'bg-[#F9ECEC] border border-[#F0CACA]' : 'bg-[#ECF9EF] border border-[#CAECD3]'">
              <div class="flex justify-center mb-1">
                <img :src="getCaseTypeIconPath(type)" alt="" class="w-8 h-8 object-contain" />
              </div>
              <div class="text-base font-bold" :class="typeInfo.count > 0 ? 'text-[#EB3C3C]' : 'text-green-600'">
                {{ typeInfo.count }}
              </div>
              <div class="text-xs text-[#666666] leading-tight">{{ getCaseTypeShortName(type) }}</div>
              <div class="text-xs mt-0.5" :class="typeInfo.count > 0 ? 'text-[#EB3C3C]' : 'text-green-600'">
                {{ typeInfo.count > 0 ? '有风险' : '无风险' }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 法院案件详情 -->
      <div v-if="courtRiskInfos && courtRiskInfos.length > 0" class="space-y-4">
        <!-- 按案件类型分组显示 -->
        <div v-for="(cases, caseType) in groupedCases" :key="caseType" class="case-section">
          <div class="bg-white rounded-xl border border-[#DDDDDD] p-4">
            <div class="flex items-center mb-3">
              <div class="w-8 h-8 flex items-center justify-center mr-2">
                <img :src="getCaseTypeIconPath(caseType)" alt="" class="w-8 h-8 object-contain" />
              </div>
              <span class="font-bold text-[#333333]">{{ getCaseTypeName(caseType) }}</span>
              <span class="ml-2 px-2 py-1 rounded-full text-xs font-medium" :class="getCaseTypeBadgeStyle(caseType)">
                {{ cases.length }}件
              </span>
            </div>

            <van-collapse v-model="activeCases[caseType]" accordion>
              <van-collapse-item v-for="(caseItem, index) in cases" :key="`${caseType}-${index}`"
                :name="`${caseType}-${index}`" :class="getCaseItemClass(caseItem)">
                <template #title>
                  <div class="case-header">
                    <div class="case-number">{{ caseItem.caseNumber || '案号未知' }}</div>
                    <div class="case-status" :class="getCaseStatusClass(caseItem.caseStatus)">
                      {{ caseItem.caseStatus || '状态未知' }}
                    </div>
                  </div>
                </template>
                <div class="case-details-content">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div class="detail-item">
                      <span class="label">案件类型：</span>
                      <span class="value">{{ caseItem.caseType || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">审理法院：</span>
                      <span class="value">{{ caseItem.court || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">诉讼地位：</span>
                      <span class="value">{{ caseItem.litigantType || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">立案时间：</span>
                      <span class="value">{{ caseItem.filingTime || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">结案时间：</span>
                      <span class="value">{{ caseItem.disposalTime || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">案件状态：</span>
                      <span class="value" :class="getCaseStatusTextClass(caseItem.caseStatus)">
                        {{ caseItem.caseStatus || '-' }}
                      </span>
                    </div>
                    <div class="detail-item" v-if="caseItem.executionAmount">
                      <span class="label">执行金额：</span>
                      <span class="value text-[#EB3C3C] font-bold">{{ caseItem.executionAmount }}</span>
                    </div>
                    <div class="detail-item" v-if="caseItem.repaidAmount">
                      <span class="label">已还款金额：</span>
                      <span class="value text-green-600 font-bold">{{ caseItem.repaidAmount }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">案由：</span>
                      <span class="value">{{ caseItem.caseReason || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">结案方式：</span>
                      <span class="value">{{ caseItem.disposalMethod || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">判决结果：</span>
                      <span class="value">{{ caseItem.judgmentResult || '-' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">案件分类：</span>
                      <span class="value">{{ caseItem.type || '-' }}</span>
                    </div>
                  </div>

                  <!-- 匹配度信息 -->
                  <div v-if="caseItem.matchScore" class="mt-3 p-3 bg-[#EBF5FF] rounded-lg">
                    <div class="flex items-center justify-between">
                      <span class="text-sm text-[#666666]">身份匹配度</span>
                      <span class="text-sm font-bold text-[#2B79EE]">
                        {{ (caseItem.matchScore * 100).toFixed(1) }}%
                      </span>
                    </div>
                    <div class="mt-2 w-full bg-gray-200 rounded-full h-2">
                      <div class="h-2 rounded-full transition-all duration-500"
                        :class="getMatchScoreBarStyle(caseItem.matchScore)"
                        :style="{ width: (caseItem.matchScore * 100) + '%' }"></div>
                    </div>
                  </div>

                  <!-- 内容摘要 -->
                  <div v-if="caseItem.contentSummary" class="mt-3">
                    <div class="text-sm text-[#666666] mb-2">案件摘要：</div>
                    <div class="bg-gray-50 rounded-lg p-3 border">
                      <p class="text-sm text-gray-700 leading-relaxed">
                        {{ formatContentSummary(caseItem.contentSummary) }}
                      </p>
                    </div>
                  </div>

                  <!-- 执行公告ID -->
                  <div v-if="caseItem.executionAnnouncementId" class="mt-3">
                    <div class="text-sm text-[#666666] mb-1">公告编号：</div>
                    <div class="bg-gray-100 rounded p-2">
                      <span class="text-xs font-mono text-gray-700">
                        {{ caseItem.executionAnnouncementId }}
                      </span>
                    </div>
                  </div>
                </div>
              </van-collapse-item>
            </van-collapse>
          </div>
        </div>
      </div>

      <!-- 高风险警告 -->
      <div v-if="hasHighRiskCases" class="mt-4 p-4 bg-[#F9ECEC] border border-[#F0CACA] rounded-lg">
        <div class="flex items-start">
          <div class="mr-3 mt-1 flex-shrink-0">
            <img src="@/assets/images/report/gfx.png" alt="高风险" class="w-10 h-10 object-contain" />
          </div>
          <div>
            <h4 class="font-semibold text-[#EB3C3C] mb-2">法院风险警告</h4>
            <p class="text-[#666666] text-sm">
              检测到法院相关案件记录，存在司法风险，建议立即停止相关业务并进行详细核实。
            </p>
            <div class="mt-2">
              <span class="text-[#666666] font-medium">涉及案件类型：</span>
              <span class="text-[#EB3C3C]">{{ getCaseTypesList.join('、') }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 无风险提示 -->
      <div v-if="!courtRiskInfos || courtRiskInfos.length === 0"
        class="mt-4 p-4 bg-[#ECF9EF] border border-[#CAECD3] rounded-lg">
        <div class="flex items-start">
          <div class="mr-3 mt-1">
            <img src="@/assets/images/report/zq.png" alt="正常" class="w-8 h-8 object-contain" />
          </div>
          <div>
            <h4 class="font-semibold text-green-600 mb-2">法院风险核验通过</h4>
            <p class="text-green-600 text-sm">
              未检测到法院相关案件记录，司法风险较低。
            </p>
          </div>
        </div>
      </div>

      <!-- 案件类型说明 -->
      <div class="mt-4 p-4 bg-gray-50 border border-[#DDDDDD] rounded-lg">
        <h4 class="font-semibold text-[#333333] mb-2">案件类型说明</h4>
        <div class="text-sm text-[#666666] space-y-1">
          <div><strong>民事案件：</strong>涉及财产、合同等民事纠纷</div>
          <div><strong>刑事案件：</strong>涉及刑法规定的犯罪行为</div>
          <div><strong>行政案件：</strong>涉及行政管理相关纠纷</div>
          <div><strong>执行案件：</strong>强制执行相关案件</div>
          <div><strong>非诉保全审查案件：</strong>财产保全等非诉讼案件</div>
          <div><strong>强制清算与破产案件：</strong>企业清算破产相关案件</div>
        </div>
      </div>
    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="法院风险信息展示申请人的司法风险情况，包括民事案件、执行案件、失信记录和限高消费等。数据来源于全国法院执行信息公开网等权威司法数据库。失信和限高记录对个人信用影响极大，会限制高消费和金融服务。执行案件可能涉及财产冻结和强制执行。建议对有司法风险记录的申请进行重点审查。" />
</template>

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

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

// 从data中解构出需要的字段
const courtRiskInfos = computed(() => {
  return props.data?.judiciaRiskInfos || []
})

// 折叠面板状态
const activeCases = ref({})

// 是否有高风险案件
const hasHighRiskCases = computed(() => {
  return courtRiskInfos.value && courtRiskInfos.value.length > 0
})

// 获取案件类型列表
const getCaseTypesList = computed(() => {
  if (!courtRiskInfos.value) return []

  const types = [...new Set(courtRiskInfos.value.map(item => inferCaseType(item)))]
  return types.filter(type => type !== '未知类型')
})

// 根据案件信息推断真实案件类型
const inferCaseType = (caseItem) => {
  // 如果type字段已经是标准的6种类型之一，直接使用
  const standardTypes = ['民事案件', '刑事案件', '行政案件', '执行案件', '非诉保全审查案件', '强制清算与破产案件']
  if (standardTypes.includes(caseItem.type)) {
    return caseItem.type
  }

  // 根据caseType字段推断案件类型
  const caseType = caseItem.caseType || ''
  if (caseType.includes('刑事')) {
    return '刑事案件'
  } else if (caseType.includes('民事')) {
    return '民事案件'
  } else if (caseType.includes('行政')) {
    return '行政案件'
  } else if (caseType.includes('执行') || caseItem.type === '执行公告') {
    return '执行案件'
  } else if (caseType.includes('破产') || caseType.includes('清算')) {
    return '强制清算与破产案件'
  } else if (caseType.includes('保全') || caseItem.type === '非诉保全审查案件') {
    return '非诉保全审查案件'
  }

  // 根据原始type字段的值进行映射
  if (caseItem.type === '涉案公告' && caseType.includes('刑事')) {
    return '刑事案件'
  }

  // 默认返回民事案件
  return '民事案件'
}

// 按案件类型分组
const groupedCases = computed(() => {
  if (!courtRiskInfos.value) return {}

  const grouped = {}
  courtRiskInfos.value.forEach(caseItem => {
    const type = inferCaseType(caseItem)
    if (!grouped[type]) {
      grouped[type] = []
    }
    grouped[type].push(caseItem)
  })

  return grouped
})

// 案件类型统计
const caseTypeStats = computed(() => {
  const stats = {}
  const allTypes = ['民事案件', '刑事案件', '行政案件', '执行案件', '非诉保全审查案件', '强制清算与破产案件']

  // 初始化所有类型
  allTypes.forEach(type => {
    stats[type] = { count: 0 }
  })

  // 统计实际案件
  if (courtRiskInfos.value) {
    courtRiskInfos.value.forEach(caseItem => {
      const type = inferCaseType(caseItem)
      if (stats[type]) {
        stats[type].count++
      } else {
        stats[type] = { count: 1 }
      }
    })
  }

  return stats
})

// 获取案件类型图标路径
const getCaseTypeIconPath = (type) => {
  const iconMap = {
    '民事案件': () => new URL('@/assets/images/report/ms.png', import.meta.url).href,
    '刑事案件': () => new URL('@/assets/images/report/xs.png', import.meta.url).href,
    '行政案件': () => new URL('@/assets/images/report/xz.png', import.meta.url).href,
    '执行案件': () => new URL('@/assets/images/report/zxaj.png', import.meta.url).href,
    '非诉保全审查案件': () => new URL('@/assets/images/report/fsbq.png', import.meta.url).href,
    '强制清算与破产案件': () => new URL('@/assets/images/report/qspc.png', import.meta.url).href,
    'default': () => new URL('@/assets/images/report/zxaj.png', import.meta.url).href
  }
  const getIcon = iconMap[type] || iconMap.default
  return getIcon()
}

// 获取案件类型名称
const getCaseTypeName = (type) => {
  const nameMap = {
    '民事案件': '民事案件',
    '刑事案件': '刑事案件',
    '行政案件': '行政案件',
    '执行案件': '执行案件',
    '非诉保全审查案件': '非诉保全审查案件',
    '强制清算与破产案件': '强制清算与破产案件'
  }
  return nameMap[type] || '未知类型'
}

// 获取案件类型简短名称（用于紧凑显示）
const getCaseTypeShortName = (type) => {
  const shortNameMap = {
    '民事案件': '民事',
    '刑事案件': '刑事',
    '行政案件': '行政',
    '执行案件': '执行',
    '非诉保全审查案件': '非诉保全',
    '强制清算与破产案件': '清算破产'
  }
  return shortNameMap[type] || '未知'
}

// 获取案件类型头部样式
const getCaseTypeHeaderStyle = (caseType) => {
  const styleMap = {
    '民事案件': 'bg-[#2B79EE]',
    '刑事案件': 'bg-[#EB3C3C]',
    '行政案件': 'bg-[#2B79EE]',
    '执行案件': 'bg-[#D6943E]',
    '非诉保全审查案件': 'bg-green-500',
    '强制清算与破产案件': 'bg-[#666666]'
  }
  return styleMap[caseType] || 'bg-[#666666]'
}

// 获取案件类型标签样式
const getCaseTypeBadgeStyle = (caseType) => {
  const styleMap = {
    '民事案件': 'bg-[#2B79EE1A] text-[#2B79EE]',
    '刑事案件': 'bg-[#F9ECEC] text-[#EB3C3C]',
    '行政案件': 'bg-[#EBF5FF] text-[#2B79EE]',
    '执行案件': 'bg-[#FFF8E1] text-[#D6943E]',
    '非诉保全审查案件': 'bg-[#ECF9EF] text-green-600',
    '强制清算与破产案件': 'bg-gray-100 text-[#666666]'
  }
  return styleMap[caseType] || 'bg-gray-100 text-[#666666]'
}

// 获取案件项样式
const getCaseItemClass = (caseItem) => {
  if (caseItem.caseStatus === '已结案') return 'case-item-settled'
  if (caseItem.caseStatus === '执行中') return 'case-item-executing'
  if (caseItem.caseStatus === '审理中') return 'case-item-hearing'
  return 'case-item-default'
}

// 获取案件状态样式
const getCaseStatusClass = (status) => {
  if (status === '已结案') return 'text-green-600 bg-green-100'
  if (status === '执行中') return 'text-[#D6943E] bg-[#FFF8E1]'
  if (status === '未执行') return 'text-[#EB3C3C] bg-[#F9ECEC]'
  if (status === '审理中') return 'text-[#2B79EE] bg-[#EBF5FF]'
  if (status === '失信中') return 'text-[#EB3C3C] bg-[#F9ECEC]'
  if (status === '限高中') return 'text-[#2B79EE] bg-[#EBF5FF]'
  return 'text-[#666666] bg-gray-100'
}

// 获取案件状态文字样式
const getCaseStatusTextClass = (status) => {
  if (status === '已结案') return 'text-green-600'
  if (status === '执行中') return 'text-[#D6943E]'
  if (status === '未执行') return 'text-[#EB3C3C]'
  if (status === '审理中') return 'text-[#2B79EE]'
  if (status === '失信中') return 'text-[#EB3C3C]'
  if (status === '限高中') return 'text-[#2B79EE]'
  return 'text-[#666666]'
}

// 获取匹配度进度条样式
const getMatchScoreBarStyle = (score) => {
  if (score >= 0.9) return 'bg-green-500'
  if (score >= 0.8) return 'bg-[#2B79EE]'
  if (score >= 0.7) return 'bg-yellow-500'
  if (score >= 0.6) return 'bg-[#D6943E]'
  return 'bg-[#EB3C3C]'
}

// 格式化内容摘要
const formatContentSummary = (summary) => {
  if (!summary) return ''

  // 如果是JSON格式，尝试解析
  if (summary.startsWith('{') && summary.includes('id')) {
    try {
      const parsed = JSON.parse(summary)
      return parsed.content || parsed.summary || '详细信息请查看完整报告'
    } catch (e) {
      return summary.substring(0, 200) + (summary.length > 200 ? '...' : '')
    }
  }

  // 普通文本，限制长度
  return summary.length > 200 ? summary.substring(0, 200) + '...' : summary
}

// 获取默认展开的案件名称
const getDefaultActiveCase = (caseType) => {
  return `${caseType}-0` // 默认展开每种类型的第一个案件
}

// 初始化折叠面板状态
onMounted(() => {
  Object.keys(groupedCases.value).forEach(caseType => {
    if (groupedCases.value[caseType].length > 0) {
      activeCases.value[caseType] = getDefaultActiveCase(caseType)
    }
  })
})

// 监听数据变化
watch(() => props.data, (newData) => {
  if (newData?.judiciaRiskInfos) {
    Object.keys(groupedCases.value).forEach(caseType => {
      if (groupedCases.value[caseType].length > 0 && !activeCases.value[caseType]) {
        activeCases.value[caseType] = getDefaultActiveCase(caseType)
      }
    })
  }
}, { immediate: true, deep: true })
</script>

<style lang="scss" scoped>
.case-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .case-number {
    font-weight: 600;
    color: #333333;
    font-size: 14px;
  }

  .case-status {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
  }
}

.case-details-content {
  padding: 12px 0;

  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 4px 0;

    .label {
      color: #666666;
      font-size: 13px;
      font-weight: 500;
    }

    .value {
      color: #333333;
      font-size: 13px;
      font-weight: 400;
      text-align: right;
      flex: 1;
      margin-left: 8px;
    }
  }
}

// 案件项样式
:deep(.van-collapse-item) {
  margin-bottom: 8px;
  border-radius: 8px;
  overflow: hidden;

  &.case-item-settled {
    border: 1px solid #CAECD3;
      background-color: #FBFDFC;
    }
    
    &.case-item-executing {
      border: 1px solid #FFE082;
        background-color: #FFFDF9;
      }
      
      &.case-item-hearing {
        border: 1px solid #EBF5FF;
          background-color: #FAFDFF;
  }

  &.case-item-default {
    border: 1px solid #DDDDDD;
    background-color: #f9fafb;
  }
}

:deep(.van-collapse-item__title) {
  padding: 12px 16px;
  background-color: transparent;
}

:deep(.van-collapse-item__content) {
  padding: 0 16px 16px;
  background-color: transparent;
}

:deep(.van-collapse-item__wrapper) {
  border-radius: 8px;
}
</style>