<template>
  <div class="card">
    <div class="rounded-lg border border-gray-200 pb-2 mb-4">

      <div class="flex items-center mb-4 p-4">
        <div class="w-8 h-8 flex items-center justify-center mr-2">
          <img src="@/assets/images/report/sxxq.png" alt="授信详情" class="w-8 h-8 object-contain" />
        </div>
        <span class="font-bold text-gray-800">授信详情</span>
      </div>
      <div class="mt-4">
        <!-- 授信概览 -->
        <div class="mb-6">
          <LTitle title="授信概览" />
          <div class="grid grid-cols-1 gap-4 p-4">
            <div class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ hasAnyCredit ? '有授信记录' : '无授信记录' }}
              </div>
              <div class="text-sm text-gray-600 mt-1">授信状态</div>
            </div>
          </div>
        </div>

        <!-- 网络贷款类授信 -->
        <div v-if="hasOnlineLoanCredit" class="mb-6">
          <LTitle title="网络贷款类授信" />
          <div class="grid grid-cols-2 gap-4 p-4">
            <div v-if="creditDetail?.maxOnlineLoanCredit"
              class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ creditDetail.maxOnlineLoanCredit }}
              </div>
              <div class="text-sm text-gray-600 mt-1">最大授信额度</div>
            </div>
            <div v-if="creditDetail?.avgOnlineLoanCredit"
              class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ creditDetail.avgOnlineLoanCredit }}
              </div>
              <div class="text-sm text-gray-600 mt-1">平均授信额度</div>
            </div>
          </div>
        </div>

        <!-- 消费分期类授信 -->
        <div v-if="hasInstallmentCredit" class="mb-6">
          <LTitle title="消费分期类授信" />
          <div class="grid grid-cols-2 gap-4 p-4">
            <div v-if="creditDetail?.maxConsumptionInstallmentCredit"
              class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ creditDetail.maxConsumptionInstallmentCredit }}
              </div>
              <div class="text-sm text-gray-600 mt-1">最大授信额度</div>
            </div>
            <div v-if="creditDetail?.avgConsumptionInstallmentCredit"
              class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ creditDetail.avgConsumptionInstallmentCredit }}
              </div>
              <div class="text-sm text-gray-600 mt-1">平均授信额度</div>
            </div>
          </div>
        </div>

        <!-- 授信分析 -->
        <div v-if="hasAnyCredit" class="mb-6">
          <LTitle title="授信分析" />
          <div class="grid grid-cols-2 gap-4 p-4">
            <div class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ getMaxCreditLevel }}
              </div>
              <div class="text-sm text-gray-600 mt-1">最高授信等级</div>
            </div>
            <div class="bg-blue-50 rounded-lg p-4 text-center border border-[#2B79EE8F]">
              <div class="text-2xl font-bold text-[#1FBE5D]">
                {{ getCreditTypeCount }}
              </div>
              <div class="text-sm text-gray-600 mt-1">授信产品类型</div>
            </div>
          </div>
        </div>

        <!-- 授信风险提示 -->
        <div v-if="hasHighCredit" class="mb-6">
          <div class="space-y-3 p-4 bg-yellow-100 border border-yellow-300 rounded-lg">
            <div class="flex items-start">
              <div class="mr-3 mt-1">
                <img src="@/assets/images/report/zfx.png" alt="风险提示" class="w-10 h-10 object-contain" />
              </div>
              <div>
                <h4 class="font-semibold text-gray-800 mb-2">高额授信风险提示</h4>
                <p class="text-gray-400 text-sm">
                  检测到较高的授信额度，可能存在过度授信风险，需关注实际使用情况和还款能力。
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 无授信提示 -->
        <div v-if="!hasAnyCredit" class="mb-6 mx-4">
          <div class="space-y-3 p-4 bg-[#ECF9EF] border border-[#CAECD3] rounded-lg">
            <div class="flex items-center">
              <div class="mr-3">
                <img src="@/assets/images/report/zq.png" alt="良好记录" class="w-10 h-10 object-contain" />
              </div>
              <div>
                <h4 class="font-semibold text-gray-800">暂无授信记录</h4>
                <p class="text-gray-400 text-sm">
                  未检测到授信详情信息，可能是新用户或未使用相关金融产品。
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 授信额度说明 -->
        <div v-if="hasAnyCredit" class="mb-6">
          <LTitle title="授信额度说明" />
          <div class="space-y-2 p-4">
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">网络贷款类</span>
              <span class="text-[#333333] font-bold">包括各类线上信贷产品的授信额度</span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">消费分期类</span>
              <span class="text-[#333333] font-bold">包括各类消费分期产品的授信额度</span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">最大授信额度</span>
              <span class="text-[#333333] font-bold">该类产品中的最高授信额度</span>
            </div>
            <div class="flex justify-between items-center text-sm">
              <span class="text-gray-600">平均授信额度</span>
              <span class="text-[#333333] font-bold">该类产品的平均授信额度</span>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="授信详情展示申请人在各金融机构的授信情况，包括授信额度、已用额度、可用额度和授信类型等。数据来源于各金融机构的授信系统。授信使用率和授信集中度是评估信用风险的重要指标。高授信使用率可能暗示资金紧张，而多个机构的授信可能存在过度授信风险。建议关注授信结构和使用情况的合理性。" />
</template>

<script setup>
import { 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,
  },
  apiId: {
    type: String,
    default: '',
  },
  index: {
    type: Number,
    default: 0,
  },
  notifyRiskStatus: {
    type: Function,
    default: () => { },
  },
})

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

// 是否有网络贷款授信
const hasOnlineLoanCredit = computed(() => {
  return creditDetail.value?.maxOnlineLoanCredit || creditDetail.value?.avgOnlineLoanCredit
})

// 是否有消费分期授信
const hasInstallmentCredit = computed(() => {
  return creditDetail.value?.maxConsumptionInstallmentCredit || creditDetail.value?.avgConsumptionInstallmentCredit
})

// 是否有任何授信记录
const hasAnyCredit = computed(() => {
  return hasOnlineLoanCredit.value || hasInstallmentCredit.value
})

// 是否有高额授信
const hasHighCredit = computed(() => {
  // 简单判断，如果最大授信额度包含较大数字（如50000以上）
  const maxOnline = creditDetail.value?.maxOnlineLoanCredit || ''
  const maxInstallment = creditDetail.value?.maxConsumptionInstallmentCredit || ''

  // 检查是否包含5万以上的数字
  const hasHighOnline = maxOnline.includes('5万') || maxOnline.includes('10万') || maxOnline.includes('20万')
  const hasHighInstallment = maxInstallment.includes('5万') || maxInstallment.includes('10万') || maxInstallment.includes('20万')

  return hasHighOnline || hasHighInstallment
})

// 获取最高授信等级
const getMaxCreditLevel = computed(() => {
  if (!hasAnyCredit.value) return '-'

  const maxOnline = creditDetail.value?.maxOnlineLoanCredit || ''
  const maxInstallment = creditDetail.value?.maxConsumptionInstallmentCredit || ''

  // 简单的等级判断
  if (maxOnline.includes('20万') || maxInstallment.includes('20万')) return '很高'
  if (maxOnline.includes('10万') || maxInstallment.includes('10万')) return '高'
  if (maxOnline.includes('5万') || maxInstallment.includes('5万')) return '中等'
  if (maxOnline.includes('万') || maxInstallment.includes('万')) return '一般'

  return '较低'
})

// 获取授信产品类型数量
const getCreditTypeCount = computed(() => {
  let count = 0
  if (hasOnlineLoanCredit.value) count++
  if (hasInstallmentCredit.value) count++

  return count > 0 ? `${count} 类` : '0 类'
})

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

  // 没有授信记录 -> 100分（无借贷行为）
  if (!hasAnyCredit.value) {
    return 100;
  }

  // 计算风险分数
  let score = 100;

  // 解析最大授信额度
  const parseCreditAmount = (amountStr) => {
    if (!amountStr || amountStr === '-') return 0;

    // 提取数字
    const matches = amountStr.match(/(\d+(?:\.\d+)?)/g);
    if (!matches) return 0;

    return parseFloat(matches[0]);
  };

  const maxOnlineLoan = parseCreditAmount(detail.maxOnlineLoanCredit);
  const maxInstallment = parseCreditAmount(detail.maxConsumptionInstallmentCredit);
  const maxCredit = Math.max(maxOnlineLoan, maxInstallment);

  // 根据最大授信额度扣分
  if (maxCredit >= 20) {
    score -= 20; // 授信额度20万以上
  } else if (maxCredit >= 10) {
    score -= 15; // 授信额度10-20万
  } else if (maxCredit >= 5) {
    score -= 10; // 授信额度5-10万
  } else if (maxCredit > 0) {
    score -= 5; // 授信额度0-5万
  }

  // 授信产品类型数量
  let typeCount = 0;
  if (hasOnlineLoanCredit.value) typeCount++;
  if (hasInstallmentCredit.value) typeCount++;

  // 多种授信类型扣分
  if (typeCount >= 2) {
    score -= 5; // 多种授信类型
  }

  // 确保分数在合理范围内
  return Math.max(20, Math.min(100, score));
});

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

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

<style lang="scss" scoped>
.border-b:last-child {
  @apply border-b-0;
}
</style>
