import { ref, unref, computed, nextTick } from 'vue'
import { useBackground } from './common/useBackground'
import { useRefreshLoad } from './common/useRefreshLoad'
import { useDataFetch } from './common/useDataFetch'
import { getBannerApi, getHotRecommendApi, getNoticeBartApi, configIndex, configSearch } from '@/api/home'
import { getTopCategoryApi } from '@/api/catogory'
import type { bannerItem, noticeBarItem } from '@/types/home'


export function useTodoPage() {
	// ==================== 使用其他 composables ====================
	const { backgroundStyle } = useBackground()
    const topGradientStyle = useBackground().setTopGradientStyle('#FCDC9D', '#F2EFE7');
	const {
		isRefreshing,
		isLoading,
		hasMore,
		currentPage,
		handleRefresh,
		handleLoadMore,
		resetState,
	} = useRefreshLoad({
		showRefreshSuccess: true,
		showLoadError: true,
	})

	// ==================== 页面数据 ====================
	const bannerList = ref<bannerItem[]>([])
	const noticeBarList = ref<string[]>([])
	const categoryList = ref<any[]>([])
	const hotRecommendList = ref<any[]>([])

	// 新增接口返回的数据
	const menuList = ref<any[]>([])
	const switchList = ref<any[]>([])
	const systemInfo = ref<any>({})
	const noticeInfo = ref<any>({})
	const hbsmNotice = ref<any>({})
	const blackInfo = ref<any>({})


	// ==================== Tab切换相关 ====================
	const activeTab = ref(0) // 当前激活的tab索引
	const activeTabKey = ref('goods') // 当前激活的tab key
	const tabContentList = ref<any[]>([]) // tab对应的内容列表
	const tabLoading = ref(false) // tab内容加载状态
	const tabCurrentPage = ref(1) // tab内容当前页
	const tabHasMore = ref(true) // tab内容是否还有更多

	// ==================== 数据获取 ====================
	const { execute: fetchBanners } = useDataFetch(getBannerApi, {
		immediate: false,
		showLoading: false,
		showError: false,
	})

	const { execute: fetchNotices } = useDataFetch(getNoticeBartApi, {
		immediate: false,
		showLoading: false,
		showError: false,
	})

	const { execute: fetchCategories } = useDataFetch(getTopCategoryApi, {
		immediate: false,
		showLoading: false,
		showError: false,
	})

	const { execute: fetchHotRecommend } = useDataFetch(getHotRecommendApi, {
		immediate: false,
		showLoading: false,
		showError: false,
	})

	// ==================== 页面初始化 ====================
	const initPage = async () => {
		try {
			await Promise.all([
				fetchBanners(),
				fetchNotices(),
				fetchCategories(),
				fetchHotRecommend(),
				configIndexApi()
			])

			// 初始化完成后，加载默认tab的内容
			if (switchList.value.length > 0) {
				activeTabKey.value = switchList.value[0].keys
				await loadTabContent(activeTabKey.value, 1, true)
			}
		} catch (error) {
			console.error('页面初始化失败:', error)
		}
	}

	// ==================== 刷新处理 ====================
	const onRefresh = async () => {
		await handleRefresh(async () => {
			await initPage()
		})
	}

	// ==================== 加载更多处理 ====================
	const onLoadMore = async () => {
		if (tabHasMore.value && !tabLoading.value) {
			await loadTabContent(activeTabKey.value, tabCurrentPage.value + 1, false)
		}
	}

	const configIndexApi = async () => {
		try {
			const res = await configIndex({ page: 1, page_size: 10 })
			console.log(res, '-----------------configIndex')

			if (res.code === 1 && res.data) {
				const { data } = res

				// 处理菜单数据
				if (data.menu && Array.isArray(data.menu)) {
					menuList.value = data.menu
				}
				bannerList.value = data.adv

				// [
				//   { title: '推荐', route: '/pages/home/index' },
				//   { title: '合作伙伴', route: '/pagesMember/pages/profile/profile' },
				//   { title: '商机', route: '/pagesForeignTrade/pages/trade/trade' },
				//   { title: '关于我们', route: '/pagesOther/pages/blank/rich-text' },
				//   { title: '找买家', route: '/pagesMember/pages/profile/profile' },
				//   { title: '找卖家', route: '/pagesMember/pages/profile/profile' },
				// ]
				// 处理切换列表数据
				if (data?.switchList && Array.isArray(data?.switchList)) {
					switchList.value = data?.switchList
					// 设置默认激活的tab
					if (data.switchList.length > 0) {
						activeTabKey.value = data.switchList[0].keys
					}
				}

				// 处理系统信息
				if (data.system) {
					systemInfo.value = data.system
				}

				// 处理通知栏数据
				if (data.notice) {
					noticeInfo.value = data.notice
					// 将通知列表转换为字符串数组格式
					if (data.notice.list && Array.isArray(data.notice.list)) {
						noticeBarList.value = data.notice.list.map((item : any) => item.content || item.title)
					}
				}
				// 处理海保世贸通知
				if (data.hbsmNotice) {
					hbsmNotice.value = data.hbsmNotice;
					//弹出系统维护窗口
					//status 系统提示状态,1=弹出系统提示, 弹出hbsm_notice.title,和hbsm_notice.content ; 0不用管  
					if (data.hbsmNotice.status == 1)
						uni.showModal({
							showCancel: false,
							title: data.hbsmNotice.title,
							content: data.hbsmNotice.content
						})
				}

				// 处理黑名单信息
				if (data.black) {
					blackInfo.value = data.black
					//status 黑名单状态,1=已被拉黑，弹窗弹窗，不能关闭,或者跳到新页面无法返回  
					if (data.black.status == 1) {
						uni.setStorage({
							key: 'blackInfo',
							data: data.black,
							success: () => {
								uni.reLaunch({
									url: '/pages/black/index'
								})
							}
						});

					}
				}
			}
		} catch (error) {
			console.error('获取首页配置失败:', error)
		}
	}

	// ==================== Tab切换和内容加载 ====================
	/**
	 * 切换Tab
	 * @param index tab索引
	 * @param tabKey tab的key值
	 */
	const switchTab = async (index : number, tabKey : string) => {
		if (activeTab.value === index) return

		activeTab.value = index
		activeTabKey.value = tabKey

		// 切换tab时重新加载内容
		await loadTabContent(tabKey, 1, true)
	}

	/**
	 * 加载Tab内容
	 * @param type tab类型
	 * @param page 页码
	 * @param isRefresh 是否刷新（清空原有数据）
	 * @param keywords 搜索关键词
	 */
	const loadTabContent = async (type : string, page : number = 1, isRefresh : boolean = false, keywords : string = '') => {
		try {
			tabLoading.value = true

			const res = await configSearch({
				page,
				page_size: 10,
				keywords,
				type
			})

			console.log(res, '-----------------configSearch')

			if (res.code === 1 && res.data) {
				const { data } = res

				if (isRefresh) {
					// 刷新时清空原有数据
					tabContentList.value = data.list || []
					tabCurrentPage.value = 1
				} else {
					// 加载更多时追加数据
					tabContentList.value = [...tabContentList.value, ...(data.list || [])]
					tabCurrentPage.value = page
				}

				// 判断是否还有更多数据
				tabHasMore.value = (data.list && data.list.length === 10) || false
			}
		} catch (error) {
			console.error('加载tab内容失败:', error)
		} finally {
			tabLoading.value = false
		}
	}

	// ==================== 返回数据和方法 ====================
	return {
		// 背景样式
		backgroundStyle,
		topGradientStyle,

		// 页面状态
		isRefreshing,
		isLoading,
		hasMore,
		currentPage,

		// 页面数据
		bannerList,
		noticeBarList,
		categoryList,
		hotRecommendList,

		// 新增的接口数据
		menuList,
		switchList,
		systemInfo,
		noticeInfo,
		hbsmNotice,
		blackInfo,

		// Tab相关数据和状态
		activeTab,
		activeTabKey,
		tabContentList,
		tabLoading,
		tabCurrentPage,
		tabHasMore,

		// 页面方法
		initPage,
		onRefresh,
		onLoadMore,
		resetState,

		// Tab相关方法
		switchTab,
		loadTabContent,
	}
}