import {
	reactive,
	ref,
	watch
} from 'vue';
import {
	storage
} from '../utils/storage';



// 防抖函数
const debounce = (fn, delay = 300) => {
	let timer = null
	return function(...args) {
		if (timer) clearTimeout(timer)
		timer = setTimeout(() => {
			fn.apply(this, args)
		}, delay)
	}
}

// 定义应用的全局状态
export const store = reactive({
	// 用户信息
	userInfo: storage.get('userInfo') || null,

	// 应用设置
	settings: storage.get('settings') || {
		theme: 'light',
		language: 'zh-CN',
		notifications: true
	},

	// 系统信息（从缓存读取，避免重复调用）
	systemInfo: uni.getStorageSync('systemInfo') || {
		statusBarHeight: 0,
		windowHeight: 0,
		windowWidth: 0,
		platform: ''
	},

	// 账单列表
	billList: JSON.parse(JSON.stringify(storage.get('bill_list') || [])),
	callInfo: {}

});


// 定义操作方法
export const useStore = () => {
	// 账单相关操作
	const addBill = (bill) => {
		store.billList.unshift(bill);
		return bill;
	};

	const updateBill = (id, updates) => {
		const index = store.billList.findIndex(bill => bill.id === id);
		if (index !== -1) {
			store.billList[index] = {
				...store.billList[index],
				...updates
			};
			return store.billList[index];
		}
		return null;
	};

	const deleteBill = (id) => {
		const index = store.billList.findIndex(bill => bill.id === id);
		if (index !== -1) {
			store.billList.splice(index, 1);
			return true;
		}
		return false;
	};

	const getBillList = () => {
		return JSON.parse(JSON.stringify(store.billList))
	}
	const getCallDetail = () => {
		return JSON.parse(JSON.stringify(store.callInfo))
	}
	const setCallDetail = (info) => {
		return store.callInfo = info
	};
	return {
		store,
		addBill,
		updateBill,
		deleteBill,
		getBillList,
		setCallDetail,
		getCallDetail
	};
};

// 优化后的监听：使用防抖减少存储频率
const debouncedSaveSettings = debounce((newValue) => {
	storage.set('settings', newValue)
}, 500)

watch(
	() => store.userInfo,
	(newValue) => storage.set('userInfo', newValue), {
		deep: true
	}
);

watch(
	() => store.settings,
	(newValue) => debouncedSaveSettings(newValue), {
		deep: true
	}
);

// 监听billList改变自动保存
watch(
	() => store.billList,
	(newValue) => {
		console.log("store.billList changed, saving...")
		storage.set('bill_list', newValue)
	}, {
		deep: true
	}
);