<template>
  <view class="ComCss">
    <!-- <u-navbar v-if="!$isDing" class="navBarCss" title="数据统计" leftIconSize="0"
      :titleStyle="{'fontSize':'36rpx','color':'#333333','fontWeight':'700'}" safeAreaInsetTop placeholder /> -->
    <view class="bigCardCss" v-if="isZbOrQy">
      <view class="titleCss">
        本财年报告已上报数
      </view>
      <view class="numCss">
        {{statistics.totalNum}}
      </view>
    </view>
    <view class="flexCss">
      <view class="cardCss">
        <view class="titleCss">
          待开发居民小区用户
        </view>
        <view class="numCss">
          {{statistics.resident}}
        </view>
      </view>
      <view class="cardCss">
        <view class="titleCss">
          待开发工商业用户
        </view>
        <view class="numCss">
          {{statistics.business}}
        </view>
      </view>
      <view class="cardCss">
        <view class="titleCss">
          流失大客户总数
        </view>
        <view class="numCss">
          {{statistics.customer}}
        </view>
      </view>
    </view>
    <view class="charCardCss" v-if="isZbOrQy">
      <view class="charTitleCss">
        本财年市场摸底分析
      </view>
      <view class="charbox">
        <echarts class="pie-chart" :option="pieOption" canvasId="pie1"></echarts>
      </view>
    </view>
    <view class="charCardCss">
      <view class="charTitleCss">
        待开发用户池数据分析
      </view>
      <view class="charbox">
        <echarts class="pie-chart" :option="pieOption2" canvasId="pie2"></echarts>
      </view>
    </view>
    <view class="charCardCss">
      <view class="charTitleCss">
        {{title}}
      </view>
      <view class="charbox">
        <echarts class="line-chart" :option="lineOption" canvasId="line"></echarts>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    getStatisticsReport,
    getStatisticsPool,
    getStatisticsLogin,
    getStatisticsChart,
    getHistogram
  } from '@/api/total.js'
  export default {
    components: {},
    props: {

    },
    data() {
      return {
        pieOption: {},
        pieOption2: {},
        lineOption: {},
        fiscalYear: "",
        statistics: {
          resident: "",
          totalNum: "",
          residentDeveloping: "",
          residentUndeveloped: "",
          business: "",
          customer: ""
        },
        title: "",
        reportCharData: null,
        reportCharBarData: null,
        data1: [],
        data2: [],
        data3: [],
        total1: 0,
        total2: 0,
        roleTypes: "",
        isZbOrQy: false,
        roleId: this.$store.state.user.roleId,
        entity: this.$store.state.user.entity,
      }
    },
    mounted() {
      if (this.roleId.includes('103')) {
        this.roleTypes = '103';
        this.isZbOrQy = true
        this.title = '各区域中心待开发用户池数据情况'
        console.log("总部账号", this.roleTypes);
      } else if (this.roleId.includes('105')) {
        this.isZbOrQy = true
        this.roleTypes = '105';
        this.title = '待开发用户池总数量排名前8的预算主体数据情况'
        console.log("区域账号", this.roleTypes);
      } else {
        this.isZbOrQy = false
        this.roleTypes = '104';
        this.title = '近七天待开发用户池数据情况'
        console.log("主体账号", this.roleTypes);
      }
    },
    computed: {

    },
    onShow() {
      this.initData()
    },
    methods: {
      async getHistogram(query) {
        const result = await getHistogram(query);
        if (this.roleTypes === '105') {
          this.reportCharBarData = this.findTopEightMaxSums(result.data);
        } else if (this.roleTypes === '103') {
          this.reportCharBarData = result.data;
        }
        console.log("柱状图数据", this.reportCharBarData);
      },
      async getSevenDayData() {
        const result = await getStatisticsChart(this.entity);
        this.reportCharData = result.data;
        console.log("近7天结果", this.reportCharData);
      },
      //取最大的八个值
      findTopEightMaxSums(data) {
        let sums = [];
        // 循环遍历 data 数组
        for (let obj of data) {
          let sum =
            obj.list.reduce((acc, curr) => {
              return (
                acc +
                curr.commerceAndIndustry +
                curr.customerRecoveryProgress +
                curr.resident
              );
            }, 0);

          sums.push(sum);
        }

        // 取前八个和最大的索引
        let maxSumIndices = [];
        for (let i = 0; i < 8; i++) {
          let maxIndex = sums.indexOf(Math.max(...sums));
          if (maxIndex !== -1) {
            maxSumIndices.push(maxIndex);
            sums[maxIndex] = -Infinity;
          }
        }
        // 获取前八个对象
        let topEightObjects = maxSumIndices.map((index) => data[index]);
        return topEightObjects;
      },
      async getStatisticsReport(data) {
        let that = this;
        await getStatisticsReport(data).then(res => {
          if (res.code === 200) {
            let data = res.data;
            that.statistics.totalNum = parseInt(data.pass) + parseInt(data.review);
            that.data1 = [{
                value: data.submit,
                name: '待申报'
              },
              {
                value: data.review,
                name: '待评审'
              },
              {
                value: data.revise,
                name: '待修改'
              },
              {
                value: data.pass,
                name: '已通过'
              },
              {
                value: data.unCreate,
                name: '未创建'
              },
            ]
            that.total1 = data.total
            console.log("报告", that.data1);
          }
        })
      },
      async getStatisticsPool(query) {
        let that = this;
        await getStatisticsPool(query).then(res => {
          if (res.code === 200) {
            let data = res.data;
            that.statistics.resident = parseInt(data.residentDeveloping) + parseInt(data.residentUndeveloped);
            that.statistics.residentDeveloping = data.residentDeveloping;
            that.statistics.residentUndeveloped = data.residentUndeveloped;
            that.statistics.business = data.commerceAndIndustry;
            that.statistics.customer = data.customerRecoveryProgress;
            that.data2 = [{
                value: data.residentDeveloping,
                name: '居民_开发中小区总数'
              },
              {
                value: data.residentUndeveloped,
                name: '居民_未开发中小区总数'
              },
              {
                value: data.commerceAndIndustry,
                name: '待开发商业用户数'
              },
              {
                value: data.customer,
                name: '待开发工业用户数'
              },
            ]
            that.total2 = data.total
          }
        })
      },
      async initData() {
        let query = {
          roleIds: this.roleId || null,
          entity: this.entity || null,
        }
        this.fiscalYear = this.$u.timeFormat("", 'yyyy');
        let data = {
          ...query,
          'fiscalYear': this.fiscalYear
        }
        await this.getStatisticsReport(data);
        await this.getStatisticsPool(query);
        if (this.roleTypes === '104') {
          await this.getSevenDayData();
        } else {
          await this.getHistogram(query)
        }

        if (this.isZbOrQy && this.reportCharBarData.length) {
          // const newData = Array(10).fill({
          //   time: '中国燃气',
          //   residentUserValue: Math.floor(Math.random() * 101),
          //   businessUserValue: Math.floor(Math.random() * 101),
          //   customerUserValue: Math.floor(Math.random() * 101)
          // });
          this.reportCharBarData.map(item => {
            this.data3.push({
              time: item.entityName,
              residentUserValue: item.list[0]?.resident || 0,
              businessUserValue: item.list[0]?.commerceAndIndustry || 0,
              customerUserValue: item.list[0]?.customerRecoveryProgress || 0
            })
            // this.data3 = this.data3.concat(newData);
          })
          console.log("区域或总部内容", this.data3);
        }
        if (!this.isZbOrQy && this.reportCharData) {
          let {
            residentLedger,
            poolIndustryAndCommerce,
            customerRecoveryProgress
          } = this.reportCharData;
          for (let i = 0; i <= 6; i++) {
            let time = (residentLedger[i]?.days) || (poolIndustryAndCommerce[i]?.days) || (customerRecoveryProgress[i]
              ?.days) || '';
            this.data3.push({
              time: time,
              residentUserValue: residentLedger[i]?.count || 0,
              businessUserValue: poolIndustryAndCommerce[i]?.count || 0,
              customerUserValue: customerRecoveryProgress[i]?.count || 0
            })
          }
          console.log("近七天待开发用户池数据情况", this.data3);
        }
        this.refreshData()
      },
      refreshData() {
        let that = this;
        const series = [{
            name: '居民用户',
            type: this.isZbOrQy ? 'bar' : 'line',
            color: '#15c2c3',
            data: this.data3.map(item => item.residentUserValue),
          },
          {
            name: '工商业用户',
            type: this.isZbOrQy ? 'bar' : 'line',
            color: '#3436c7',
            data: this.data3.map(item => item.businessUserValue),
          },
          {
            name: '流失大客户',
            type: this.isZbOrQy ? 'bar' : 'line',
            color: '#f04864',
            data: this.data3.map(item => item.customerUserValue),
          }
        ]
        console.log("series", series);
        this.pieOption = {
          tooltip: {
            trigger: 'item',
            confine: true
          },
          legend: {
            top: 'middle',
            right: '10%',
            orient: 'vertical',
            itemWidth: 8,
            itemGap: 14,
            icon: 'circle',
            data: this.data1.map(item => item.name)
          },
          color: ['#5875EB', '#FFA500', '#E74C3C', '#15C2C3', '#666666'],
          series: [{
            name: '摸底分析',
            type: 'pie',
            right: 150,
            radius: ['65%', '80%'],
            avoidLabelOverlap: false,
            label: {
              position: 'outer',
              alignTo: 'edge',
              margin: 0,
              normal: {
                show: true,
                position: 'center',
                color: '#4c4a4a',
                formatter: '{total|' + this.total1 + '}' + '\n\r' + '{active|本财年总预算主体数}',
                rich: {
                  total: {
                    fontSize: 20,
                    fontFamily: '微软雅黑',
                    color: '#45496a'
                  },
                  active: {
                    fontSize: 14,
                    fontFamily: '苹方 中等',
                    color: '#999',
                    lineHeight: 30
                  }
                }
              },
              emphasis: { //中间文字显示
                show: true
              }
            },
            labelLine: {
              show: true
            },
            data: this.data1
          }]
        };
        this.pieOption2 = {
          tooltip: {
            trigger: 'item',
            confine: true
          },
          legend: {
            orient: 'vertical',
            y: 'center',
            right: 0,
            itemWidth: 8,
            itemGap: 14,
            icon: 'circle',
            align: 'left',
            data: this.data2.map(item => item.name)
          },
          color: ['#15C2C3', '#5875EB', '#E74C3C'],
          series: [{
            name: '待开发用户池数据分析',
            type: 'pie',
            right: 150,
            radius: ['65%', '80%'],
            avoidLabelOverlap: false,
            label: {
              position: 'outer',
              alignTo: 'edge',
              margin: 0,
              normal: {
                show: true,
                position: 'center',
                color: '#4c4a4a',
                formatter: '{total|' + this.total2 + '}' + '\n\r' + '{active|总待开发用户数}',
                rich: {
                  total: {
                    fontSize: 20,
                    fontFamily: '微软雅黑',
                    color: '#45496a'
                  },
                  active: {
                    fontSize: 14,
                    fontFamily: '苹方 中等',
                    color: '#999',
                    lineHeight: 30
                  }
                }
              },
              emphasis: { //中间文字显示
                show: true
              }
            },
            labelLine: {
              show: true
            },
            data: this.data2
          }]
        };
        this.lineOption = {
          tooltip: {
            trigger: 'axis',
            confine: true
          },
          legend: {
            right: 10,
            top: '10%',
            icon: 'roundRect',
            itemWidth: 10,
            itemHeight: 2,
            itemGap: 20,
            data: series.map(item => item.name)
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          dataZoom: [{
            type: 'inside', // 放大和缩小
            orient: 'vertical',
          }, {
            type: 'inside',
          }, {
            start: 0, //默认为0
            end: 100, //默认为100
            type: 'slider',
            show: true,
            handleSize: 0, //滑动条的 左右2个滑动条的大小
            startValue: 0, // 初始显示值
            endValue: 500000, // 结束显示值,自己定
            height: 5, //组件高度
            left: '10%', //左边的距离
            right: '10%', //右边的距离
            bottom: 15, //底边的距离
            borderColor: "#ccc",
            fillerColor: '#4cccfe',
            borderRadius: 5,
            backgroundColor: '#efefef', //两边未选中的滑动条区域的颜色
            showDataShadow: false, //是否显示数据阴影 默认auto
            showDetail: false, //即拖拽时候是否显示详细数值信息 默认true
            realtime: true, //是否实时更新
            filterMode: 'filter',
          }],
          xAxis: {
            show: true,
            type: 'category',
            boundaryGap: true,
            scrollShow: true,
            data: this.data3.map(item => item.time),
            axisLabel: {
              fontSize: 14,
              color: '#666666',
              // interval:1,
              formatter: function(value) {
                if (that.isZbOrQy) {
                  if (value.length > 3) {
                    return `${value.slice(0, 2)}...`
                  }
                }
                return value
              },
            },
          },
          yAxis: {
            type: 'value'
          },
          series: series
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .ComCss {
    position: relative;
    background: #f2f4f3;
    padding-bottom: 10rpx;
    height: 100%;
  }

  .bigCardCss {
    margin: 20rpx;
    padding: 40rpx 25rpx;
    height: 177rpx;
    border-radius: 20rpx;
    background-color: #ffffff;
  }

  .cardCss {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 220rpx;
    padding: 40rpx 25rpx;
    border-radius: 20rpx;
    background-color: #ffffff;
    box-sizing: border-box;
  }

  .titleCss {
    background-color: rgba(255, 255, 255, 0);
    box-sizing: border-box;
    font-family: '苹方 中等', '苹方', sans-serif;
    color: #45496a;
    text-align: left;
    line-height: normal;
    font-size: 24rpx;
  }

  .numCss {
    margin-top: 17rpx;
    background-color: rgba(255, 255, 255, 0);
    box-sizing: border-box;
    font-family: '苹方 中等', '苹方', sans-serif;
    color: #cf000d;
    text-align: left;
    line-height: normal;
    font-size: 34rpx;
  }

  .flexCss {
    display: flex;
    justify-content: space-between;
    margin: 20rpx;
  }

  .charCardCss {
    margin: 0rpx 24rpx 20rpx 24rpx;
    height: 486rpx;
    padding: 16rpx 2rpx 20rpx 20rpx;
    border-radius: 20rpx;
    background-color: #ffffff;
    box-sizing: border-box;
  }

  .charTitleCss {
    height: 40rpx;
    margin: 32rpx 0rpx 0rpx 30rpx;
    background-color: rgba(255, 255, 255, 0);
    box-sizing: border-box;
    font-family: '苹方 中等', '苹方', sans-serif;
    color: #45496a;
    text-align: left;
    line-height: normal;
    font-size: 30rpx;
  }

  .charbox {
    width: 100%;
    height: 400rpx;
  }

  .charCss {}
</style>
