import { CSSProperties } from 'react';
import * as echarts from 'echarts';
import { BarSeriesOption } from 'echarts';
import { useRef, useEffect } from 'react';
import { isEmpty, merge } from 'lodash';
import { CHARTS_COLORS, LOADING_COLOR } from './type';
import { useSize } from 'ahooks';
// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = echarts.ComposeOption<BarSeriesOption>;

export interface BarProps {
	color?: Array<string>;
	category: Array<string | number>;
	series: Array<any>;
	loading?: boolean;
	style?: CSSProperties;
	options?: ECOption;
	onDownCallBack?: any;
	loadingType?: any;
}

export function ChartsBar(props: BarProps) {
	const {
		color = CHARTS_COLORS,
		category = [],
		series,
		loading,
		style,
		options,
		onDownCallBack,
		loadingType = { color: LOADING_COLOR },
	} = props;

	const contentEle = useRef<any>();

	const chartRef = useRef<any>();

	const defaultOptions: ECOption = merge(
		{
			color: color,
			title: {
				show: false,
			},
			tooltip: {
				trigger: 'axis',
			},
			legend: {
				show: true,
				itemWidth: 10,
				itemHeight: 10,
				left: 'right',
				top: 0,
			},
			grid: {
				top: 30,
				left: 0,
				right: 0,
				bottom: 0,
				containLabel: true,
			},
			xAxis: {
				type: 'category',
				data: category,
				axisPointer: {
					type: 'shadow',
				},
			},
			yAxis: {
				type: 'value',
			},
		},
		options,
	);
	const responsive = useSize(contentEle.current);

	useEffect(() => {
		chartRef.current?.resize();
	}, [JSON.stringify(responsive)]);

	useEffect(() => {
		if (!Boolean(chartRef.current)) {
			chartRef.current = echarts.init(contentEle.current);
		}

		if (loading) {
			chartRef.current.showLoading(Object.assign({ text: '' }, loadingType));
			return;
		} else {
			chartRef.current.hideLoading();
		}

		if (!isEmpty(series)) {
			const options = {
				...defaultOptions,
				series: series.map((item) => ({
					type: 'bar',
					data: item.data,
					barMaxWidth: 30,
					...item,
				})),
			};
			chartRef.current.setOption(options);
			if (onDownCallBack) {
				chartRef.current.on('click', function (params: any) {
					onDownCallBack(chartRef.current, params, options);
				});
			}
		} else {
			chartRef.current.setOption(options);
		}
	}, [series, loading]);
	return (
		<div ref={contentEle} style={{ width: '100%', height: '100%', ...style }} />
	);
}
