import echarts from 'echarts';
import { isFun, isArray, setNewValue , newlineEcharts } from '../../utils/util';

/*
 * data 需要渲染的数据
 * id 容器id名
 * brNewLine 超出指定长度的文字是否进行换行
 * codeNum 文字超出该长度进行换行
 * clickBack 点击回调函数
 * showTip 是否展示提示
 * title 标题
 * colors 颜色
 * titleStyle 标题配置
 * titlePosition 标题位置
 */ 
const BarVerticalChart = (params)=>{
	const defaultConfig = {
		brNewLine: false,
		codeNum: 5,
		colors: ['#FF7737'],
		showTip: false,
		titlePosition: {
			left: 'auto',
			top: 'auto',
			right: 'auto',
			bottom: 'auto'
		},
		titleStyle: {
			color: '#333',
			fontStyle: 'normal',
			fontWeight: 'normal',
			fontSize: 18
		}
  }
	const {
		data,
		id,
		brNewLine,
		codeNum,
		colors,
		showTip,
		title,
		titleStyle,
		titlePosition,
		clickBack,
		formatFunY,
		formatFunX
	} = params;

	const _brNewLine = brNewLine || defaultConfig.brNewLine;
  const _codeNum = codeNum || defaultConfig.codeNum;
	const _colors = isArray(colors) && colors.length ? colors : defaultConfig.colors;
	const _showTip = showTip || defaultConfig.showTip;
	const _titleStyle = setNewValue(titleStyle, defaultConfig.titleStyle);
	const _titlePosition = setNewValue(titlePosition, defaultConfig.titlePosition);

	let dataX = data.map(item => {
		return isFun(formatFunX) ? formatFunX(item.key) : item.key;
	})
	let dataY = data.map(item => {
		return isFun(formatFunY) ? formatFunY(item.value) : item.value;
	})
	let main = document.getElementById(`${id}`);
	const myChart = echarts.init(main);
	var option = {
    title: {
			text: title,
			show: !!title,
			textStyle: _titleStyle,
			..._titlePosition
		},
    tooltip: {
			show: _showTip,
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
    },
		color: _colors,
		grid: {
			left: '-10%',
			right: '4%',
			bottom: '15%',
			// y:40,
			// y2:40,
			containLabel: true
		},
		xAxis: {
	    type: 'category',
		axisTick: {
			alignWithLabel: true
		},
		axisLine: {
			lineStyle: {
				color: '#fff',
			}
		},
		axisLabel: {
			margin: 20,
			color: '#333'
		},
	    data: dataX
		},
    yAxis: {
			type: 'value',
			axisLabel: {
				margin: 20,
				color: '#fff'
			},
			axisLine: {
				lineStyle: {
					color: '#fff',
				}
			},
			splitLine: {
				show: true,
				lineStyle: {
					color: '#fff'
				}
			}
    },
    series: [
			{
				type: 'bar',
				barWidth : 8,
				label: {
					normal: {
						show: true,
						position: 'top',
						color:'#666666'
					}
				},
				data: dataY
			}
		]
	};
	myChart.on('click', function (params) {
		if(clickBack) {
			clickBack(params);
		}
	})
	if (_brNewLine) {
		option = newlineEcharts(option, _codeNum, 'xAxis');
	}
	myChart.setOption(option);
	myChart.on('click', function (params) {
		if (isFun(clickBack)) {
			clickBack(params);
		}
	})
}
export default BarVerticalChart;