// pages/data/index.js
import http from '../../utils/http'
import util from '../../utils/util'
import api from '../../utils/api'
const app = getApp()
import * as echarts from '../../ec-canvas/echarts';

let chart = null;
let option = {}

function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  option = {
    legend: {
      data: []
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      show: false
    },
    series: [{
      data: [],
      type: 'bar'
    }]
  };

  chart.setOption(option);
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    projects: [],
    project_ids: [],
    project_names: '',
    total_money: '0',
    month_money: '0',
    projectShow: false,
    index: 0,
    show: false,
    isSearch: true,
    charts: [{
      name: '柱状图',
      type: 'bar'
    }, {
      name: '折线图',
      type: 'line'
    }, {
      name: '饼状图',
      type: 'pie'
    }, {
      name: '明细图',
      type: 'detail'
    }, {
      name: '雷达图',
      type: 'radar'
    }],
    chartIndex: 0,
    dateTypes: [{
      name: '按年',
      type: 'year'
    }, {
      name: '按月',
      type: 'month'
    }],
    dateIndex: 0,
    dateShow: false,
    years_months: [],
    date: '',
    start: '',
    end: '',
    max_date: '',
    min_date: '',
    filter: {},
    data: [],
    ec: {
      onInit: initChart
    },
    detail_data: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    api.getByName(this, 'projects/getAll', 'projects', {}, function (res) {
      that.getData()
    });
    // api.getByName(this, 'data/getYearsAndMonths', 'years_months');
    // var maxDate = (new Date()).getTime()
    // var minDate = (new Date()).getTime() - 2 * 365 * 24 * 3600 * 1000
    // this.setData({
    //   minDate,
    //   maxDate
    // })
    this.getDateInfo()
    app.resetDataFilter()
  },

  switchCheck: function (e) {
    var index = e.currentTarget.dataset.index
    var projects = this.data.projects
    projects[index].checked = projects[index].checked ? false : true
    this.setData({
      projects
    })
  },

  closeProject: function (e) {
    var project_ids = []
    var project_names = []
    var projects = this.data.projects
    for (var i = 0; i < projects.length; ++i) {
      if (projects[i].checked) {
        project_ids.push(projects[i].id)
        project_names.push(projects[i].name)
      }
    }
    project_names = project_names.join(',')
    this.setData({
      project_ids,
      project_names
    })
    this.switchShow(e)
    this.getData()
    this.getTotalInfo()
  },

  getSearchItems: function () {
    var ids = this.data.project_ids
    if (ids.length <= 0) return false
    var filter = this.data.filter
    var chart_type = this.data.charts[this.data.chartIndex]
    // var chat 
    return {
      project_ids: ids,
      start_date: this.data.start_date,
      end_date: this.data.end_date,
      date: this.data.date,
      type: this.data.dateIndex == 0 ? 'year' : 'month',
      device_ids: filter.device_ids,
      device_name_ids: filter.device_name_ids,
      spec_ids: filter.spec_ids,
      rent_type_ids: filter.rent_type_ids,
      chart_type: chart_type.type
    }
  },

  getTotalInfo() {
    var data = this.getSearchItems()
    var that = this
    http({
      url: 'data/getTotalInfo',
      data: data,
      success: function (res) {
        if (res.code == 0) {
          that.setData(res.data)
        }
      }
    })
  },

  getDetailData() {
    var data = this.getSearchItems()
    var that = this
    http({
      url: 'data/getDetailData',
      data: data,
      success: function (res) {
        if (res.code == 0) {
          that.setData({
            detail_data: res.data
          })
        }
      }
    })
  },

  getData() {
    var data = this.getSearchItems()
    var that = this
    if (!data.project_ids || data.project_ids.length <= 0) return false
    var chart_type = this.data.charts[this.data.chartIndex]
    http({
      url: 'data/getStat',
      data: data,
      success: function (res) {
        if (res.code == 0) {
          if (chart_type == 'detail') {
            that.setData({
              detail_data: res.data
            })
          } else {
            that.setData({
              data: res.data
            })
            that.updateChart()
          }
        }
      }
    })
  },

  getDateInfo() {
    var that = this
    http({
      url: 'data/getDateInfo',
      data: {},
      success: function (res) {
        if (res.code == 0) {
          that.setData(res.data)
        }
      }
    })
  },

  onChange: function (e) {
    var value = e.detail.value
    var name = e.currentTarget.dataset.name
    if (this.data[name] == value) return false;
    this.setData({
      [name]: value
    })
    if (name == 'chartIndex') {
      var chart = this.data.charts[this.data.chartIndex]
      if (chart.type == 'detail') {
        this.getDetailData()
      } else {
        this.getData()
      }
    } else if (name == 'date') {
      this.getTotalInfo()
    }
  },
  updateChart: function () {
    var data = this.data.data
    option.xAxis.data = data.names;
    option.legend = {
      data: data.legends
    }

    var type = this.data.charts[this.data.chartIndex].type
    if (type == 'pie') {
      option.series = [{
        data: data.data,
        type: type,
        label: {
          position: 'inner',
          formatter: '{b}\n{d}%'
        }
      }]
      option.xAxis.show = false
    } else if (type == 'radar') {
      option.xAxis.show = false
      option.radar = {
        // shape: 'circle',
        indicator: data.indicator
      }
      option.series = [{
        type: type,
        data: data.data
      }]
    } else {
      option.xAxis.show = true
      var values = data.values
      for (var i = 0; i < values.length; ++i) {
        option.series[i] = {
          label: {
            show: true,
            position: 'top'
          },
          name: data.legends[i],
          type: type,
          data: values[i]
        }
      }
    }

    chart.setOption(option)
  },

  radioChange: function (e) {
    var dateIndex = e.currentTarget.dataset.index
    if (dateIndex == this.data.dateIndex) return false
    var start_date = this.data.start_date
    var end_date = this.data.end_date
    var start_date = dateIndex == 1 ? start_date + '-01' : start_date.substr(0, 7)
    var end_date = dateIndex == 1 ? end_date + '-01' : end_date.substr(0, 7)
    this.setData({
      dateIndex,
      start_date,
      end_date
    })
  },

  switchShow: function (e) {
    var name = e.currentTarget.dataset.name
    var show = e.currentTarget.dataset.show ? e.currentTarget.dataset.show : !this.data[name]
    this.setData({
      [name]: show
    })
    if (name == 'dateShow' && !show) {
      this.getData()
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getTabBar().init();
    var filter = wx.getStorageSync('sg-data-filters')
    this.setData({
      filter: filter
    })
    this.getData()
  },

  navigate: function (e) {
    var url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url,
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})