import React from 'react';
import { useRequest } from 'umi';
import { Tabs, DatePicker } from 'antd';
import 'echarts/lib/chart/line';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/grid';
import 'echarts/lib/component/legend';
import get from 'lodash/get';
import map from 'lodash/map';
import isNumber from 'lodash/isNumber';
import moment from 'moment';
import AntdModal from '../../components/AntdModal';
import Select from '../../components/Select';
import Container from '../../components/Container';
import EnergyChart from '../EnergyChart';
import RealData from './RealData';
import ChartPeak from './ChartPeak';
import ChartLine from '../ChartLine';
import * as services from '../../services';
import * as _ from 'lodash';
import styles from './index.less';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const REAL_DATA = 'REAL_DATA';
const ENERGY_CHART = 'ENERGY_CHART';
const toPercent = val => (isNumber(val) ? val * 100 : val);

export default React.memo(function SmartMonitor(props) {
  const { customerInfo } = props
  const number = get(customerInfo, 'number');
  const stationId = '79248';
  const { data: points, loading: pointsLoading } = useRequest(
    () => services.getMonitorPoints(number, stationId),
    {
      formatResult(res) {
        return get(res, 'data.list', []);
      },
      ready: number
    },
  );

  const [point, setPoint] = React.useState(null);
  const [tab, setTab] = React.useState(REAL_DATA);
  const [hackValue, setHackValue] = React.useState();
  const [date, setDate] = React.useState([
    moment(moment().format('YYYY-MM-DD')),
    moment(),
  ]);

  const onChange = item => {
    setPoint(item.value);
  };

  React.useEffect(() => {
    if (points && points.length) {
      setPoint(points[0].line);
    }
  }, [points]);

  const paramProps = {
    number,
    stationId,
    point,
    startTime: date[0] ? `${date[0].format('YYYY-MM-DD')} 00:00:00` : null,
    endTime: date[1] ? `${date[1].format('YYYY-MM-DD')} 23:59:59` : null,
  };

  const disabledDate = current => {
    const limit = 30;
    const tooLate = date[0] && current.diff(date[0], 'days') > limit;
    const tooEarly = date[1] && date[1].diff(current, 'days') > limit;

    return tooEarly || tooLate || current > moment().endOf('day');
  };

  const onOpenChange = open => {
    if (open) {
      setHackValue([]);
      setDate([]);
    } else {
      setHackValue(undefined);
    }
  };
  const hiddenDate = tab === REAL_DATA || tab === ENERGY_CHART;

  const renderPayloadNote = ([chartData]) => {
    const data = get(chartData, 'data', []);
    const time = get(chartData, 'time', []);
    const max = _.max(data) || '-';
    let ave = _.mean(data);
    ave = ave ? ave.toFixed(2) : '-';
    const maxTime = time[data.indexOf(max)] || '-';
    return (
      <div style={{ marginTop: -20 }}>
        <span>最大负荷：{max} KW </span>
        <span>时间：{maxTime} </span>
        <span>平均负荷：{ave} KW</span>
      </div>
    );
  };

  return (
    // <AntdModal title="智能监控" className={styles.table} onClose={onClose}>
    <div className={styles.table}>
      <div className={styles.subtitleBox}>
        <div className={styles.subtitle}></div>
        <Select
          className={styles.select}
          onSelect={onChange}
          options={map(points, item => ({
            label: item.name,
            value: item.line,
          }))}
          value={point}
        />
      </div>
      <div
        className={styles.date}
        style={{ visibility: hiddenDate ? 'hidden' : 'visible' }}
      >
        <div>选择时间：</div>
        <RangePicker
          allowClear={false}
          onChange={setDate}
          onOpenChange={onOpenChange}
          onCalendarChange={val => setDate(val)}
          disabledDate={disabledDate}
          value={hackValue || date}
          dropdownClassName={styles.datepicker}
          bordered={false}
        />
      </div>
      <Container loading={pointsLoading} empty={!get(points, 'length')}>
        <Tabs onChange={val => setTab(val)}>
          <TabPane tab="实时监控数据" key={REAL_DATA}>
            <RealData {...paramProps} load={tab === REAL_DATA} />
          </TabPane>
          <TabPane tab="能耗曲线" key={ENERGY_CHART}>
            <EnergyChart {...paramProps} load={tab === ENERGY_CHART} />
          </TabPane>
          <TabPane tab="电压" key="u">
            <ChartLine
              {...paramProps}
              unit="V"
              min={215}
              load={tab === 'u'}
              fields={[
                {
                  name: 'A相电压',
                  value: 'ua',
                },
                {
                  name: 'B相电压',
                  value: 'ub',
                },
                {
                  name: 'C相电压',
                  value: 'uc',
                },
              ]}
            />
          </TabPane>
          <TabPane tab="电流" key="a">
            <ChartLine
              {...paramProps}
              unit="A"
              load={tab === 'a'}
              fields={[
                {
                  name: 'A相电流',
                  value: 'ia',
                },
                {
                  name: 'B相电流',
                  value: 'ib',
                },
                {
                  name: 'C相电流',
                  value: 'ic',
                },
              ]}
            />
          </TabPane>
          <TabPane tab="MD" key="md">
            <ChartLine
              {...paramProps}
              unit="KW"
              load={tab === 'md'}
              fields={[
                {
                  name: '有功需量',
                  value: 'px',
                },
              ]}
            />
          </TabPane>
          <TabPane tab="负荷" key="payload">
            <ChartLine
              {...paramProps}
              unit="KW"
              load={tab === 'payload'}
              fields={[
                {
                  name: '负荷',
                  value: 'psum',
                },
              ]}
              renderBottom={renderPayloadNote}
            />
          </TabPane>
          <TabPane tab="变压器负载率" key="lb">
            <ChartLine
              {...paramProps}
              unit="%"
              load={tab === 'lb'}
              fields={[
                {
                  name: '变压器负载率',
                  value: 'p_rate',
                },
              ]}
              formatter={v => toPercent(v)}
            />
          </TabPane>
          <TabPane tab="功率因数" key="num">
            <ChartLine
              {...paramProps}
              unit="A"
              min={0.7}
              load={tab === 'num'}
              fields={[
                {
                  name: 'A相功率因数',
                  value: 'pfa',
                },
                {
                  name: 'B相功率因数',
                  value: 'pfb',
                },
                {
                  name: 'C相功率因数',
                  value: 'pfc',
                },
                {
                  name: '总功率因数',
                  value: 'pfsum',
                },
              ]}
            />
          </TabPane>
          <TabPane tab="峰平谷" key="peak">
            <ChartPeak {...paramProps} load={tab === 'peak'} />
          </TabPane>
        </Tabs>
      </Container>
    </div>
  );
});
