<template>
  <div class="card shadow-sm rounded-xl overflow-hidden p-4">
    <div class="border border-[#EEEEEE] p-4 rounded-xl">
      <div class="flex items-center mb-3">
        <div class="w-8 h-8 flex items-center justify-center mr-2">
          <img src="@/assets/images/report/jyyc.png" alt="经营异常" class="w-8 h-8 object-contain" />
        </div>
        <span class="font-bold text-gray-800">经营异常</span>
      </div>

      <!-- 按异常企业分组显示 -->
      <div v-if="groupedAbnormal.length > 0" class="space-y-4">
        <div v-for="(group, groupIndex) in groupedAbnormal" :key="groupIndex" class="abnormal-group">
          <!-- 异常企业容器 -->
          <div class="bg-[#F5F5F5] rounded-lg p-3">
            <!-- 异常企业标题 -->
            <div class="mb-3">
              <div class="flex items-center border-b border-[#0000000A] pb-2">
                <div class="text-[#333333] font-medium">{{ group.companyName }}</div>
              </div>
              <div class="flex items-center justify-between pt-2">
                <span class="text-sm text-gray-600">异常企业</span>
                <span class="text-sm text-gray-600">异常记录: <span class="ml-1 font-medium text-[#333333]">{{
                  group.totalAbnormals }}</span></span>
              </div>
            </div>

            <!-- 异常记录列表 -->
            <div class="space-y-3">
              <div v-for="(abnormal, index) in group.abnormals" :key="index"
                class="abnormal-wrapper bg-white rounded-lg overflow-hidden shadow-sm border border-[#EEEEEE]">
                <!-- 异常卡片 - 可点击展开 -->
                <div class="cursor-pointer relative"
                  @click="toggleAbnormalExpand(abnormal.putReason, 'abnormal', index)">
                  <!-- 异常原因 -->
                  <div class="px-4 py-2">
                    <div class="font-medium text-[#333333]">{{ abnormal.putReason || '经营异常' }}</div>
                  </div>

                  <!-- 异常信息 -->
                  <div class="px-4">
                    <!-- 状态标签 -->
                    <div class="mb-2">
                      <span class="text-xs bg-[#1FBE5D1A] rounded py-1 px-2 text-[#1FBE5D]">
                        已移出
                      </span>
                      <span v-if="abnormal.removeDepartment"
                        class="text-xs bg-primary-light rounded py-1 px-2 text-primary ml-1">
                        {{ abnormal.removeDepartment }}
                      </span>
                    </div>

                    <!-- 列入部门 -->
                    <div class="text-sm text-gray-600 mb-2">
                      <span>{{ abnormal.putDepartment || '—' }}</span>
                    </div>

                    <!-- 列入和移出日期 -->
                    <div class="text-sm text-gray-600 mb-2 flex items-center gap-4">
                      <div>
                        <span class="text-gray-500">列入：</span>
                        <span>{{ formatDate(abnormal.putDate) }}</span>
                      </div>
                      <div v-if="abnormal.removeDate">
                        <span class="text-gray-500">移出：</span>
                        <span>{{ formatDate(abnormal.removeDate) }}</span>
                      </div>
                    </div>

                    <!-- 移出部门 -->
                    <div v-if="abnormal.removeDepartment" class="text-sm text-gray-600">
                      <span class="text-gray-500">移出部门：</span>
                      <span>{{ abnormal.removeDepartment }}</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': isAbnormalExpanded(abnormal.putReason, 'abnormal', index) }" />
                  </div>
                </div>

                <!-- 异常详情抽屉 -->
                <div class="mt-4 overflow-hidden transition-all duration-300 ease-in-out" :class="{
                  'max-h-0 opacity-0': !isAbnormalExpanded(abnormal.putReason, 'abnormal', index),
                  'max-h-none opacity-100': isAbnormalExpanded(abnormal.putReason, 'abnormal', index),
                }">
                  <div class="mt-1 transform transition-all duration-300">
                    <div class="grid grid-cols-[max-content_1fr] gap-y-3 p-4">
                      <!-- 异常状态 -->
                      <span class="text-base text-[#666666] flex-shrink-0">异常状态：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{
                        getStatusText(abnormal.removeDate) }}</span>

                      <!-- 列入原因 -->
                      <span class="text-base text-[#666666] flex-shrink-0">列入原因：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{ abnormal.putReason || '-'
                      }}</span>

                      <!-- 列入部门 -->
                      <span class="text-base text-[#666666] flex-shrink-0">列入部门：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{ abnormal.putDepartment || '-'
                      }}</span>

                      <!-- 列入日期 -->
                      <span class="text-base text-[#666666] flex-shrink-0">列入日期：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{ formatDate(abnormal.putDate)
                      }}</span>

                      <!-- 移出日期 -->
                      <template v-if="abnormal.removeDate">
                        <span class="text-base text-[#666666] flex-shrink-0">移出日期：</span>
                        <span class="text-base font-medium text-[#333333] break-words">{{
                          formatDate(abnormal.removeDate) }}</span>
                      </template>

                      <!-- 移出原因 -->
                      <template v-if="abnormal.removeReason">
                        <span class="text-base text-[#666666] flex-shrink-0">移出原因：</span>
                        <span class="text-base font-medium text-[#333333] break-words">{{ abnormal.removeReason
                        }}</span>
                      </template>

                      <!-- 移出部门 -->
                      <template v-if="abnormal.removeDepartment">
                        <span class="text-base text-[#666666] flex-shrink-0">移出部门：</span>
                        <span class="text-base font-medium text-[#333333] break-words">{{ abnormal.removeDepartment
                        }}</span>
                      </template>

                      <!-- 持续时长 -->
                      <span class="text-base text-[#666666] flex-shrink-0">持续时长：</span>
                      <span class="text-base font-medium text-[#333333] break-words">{{
                        calculateDuration(abnormal.putDate,
                          abnormal.removeDate) }} 天</span>
                    </div>
                  </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>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="经营异常展示申请人相关企业的经营异常情况，包括异常类型、异常原因、异常时间和移出情况等。数据来源于国家企业信用信息公示系统等权威渠道。异常状态分为异常中和已移出，已移出的异常风险相对较低。建议重点关注未移出的经营异常记录，特别是严重违法违规类型的异常。" />
</template>

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

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

const abnormalInfo = computed(() => props.data?.items || [])

// 按异常企业分组
const groupedAbnormal = computed(() => {
  const groups = {}

  abnormalInfo.value.forEach(abnormal => {
    const companyName = abnormal.companyName || '未知企业'

    if (!groups[companyName]) {
      groups[companyName] = {
        companyName,
        abnormals: [],
        totalAbnormals: 0
      }
    }

    groups[companyName].abnormals.push(abnormal)
    groups[companyName].totalAbnormals++
  })

  return Object.values(groups)
})

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

// 切换展开/收起企业详情
const toggleAbnormalExpand = (abnormalId, listType, index) => {
  const uniqueKey = `${abnormalId}_${listType}_${index}`
  expandedAbnormal.value[uniqueKey] = !expandedAbnormal.value[uniqueKey]
}

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

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

// 计算异常持续天数
const calculateDuration = (startDateStr, endDateStr) => {
  if (!startDateStr) return '—'
  const start = new Date(startDateStr)
  const end = endDateStr ? new Date(endDateStr) : new Date() // 如果没有结束日期，则计算到今天

  if (isNaN(start.getTime()) || isNaN(end.getTime())) return '—'

  const diffTime = Math.abs(end.getTime() - start.getTime())
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 获取状态文本
const getStatusText = (removeDate) => {
  if (removeDate) {
    return '已移出'
  } else {
    return '异常中'
  }
}

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

  // 没有经营异常 -> 无风险 -> 100分
  if (abnormalList.length === 0) {
    return 100;
  }

  // 有经营异常 -> 中风险 -> 60分
  return 60;
});

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

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

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