/** 雷达图 */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import TableChart from './TableChart'

class RadarChart extends Component {
  // 初始化 option
  initOption = () => {
    const { data, radar, titleText, saveImgName } = this.props

    // 设置图例的默认选中，如果没有 Selected 属性，则默认为 true，即默认选中
    const legendData = []
    const selectedData = {}
    data.forEach(item => {
      legendData.push({ name: item.Name, icon: 'roundRect' })
      selectedData[item.Name] = item.LegendSelected !== undefined ? item.LegendSelected : true
    })

    return {
      title: {
        text: titleText,
        textStyle: {
          fontWeight: 'normal',
          fontSize: 16
        },
        left: 'center',
        top: 0
      },
      legend: {
        top: '6%',
        left: 'center',
        textStyle: {
          color: '#333333'
        },
        data: legendData,
        selected: selectedData
      },
      radar: radar.map(item => ({
        name: { color: '#000000' },
        nameGap: 8,
        center: ['50%', '60%'],
        radius: '60%',
        indicator: item.IndiCator.map(({ Text: text, Max: max }) => ({ text, max }))
      })),
      tooltip: {
        trigger: 'item'
      },
      toolbox: {
        show: true,
        orient: 'vertical',
        right: 0,
        top: 'center',
        itemSize: 12,
        feature: {
          restore: { show: true },
          saveAsImage: { show: true, name: saveImgName || titleText }
        }
      },
      series: []
    }
  }

  // 生成 echarts 所需要 option
  getOption = () => {
    const option = this.initOption()

    // 组装 option.series 数据
    const { data } = this.props
    data.forEach(item => {
      const dataseries = {
        name: item.Name,
        type: 'radar',
        // itemStyle 会同时设置 lineStyle 的 color 配置
        itemStyle: {
          color: item.Color || ''
        },
        data: [{
          areaStyle: { opacity: 0.2 },
          value: item.Data.map(element => element.Value)
        }]
      }
      option.series.push(dataseries)
    })

    return option
  }

  render () {
    const { loading, style } = this.props
    return (
      <TableChart
        type={3}
        option={this.getOption()}
        loading={loading}
        style={style}
      />
    )
  }
}

RadarChart.propTypes = {
  data: PropTypes.array,
  radar: PropTypes.array,
  titleText: PropTypes.string,
  saveImgName: PropTypes.string
}

RadarChart.defaultProps = {
  data: [], // 图表数据
  radar: [], // 雷达配置数据
  titleText: '', // 图表 top center 位置的标题
  saveImgName: '' // 导出为图片的图片文件名称
}

export default RadarChart