import React ,{ useEffect, useState } from 'react';
import * as echarts from 'echarts';
import moment from 'moment';
import Axios from 'axios';

function Calendar({ userLogin , time , chooseTime }) {
  const [ endT, setEndT ] = useState("");
  const [ baginT, setBaginT ] = useState("");

  useEffect(()=>{
    if(time){
      let e,b = "";
      if(parseInt(time,0) === parseInt(moment().get('year'),0)){
        let y = moment().get('year');
        let m = moment().get('month');
        let d = moment().get('date');
        e = `${y}-${m+1}-${d}`;
        b = `${y-1}-${m+1}-${d}`;
      }else{
        e = `${time}-12-31`;
        b = `${time}-01-01`;
      }
      setEndT(e);
      setBaginT(b);
    }
  },[time])

  useEffect(()=>{
    if(baginT && endT){
      getData();
    }
  },[baginT,endT])

  function getData() {
    const url = `/users/${userLogin}/headmaps.json`;
    Axios.get(url).then(result=>{
      if(result && result.data){
        let m = [];
        let flag = true;
        if(result.data.headmaps && result.data.headmaps.length>0){
          m = result.data.headmaps;
          flag = true;
        }else{
          var date = +echarts.number.parseDate(baginT);
          let d = timestampToTime(date);
          m=[{
            contributions:"",date:d
          }]
          flag = false;
        }
        m.sort(compare('contributions'));
        let max = m[m.length -1].contributions;

        Init(m,max,flag);
      }
    }).catch(error=>{})
  }

  function compare(property){
    return function(a,b){
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  }

  function getVirtulData(data) {
    var date = +echarts.number.parseDate(baginT);
    var end = +echarts.number.parseDate(endT);
    var dayTime = 3600 * 24 * 1000;
    var array = [];
    for (var time = date; time <= end; time += dayTime) {
      let stamp = timestampToTime(time);
      let stampFilter = data.filter(i=>i.date === stamp);
      if(stampFilter && stampFilter.length > 0){
        array.push([stampFilter[0].date,stampFilter[0].contributions]);
      }else{
        array.push([stamp,0]);
      }
    }
    return array;
  }

  function timestampToTime(timestamp) {
    var date = new Date(timestamp);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return Y+M+D;
  }

  function Init(data,max,flag) {
    var huan_val = document.getElementById("Calendar");
    var myEcharts = echarts.init(huan_val);
    let option = {
      title: {
        show:false
      },
      tooltip: {
        formatter:function(params){
          return params.data[0] + ': ' + params.data[1] + '个贡献';
        }
      },
      visualMap: {
        min: 0,
        max: max,
        type: 'piecewise',
        orient: 'horizontal',
        left: 'center',
        bottom: 40,
        inRange:{
          color:flag ? ['#fafafa', '#216e39'] :['#fff','#fff']
        },
        show:flag
      },
      calendar: {
        top: 50,
        left: 40,
        right: 30,
        cellSize: ['auto', 13],
        range: [baginT, endT],
        splitLine:{
            show:false,
            lineStyle:{
              color:"#fff",
              width:1,
              type:"solid"
            }
        },
        itemStyle: {
          borderWidth: 0.5
        },
        yearLabel: {show: false},
        monthLabel:{
          nameMap:"cn"
        },
        dayLabel:{
          nameMap:"cn",
          firstDay:1
        }
      },
      series: {
        type: 'heatmap',
        coordinateSystem: 'calendar',
        data: getVirtulData(data)
      }
    };
    myEcharts.setOption(option);
    myEcharts.on('click', function (params) {
      chooseTime(params.data);
    });
  }


  return(
    <div id="Calendar" style={{height:"210px"}}></div>
  )
}
export default Calendar;