import echarts from 'echarts';
import { isFun, isArray, setNewValue } from '../../utils/util';
/*
 * data 需要渲染的数据
 * id 容器id名
 * title 标题
 * colors 颜色
 * titleStyle 标题配置
 * titlePosition 标题位置
 * showTip 是否展示提示
 * clickBack 点击回调函数
 * legendConfig 图例配置
 * legendIcon 图例图标 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow', 'none', 'image://url'
 * legendText 图例样式字体配置
 */ 
const PieChart = (params)=>{
	const defaultConfig = {
		showTip: false,
		colors: ['#00bfb7','#ff9080','#A276A4','#F36A5A','#CAC12C','#4C5667'],
		titlePosition: {
			left: 'auto',
			top: 'auto',
			right: 'auto',
			bottom: 'auto'
		},
		titleStyle: {
			color: '#333',
			fontStyle: 'normal',
			fontWeight: 'normal',
			fontSize: 18
		},
		legendConfig: {
			type: 'plain',
			orient: 'horizontal'
		},
		legendIcon: 'rect',
		legendText: {
			color: '#333',
			fontStyle: 'normal',
			fontWeight: 'normal',
			fontSize: 12
		}
  }
	const {
		data,
		id,
		colors,
		title,
		showTip,
		titleStyle,
		titlePosition,
		legendConfig,
		legendIcon,
		legendText,
		clickBack
	} = params;

	let newData = data.reduce((item, next) => {
		item.push({
			name: next.key,
			value: next.value
		});
		return item;
	}, []);

	const _showTip = showTip || defaultConfig.showTip;
	const _colors = isArray(colors) && colors.length ? colors : defaultConfig.colors;
	const _titleStyle = setNewValue(titleStyle, defaultConfig.titleStyle);
	const _titlePosition = setNewValue(titlePosition, defaultConfig.titlePosition);
	const _legendConfig = setNewValue(legendConfig, defaultConfig.legendConfig);
	const _legendText = setNewValue(legendText, defaultConfig.legendText);

	let legend = [];
	data.map((it)=>{
		legend.push({
			name: it.key,
			icon: legendIcon || defaultConfig.legendIcon,
			// 设置文本为红色
			textStyle: _legendText
		})
	})

	let main = document.getElementById(`${id}`);
	const myChart = echarts.init(main);
	var option = {
    title: {
			text: title,
			show: !!title,
			textStyle: _titleStyle,
			..._titlePosition
		},
    tooltip: {
			show: _showTip,
			trigger: 'item',
			formatter: '{b} : {c} ({d}%)'
    },
		color: _colors,
    legend: {
			data: legend,
			..._legendConfig
    },
    series: [
			{
				type: 'pie',
				radius: '46%',
				center: ['50%', '40%'],
				data: newData,
				label: {
					lineHeight: 60,
					formatter: '{b}({@2012}):{d}%'
				},
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}
    ]
	};
	myChart.on('click', function (params) {
		if (isFun(clickBack)) {
			clickBack(params);
		}
	})
	myChart.setOption(option);
}
export default PieChart;