<!--
 * @Author: ysh
 * @Date: 2024-10-18 11:17:48
 * @LastEditors: wrh
 * @LastEditTime: 2025-12-26 15:00:24
-->
<template>
  <div style="width:100%;" v-loading="loading">
    <div class="titles">借款统计</div>
    <div class="warpper">
      <div class="left">
        <div class="left-top" id="borrowBar"></div>
        <div class="left-top" id="borrowUsagePie" v-loading="dataLoading"></div>
      </div>
      <div class="middle">
        <div class="middle-top" id="borrowLine"></div>
        <div class="middle-top" id="borrowProject"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { echartsInit } from '@/utils/echarts'
import { getBorrowStatistic } from '@/api/oa/borrow/borrow';
let borrowYearChart, borrowAmountChart, borrowUsageChart, borrowProjectChart
export default {
  props: {
    borrowData: {
      type: Object,
      require: true,
    },
  },
  watch: {
    borrowUsage() {
      this.initBorrowUsagePie(this.activeYear)
    },
    borrowUsageAmount() {
      // this.initBorrowUsageAmountPie(this.activeYear)
    },
    borrowYear() {
      if (this.isYearView) {
        this.initBorrowYearBar();
      }
    },
    borrowData: {
      handler(newVal) {
        if (newVal) {
          this.initDatas();
        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      loading: false,
      borrowAmount: {},
      borrowUsage: {},
      borrowUsageAmount: {},
      borrowYear: {},
      borrowMonth: {},
      borrowMonthAmount: {},
      yearProjectAmount: {},
      yearProjectCount: {},
      sumBorrowAmount: 0,
      dataLoading: false,
      activeYear: '',
      isYearView: true,
      mainChart: null
    }
  },
  created() {
    this.loading = true;
    this.initDatas();
    this.loading = false;
  },
  mounted() {
    this.initBorrowYearBar();
    this.initBorrowAmountLine();
    this.initBorrowUsagePie('');
    // this.initBorrowUsageAmountPie('');
    this.initBorrowProjectLineBar();
  },
  methods: {
    initDatas() {
      if (Object.keys(this.borrowData).length !== 0) {
        this.borrowAmount = this.borrowData.amount[0];
        this.borrowUsage = this.borrowData.usage[0];
        this.borrowUsageAmount = this.borrowData.usageAmount[0];
        this.borrowYear = this.borrowData.year[0];
        this.borrowMonth = this.borrowData.month ? this.borrowData.month[0] : {};
        this.borrowMonthAmount = this.borrowData.monthAmount ? this.borrowData.monthAmount[0] : {};
        this.yearProjectAmount = this.borrowData.yearProjectAmount[0];
        this.yearProjectCount = this.borrowData.yearProjectCount[0];
        let sum = Object.values(this.borrowAmount).reduce((accumulator, currentValue) => accumulator + currentValue, 0);
        this.sumBorrowAmount = (sum / 10000).toFixed(2)
      }
    },
    clickYear(charts) {
      let that = this;
      that.mainChart = charts;
      charts.off('click');
      charts.on('click', async function (event) {
        if (event) {
          if (event.name === '' || event.name === undefined) {
            that.isYearView = true;
            that.activeYear = '';
            that.initBorrowYearBar();
            that.initBorrowAmountLine();
          } else {
            that.activeYear = event.name;
            that.isYearView = false;
            that.dataLoading = true;
            let res = await getBorrowStatistic({ lendTime: event.name + '-01-01' });
            that.borrowYear = res.data.year[0];
            that.borrowAmount = res.data.amount[0];
            that.borrowMonth = res.data.month ? res.data.month[0] : {};
            that.borrowMonthAmount = res.data.monthAmount ? res.data.monthAmount[0] : {};
            that.borrowUsage = res.data.usage[0];
            that.borrowUsageAmount = res.data.usageAmount[0];
            that.dataLoading = false;
            that.initBorrowMonthChart();
            that.initBorrowAmountLine();
          }
        }
      })
    },
    initBorrowYearBar() {
      let option = {
        title: {
          text: '借款次数',
          subtext: '借款次数：' + Object.values(this.borrowYear).reduce((accumulator, currentValue) => accumulator + currentValue, 0) + '次'
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        graphic: [
          {
            type: 'text',
            name: '',
            right: '0',
            top: '20%',
            style: {
              text: '全部年份',
              fill: '#000', // 文本颜色  
              fontSize: 12, // 文本大小  
              fontWeight: '' // 文本粗细  
            }
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          name: '年',
          type: 'category',
          data: Object.keys(this.borrowYear),
        },
        yAxis: {
          type: 'value',
          name: '单位：次'
        },
        series: [
          {
            data: Object.values(this.borrowYear),
            type: 'bar',
            smooth: true,
            label: {
              show: true,
              position: 'top'
            },
            itemStyle: {
              color: '#3498DB'
            }
          }
        ]
      };
      let charts = echartsInit(borrowYearChart, 'borrowBar', option);
      this.clickYear(charts)
    },
    initBorrowAmountLine() {
      let xData = this.isYearView ? Object.keys(this.borrowAmount) : Object.keys(this.borrowMonthAmount);
      let amountData = this.isYearView ? Object.values(this.borrowAmount) : Object.values(this.borrowMonthAmount);
      let titleText = this.isYearView ? '借款金额' : this.activeYear + '年借款金额';
      let sumAmount = amountData.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
      
      let option = {
        title: {
          text: titleText,
          subtext: '借款总额：' + sumAmount.toFixed(2) + '元' +
            '（约' + (sumAmount / 10000).toFixed(2) + '万元）'
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: xData,
        },
        yAxis: {
          type: 'value',
          name: '单位：元'
        },
        series: [
          {
            min: 0,
            data: amountData,
            type: 'line',
            smooth: true,
            label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                let value = params.value;
                if (value >= 10000) {
                  return '约' + (value / 10000).toFixed(2) + '万元'
                }
              }
            }
          }
        ]
      };
      echartsInit(borrowAmountChart, 'borrowLine', option);
    },
    initBorrowUsagePie(year) {
      let option = {
        title: {
          text: year + '借款类型占比',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '占比',
            type: 'pie',
            radius: '30%',
            center: ['25%', '50%'],
            avoidLabelOverlap: false,
            data: Object.entries(this.borrowUsage).map(([key, value]) => {
              return { name: key, value: value }
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              alignTo: 'none',
              formatter: '{name|{b}}\n{value|{c}个}',
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
          },
          {
            name: '占比',
            type: 'pie',
            radius: '30%',
            center: ['65%', '50%'],
            avoidLabelOverlap: false,
            data: Object.entries(this.borrowUsageAmount).map(([key, value]) => {
              return { name: key, value: value }
            }),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              alignTo: 'none',
              formatter: '{name|{b}}\n{value|{c}元}',
              minMargin: 5,
              edgeDistance: 8,
              lineHeight: 15,
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
          },
        ]
      };
      echartsInit(borrowUsageChart, 'borrowUsagePie', option);
    },
    initBorrowProjectLineBar(year) {
      let option = {
        title: {
          text: '项目借款金额',
        },
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          containLabel: true
        },
        legend: {
          right: '0%',
          orient: 'vertical'
        },
        xAxis: [
          {
            type: 'category',
            data: Object.keys(this.yearProjectAmount),
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '单位：元',
          }
        ],
        series: [
          {
            type: 'line',
            tooltip: {
              valueFormatter: function (value) {
                return value + ' 元';
              }
            },
            smooth: true,
            data: Object.values(this.yearProjectAmount),
            label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                let value = params.value;
                if (value >= 10000) {
                  return '约' + (value / 10000).toFixed(2) + '万元'
                }
              }
            }
          },
        ]
      };
      echartsInit(borrowProjectChart, 'borrowProject', option);
    },
    initBorrowMonthChart() {
      let option = {
        title: {
          text: this.activeYear + '年借款次数',
          subtext: '借款次数：' + Object.values(this.borrowMonth).reduce((a, b) => a + b, 0) + '次'
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        graphic: [
          {
            type: 'text',
            name: '',
            right: '0',
            top: '20%',
            style: {
              text: '返回',
              fill: '#409EFF',
              fontSize: 12,
              fontWeight: ''
            },
            onclick: () => { this.goBackToYear(); }
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          name: '月',
          type: 'category',
          data: Object.keys(this.borrowMonth),
        },
        yAxis: {
          type: 'value',
          name: '单位：次'
        },
        series: [
          {
            data: Object.values(this.borrowMonth),
            type: 'bar',
            smooth: true,
            label: {
              show: true,
              position: 'top'
            },
            itemStyle: {
              color: '#3498DB'
            }
          }
        ]
      };
      let charts = echartsInit(borrowYearChart, 'borrowBar', option);
    },
    goBackToYear() {
      this.isYearView = true;
      this.activeYear = '';
      this.initDatas();
      this.initBorrowYearBar();
      this.initBorrowAmountLine();
      this.initBorrowUsagePie('');
    },
  },
}
</script>

<style lang="scss" scoped>
.titles {
  font-family: 'puhuiti';
  font-size: 16px;
  margin-bottom: 16px;
}

.warpper {
  width: 100%;
  height: 100%;
  display: flex;

  .left {
    flex: 1;

    .left-top {
      width: 100%;
      height: 300px;
      padding: 10px;
      border: 1px solid #ececec;
    }
  }

  .middle {
    flex: 1;

    .middle-top {
      width: 100%;
      height: 300px;
      padding: 10px;
      border: 1px solid #ececec;
    }
  }

  .right {
    // flex: 1;

    .right-top {
      width: 100%;
      height: 300px;
      padding: 10px;
      border: 1px solid #ececec;
    }
  }
}
</style>