// pages/statistics/statistics.js
import * as UTIL from '../../utils/util.js';
import * as API from '../../utils/API.js';
import * as echarts from '../../ec-canvas/echarts';
let EVN_CONFIG = require('../../env/env');

const app = getApp();

function setOption(chart, rowRows1, rowRows2) {
  var option = {
    title: [
      { // 第一个圆环标题
        text: '收入', // 主标题
        textStyle: { // 主标题样式
          color: '#5CAE77',
          fontWeight: '400',
          fontSize: 14
        },
        left: '27%', // 定位到适合的位置
        top: '45%', // 定位到适合的位置
        textAlign: 'center' // 主、副标题水平居中显示
      },
      {// 第二个圆环标题
        text: '支出',
        textStyle: {
          color: '#E90000',
          fontWeight: '400',
          fontSize: 14
        },
        left: '76%',
        top: '45%',
        textAlign: 'center'
      }
    ],
    tooltip: {
      trigger: 'item'
    },
    series: [
      { // 第一个圆环
        type: 'pie',
        radius: ['30%', '50%'],
        center: ['28%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside', // 数据会显示在图形上，'center':会显示在圆环的内部
          color: '#333',
        },
        labelLine:{
          length:'5',
          length2:'5',
        },
        data: rowRows1,
      },
      { // 第二个圆环
        type: 'pie',
        radius: ['30%', '50%'],
        center: ['77%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
        },
        label: {
          show: true,
          position: 'outside', // 数据会显示在图形上，'center':会显示在圆环的内部
          color: '#333',
        },
        labelLine:{
          length:'5',
          length2:'5',
        },
        data: rowRows2,
      }
    ]
  };

  chart.setOption(option);
}
function initChart3(chart, rowRows1) {
  var option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      { // 第一个圆环
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          color: '#333',
        },
        data: rowRows1
      }
    ]
  };
  chart.setOption(option);
}
function initChart4(chart, rowRows2) {
  var option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      { // 第二个圆环
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          color: '#333',
        },
        data:rowRows2,
      }
    ]
  };
  chart.setOption(option);
}
function initChartLine(chart,lineRowsSR,lineRowsZC) {
  console.log(lineRowsSR);
  var option = {
    legend: {
      data: ['收入', '支出'],
      top: 0,
      left: 'center',
      z: 100
    },
    grid: {
      left: '0',
      top:'20%',
      right: '3%',
      bottom: '3%',
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      // show: false
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
      // show: false
    },
    series: [{
      name: '收入',
      type: 'line',
      smooth: true,
      data: lineRowsSR
    }, {
      name: '支出',
      type: 'line',
      smooth: true,
      data: lineRowsZC
    }]
  };

  chart.setOption(option);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    ec: {
      lazyLoad: true,
    },
    ec2: {
      lazyLoad: true
    },
    ec3: {
      lazyLoad: true
    },
    ec4: {
      lazyLoad: true
    },
    showList:false,
    showZC:false,
    showSR:false,
    date:'2022',
    topDetail:[],
  },
  showList(){
    this.setData({
      showList:!this.data.showList,
      showSR:true
    })
    if (this.data.showList) {
      this.oneComponent2 = this.selectComponent('#mychart-one2');
      this.init_one2(this.data.rowRows1)
    }
  },
  bindDateChange(e){
    this.setData({
      showList:false,
      showSR:false,
      showZC:false,
    })
    this.setData({
      date: e.detail.value
    })
    this.onLoad();
  },
  CloseList(){
    this.setData({
      showList:!this.data.showList,
      showSR:false,
      showZC:false,
    })
    this.oneComponent = this.selectComponent('#mychart-one');
    this.init_one(this.data.rowRows1,this.data.rowRows2)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    that.oneComponent = that.selectComponent('#mychart-one');
    that.oneComponent4 = that.selectComponent('#mychart-one4');
    let sendData = {
      year:that.data.date,
      method:'GET'
    }
    //收入类型字典
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'income_type', {method:'GET'}, {
      success: (res) => {
        this.setData({
          incomeTypeOptions:res.data,
        })
      }
    })
    //支出类型字典
    UTIL.httpRequest(API.URL_GET_GETDICTTYPE + 'capital_expenditure_type', {method:'GET'}, {
      success: (res) => {
        this.setData({
          expenditureTypeOptions:res.data,
        })
      }
    })
    wx.showLoading({
      title: '加载中',
    })
    
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)
    setTimeout(function(){
      UTIL.httpRequest(API.URL_GET_GETSTATISTICS, sendData,{
        success: (res) => {
          let lineRowsSR = [];
          let lineRowsZC = [];
          for (let i = 0; i < res.rows.length; i++) {
            const element = res.rows[i];
            lineRowsSR.push(element.jieAmount)
            lineRowsZC.push(element.daiAmount)
            element.daiAmount = Number(element.daiAmount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, "");
            element.jieAmount = Number(element.jieAmount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, "");
          }
          that.setData({
            list:res.rows,
          })
          that.init_one4(lineRowsSR,lineRowsZC)
        }
      })
      UTIL.httpRequest(API.URL_GET_GETSUMSTATISTICS, sendData,{
        success: (res) => {
          res.data.jieAmount =  Number(res.data.jieAmount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, "");
          res.data.daiAmount =  Number(res.data.daiAmount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, "");
          that.setData({
            topDetail:res.data
          })
        }
      })
      UTIL.httpRequest(API.URL_GET_GETSUMGROUPTYPE, sendData,{
        success: (res) => {
          console.log(res);
          let rowRows1 = [];
          let rowRows2 = [];
          res.data[1].forEach(rr=>{
            console.log('aaa');
            rowRows1.push({
              value: rr.percentage,
              name: UTIL.getTransform(rr.incomeType,that.data.incomeTypeOptions).substr(0,2)+'\n'+rr.percentage+'%'
            })
            rr.jieAmount = Number(rr.jieAmount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, "");
          })
          res.data[2].forEach(rrr=>{
            rowRows2.push({
              value: rrr.percentage,
              name: UTIL.getTransform(rrr.expenditureType,that.data.expenditureTypeOptions).substr(0,2)+'\n'+rrr.percentage+'%'
            })
            rrr.daiAmount = Number(rrr.daiAmount).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, "");
          })
          that.setData({
            centerRow:res.data,
            rowRows1:rowRows1,
            rowRows2:rowRows2
          })
          that.init_one(rowRows1,rowRows2)
        }
      })
    },2000)
    
  },
  init_one: function (rowRows1,rowRows2) {//饼图汇总
    this.oneComponent.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      setOption(chart, rowRows1 , rowRows2)
    });
  },
  init_one2: function (rowRows1) {//收入饼图
    this.oneComponent2.init((canvas, width, height) => {
      const chart2 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      initChart3(chart2, rowRows1)
    });
  },
  init_one3: function (rowRows2) {//支出饼图
    this.oneComponent3.init((canvas, width, height) => {
      const chart3 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      initChart4(chart3, rowRows2)
    });
  },
  init_one4: function (lineRowsSR,lineRowsZC) {//折线图
    this.oneComponent4.init((canvas, width, height) => {
      const chart4 = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      initChartLine(chart4, lineRowsSR,lineRowsZC)
    });
  },
  goSR(){
    this.setData({
      showZC:false,
      showSR:true
    })
    this.oneComponent2 = this.selectComponent('#mychart-one2');
    this.init_one2(this.data.rowRows1)
  },
  goZC(){
    this.setData({
      showZC:true,
      showSR:false
    })
    this.oneComponent3 = this.selectComponent('#mychart-one3');
    this.init_one3(this.data.rowRows2)
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  onTimeShow(e){
    this.setData({
      timeShow:true
    })
  },
  back:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})