import * as echarts from '../../components/ec-canvas/echarts';
const app = getApp();
let json = {};
let chart = null;
Page({
  data: {
    height: [0, 0, 0],
    width: 0,
    ec_map: {
      onInit: undefined,
      show: false
    },
    eclook: {
      onInit: undefined,
      show: false
    },
    portrait: {
      onInit: undefined,
      show: false
    },
    tabActive: 0,
    getData: {
      character: { emotion: [], sex: [], feeling: [] }
    },
    cloud: {
      width: 0,
      height: 0
    },
    detailList: [],
    diglogTitle: ""
  },

  onLoad(option) {
    let that = this;
    const sys = wx.getSystemInfoSync();
    let h = [sys.windowHeight, 0.7 * sys.windowHeight, 0.75 * sys.windowHeight, 0.75 * sys.windowHeight]
    wx.showLoading()
    const fs = wx.getFileSystemManager();
    wx.downloadFile({
      url: app.base.url + '/chinaMap.json',
      success: r => {
        fs.readFile({
          filePath: r.tempFilePath,
          encoding: 'utf8',
          position: 0,
          success(map) {
            json = JSON.parse(map.data || "{}").json || {};
            let data = app.globalData.origin;
            console.log(data.totalDetails)
            that.setData({
              detailList: data.totalDetails || [],
              getData: {
                platform: data.platform || [],
                map: data.map || [],
                total: data.total || { all: 0, sensitive: 0 },
                ActivityAuthor: (data.ActivityAuthor || []).sort((a, b) => {
                  if (!a.detailUrl) a.detailUrl = app.base.url + '/author/' + a.id + '.json';
                  if (!b.detailUrl) b.detailUrl = app.base.url + '/author/' + b.id + '.json';
                  return b.total - a.total
                }),
                Activity: data.Activity || [],
                character: data.character || { emotion: [], sex: [], feeling: [] }
              },
              ec_map: {
                onInit: that.initChartMap.bind(that),
                show: true
              },
              eclook: {
                onInit: that.initChartLook.bind(that),
                show: true
              },
              portrait: {
                onInit: that.initChartPortrait.bind(that),
                show: true
              },
              height: h,
              width: sys.windowWidth
            }, () => {
              wx.hideLoading()
            })
          },
          fail(res) {
            wx.hideLoading()
          }
        })

      },
      fail() {
        wx.hideLoading()
      }
    })
  },
  loadimg(e) {
    let info = wx.getSystemInfoSync();
    let h = e.detail.height * info.screenWidth / e.detail.width
    this.setData({
      cloud: {
        width: info.screenWidth,
        height: h
      }
    })
  },
  clickTab(e) {
    this.setData({
      tabActive: e.currentTarget.dataset.i
    })
  },
  initChartMap(canvas, width, height, dpr) {
    let D = this.data.getData || {};
    chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    echarts.registerMap('china', json);
    let max = 0;
    let min = Infinity;
    D.map.map(v => {
      max < v.value && (max = v.value);
      min > v.value && (min = v.value);
    })
    var option = {
      tooltip: {
        show: true,
        formatter: function (res) {
          if (!res.data) return ""
          return res.data.name + ":" + (res.data.value || 0)
        }
      },
      visualMap: {
        show: false,
        min,
        max,
        inRange: {
          color: ['rgba(118,172,255, .2)', 'orangered']
        }
      },
      series: [
        {
          type: "map",
          mapType: "china",
          geoIndex: 0,
          zppm: 1.25,
          label: {
            normal: {
              show: true,
              formatter: function (r) {
                let d = r.data || {}
                if (!d.name) return "";
                var out = d.value;
                if (out >= 100000000) {
                  out = (out / 100000000).toFixed(2) + '亿';
                } else if (out >= 10000) {
                  out = (out / 10000).toFixed(2) + '万';
                }
                return d.name + ":" + out
              }
            },
            emphasis: {
              show: false
            }
          },
          scaleLimit: {
            //滚轮缩放的极限控制
            min: 1.25,
            max: 2,
          },
          itemStyle: {
            normal: {
              borderColor: "#76acff",//每个区域的边框色
              areaColor: 'rgba(118,172,255, 0)'//区域背景色
            },
          },
          data: D.map || []
        }
      ]
    };
    chart.setOption(option);
    return chart;
  },
  initChartLook(canvas, width, height, dpr) {
    let D = this.data.getData || {};
    D = D.platform || [];
    let source = [];
    let pie = [];
    D.map(v => {
      if (!source[0]) {
        source[0] = ['product', ...(v.subGroups || []).map(val => val.groupValue)]
      }
      let item = [v.groupValue];
      let p = 0;
      (v.subGroups || []).map(val => {
        item.push(val.total);
        p += val.total;
      })
      pie.push({
        name: v.groupValue,
        value: p
      });
      source.push(item)
    })
    chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chart);
    let p = 0;
    var option = {
      legend: {},
      tooltip: {
        trigger: 'axis',
        showContent: false
      },
      dataset: {
        source
      },
      xAxis: { type: 'category' },
      yAxis: { gridIndex: 0 },
      grid: [{ top: '55%' }],
      title: [
        {
          text: '发稿量',
          left: 'center',
          top: '10%',
          textStyle: {
            color: '#031f2d',
            fontSize: 12,
            align: 'center'
          }
        },
        {
          text: '发稿趋势图',
          left: 'center',
          top: '50%',
          textStyle: {
            color: '#031f2d',
            fontSize: 12,
            align: 'center'
          }
        },
      ],
      series: [
        {
          type: 'line', lineStyle: { width: 1 }, smooth: true, seriesLayoutBy: 'row',
          symbolSize: p,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: 'rgba(84,112,198, .4)' },
                { offset: 1, color: 'rgba(84,112,198, 0)' },
              ]
            )
          }
        },
        {
          type: 'line', lineStyle: { width: 1 }, smooth: true, seriesLayoutBy: 'row',
          symbolSize: p,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: 'rgba(145,204,117, .4)' },
                { offset: 1, color: 'rgba(145,204,117, 0)' },
              ]
            )
          }
        },
        {
          type: 'line', lineStyle: { width: 1 }, smooth: true, seriesLayoutBy: 'row',
          symbolSize: p,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: 'rgba(250,200,88, .4)' },
                { offset: 1, color: 'rgba(250,200,88, 0)' },
              ]
            )
          }
        },
        {
          type: 'line', lineStyle: { width: 1 }, smooth: true, seriesLayoutBy: 'row',
          symbolSize: p,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: 'rgba(238,102,102, .4)' },
                { offset: 1, color: 'rgba(238,102,102, 0)' },
              ]
            )
          }
        },
        {
          type: 'line', lineStyle: { width: 1 }, smooth: true, seriesLayoutBy: 'row',
          symbolSize: p,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: 'rgba(115,192,222, .4)' },
                { offset: 1, color: 'rgba(115,192,222, 0)' },
              ]
            )
          }
        },
        {
          type: 'line', lineStyle: { width: 1 }, smooth: true, seriesLayoutBy: 'row',
          symbolSize: p,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: 'rgba(59,162,114, .4)' },
                { offset: 1, color: 'rgba(59,162,114, 0)' },
              ]
            )
          }
        },
        {
          type: 'line', lineStyle: { width: 1 }, smooth: true, seriesLayoutBy: 'row',
          symbolSize: p,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: 'rgba(252,132,82, .4)' },
                { offset: 1, color: 'rgba(252,132,82, 0)' },
              ]
            )
          }
        },
        {
          type: 'pie',
          id: 'pie1',
          radius: ['15%', '30%'],
          center: ['50%', '30%'],
          emphasis: { focus: 'data' },
          data: pie,
          itemStyle: {
            borderRadius: 3,
            borderColor: '#fff',
            borderWidth: 1
          },
          label: {
            formatter: '{b}: {d}%'
          },
          encode: {
            itemName: 'product',
            value: '2012',
            tooltip: '2012'
          }
        }
      ]
    };
    chart.setOption(option);
    return chart;
  },
  initChartPortrait(canvas, width, height, dpr) {
    let D = this.data.getData || { character: {} };
    const { emotion, feeling, sex } = D.character;
    chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    var option = {
      title: [
        {
          text: '情绪分布',
          left: 'center',
          top: 10,
          textStyle: {
            color: '#031f2d',
            fontSize: 12,
            align: 'center'
          }
        },
        {
          text: '情感属性，性别占比',
          left: 'center',
          top: '50%',
          textStyle: {
            color: '#031f2d',
            fontSize: 12,
            align: 'center'
          }
        },
      ],
      series: [
        {
          type: 'pie',
          id: 'pie1',
          radius: ['15%', '30%'],
          center: ['50%', '30%'],
          data: emotion || [],
          itemStyle: {
            borderRadius: 3,
            borderColor: '#fff',
            borderWidth: 1
          },
          label: {
            formatter: '{b}: {d}%'
          },
          encode: {
            itemName: 'product',
            value: '2012',
            tooltip: '2012'
          }
        },
        {
          type: 'pie',
          selectedMode: 'single',
          top: '55%',
          radius: [0, '50%'],
          label: {
            position: 'inner',
            formatter: "{b}\n{d}%",
            fontSize: 12,
          },
          labelLine: {
            show: false
          },
          data: sex || []
        },
        {
          type: 'pie',
          top: '55%',
          radius: ['60%', '75%'],
          labelLine: {
            length: 30,
          },
          label: {
            alignTo: 'edge',
            formatter: "{b}\n{d}%",
            minMargin: 5,
            edgeDistance: 20,
            lineHeight: 20,
            rich: {
              time: {
                fontSize: 10,
                color: '#999'
              }
            }
          },
          labelLine: {
            length: 15,
            length2: 20,
            maxSurfaceAngle: 80
          },
          data: feeling || []
        }
      ]
    };
    chart.setOption(option);
    return chart;
  },
  showDetail: function (e) {
    console.log(e.currentTarget.dataset.title)
    this.setData({
      diglogTitle: (e.currentTarget.dataset.title || "")
    })
  }
});
