<template>
  <div class="loan-evaluation-section card">
    <div class="p-2 relative">
      <div class="flex items-center justify-between mb-3 border  border-[#DDDDDD] rounded-lg p-4 bg-[#F9F9F9]">
        <div class="flex items-center ">
          <div class="w-8 h-8 flex items-center justify-center mr-2">
            <img src="@/assets/images/report/jdpggl.png" alt="借贷评估概览" class="w-8 h-8 object-contain" />
          </div>
          <span class="font-bold text-gray-800">借贷评估概览</span>
        </div>
        <div class="font-bold" :class="getRiskFlagTagClass(loanEvaluationVerificationDetail.riskFlag)">
          {{ getRiskFlagText(loanEvaluationVerificationDetail.riskFlag) }}
        </div>
      </div>

      <!-- 机构借贷表现 -->
      <div v-if="loanEvaluationVerificationDetail.organLoanPerformances"
        class="border  border-[#DDDDDD] mb-4 rounded-lg">
        <div class="flex items-center p-4">
          <div class="w-8 h-8 flex items-center justify-center mr-2">
            <img src="@/assets/images/report/yzgz.png" alt="借贷评估概览" class="w-8 h-8 object-contain" />
          </div>
          <span class="font-bold text-gray-800">机构借贷表现</span>
        </div>

        <div class="space-y-4 py-2">
          <div v-for="(item, index) in loanEvaluationVerificationDetail.organLoanPerformances" :key="index"
            class="performance-item">
            <div class="flex items-center">
              <LTitle :title="item.applyCount" />
              <span
                class="ml-2 px-2 bg-[#61D2F41A] border border-[#61D2F44D] text-[#61D2F4] rounded-md text-sm font-medium">
                {{ item.applyCount === '银行' ? '银行机构' : '非银机构' }}
              </span>
            </div>
            <div class="loan-evaluation-wrap">
              <!-- 标签页 -->
              <div class="mb-3">
                <van-tabs v-model:active="activePeriods[`organ-${index}`]" line-width="20" line-height="2"
                  color="var(--color-primary)" :key="`organ-${index}`" class="loan-evaluation-tabs">
                  <van-tab v-for="period in timePeriods" :key="period.key" :name="period.key" :title="period.label" />
                </van-tabs>
              </div>

              <!-- 内容显示 -->
              <div class="loan-evaluation-content">
                <div class="flex items-center justify-between">
                  <div class="text-2xl font-bold text-gray-800">
                    {{ getPeriodValue(item, activePeriods[`organ-${index}`] || 'last7Day') }}
                  </div>
                  <div class="text-sm text-gray-400">申请次数</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 客户类型借贷表现 -->
      <div v-if="loanEvaluationVerificationDetail.customerLoanPerformances"
        class="border border-[#DDDDDD] mb-4 rounded-lg">
        <div class="flex items-center p-4">
          <div class="w-8 h-8 flex items-center justify-center mr-2">
            <img src="@/assets/images/report/khlxjdbx.png" alt="客户类型借贷表现" class="w-8 h-8 object-contain" />
          </div>
          <span class="font-bold text-gray-800">客户类型借贷表现</span>
        </div>

        <div class="space-y-4 py-2">
          <div v-for="(item, index) in loanEvaluationVerificationDetail.customerLoanPerformances" :key="index"
            class="performance-item">
            <div class="flex items-center">
              <LTitle :title="item.type" />
              <span
                class="ml-2 px-2 bg-[#61D2F41A] border border-[#61D2F44D] text-[#61D2F4] rounded-md text-sm font-medium">
                {{ getCustomerTypeText(item.type) }}
              </span>
            </div>
            <!-- 机构数 -->
            <div class="text-[#333333] pl-4 font-bold mt-3">机构数</div>
            <div class="loan-evaluation-wrap">
              <div class="mb-3">
                <van-tabs v-model:active="activeCustomerPeriods[`customer-${index}`]" line-width="20" line-height="2"
                  color="var(--color-primary)" :key="`customer-${index}`" class="loan-evaluation-tabs">
                  <van-tab v-for="period in timePeriods" :key="period.key" :name="period.key" :title="period.label" />
                </van-tabs>
              </div>
              <div class="loan-evaluation-content">
                <div class="flex items-center justify-between">
                  <div class="text-2xl font-bold text-gray-800">
                    {{ getCustomerPeriodValue(item, activeCustomerPeriods[`customer-${index}`] || 'last7Day',
                      'institution') }}
                  </div>
                  <div class="text-sm text-gray-400">机构个数</div>
                </div>
              </div>
            </div>

            <!-- 次数 -->
            <div class="text-[#333333] pl-4 font-bold mt-3">次数</div>
            <div class="loan-evaluation-wrap">
              <div class="mb-3">
                <van-tabs v-model:active="activeCustomerCountPeriods[`count-${index}`]" line-width="20" line-height="2"
                  color="var(--color-primary)" :key="`count-${index}`" class="loan-evaluation-tabs">
                  <van-tab v-for="period in timePeriods" :key="period.key" :name="period.key" :title="period.label" />
                </van-tabs>
              </div>
              <div class="loan-evaluation-content">
                <div class="flex items-center justify-between">
                  <div class="text-2xl font-bold text-gray-800">
                    {{ getCustomerPeriodValue(item, activeCustomerCountPeriods[`count-${index}`] || 'last7Day', 'count')
                    }}
                  </div>
                  <div class="text-sm text-gray-400">申请次数</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 业务类型借贷表现 -->
      <div v-if="loanEvaluationVerificationDetail.businessLoanPerformances"
        class="border border-[#DDDDDD] mb-4 rounded-lg">
        <div class="flex items-center p-4">
          <div class="w-8 h-8 flex items-center justify-center mr-2">
            <img src="@/assets/images/report/ywlxjdbx.png" alt="业务类型借贷表现" class="w-8 h-8 object-contain" />
          </div>
          <span class="font-bold text-gray-800">业务类型借贷表现</span>
        </div>

        <div class="space-y-4 py-2">
          <div v-for="(item, index) in loanEvaluationVerificationDetail.businessLoanPerformances" :key="index"
            class="performance-item">
            <div class="flex items-center">
              <LTitle :title="item.type" />
              <span
                class="ml-2 px-2 bg-[#61D2F41A] border border-[#61D2F44D] text-[#61D2F4] rounded-md text-sm font-medium">
                业务类型
              </span>
            </div>
            <!-- 机构数 -->
            <div class="text-[#333333] pl-4 font-bold mt-3">机构数</div>
            <div class="loan-evaluation-wrap">
              <div class="mb-3">
                <van-tabs v-model:active="activeBusinessPeriods[`business-${index}`]" line-width="20" line-height="2"
                  color="var(--color-primary)" :key="`business-${index}`" class="loan-evaluation-tabs">
                  <van-tab v-for="period in timePeriods" :key="period.key" :name="period.key" :title="period.label" />
                </van-tabs>
              </div>
              <div class="loan-evaluation-content">
                <div class="flex items-center justify-between">
                  <div class="text-2xl font-bold text-gray-800">
                    {{ getBusinessPeriodValue(item, activeBusinessPeriods[`business-${index}`] || 'last7Day',
                      'institution') }}
                  </div>
                  <div class="text-sm text-gray-400">机构个数</div>
                </div>
              </div>
            </div>

            <!-- 次数 -->
            <div class="text-[#333333] pl-4 font-bold mt-3">次数</div>
            <div class="loan-evaluation-wrap">
              <div class="mb-3">
                <van-tabs v-model:active="activeBusinessCountPeriods[`business-count-${index}`]" line-width="20"
                  line-height="2" color="var(--color-primary)" :key="`business-count-${index}`"
                  class="loan-evaluation-tabs">
                  <van-tab v-for="period in timePeriods" :key="period.key" :name="period.key" :title="period.label" />
                </van-tabs>
              </div>
              <div class="loan-evaluation-content">
                <div class="flex items-center justify-between">
                  <div class="text-2xl font-bold text-gray-800">
                    {{ getBusinessPeriodValue(item, activeBusinessCountPeriods[`business-count-${index}`] || 'last7Day',
                      'count') }}
                  </div>
                  <div class="text-sm text-gray-400">申请次数</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 异常时间段借贷表现 -->
      <div v-if="loanEvaluationVerificationDetail.timeLoanPerformances" class="border border-[#DDDDDD] mb-4 rounded-lg">
        <div class="flex items-center p-4">
          <div class="w-8 h-8 flex items-center justify-center mr-2">
            <img src="@/assets/images/report/ycsjdjdbx.png" alt="异常时间段借贷表现" class="w-8 h-8 object-contain" />
          </div>
          <span class="font-bold text-gray-800">异常时间段借贷表现</span>
        </div>

        <div class="space-y-4 py-2">
          <div v-for="(item, index) in loanEvaluationVerificationDetail.timeLoanPerformances" :key="index"
            class="performance-item">
            <div class="flex items-center">
              <LTitle :title="item.type" />
              <span
                class="ml-2 px-2 bg-[#61D2F41A] border border-[#61D2F44D] text-[#61D2F4] rounded-md text-sm font-medium">
                {{ getTimeTypeText(item.type) }}
              </span>
            </div>
            <!-- 机构数 -->
            <div class="text-[#333333] pl-4 font-bold mt-3">机构数</div>
            <div class="loan-evaluation-wrap">
              <div class="mb-3">
                <van-tabs v-model:active="activeTimePeriods[`time-${index}`]" line-width="20" line-height="2"
                  color="var(--color-primary)" :key="`time-${index}`" class="loan-evaluation-tabs">
                  <van-tab v-for="period in timePeriods" :key="period.key" :name="period.key" :title="period.label" />
                </van-tabs>
              </div>
              <div class="loan-evaluation-content">
                <div class="flex items-center justify-between">
                  <div class="text-2xl font-bold text-gray-800">
                    {{ getTimePeriodValue(item, activeTimePeriods[`time-${index}`] || 'last7Day', 'institution') }}
                  </div>
                  <div class="text-sm text-gray-400">机构个数</div>
                </div>
              </div>
            </div>

            <!-- 次数 -->
            <div class="text-[#333333] pl-4 font-bold mt-3">次数</div>
            <div class="loan-evaluation-wrap">
              <div class="mb-3">
                <van-tabs v-model:active="activeTimeCountPeriods[`time-count-${index}`]" line-width="20" line-height="2"
                  color="var(--color-primary)" :key="`time-count-${index}`" class="loan-evaluation-tabs">
                  <van-tab v-for="period in timePeriods" :key="period.key" :name="period.key" :title="period.label" />
                </van-tabs>
              </div>
              <div class="loan-evaluation-content">
                <div class="flex items-center justify-between">
                  <div class="text-2xl font-bold text-gray-800">
                    {{ getTimePeriodValue(item, activeTimeCountPeriods[`time-count-${index}`] || 'last7Day', 'count') }}
                  </div>
                  <div class="text-sm text-gray-400">申请次数</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- 温馨提示 -->
  <LRemark
    content="借贷评估提供多维度的借贷风险分析，包括机构借贷表现、客户类型借贷表现、业务类型借贷表现和异常时间段借贷表现。数据格式为'X/Y'，其中X表示身份证匹配到的数据，Y表示手机号匹配到的数据。数据来源于银行和非银行金融机构，统计不同时间段的申请机构数和申请次数。夜间和周末申请通常风险较高，建议重点关注短期内频繁申请的行为模式。评估结果仅供参考，具体风险判断需结合其他因素综合考虑。" />
</template>

<script setup>
import LTitle from '@/components/LTitle.vue'
import LRemark from '@/components/LRemark.vue'
import { ref } from '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 { loanEvaluationVerificationDetail = {} } = props.data
// 标签页状态 - 为每个标签组创建独立的状态管理
const activePeriods = ref({})
const activeCustomerPeriods = ref({})
const activeCustomerCountPeriods = ref({})
const activeBusinessPeriods = ref({})
const activeBusinessCountPeriods = ref({})
const activeTimePeriods = ref({})
const activeTimeCountPeriods = ref({})


// 时间段配置
const timePeriods = [
  { key: 'last7Day', label: '近7天' },
  { key: 'last15Day', label: '近15天' },
  { key: 'last1Month', label: '近1个月' },
  { key: 'last3Month', label: '近3个月' },
  { key: 'last6Month', label: '近6个月' },
  { key: 'last12Month', label: '近12个月' }
]

// 获取风险标识文本
const getRiskFlagText = (flag) => {
  if (flag === 1) return '高风险'
  if (flag === 2) return '低风险'
  return '未查得'
}

// 获取风险标识样式
const getRiskFlagClass = (flag) => {
  if (flag === 1) return 'text-red-600'
  if (flag === 2) return 'text-green-600'
  return 'text-gray-600'
}

// 获取风险标识标签颜色
const getRiskFlagTagClass = (flag) => {
  if (flag === 1) return 'text-[#EB3C3C]'
  if (flag === 2) return 'text-[#4CAF50]'
  return 'text-gray-500'
}

// 获取时间段数值
const getPeriodValue = (item, period) => {
  const value = item[period] || '0/0'
  return value
}

// 获取客户类型时间段数值
const getCustomerPeriodValue = (item, period, type) => {
  const key = type === 'institution' ? period : period + 'Count'
  const value = item[key] || '0/0'
  return value
}

// 获取业务类型时间段数值
const getBusinessPeriodValue = (item, period, type) => {
  const key = type === 'institution' ? period : period + 'Count'
  const value = item[key] || '0/0'
  return value
}

// 获取异常时间段数值
const getTimePeriodValue = (item, period, type) => {
  const key = type === 'institution' ? period : period + 'Count'
  const value = item[key] || '0/0'
  return value
}

// 获取客户类型文本
const getCustomerTypeText = (type) => {
  const typeMap = {
    '银行汇总': '银行类',
    '传统银行': '传统银行',
    '网络零售银行': '网络银行',
    '非银汇总': '非银类',
    '持牌网络小贷': '网络小贷',
    '持牌消费金融': '消费金融',
    '持牌融资租赁机构': '融资租赁',
    '持牌汽车金融': '汽车金融'
  }
  return typeMap[type] || type
}

// 获取客户类型样式
const getCustomerTypeClass = (type) => {
  if (type.includes('银行')) return 'bg-[#61D2F41A] border border-[#61D2F44D] text-[#61D2F4]'
  if (type.includes('非银')) return 'bg-[#FF95001A] border border-[#FF95004D] text-[#FF9500]'
  return 'bg-gray-100 text-gray-700'
}

// 获取时间段类型文本
const getTimeTypeText = (type) => {
  if (type.includes('夜间')) return '夜间申请'
  if (type.includes('周末')) return '周末申请'
  return type
}

// 获取时间段类型样式
const getTimeTypeClass = (type) => {
  if (type.includes('夜间')) return 'bg-[#EB3C3C1A] border border-[#EB3C3C4D] text-[#EB3C3C]'
  if (type.includes('周末')) return 'bg-[#FFC1071A] border border-[#FFC1074D] text-[#FFC107]'
  return 'bg-gray-100 text-gray-700'
}

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

  // 没有数据 -> 无风险 -> 100分
  if (Object.keys(detail).length === 0) {
    return 100;
  }

  // 风险标识为高风险 -> 高风险 -> 30分
  if (detail.riskFlag === 1) {
    return 30;
  }
  // 风险标识为低风险 -> 低风险 -> 90分
  if (detail.riskFlag === 2) {
    return 90;
  }

  // 根据借贷表现计算风险分数
  let riskPoints = 0;
  let totalPoints = 0;

  // 机构借贷表现
  if (detail.organLoanPerformances && detail.organLoanPerformances.length > 0) {
    detail.organLoanPerformances.forEach(item => {
      // 检查近7天申请次数
      const last7Day = item.last7Day || '0/0';
      const [idCardCount, phoneCount] = last7Day.split('/').map(v => parseInt(v) || 0);
      const count = Math.max(idCardCount, phoneCount);

      if (count >= 10) {
        riskPoints += 3; // 高风险
      } else if (count >= 5) {
        riskPoints += 2; // 中风险
      } else if (count > 0) {
        riskPoints += 1; // 低风险
      }
      totalPoints += 3;
    });
  }

  // 客户类型借贷表现
  if (detail.customerLoanPerformances && detail.customerLoanPerformances.length > 0) {
    detail.customerLoanPerformances.forEach(item => {
      const last7DayCount = item.last7DayCount || '0/0';
      const [idCardCount, phoneCount] = last7DayCount.split('/').map(v => parseInt(v) || 0);
      const count = Math.max(idCardCount, phoneCount);

      if (count >= 10) {
        riskPoints += 2;
      } else if (count >= 5) {
        riskPoints += 1;
      }
      totalPoints += 2;
    });
  }

  // 异常时间段借贷表现（夜间和周末申请）
  if (detail.timeLoanPerformances && detail.timeLoanPerformances.length > 0) {
    detail.timeLoanPerformances.forEach(item => {
      const last7DayCount = item.last7DayCount || '0/0';
      const [idCardCount, phoneCount] = last7DayCount.split('/').map(v => parseInt(v) || 0);
      const count = Math.max(idCardCount, phoneCount);

      if (count >= 5) {
        riskPoints += 3; // 夜间/周末申请风险更高
      } else if (count > 0) {
        riskPoints += 2;
      }
      totalPoints += 3;
    });
  }

  // 计算最终分数
  if (totalPoints === 0) {
    return 90; // 没有借贷数据，默认低风险
  }

  const riskRatio = riskPoints / totalPoints;
  // 风险比例越高，分数越低
  return Math.max(30, 100 - Math.round(riskRatio * 70));
});

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

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

<style lang="scss" scoped>
.loan-evaluation-section {
  @apply space-y-4;
}

.loan-evaluation-tabs {}

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

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

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

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

}

.loan-evaluation-tabs :deep(.van-tabs__line) {
  height: 2px !important;
  border-radius: 1px !important;
}

/* 内容区域样式 */
.loan-evaluation-wrap {
  @apply mx-4 my-1;
  border: 1px solid #DDDDDD;
  background-color: #F9F9F9;
  border-radius: 8px;
}

.loan-evaluation-content {
  @apply m-4;
  padding: 8px 16px;
}
</style>
