import React from 'react';
import ReactEchartsCore from 'echarts-for-react/lib/core';
import echarts from 'echarts/lib/echarts';
import { useRequest } from 'umi';
import { connect } from 'dva';
import get from 'lodash/get';
import moment from 'moment';
import isEmpty from 'lodash/isEmpty';
import * as services from '../../services';
import Container from '../../components/Container';
import './index.less';
import { DoubleRightOutlined } from '@ant-design/icons';
import { Collapse } from 'antd';

const { Panel } = Collapse;
const text = val => (val ? val.toFixed(2) : '-');

const areaColor = [
  'rgba(255, 64, 65, .2)',
  'rgba(14, 244, 245, .2)',
  'rgba(255, 174, 50, .2)',
  'rgba(12, 235, 163, .2)',
];

const getOption = (data = [], time) => {
  const date = get(data, '[0].time', []);
  const startDate = moment(date[0]);
  const dateCount = date.length;
  const endDate = moment(date[dateCount - 1]);
  const diff = endDate.diff(startDate, 'days');
  const option = {
    title: {
      text: '功率、负载趋势图',
      textStyle: {
        color: '#ffffff',
        fontSize: 16,
      },
    },
    legend: {
      data: ['负载','功率'],
      left: 150,
      icon: 'rect',
      itemWidth: 15,
      itemHeight: 3,
      textStyle: {
        color: '#ffffff',
      },
    },
    color: [
      'rgba(255, 64, 65, .8)',
      'rgba(14, 244, 245, .8)',
      'rgba(255, 174, 50, .8)',
      'rgba(12, 235, 163, .8)',
    ],
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: '2%',
      right: 20,
      bottom: 20,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      // name: '时间',
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#ffffff',
        },
      },
      axisLabel: {
        formatter: function(value, index) {
          const momentValue = moment(value);
          return `${momentValue.format('HH:mm')}`;
        },
        // interval: 11,
      },
      data: time,
    },
    yAxis: [
      {
        type: 'value',
        name: 'kW',
        axisLine: {
          lineStyle: {
            color: '#ffffff',
          },
        },
        splitLine: {
          lineStyle: {
            color: '#222E34',
          },
        },
      },
      {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%',
        },
        axisLine: {
          lineStyle: {
            color: '#ffffff',
          },
        },
        splitLine: {
          lineStyle: {
            color: '#222E34',
          },
        },
      },
    ],
    series: [
      {
        type: 'line',
        yAxisIndex: 1,
        showSymbol: false,
        smooth: false,
        name: '负载',
        data: data[0],
      },
      {
        type: 'line',
        yAxisIndex: 0,
        showSymbol: false,
        smooth: false,
        name: '功率',
        data: data[1],
        // tooltip: {
        //   formatter: '{a}:'
        // }
      },
    ],
  };
  return option;
};

export default connect(({ screen, overview }) => ({
  area: screen.area,
  sumPayload: overview.sumPayload,
  sumPower: overview.sumPower,
}))(React.memo(function PowerPayload(props) {
  const { area, sumPower, sumPayload } = props;
  const date = moment()
  // .subtract(1, 'days')
  const chart = [[], []]
  const { data, loading } = useRequest(
    () => {
      return services.getPayloadData({
        startTime: `${date.format('YYYY-MM-DD')} 00:00:00`,
        endTime: `${date.format('YYYY-MM-DD')} 23:59:59`,
        province: area[0],
        city: area[1],
      });
    },
    {
      formatResult(res) {
        return get(res, 'data.list', []);
      },
      refreshDeps: [area],
    },
  );

  const icon = ({ isActive }) => {
    const style = isActive
      ? { transform: 'rotate(90deg)' }
      : { transform: 'rotate(-90deg)' };
    return <DoubleRightOutlined style={style} />;
  };
  const time = []

  data && data.map((item) => {
    chart[0].push(text(item.load_rate))
    chart[1].push(text(item.power))
    time.push(item.tm)
  })

  return (
    <Collapse
      defaultActiveKey={['1']}
      ghost
      className="power-content"
      expandIcon={icon}
    >
      <Panel header="" key="1">
        <Container loading={loading} empty={isEmpty(chart)}>
          <div>
            <div className="power-content-count">
              <div>
                <label>实时总功率（kW）：</label>
                <span>{text(sumPower)}</span>
              </div>
              <div>
                <label>总负载率（%）：</label>
                <span>{text(sumPayload)}</span>
              </div>
            </div>
            <ReactEchartsCore
              option={getOption(chart, time)}
              echarts={echarts}
              notMerge={true}
              lazyUpdate={true}
            />
          </div>
        </Container>
      </Panel>
    </Collapse>
  );
}));
