import { computed, ref, watch } from 'vue';
import { useDark } from '@vueuse/core';
import { useTheme } from '/#/theme';
import { useCool } from '/@/cool';
import { emptyScreen, type ScreenData, type TimeRange } from '../data/screen';

const sharedTimeRange = ref<TimeRange>('month');
const screenData = ref<ScreenData>(emptyScreen());
const loading = ref(false);
const loadError = ref('');

export function provideScreenTime() {
	return sharedTimeRange;
}

export function useScreenTime() {
	return sharedTimeRange;
}

export function useScreenData() {
	return {
		timeRange: sharedTimeRange,
		data: screenData,
		loading,
		loadError,
		reload: () => loadImpl()
	};
}

let inited = false;
let loadImpl: () => Promise<void> = async () => {};

export function useScreenLoader() {
	const { service } = useCool();

	async function load() {
		loading.value = true;
		loadError.value = '';
		try {
			const payload = { range: sharedTimeRange.value };
			const screen = service.report?.screen;
			const res: ScreenData = screen?.query
				? await screen.query(payload)
				: await service.request({
						url: 'admin/report/screen/query',
						method: 'POST',
						data: payload
				  });
			const fallback = emptyScreen(sharedTimeRange.value);
			screenData.value = {
				...fallback,
				...(res || {}),
				kpis: { ...fallback.kpis, ...(res?.kpis || {}) },
				trend: { ...fallback.trend, ...(res?.trend || {}) },
				pointFlow: { ...fallback.pointFlow, ...(res?.pointFlow || {}) },
				ordersByType: { ...fallback.ordersByType, ...(res?.ordersByType || {}) }
			};
		} catch (e: any) {
			screenData.value = emptyScreen(sharedTimeRange.value);
			loadError.value = e?.message || '驾驶舱接口调用失败';
		} finally {
			loading.value = false;
		}
	}

	loadImpl = load;

	if (!inited) {
		inited = true;
		watch(sharedTimeRange, () => load());
	}

	load();

	return { load, loading, loadError };
}

export function useChartTheme() {
	const isDark = useDark();
	const theme = useTheme();

	const textColor = computed(() => (isDark.value ? '#e5e7eb' : '#334155'));
	const mutedColor = computed(() => (isDark.value ? '#94a3b8' : '#64748b'));
	const splitColor = computed(() => (isDark.value ? '#334155' : '#e2e8f0'));
	const tooltipBg = computed(() => (isDark.value ? '#0f172a' : '#ffffff'));
	const primary = computed(() => theme.color || '#16a34a');

	function baseGrid() {
		return { containLabel: true, left: 12, right: 16, top: 28, bottom: 8 };
	}

	function axisStyle() {
		return {
			axisLine: { show: false },
			axisTick: { show: false },
			splitLine: { show: false },
			axisLabel: { color: mutedColor.value }
		};
	}

	function tooltip() {
		return {
			backgroundColor: tooltipBg.value,
			borderColor: splitColor.value,
			textStyle: { color: textColor.value }
		};
	}

	return {
		isDark,
		textColor,
		mutedColor,
		splitColor,
		tooltipBg,
		primary,
		baseGrid,
		axisStyle,
		tooltip
	};
}
