import { ref, onMounted } from "vue";
import { getSevenDayApi } from "@/api/ShopContent.ts";
import { getTimeVal, oneDay } from "@/util/tools.ts";



export function SevenDay(businessId: any = '', dayNum: number = 7, showMounted: boolean = true) {
	let DefaultData = [];

	const getSevenDayTime = () => {
		DefaultData = [];
		const Today = getTimeVal();

		for (let i = 0; i < dayNum; i++) {
			const t = getTimeVal({ time: Today - (oneDay * i), format: 'MMDD' });
			DefaultData.unshift(t)
		}
	}


	// 近七日交易趋势
	const DealTrendData = ref(null);
	const DealTrendVo = [
		{
			name: '总交易额',
			data: [],
			color: '#E36868',
			gradientStart: '#E36868',
			gradientEnd: '#E36868'
		},
		{
			name: '预估结算',
			data: [],
			color: '#5CBD76',
			gradientStart: '#5CBD76',
			gradientEnd: '#5CBD76'
		},
		{
			name: '让利金额',
			data: [],
			color: '#6295F2',
			gradientStart: '#6295F2',
			gradientEnd: '#6295F2'
		}
	]
	const getDealTrend = (item : any) => {
		DealTrendVo[0].data.push(item.actualReceivePayment || 0)
		DealTrendVo[1].data.push(item.todaySettlement || 0)
		DealTrendVo[2].data.push(item.businessShouldSubsidy || 0)
	};

	// 近七日订单趋势
	const OrderTrendData = ref(null);
	const OrderTrendVo = [
		{
			name: '在线买单',
			data: [],
			color: '#E36868',
			gradientStart: '#E36868',
			gradientEnd: '#E36868'
		},
		{
			name: '线上商城订单',
			data: [],
			color: '#6295F2',
			gradientStart: '#6295F2',
			gradientEnd: '#6295F2'
		}
	]
	const getOrderTrend = (item : any) => {
		OrderTrendVo[0].data.push(item.onlineOrderNum || 0)
		OrderTrendVo[1].data.push(item.shopOrderNum || 0)
	};


	const getLineChart = async (businessIds: any) => {
		getSevenDayTime();
		try {
			let id = businessIds || businessId;
			const Parmas = { businessId: id, dayNum };
			// console.log(Parmas)
			const { data } = await getSevenDayApi(Parmas);

			const MapData = DefaultData.map(el => {
				const item = data.find(r => getTimeVal({ time: r.dayValue, format: 'MMDD' }) === el)
				if (item) return item
				else return {
					dayValue: el
				};
			})

			MapData.forEach(item => {
				getDealTrend(item);
				getOrderTrend(item)
			})

			DealTrendData.value = {
				categories: DefaultData,
				series: DealTrendVo
			};
			OrderTrendData.value = {
				categories: DefaultData,
				series: OrderTrendVo
			}
		} catch (error) {

		}
	};





	onMounted(() => {
		if (showMounted) {
			getLineChart();
		}
	})





	return {
		OrderTrendData,
		DealTrendData,
		getLineChart
	}
}