<!--
 * @Author: ysh
 * @Date: 2024-10-18 11:17:48
 * @LastEditors: wrh
 * @LastEditTime: 2025-12-26 14:47:09
-->
<template>
  <div style="width:100%;" v-loading="loading">
    <div class="titles">结算和核算统计</div>
    <div class="warpper">
      <div class="left">
        <div class="left-top" id="settleBar"></div>
        <div class="left-top" id="settleTypePie" v-loading="dataLoading"></div>
      </div>
      <div class="middle">
        <div class="middle-top" id="settleLine"></div>
        <div class="middle-top" id="settleProject"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { echartsInit } from '@/utils/echarts'
import { getSettleStatistic } from '@/api/oa/settle/settle';
import { getCheckStatistic } from '@/api/oa/budget/check';
let settleYearChart, settleAmountChart, settleTypeChart, settleProjectChart
export default {
  props: {
    settleData: {
      type: Object,
      require: true,
    },
    checkData: {
      type: Object,
      require: true,
    },
  },
  watch: {
    settleType() {
      this.initSettleTypePie(this.activeYear)
    },
    settleData() {
      this.initSettleDatas();
    },
    checkData() {
      this.initCheckDatas();
    }
  },
  data() {
    return {
      loading: false,
      settleType: {},
      settleTypeAmount: {},
      settleYear: {},
      settleAmount: {},
      yearSettleProjectAmount: {},
      yearSettleProjectCount: {},
      yearCheckProjectAmount: {},
      yearCheckProjectCount: {},
      sumSettleAmount: 0,
      sumCheckAmount: 0,
      checkYear: {},
      checkAmount: {},
      dataLoading: false,
      activeYear: '',
      isYearView: true,
      settleMonth: {},
      settleMonthAmount: {},
      checkMonth: {},
      checkMonthAmount: {}
    }
  },
  created() {
    this.loading = true;
    this.initSettleDatas();
    this.initCheckDatas();
  },
  mounted() {
    this.initSettleYearBar();
    this.initSettleAmountLine();
    this.initSettleTypePie('');
    // this.initSettleTypeAmountPie('');
    this.initSettleProjectLineBar();
  },
  methods: {
    initSettleDatas() {
      if (Object.keys(this.settleData).length !== 0) {
        this.settleAmount = this.settleData.amount[0];
        this.settleType = this.settleData.type[0];
        this.settleTypeAmount = this.settleData.typeAmount[0];
        this.settleYear = this.settleData.year[0];
        this.yearSettleProjectAmount = this.settleData.yearProjectAmount[0];
        this.yearSettleProjectCount = this.settleData.yearProjectCount[0];
        if (this.settleData.month) {
          this.settleMonth = this.settleData.month[0];
        }
        if (this.settleData.monthAmount) {
          this.settleMonthAmount = this.settleData.monthAmount[0];
        }
        let sum = Object.values(this.settleAmount).reduce((accumulator, currentValue) => accumulator + currentValue, 0);
        this.sumSettleAmount = (sum / 10000).toFixed(2)
        this.loading = false;
      } else {
        this.loading = true;
      }
    },
    initCheckDatas() {
      if (Object.keys(this.checkData).length !== 0) {
        this.checkAmount = this.checkData.amount[0];
        this.checkYear = this.checkData.year[0];
        this.yearCheckProjectAmount = this.checkData.yearProjectAmount[0];
        this.yearCheckProjectCount = this.checkData.yearProjectCount[0];
        if (this.checkData.month) {
          this.checkMonth = this.checkData.month[0];
        }
        if (this.checkData.monthAmount) {
          this.checkMonthAmount = this.checkData.monthAmount[0];
        }
        let sum = Object.values(this.checkAmount).reduce((accumulator, currentValue) => accumulator + currentValue, 0);
        this.sumCheckAmount = (sum / 10000).toFixed(2)
        this.loading = false;
      } else {
        this.loading = true;
      }
    },
    clickYear(charts) {
      let that = this;
      charts.off('click');
      charts.on('click', function (event) {
        if (event) {
          if (event.name === '' || event.name === undefined) {
            that.isYearView = true;
            that.activeYear = '';
            that.initSettleYearBar();
            that.initSettleAmountLine();
          } else {
            that.activeYear = event.name;
            that.isYearView = false;
            that.dataLoading = true;
            Promise.all([
              getSettleStatistic({ gmTime: event.name + '-01-01' }),
              getCheckStatistic({ checkTime: event.name + '-01-01' })
            ]).then(([settleRes, checkRes]) => {
              // 处理结算数据
              if (settleRes.data.month) {
                that.settleMonth = settleRes.data.month[0];
              }
              if (settleRes.data.monthAmount) {
                that.settleMonthAmount = settleRes.data.monthAmount[0];
              }
              that.settleType = settleRes.data.type[0];
              that.settleTypeAmount = settleRes.data.typeAmount[0];
              if (settleRes.data.year) {
                that.settleYear = settleRes.data.year[0];
              }
              if (settleRes.data.amount) {
                that.settleAmount = settleRes.data.amount[0];
              }
              // 处理核算数据
              if (checkRes.data.month) {
                that.checkMonth = checkRes.data.month[0];
              }
              if (checkRes.data.monthAmount) {
                that.checkMonthAmount = checkRes.data.monthAmount[0];
              }
              if (checkRes.data.year) {
                that.checkYear = checkRes.data.year[0];
              }
              if (checkRes.data.amount) {
                that.checkAmount = checkRes.data.amount[0];
              }
              that.dataLoading = false;
              that.initSettleYearBar();
              that.initSettleAmountLine();
            })
          }
        }
      })
    },
    goBackToYear() {
      this.isYearView = true;
      this.activeYear = '';
      this.settleMonth = {};
      this.settleMonthAmount = {};
      this.checkMonth = {};
      this.checkMonthAmount = {};
      this.initSettleDatas();
      this.initCheckDatas();
      this.initSettleYearBar();
      this.initSettleAmountLine();
    },
    initSettleYearBar() {
      let xData = this.isYearView ? Object.keys(this.settleYear) : Object.keys(this.settleMonth);
      let settleData = this.isYearView ? Object.values(this.settleYear) : Object.values(this.settleMonth);
      let checkData = this.isYearView ? Object.values(this.checkYear) : Object.values(this.checkMonth);
      let titleText = this.isYearView ? '结算次数' : this.activeYear + '年结算次数';
      let settleSum = this.isYearView ? Object.values(this.settleYear).reduce((accumulator, currentValue) => accumulator + currentValue, 0) : Object.values(this.settleMonth).reduce((accumulator, currentValue) => accumulator + currentValue, 0);
      let checkSum = this.isYearView ? Object.values(this.checkYear).reduce((accumulator, currentValue) => accumulator + currentValue, 0) : Object.values(this.checkMonth).reduce((accumulator, currentValue) => accumulator + currentValue, 0);
      let subtext = '结算次数：' + settleSum + '次\n核算次数：' + checkSum + '次';
      let xName = this.isYearView ? '年' : '月';
      
      let option = {
        title: {
          text: titleText,
          subtext: subtext
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        legend: {},
        graphic: this.isYearView ? [{
          type: 'text',
          name: '',
          right: '0',
          top: '20%',
          style: {
            text: '全部年份',
            fill: '#000',
            fontSize: 12,
            fontWeight: ''
          }
        }] : [{
          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: xName,
          type: 'category',
          data: xData,
        },
        yAxis: {
          type: 'value',
          name: '单位：次'
        },
        series: [
          {
            name: "结算",
            data: settleData,
            type: 'bar',
            smooth: true,
            label: {
              show: true,
              position: 'top'
            },
            itemStyle: {
              color: '#3498DB'
            }
          },
          {
            name: "核算",
            data: checkData,
            type: 'bar',
            smooth: true,
            label: {
              show: true,
              position: 'top'
            },
            itemStyle: {
              color: '#46CB2B'
            }
          }
        ]
      };
      let charts = echartsInit(settleYearChart, 'settleBar', option);
      this.clickYear(charts)
    },
    initSettleAmountLine() {
      let xData = this.isYearView ? Object.keys(this.settleAmount) : Object.keys(this.settleMonthAmount);
      let settleData = this.isYearView ? Object.values(this.settleAmount) : Object.values(this.settleMonthAmount);
      let checkData = this.isYearView ? Object.values(this.checkAmount) : Object.values(this.checkMonthAmount);
      let titleText = this.isYearView ? '结算金额' : this.activeYear + '年结算金额';
      
      let settleSum = settleData.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
      let checkSum = checkData.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
      
      let option = {
        title: {
          text: titleText,
          subtext: '结算总额：' + settleSum.toFixed(2) + '元' +
            '（约' + (settleSum / 10000).toFixed(2) + '万元）' +
            "\n" + 
            '核算总额：' + checkSum.toFixed(2) + '元' +
            '（约' + (checkSum / 10000).toFixed(2) + '万元）'
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },        
        legend: {
          right: '0%',
          orient: 'vertical'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: xData,
        },
        yAxis: {
          type: 'value',
          name: '单位：元'
        },
        series: [
          {
            name: "结算",
            data: settleData,
            type: 'line',
            smooth: true,
            label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                let value = params.value;
                if (value >= 10000) {
                  return '约' + (value / 10000).toFixed(2) + '万元'
                }
              }
            }
          },
          {
            name: "核算",
            data: checkData,
            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(settleAmountChart, 'settleLine', option);
    },
    initSettleTypePie(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.settleType).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.settleTypeAmount).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(settleTypeChart, 'settleTypePie', option);
    },
    initSettleProjectLineBar(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.yearSettleProjectAmount),
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '单位：元',
          }
        ],
        series: [
          {
            name: "结算",
            type: 'line',
            tooltip: {
              valueFormatter: function (value) {
                return value + ' 元';
              }
            },
            smooth: true,
            data: Object.values(this.yearSettleProjectAmount),
            label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                let value = params.value;
                if (value >= 10000) {
                  return '约' + (value / 10000).toFixed(2) + '万元'
                }
              }
            }
          },
          {
            name: "核算",
            type: 'line',
            tooltip: {
              valueFormatter: function (value) {
                return value + ' 元';
              }
            },
            smooth: true,
            data: Object.values(this.yearCheckProjectAmount),
            label: {
              show: true,
              position: 'top',
              formatter: function (params) {
                let value = params.value;
                if (value >= 10000) {
                  return '约' + (value / 10000).toFixed(2) + '万元'
                }
              }
            }
          }
        ]
      };
      echartsInit(settleProjectChart, 'settleProject', option);
    },
  },
}
</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>