import { ref } from 'vue'
import { GlobalStore } from '@/stores/index'
import { Storehouse_StockOut_Company_Name_List, Storehouse_StockOut_Project_List } from '@/api/storehouse/index'

/**
 * 公司名称和退库项目的远程搜索
 */
export const useRemoteSearch = () => {
	const globalStore = GlobalStore()

	// 公司名称远程搜索
	const stockOutCompanyNameOptions = ref<any[]>([])
	const isStockOutCompanyNameLoading = ref(false)

	// 退库项目远程搜索
	const stockOutProjectOptions = ref<any[]>([])
	const isStockOutProjectLoading = ref(false)

	/**
	 * 公司名称远程搜索
	 */
	const queryStockOutCompanyNameAsync = async (query: string) => {
		if (!query) {
			stockOutCompanyNameOptions.value = []
			return
		}
		isStockOutCompanyNameLoading.value = true
		try {
			const res: any = await Storehouse_StockOut_Company_Name_List({
				User_tokey: globalStore.GET_User_tokey,
				T_name: query
			})
			if (res.Code === 200 && res.Data) {
				stockOutCompanyNameOptions.value = res.Data.map((item: any) => ({
					value: item,
					label: item
				}))
			}
		} catch (error) {
			console.error('查询公司名称失败:', error)
		} finally {
			isStockOutCompanyNameLoading.value = false
		}
	}

	/**
	 * 退库项目远程搜索
	 */
	const queryStockOutProjectAsync = async (query: string) => {
		if (!query) {
			stockOutProjectOptions.value = []
			return
		}
		isStockOutProjectLoading.value = true
		try {
			const res: any = await Storehouse_StockOut_Project_List({
				User_tokey: globalStore.GET_User_tokey,
				T_name: query
			})
			if (res.Code === 200 && res.Data) {
				stockOutProjectOptions.value = res.Data.map((item: any) => ({
					value: item,
					label: item
				}))
			}
		} catch (error) {
			console.error('查询退库项目失败:', error)
		} finally {
			isStockOutProjectLoading.value = false
		}
	}

	return {
		// 公司名称相关
		stockOutCompanyNameOptions,
		isStockOutCompanyNameLoading,
		queryStockOutCompanyNameAsync,
		
		// 退库项目相关
		stockOutProjectOptions,
		isStockOutProjectLoading,
		queryStockOutProjectAsync
	}
}

