// 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);
  chart.on('click', function (params) {
    console.log(params)
  })
  option = {
    color: ["#5992fd"],
    legend: {
      data: []
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      show: false,
    },
    dataZoom: [{ //Y轴固定,让内容滚动
      type: 'slider',
      show: true,
      yAxisIndex: [0],
      start: 1,
      end: 50, //设置X轴刻度之间的间隔(根据数据量来调整)
      filterMode: 'none',
      zoomLock: true,
    }, ],
    series: [{
      data: [],
      type: 'bar',
      label: {
        normal: {
          show: true
        }
      },
    }],
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器，坐标轴触发有效
        type: 'cross', // 默认为直线，可选为：'line' | 'shadow' | 'cross'
        axis: "y",
      },
      showContent: false
    },
  };
  chart.setOption(option);
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    projectinfoname: "",
    projectinfoprice: "",
    projects: [],
    project_id: '',
    project_ids: [],
    sort_types: [{
        text: '筛选类型',
        value: ''
      },
      {
        text: '按年筛选',
        value: 'year'
      },
      {
        text: '按月筛选',
        value: 'month'
      }
    ],
    sort_type: '',
    project_names: '',
    year_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: 1,
    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: [],
    orderBy: 'asc',
    recordX: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.resetDataFilter()
    api.getByName(this, 'projects/getAll', 'projects', {
      type: 'drop_menu'
    });
  },

  // startX(e) {
  //   console.log(e)
  //   this.setData({
  //     recordX: e.touches[0].clientX
  //   })
  // },
  // moveX(e) {
  //   console.log(e)
  //   let currentX = e.changedTouches[0].clientX
  //   var chartIndex = this.data.chartIndex
  //   if (currentX - this.data.recordX <= -60) {
  //     chartIndex = (chartIndex + 1)
  //     console.log(chartIndex)
  //   }
  //   if (currentX - this.data.recordX >= 60) {
  //     chartIndex = (chartIndex - 1)
  //     console.log(chartIndex)
  //   }
  //   if (chartIndex < 0 || chartIndex > 2) return false;
  //   this.setData({ chartIndex })
  //   this.getChartData()
  // },

  changeChartIndex: function (e) {
    var type = e.currentTarget.dataset.type
    var chartIndex = this.data.chartIndex
    chartIndex = type == '+' ? (chartIndex + 1) : (chartIndex - 1)
    if (chartIndex < 0 || chartIndex > 2) return false;
    this.setData({
      chartIndex
    })
    this.getChartData()
  },
  popclose: function () {
    this.setData({
      projectShow: false
    })
  },
  updateValue: function (e) {
    var name = e.currentTarget.dataset.name
    var value = e.currentTarget.dataset.value
    this.setData({
      [name]: value
    })
    if (name == 'orderBy') {
      this.getChartData()
    }
  },

  updateDate(e) {
    this.setData({
      date: e.detail.date
    })
    this.getYearAndMonthMoney()
    this.getChartData()
  },

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

  getChartData: function () {
    var chartIndex = this.data.chartIndex
    var that = this
    var data = {
      date: this.data.date,
      orderBy: this.data.orderBy,
      chartIndex: chartIndex,
      project_id: this.data.project_id,
      sort_type: this.data.sort_type
    }
    data = Object.assign({}, data, this.data.filter)
    http({
      url: 'data/projectStat',
      data: data,
      success: function (res) {
        if (res.code == 0) {
          that.setData({
            data: res.data
          })
          that.updateChart()
        }
      }
    })
  },
  onChange(e) {
    var name = e.currentTarget.dataset.name
    var val = e.detail
    this.setData({
      [name]: val
    })
    this.getChartData()
  },
  updateChart: function () {
    var data = this.data.data
    var chartIndex = this.data.chartIndex
    if (chartIndex == 0) {
      option.xAxis = [{
        type: 'value',
        show: false
      }]

      option.legend = {
        data: data.legends,
        bottom: 40
      }
      var title = '设备租赁费用明细'
      var date = this.data.date
      date = date.length > 7 ? date.substr(0, 4) + '年' : ''
      title = (data.project ? data.project.name + '\n' + '\n' : '-') + date + title
      option.title = {
        text: title,
        left: 'center',
        bottom: 10,
        textStyle: {
          fontSize: 14,
          color: "#5992fd"
        },
      }
      option.yAxis = [{
        type: 'category',
        data: data.names,
        axisLabel: {
          color: "#000",
          interval: 0,
          formatter: function (value) {
            if (value.length > 4) {
              return value.substring(0, 4) + "...";
            } else {
              return value;
            }
          }
        },
      }];
      var values = data.values

      option.series = [{
        label: {
          show: true
        },
        // name: data.name,
        type: 'bar',
        data: values
      }]
      option.grid = {
        left: 20,
        right: 45,
        bottom: 60,
        top: 0,
        containLabel: true
      }
    } else if (chartIndex == 1) {
      option.xAxis = [{
        type: 'value',
        show: false
      }]
      option.legend = {
        data: data.legends,
        bottom: 40
      }
      var title = '项目租赁总费用排行'
      var date = this.data.date
      date = date.length > 7 ? date.substr(0, 7) : ''
      title = date + title
      option.title = {
        text: title,
        left: 'center',
        bottom: 10,
        textStyle: {
          fontSize: 14,
          color: "#5992fd"
        },
      }
      option.yAxis = [{
        type: 'category',
        data: data.names,
        axisLabel: {
          color: "#000",
          interval: 0,
          formatter: function (value) {
            if (value.length > 4) {
              return value.substring(0, 4) + "...";
            } else {
              return value;
            }
          }
        },
      }];
      var values = data.values

      option.series = [{
        label: {
          show: true
        },
        // name: '租赁费用',
        type: 'bar',
        data: values
      }]
      option.grid = {
        left: 20,
        right: 45,
        bottom: 60,
        top: 0,
        containLabel: true
      }
      // chart.resize({width: '80vw', height: '80vh'})
    } else {
      option.xAxis = [{
        type: 'value',
        show: false
      }]

      option.legend = {
        data: data.legends,
        bottom: 40
      }
      var title = '设备最大单价费用排行'
      title = (data.info.length != 0 ? (data.info[0] != null ? data.info[0] + '-' : '') + (data.info[1] != null ? data.info[1] + '-' : '') + (data.info[2] != null ? data.info[2] + '-' : '') + (data.info[3] != null ? data.info[3] : '') : '') + '\n' + '\n' + title
      console.log(data)
      option.title = {
        text: title,
        left: 'center',
        bottom: 10,
        textStyle: {
          fontSize: 14,
          color: "#5992fd"
        },
      }
      option.yAxis = [{
        type: 'category',
        data: data.names,
        axisLabel: {
          color: "#000",
          interval: 0,
          formatter: function (value) {
            if (value.length > 4) {
              return value.substring(0, 4) + "...";
            } else {
              return value;
            }
          }
        },
      }];
      var values = data.values

      option.series = [{
        label: {
          show: true
        },
        // name: '租赁最大单价',
        type: 'bar',
        data: values
      }]
      option.grid = {
        left: 20,
        right: 45,
        bottom: 60,
        top: 0,
        containLabel: true
      }
    }

    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.getChartData()
  },

  navigate: function (e) {
    var url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url + '?status=1',
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})