<script setup>
import { ref, onMounted, watch } from 'vue';
import request from "@/utils/request.js";
import * as echarts from 'echarts';
import { ElMessage } from "element-plus";

const loanData = ref([]);
const year = ref('2024');
const month = ref(null);
const chartRef = ref(null);
const pieChartRef = ref(null);
const bankLoanChartRef = ref(null);
let chart = null;
let pieChart = null;
let bankLoanChart = null;
const companyNum = ref(0);
const totalLoanAmount = ref(0);
const bankLoanPercentageData = ref([]);

const fetchData = async () => {
  // if (!year.value || !month.value) {
  //   ElMessage.warning('请填写年份和月份');
  //   return;
  // }

  if (!year.value) {
    ElMessage.warning('请填写年份和月份');
    return;
  }

  try {
    const res = await request.get('/basicData/xcrSummaryLoanDetails/annual-statistics', {
      params: {
        year: year.value,
        month: month.value,
      }
    });
    console.log(res.data);
    loanData.value = res.data.companyLoanDetailList;
    companyNum.value = res.data.companyNum;
    totalLoanAmount.value = res.data.totalLoanAmount;
    bankLoanPercentageData.value = res.data.bankLoanPercentageDetailList;
    updateChart();
    updatePieChart();
    updateBankLoanChart();
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
  }
};

const updateChart = () => {
  if (!chart) {
    chart = echarts.init(chartRef.value);
  }

  const option = {
    title: {
      text: '企业贷款金额和已还本金分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['贷款金额(万元)', '已还本金(万元)'],
      top:30
    },
    yAxis: {  // 将 xAxis 改为 yAxis
      type: 'category',
      data: loanData.value.map(item => item.enterpriseName),
      axisLabel: {
        rotate: 20,
        interval: 0
      }
    },
    xAxis: {  // 将 yAxis 改为 xAxis
      type: 'value',
      name: '金额(万元)'
    },
    series: [
      {
        name: '贷款金额(万元)',
        type: 'bar',
        data: loanData.value.map(item => item.loanAmount),
        itemStyle: {
          color: '#3498db'
        }
      },
      {
        name: '已还本金(万元)',
        type: 'bar',
        data: loanData.value.map(item => item.repaidPrincipal),
        itemStyle: {
          color: '#2ecc71'
        }
      }
    ],
    dataZoom: [{ // 这是一个 dataZoom 组件，可以控制 x 轴或 y 轴的区域缩放
      type: 'inside', // 这里设置为 slider 类型，表示使用滑动条形式的 dataZoom 组件
      yAxisIndex: 0, // 表示这个 dataZoom 组件控制第一个 y 轴
      start: 100, // 数据窗口范围的起始百分比, 表示从10%的位置开始显示
      end: month.value ?50:95, // 数据窗口范围的结束百分比, 表示到60%的位置结束
      moveOnMouseWheel: true, // 启用滚轮滚动
      moveOnMouseMove: false,
      zoomOnMouseWheel: false,
    },{ // 这是一个 dataZoom 组件，可以控制 x 轴或 y 轴的区域缩放
      type: 'slider', // 这里设置为 slider 类型，表示使用滑动条形式的 dataZoom 组件
      yAxisIndex: 0, // 表示这个 dataZoom 组件控制第一个 y 轴
      start: 100, // 数据窗口范围的起始百分比, 表示从10%的位置开始显示
      end: month.value ?50:95, // 数据窗口范围的结束百分比, 表示到60%的位置结束
      moveOnMouseWheel: true, // 启用滚轮滚动
      moveOnMouseMove: false,
      zoomOnMouseWheel: false,
    }]
  };

  chart.setOption(option);
};

const updatePieChart = () => {
  if (!pieChart) {
    pieChart = echarts.init(pieChartRef.value);
  }

  const option = {
    title: {
      text: '贷款总额分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '贷款总额',
        type: 'pie',
        radius: '70%',
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: loanData.value.map(item => ({
          value: item.loanAmount,
          name: item.enterpriseName
        }))
      }
    ]
  };

  pieChart.setOption(option);
};

const updateBankLoanChart = () => {
  if (!bankLoanChart) {
    bankLoanChart = echarts.init(bankLoanChartRef.value);
  }

  const option = {
    title: {
      text: '银行贷款百分比分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}%'
    },
    series: [
      {
        name: '银行贷款百分比',
        type: 'pie',
        radius: '70%',
        data: bankLoanPercentageData.value.map(item => ({
          value: item.percentage,
          name: item.bankName
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  bankLoanChart.setOption(option);
};

onMounted(() => {
  fetchData();
});

watch([year, month], () => {
  if (year.value && month.value) {
    fetchData();
  }
});

// 确保在组件卸载时销毁图表实例
onUnmounted(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
  if (pieChart) {
    pieChart.dispose();
    pieChart = null;
  }
  if (bankLoanChart) {
    bankLoanChart.dispose();
    bankLoanChart = null;
  }
});
</script>

<template>
  <div class="container mx-auto p-4">
    <el-row>
      <el-col :span="4" :offset="10">
        <h1 class="text-2xl font-bold mb-4 text-center text-gray-800">贷款数据可视化</h1>
      </el-col>
      <el-col :span="8" :offset="2">

      </el-col>
    </el-row>

    <el-form :inline="true" @submit.prevent="fetchData" class="mb-4">
      <el-form-item label="年份" required>
        <el-input v-model="year" placeholder="年份" :rules="[{ required: true, message: '年份为必填项' }]"></el-input>
      </el-form-item>
      <el-form-item label="月份">
        <el-select clearable v-model="month" class="w-100px" placeholder="月份" :rules="[{ required: true, message: '月份为必填项' }]">
          <el-option v-for="m in 12" :key="m" :label="m" :value="m.toString()"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
<!--        <el-button type="primary" @click="fetchData" :disabled="!year || !month">搜索</el-button>-->
        <el-button type="primary" @click="fetchData" :disabled="!year">搜索</el-button>
      </el-form-item>
    </el-form>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>贷款企业数量</span>
          </div>
        </template>
        <div class="text-2xl font-bold">{{ companyNum }}</div>
      </el-card>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>贷款总额 (万元)</span>
          </div>
        </template>
        <div class="text-2xl font-bold">{{ totalLoanAmount }}</div>
      </el-card>
    </div>

    <!-- Loan Amount and Repaid Principal Chart -->
    <div ref="chartRef" style="width: 100%; height: 400px;" class="mb-4"></div>

    <div class="flex">
      <!-- Total Loan Amount Distribution Chart -->
      <div ref="pieChartRef" style="width: 100%; height: 400px;" class="mb-4"></div>

      <!-- Bank Loan Percentage Chart -->
      <div ref="bankLoanChartRef" style="width: 100%; height: 400px;" class="mb-4"></div>
    </div>

    <el-table :data="loanData" style="width: 100%" stripe border class="mb-4">
      <el-table-column prop="disbursementDate" label="放款日期" width="120"></el-table-column>
      <el-table-column prop="enterpriseName" label="企业名称" width="180"></el-table-column>
      <el-table-column prop="limitTime" label="还款时间" width="120"></el-table-column>
      <el-table-column prop="loanAmount" label="贷款金额(万元)" width="120"></el-table-column>
      <el-table-column prop="nowOfYear" label="当前年份" width="100"></el-table-column>
      <el-table-column prop="repaidPrincipal" label="已还本金(万元)" width="120"></el-table-column>
      <el-table-column prop="uniCode" label="统一社会信用代码"></el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
