<template>
  <div class="card shadow-sm rounded-xl overflow-hidden p-4">
    <div class="border border-[#EEEEEE] rounded-xl">
      <!-- 标题 -->
      <div class="flex items-center mb-3 p-4">
        <div class="w-8 h-8 flex items-center justify-center mr-2">
          <img src="@/assets/images/report/ssfxfx.png" alt="涉诉风险整体" class="w-8 h-8 object-contain" />
        </div>
        <span class="font-bold text-gray-800">涉诉风险分析</span>
      </div>
      <LTitle title="涉诉风险整体概览" />
      <!-- 全局风险概览面板 -->
      <StatisticsOverview class="" v-if="totalCases > 0 && lawsuitStats" :stats="lawsuitStats"
        :total-cases="totalCases" />

      <!-- 案件类型筛选tab -->
      <div v-if="totalCases > 0" class="p-4">
        <van-tabs v-model:active="activeCaseTypeFilter" line-width="30px" swipeable class="lawsuit-tabs">
          <!-- 全部风险 -->
          <van-tab name="all">
            <template #title>
              <div class="flex items-center gap-1">
                <span>全部风险</span>
                <span>({{ caseTypeCounts.all }})</span>
              </div>
            </template>
          </van-tab>

          <!-- 各类型案件 - 使用v-for渲染 -->
          <van-tab v-for="(typeInfo, type) in lawsuitTypeMap" :key="type" :name="type">
            <template #title>
              <div class="flex items-center gap-1">
                <span>{{ typeInfo.text }}({{ caseTypeCounts[type] || 0 }})</span>
              </div>
            </template>
            <div v-if="filteredCases.length === 0" class="p-8 text-center text-gray-500">
              <div class="flex flex-col items-center justify-center">
                <van-empty :description="`暂无${typeInfo.text}记录`" />
              </div>
            </div>
          </van-tab>
        </van-tabs>
      </div>

      <!-- 案件列表 -->
      <div v-if="filteredCases.length > 0" class="space-y-3 px-4 mb-4">
        <div v-for="(caseItem, index) in filteredCases" :key="index" class="case-wrapper">
          <!-- 案件卡片 - 可点击展开 -->
          <div class="bg-white rounded-xl overflow-hidden border px-4 pt-3 border-[#DDDDDD]">
            <div class="cursor-pointer relative" @click="toggleCaseExpand(caseItem.id || index, 'case', index)">
              <!-- 顶部区域：案件标题和案件类型 -->
              <div class=" flex items-center">
                <!-- 案件标题 -->
                <div class="font-bold text-base text-[#333333] mr-2">{{ caseItem.c_ah || caseItem.ah || '暂无案号' }}</div>

                <!-- 案件类型标签 -->
                <span class="px-2 py-1 text-xs rounded-md font-medium bg-[#F9ECEC] text-[#EB3C3C]">
                  {{ getCaseTypeText(caseItem.type) }}
                </span>
              </div>

              <!-- 中间区域：立案时间 -->
              <div class="pb-2">
                <span class="text-sm text-[#666666]">立案：</span>
                <span class="text-sm text-[#333333]">{{ formatDate(caseItem.d_larq || caseItem.larq) }}</span>
              </div>

              <!-- 底部区域：风险等级和案件状态 -->
              <div class="flex items-center gap-2">
                <!-- 风险等级标签 -->
                <span class="px-2 py-1 text-xs rounded-md font-medium"
                  :class="getCaseTypeRiskLevel(caseItem.type).color">
                  {{ getCaseTypeRiskLevel(caseItem.type).text }}
                </span>
                <!-- 案件状态标签 -->
                <span v-if="caseItem.n_ajjzjd" class="px-2 py-1 text-xs rounded-md font-medium"
                  :class="getCaseStatusClass(caseItem.n_ajjzjd)">
                  {{ caseItem.n_ajjzjd }}
                </span>
              </div>

              <!-- 展开指示器 -->
              <div class="absolute right-4 bottom-3 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': isCaseExpanded(caseItem.id || index, 'case', index) }" />
              </div>
            </div>

            <!-- 案件详情抽屉 -->
            <div class="mt-4 overflow-hidden transition-all duration-300 ease-in-out" :class="{
              'max-h-0 opacity-0': !isCaseExpanded(caseItem.id || index, 'case', index),
              'max-h-none opacity-100': isCaseExpanded(caseItem.id || index, 'case', index),
            }">
              <div class="mt-1 transform transition-all duration-300">
                <div class="relative">
                  <CaseDetail :case-data="caseItem" :type-color="getCaseTypeColor(caseItem.type)"
                    :case-type="caseItem.type" />
                </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, onMounted, watch } from 'vue'
import LTitle from '@/components/LTitle.vue'
import LRemark from '@/components/LRemark.vue'
import StatisticsOverview from './components/StatisticsOverview.vue'
import CaseDetail from './components/CaseDetail.vue'
import { useRiskNotifier } from '@/composables/useRiskNotifier'
import {
  lawsuitTypeMap,
  getCaseTypeText,
  getCaseTypeColor,
  getRiskLevel,
  getCaseStatusClass,
  formatDate,
  getLawsuitStats,
  getCaseTypeRiskLevel,
} from './utils/lawsuitUtils.js'

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

// 正确解构props.data中的字段并处理默认值
const { entout: PropEntout = {}, sxbzxr: PropSxbzxr = {}, xgbzxr: PropXgbzxr = {} } = props.data || {}

// 安全获取entout数据(带响应式)
const entout = ref(
  PropEntout.data || {
    administrative: {},
    bankrupt: {},
    cases_tree: { criminal: [], civil: [] },
    civil: {},
    count: {},
    criminal: { cases: [], count: {} },
    implement: {},
    preservation: {},
  }
)

// 获取其他字段(按需添加响应式)
const sx = ref(PropSxbzxr.data?.sxbzxr || [])
const xg = ref(PropXgbzxr.data?.xgbzxr || [])

// 用于跟踪展开的案件卡片
const expandedCases = ref({})

// 切换展开/收起案件详情
const toggleCaseExpand = (caseId, listType, index) => {
  const uniqueKey = `${caseId}_${listType}_${index}`
  expandedCases.value[uniqueKey] = !expandedCases.value[uniqueKey]
}

// 检查案件是否展开
const isCaseExpanded = (caseId, listType, index) => {
  const uniqueKey = `${caseId}_${listType}_${index}`
  return !!expandedCases.value[uniqueKey]
}

// 当前选中的案件类型筛选
const activeCaseTypeFilter = ref('all')

// 计算所有案件数据
const allCases = computed(() => {
  const cases = []

  // 添加失信被执行人案件
  sx.value.forEach((item, index) => {
    cases.push({
      ...item,
      type: 'sxbzxr',
      id: `sxbzxr_${index}`,
      // 映射字段以保持兼容性
      c_ah: item.ah,
      d_larq: item.larq,
      n_ajjzjd: item.lxqk === '全部未履行' ? '未结案' : '已结案',
    })
  })

  // 添加限高被执行人案件
  xg.value.forEach((item, index) => {
    cases.push({
      ...item,
      type: 'xgbzxr',
      id: `xgbzxr_${index}`,
      // 映射字段以保持兼容性
      c_ah: item.ah,
      d_larq: item.fbrq,
      n_ajjzjd: '未结案', // 限高案件通常为未结案
    })
  })

  // 添加其他类型案件
  if (entout.value) {
    // 处理民事案件
    if (entout.value.civil && entout.value.civil.cases) {
      entout.value.civil.cases.forEach((item, index) => {
        cases.push({
          ...item,
          type: 'civil',
          id: `civil_${index}`,
        })
      })
    }

    // 处理刑事案件
    if (entout.value.criminal && entout.value.criminal.cases) {
      entout.value.criminal.cases.forEach((item, index) => {
        cases.push({
          ...item,
          type: 'criminal',
          id: `criminal_${index}`,
        })
      })
    }

    // 处理执行案件
    if (entout.value.implement && entout.value.implement.cases) {
      entout.value.implement.cases.forEach((item, index) => {
        cases.push({
          ...item,
          type: 'implement',
          id: `implement_${index}`,
        })
      })
    }

    // 处理行政案件
    if (entout.value.administrative && entout.value.administrative.cases) {
      entout.value.administrative.cases.forEach((item, index) => {
        cases.push({
          ...item,
          type: 'administrative',
          id: `administrative_${index}`,
        })
      })
    }

    // 处理破产案件
    if (entout.value.bankrupt && entout.value.bankrupt.cases) {
      entout.value.bankrupt.cases.forEach((item, index) => {
        cases.push({
          ...item,
          type: 'bankrupt',
          id: `bankrupt_${index}`,
        })
      })
    }

    // 处理保全案件
    if (entout.value.preservation && entout.value.preservation.cases) {
      entout.value.preservation.cases.forEach((item, index) => {
        cases.push({
          ...item,
          type: 'preservation',
          id: `preservation_${index}`,
        })
      })
    }
  }

  return cases
})

// 计算总案件数
const totalCases = computed(() => allCases.value.length)

// 计算涉诉风险统计
const lawsuitStats = computed(() => {
  if (totalCases.value === 0) return null

  const stats = {
    totalRiskItems: totalCases.value,
    highRiskItems: 0,
    mediumRiskItems: 0,
    lowRiskItems: 0,
    sxbzxrCount: sx.value.length,
    xgbzxrCount: xg.value.length,
    closedCases: 0,
    caseTypes: [],
  }

  // 统计各类型案件数量
  const typeCounts = {}
  Object.keys(lawsuitTypeMap).forEach(type => {
    typeCounts[type] = 0
  })

  allCases.value.forEach(caseItem => {
    // 根据案件类型统计风险等级
    const riskLevel = getCaseTypeRiskLevel(caseItem.type).level
    if (riskLevel === 'high') {
      stats.highRiskItems++
    } else if (riskLevel === 'medium') {
      stats.mediumRiskItems++
    } else {
      stats.lowRiskItems++
    }

    // 统计已结案件
    if (caseItem.n_ajjzjd && caseItem.n_ajjzjd.includes('已结')) {
      stats.closedCases++
    }

    // 统计案件类型
    if (caseItem.type) {
      typeCounts[caseItem.type] = (typeCounts[caseItem.type] || 0) + 1
    }
  })

  // 转换为数组格式
  stats.caseTypes = Object.keys(typeCounts)
    .filter(type => typeCounts[type] > 0)
    .map(type => ({
      type,
      count: typeCounts[type],
      name: getCaseTypeText(type),
      color: getCaseTypeColor(type),
    }))
    .sort((a, b) => b.count - a.count)

  return stats
})

// 按案件类型筛选案件
const filteredCases = computed(() => {
  if (activeCaseTypeFilter.value === 'all') {
    return allCases.value
  }

  return allCases.value.filter(caseItem => caseItem.type === activeCaseTypeFilter.value)
})

// 获取每种案件类型的数量
const caseTypeCounts = computed(() => {
  const counts = {
    all: totalCases.value,
  }

  // 初始化所有案件类型的计数
  Object.keys(lawsuitTypeMap).forEach(type => {
    counts[type] = 0
  })

  // 计算每种类型的案件数量
  allCases.value.forEach(caseItem => {
    if (caseItem.type) {
      counts[caseItem.type]++
    }
  })

  return counts
})

// 设置当前筛选类型
const setCaseTypeFilter = type => {
  activeCaseTypeFilter.value = type
}

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

  // 根据涉诉案件数量计算评分
  // 0件：100分（最安全）
  // 1-2件：70分（中等风险）
  // 3-5件：50分（较高风险）
  // 6-10件：30分（高风险）
  // 10件以上：10分（极高风险）
  if (cases === 0) return 100;
  if (cases <= 2) return 70;
  if (cases <= 5) return 50;
  if (cases <= 10) return 30;
  return 10;
});

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

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

<style lang="scss" scoped>
.case-wrapper {
  @apply relative;
}

.lawsuit-tabs :deep(.van-tabs__wrap) {
  height: 32px !important;
  background-color: transparent !important;
  padding: 0 !important;
  border-bottom: 1px solid #DDDDDD !important;
}

.lawsuit-tabs :deep(.van-tabs__nav) {
  background-color: transparent !important;
  gap: 0;
  height: 32px !important;
}

.lawsuit-tabs :deep(.van-tab) {
  color: #999999 !important;
  font-size: 14px !important;
  font-weight: 400 !important;
}

.lawsuit-tabs :deep(.van-tab--active) {
  color: var(--van-theme-primary) !important;
  background-color: unset !important;
}

.lawsuit-tabs :deep(.van-tabs__line) {
  height: 3px !important;
  border-radius: 1px !important;
}
</style>
