'use strict';

import React, { Component } from 'react';
import { Chart, Axis, Geom, Tooltip } from 'bizcharts';
import IceEvents from '@ali/ice-events';
import { Feedback } from '@icedesign/base';
import axios from 'axios';
import { apiList, getUrlParam } from '../utils';
import Loading from '../../../components/Loading';

const baseComponents = {
  ice: '@ali/ice',
  next: '@alife/next',
  mext: '@alife/mext',
};

@IceEvents
export default class ProjectCountChart extends Component {
  state = {
    chartData: null,
  };

  componentDidMount() {
    const type = getUrlParam('type') || 'ice';
    this.fetchData(baseComponents[type]);
  }

  fetchData = (baseComponent) => {
    const d = new Date();
    const endDate = +d;
    const startDate = +new Date(d.getFullYear(), d.getMonth() - 5, d.getDate());

    axios
      .get(apiList.getTrendingData, {
        params: {
          type: 'month',
          endDate,
          startDate,
          baseComponent,
          appId: 'ice-site',
        },
      })
      .then((response) => {
        const { data = [] } = response.data;

        const newData = data
          .map((item, idx) => {
            return {
              count: item.addedCount,
              month: `${new Date(item.endDate).getMonth() + 1}月`,
            };
          })
          .reverse();

        this.setState({
          chartData: newData,
        });
      })
      .catch((err) => {
        Feedback.toast.error(err.message);
      });
  };

  render() {
    const { chartData } = this.state;

    const cols = {
      count: { min: 0 },
      month: { range: [0, 1] },
    };

    if (!chartData) {
      return (
        <div style={{ height: '500px' }}>
          <Loading />
        </div>
      );
    }

    return (
      <Chart
        height={500}
        data={chartData}
        scale={cols}
        padding={[40, 60, 70, 60]}
        forceFit
      >
        <Axis name="month" />
        <Axis name="count" />
        <Tooltip crosshairs={{ type: 'y' }} />
        <Geom type="line" position="month*count" size={2} />
        <Geom
          type="point"
          position="month*count"
          size={4}
          shape="circle"
          style={{ stroke: '#fff', lineWidth: 1 }}
        />
      </Chart>
    );
  }
}
