import React, { Component } from 'react';
// 引入high chart
import Highcharts from 'highcharts/highstock';
// 地图模块
import HighchartsMap from 'highcharts/modules/map';
// import theme from '../theme/gray';
import HighchartsMore from 'highcharts/highcharts-more';
import HighchartsDL from 'highcharts/modules/exporting';
import HighchartsAnnotations from 'highcharts/modules/annotations';
HighchartsAnnotations(Highcharts);
HighchartsDL(Highcharts);
HighchartsMore(Highcharts);
HighchartsMap(Highcharts);

/*
  更多图表类型扩展模块（highcharts-more.js）
  3D 图表模块 （highcharts-3d.js）
  导出功能模块（modules/exporting.js）
  金字塔图表类型（modules/funnel.js）
  钻取功能模块（modules/drilldown.js）
  数据加载功能模块（modules/data.js）
*/
// Highstock 或 Highmaps 不在本模块范围内
// 详见: https://www.hcharts.cn/docs/install-from-npm
// 引入主题
 // import theme from '../theme/theme1';
 // import theme from  '../theme/dark-blue';
// 更改主题
// Highcharts.setOptions(theme);
// 国际化
Highcharts.setOptions({
  lang: {
    contextButtonTitle: "图表导出菜单",
    decimalPoint: ".",
    downloadJPEG: "下载JPEG图片",
    downloadPDF: "下载PDF文件",
    downloadPNG: "下载PNG文件",
    downloadSVG: "下载SVG文件",
    drillUpText: "返回 {series.name}",
    loading: "加载中",
    months: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
    noData: "没有数据",
    numericSymbols: ["千", "兆", "G", "T", "P", "E"],
    printChart: "打印图表",
    resetZoom: "恢复缩放",
    resetZoomTitle: "恢复图表",
    shortMonths: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
    thousandsSep: ",",
    shortWeekdays: ['周天', '周一', '周二', '周三', '周四', '周五', '周六'],
    weekdays: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"]
  }
});
// 图标容器
const chartContainer = {};
// 对象转化为url参数
const urlEncode = function (param, key, encode) {
  if (param == null) return '';
  let paramStr = '';
  const t = typeof (param);
  if (t === 'string' || t === 'number' || t === 'boolean') {
    paramStr += `&${key}=${((encode === null || encode) ? encodeURIComponent(param) : param)}`;
  } else {
    for (let i in param) {
      const k = key == null ? i : key + (param instanceof Array ? `[${i}]` : `.${i}`);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
};

class AdminChart extends Component {
  constructor() {
    super();
    this.renderChart = this.renderChart.bind(this);
  }
  componentWillMount() {
    chartContainer[this.props.id] = React.createElement('div', {id: this.props.id});
  }
  componentDidMount() {
    let { param, url, method } = this.props.fetch;
    const parameters = urlEncode(param).replace('&', '?');
    if (param) {
      url += method.toUpperCase() === 'GET' ? parameters : '';
    }
    fetch(
      url,
      {
        credentials: 'include',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        method: method,
        body: method === 'POST' ? JSON.stringify(param) : null, // 搜素方式待定
      })
      .then(response => response.json())
      .then((data) => {
        this.renderChart(this.props.fetch.catchData(data));
      })
      .catch(error => {
        console.log(error);
      });
  }
  renderChart(data) {
    const {
      title,
      subtitle,
      xAxis,
      yAxis,
      legend,
      responsive,
      colors,
      tooltip,
      plotOptions,
      series,
      chart,
      rangeSelector
    } = this.props;
    // 混合y轴
    let yAxis_conver = [];
    if (yAxis &&yAxis.length > 1) {
      yAxis.map((item) => {
        yAxis_conver.push(Object.assign({}, item));
      });
    } else {
      yAxis_conver = Object.assign({}, yAxis);
    }
    // 数据列生成
    /*
    * 由数据生成series
    * 遍历json中数据数组data,生成series(对象构成的数组)
    * 用户自定义函数,过滤特殊数据生成mark点等
    * */
    // 数据列容器
    let seriesContainer = [];
    // 遍历json数据
    if (this.props.series.convert(data).type === 'pie') {
      seriesContainer.push(Object.assign({},{data:data},series))
    }else{
      data.map((item) => {
        seriesContainer.push(Object.assign({},this.props.series.convert(item),series));
      })
    }
    const config = {
      chart: Object.assign({},{type:this.props.series.convert(data).type === 'pie'?'pie':null},chart),
      // 标题
      title: Object.assign({}, title),
      subtitle: Object.assign({}, subtitle),
      // 坐标轴
      xAxis: Object.assign({}, xAxis),
      yAxis: yAxis_conver,
      // 图例
      legend: Object.assign({},{enabled:false}, legend),
      // 响应式
      responsive: Object.assign({}, responsive),
      // 颜色
      colors: Object.assign({},['#3c8dbc', '#f39c12', '#d2d6de', '#00c0ef', '#f56954', '#00a65a'], colors),
      // 数据系统
      series: seriesContainer,
      // 悬浮提示框
      tooltip: Object.assign({}, tooltip),
      // 数据列配置
      plotOptions: Object.assign({}, plotOptions),
      //
      rangeSelector: Object.assign({}, rangeSelector),
      // 版权信息
      credits: {
        enabled: false
      },
    }
    switch (this.props.category){
      case 'highStock':
        Highcharts.StockChart(this.props.id, config);
        break;
      default :
        Highcharts.chart(this.props.id, config);

    }
  }
  render() {
    return (
      chartContainer[this.props.id]
    );
  }
}
export default AdminChart;
