import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AmosEcharts from 'amos-viz/lib/echarts';
import { ScreenCard, withSubscribeMQTT } from './../../common';
import { message, eventConsts } from './../../eventConsts';

import {
  queryRiskSourceRpnCountAction
} from './../api';

const labelOption = {
  normal: {
    show: true,
    position: 'right',
    distance: 5,
    align: 'left',
    formatter: '{c}',
    color: 'white'
  }
};

/**
 * 风险度（RPN）top10
 * @class RiskDegree
 * @extends {Component}
 */
@withSubscribeMQTT({ topic: 'meteorological' })
class RiskDegree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      riskNameList: [],
      rpniData: [],
      rpnrData: [],
      code: (message.getStorageData(eventConsts.STATION_CODE) || {}).message
    };
  }

  componentDidMount() {
    message.storageSubscribe(eventConsts.STATION_CODE, (data) => {
      console.log('rpn右侧');
      console.log(data);
      this.setState({
        riskNameList: [],
        rpniData: [],
        rpnrData: [],
        code: data.message || ''
      },() => this.onRequest());
    });
    this.onRequest();
  }

  onRequest = () => {
    // const code = '101';
    const { code } = this.state;
    queryRiskSourceRpnCountAction(code).then(
      data => {
        let riskNameList = [];
        let rpniData = [];
        let rpnrData = [];
        // eslint-disable-next-line array-callback-return
        data && data.map(e => {
          riskNameList.push(e.name);
          rpniData.push(e.rpni);
          rpnrData.push(e.rpn);
        });
        this.setState({
          riskNameList: riskNameList.reverse(),
          rpniData: rpniData.reverse(),
          rpnrData: rpnrData.reverse()
        });
      },
      err => {
        console.log(err);
      }
    );
  }

  /**
   * 轴文字换行
   */
  textStytle = (params) => {
    let newParamsName = ''; // 最终拼接成的字符串
    let paramsNameNumber = params.length; // 实际标签的个数
    const provideNumber = 5; // 每行能显示的字的个数
    let rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
    /**
     * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
     */
    // 条件等同于rowNumber>1
    if (paramsNameNumber > provideNumber) {
      /** 循环每一行,p表示行 */
      for (let p = 0; p < rowNumber; p++) {
        let tempStr = ''; // 表示每一次截取的字符串
        let start = p * provideNumber; // 开始截取的位置
        let end = start + provideNumber; // 结束截取的位置
        // 此处特殊处理最后一行的索引值
        if (p === rowNumber - 1) {
          // 最后一次不换行
          tempStr = params.substring(start, paramsNameNumber);
        } else {
          // 每一次拼接字符串并换行
          tempStr = `${params.substring(start, end)}\n`;
        }
        newParamsName += tempStr; // 最终拼成的字符串
      }

    } else {
      // 将旧标签的值赋给新标签
      newParamsName = params;
    }
    // 将最终的字符串返回
    return newParamsName;
  }

  textStytle1 = (value) => {
    // eslint-disable-next-line no-magic-numbers
    if (value.length > 3) {
      // eslint-disable-next-line no-magic-numbers
      return `${value.substring(0, 3)}...`;
    } else {
      return value;
    }
  }

  getOptions = () => {
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        textStyle: { // 图例文字的样式
          color: 'white',
          fontSize: 14
        },
        data: [
          {
            name: 'RPNi',
            icon: 'circle'
          },
          {
            name: 'RPNr',
            icon: 'circle'
          }
        ],
        x: 'right',
        top: '20',
        right: '120'
      },
      grid: {
        left: '3%',
        right: '6%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLabel: {
          show: false
        },
        // eslint-disable-next-line no-magic-numbers
        boundaryGap: [0, 0.03],
        splitLine: {
          show: false
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      },
      yAxis: {
        type: 'category',
        axisTick: {
          show: false
        },
        axisLabel: {
          textStyle: {
            color: 'white',
            fontSize: 14
          },
          formatter: value =>  this.textStytle(value)
        },
        data: this.state.riskNameList,
        splitLine: {
          show: false
        },
        axisLine: {
          show: false
        }
      },
      color: ['#35bf73', '#f16060'],
      series: [
        {
          name: 'RPNi',
          type: 'bar',
          label: labelOption,
          data: this.state.rpniData,
          // barGap: 2
          barWidth: 14,
          itemStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#FD7D47'
                  },
                  {
                    offset: 1,
                    color: '#EE6328'
                  }
                ],
                global: false
              },
              // color: ['#3977E6', '#37BBF8'],
              barBorderRadius: 7
            },
            emphasis: {
              barBorderRadius: 7
            }
          }
        },
        {
          name: 'RPNr',
          type: 'bar',
          label: labelOption,
          data: this.state.rpnrData,
          barWidth: 14,
          itemStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#4AEFA0'
                  },
                  {
                    offset: 1,
                    color: '#1E9957'
                  }
                ],
                global: false
              },
              // color: ['#3977E6', '#37BBF8'],
              barBorderRadius: 7
            },
            emphasis: {
              barBorderRadius: 7
            }
          }
        }
      ]
    };
  }

  render() {
    const option = this.getOptions();
    return (
      <ScreenCard wrapperClassName="ccs-long-header" title="风险度(RPN)TOP10">
        <div className="ccs-risk-situation-right-chart">
          <AmosEcharts option={option} />
        </div>
      </ScreenCard>
    );
  }
}

RiskDegree.propTypes = {
  messageFlag: PropTypes.number
};

export default RiskDegree;
