
import api from "./api.uts"

// 定义并导出响应数据类型
export type ResponseData = {
    code : number
    message : string
    // data/meta 可能为对象或数组，保持为 any，由调用方按需转换
    data ?: any | null
    meta ?: any | null
}

// 缓存获取函数，确保每次都获取最新的缓存值
const getAuthHeaders = () : UTSJSONObject => {
	const machine_code = uni.getStorageSync('machine_code')
	const guest_Token = uni.getStorageSync('guestToken') ?? ''
	const device_id = uni.getStorageSync('device_id') ?? ''
	return {
		'machine-code': machine_code,
		'Authorization': `Guest ${guest_Token}`,
		'device-id': device_id,
	} as UTSJSONObject
}


// 显示Toast后延迟跳转，避免立即reLaunch导致Toast不显示
function showToastThenReLaunch(msg : string, url : string, duration : number = 4500) : void {
    // 先关闭可能存在的Loading遮罩，确保Toast可见
    uni.showToast({
        title: msg,
        icon: 'none',
        duration: duration
    })
    // 延迟跳转，等待Toast展示完成
    setTimeout(() : void => {
        uni.reLaunch({
            url: url
        })
    }, duration)
}

const request = (url : string, method : string, data : any) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            method: method as RequestMethod,
            timeout: 15000,
            data: data,
            header: getAuthHeaders(),
			success: (res) => {
				// 直接使用 res.data，不进行类型转换
                const responseData = res.data as UTSJSONObject
                const code = responseData.getNumber('code') ?? 0
                const message = responseData.getString('message') ?? ''
                const dataField = responseData.getAny('data')
                const meta = responseData.getAny('meta')
				if ((code as number) == 0) {
                    const result : ResponseData = {
                        code: (code as number),
                        message: message,
                        data: dataField != null ? dataField : null,
                        meta: meta != null ? meta : null,
                    }
                    resolve(result)
                } else {
                    console.log('message', message)
                    if ((code as number) == 130001) {
                        showToastThenReLaunch(message, '/pages/stop/index', 4500)
                        return;
                    }
                    // 处理错误码130002 - 清除machine_code并跳转首页
                    if ((code as number) == 130002) {
                        uni.removeStorage({
                            key: 'machine_code',
                            success: function (res) {
                                console.log('success，清除machine_code并跳转首页');
                            }
                        });
                        // 先显示提示，再延迟跳转，避免Toast未显示
                        showToastThenReLaunch(message, '/pages/index/index', 4500)
                        
                        return;
                    }
                    // 对于其他错误码，reject promise 以便调用方的 catch 块能够处理
                    reject({ code: code, message: message })
                }

			},
			fail: (error) => {
				uni.showToast({
					title: `网络错误`,
					icon: 'error'
				})
				reject(error)
			}
		})
	})
}

const ossUpload = (
    filePath : string
) => {
    return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中...',
			mask: true
		})
		uni.uploadFile({
			url: api.ossUpload as string,
			filePath: filePath,
			name: 'file',
			timeout: 15000,
			header: getAuthHeaders(),
			success(res) {
				
				try {
                    const dataStr = (res.data as string) ?? ''
                    if (dataStr.length == 0) {
						const emptyResult : ResponseData = { code: 0, message: '', data: null }
						resolve(emptyResult)
						return
					}
					
					const responseJSON = JSON.parse(dataStr) as UTSJSONObject
					const code = responseJSON.getNumber('code') ?? 0
					const message = responseJSON.getString('message') ?? ''
					const dataField = responseJSON.getAny('data')

					// 处理错误码130002 - 清除machine_code并跳转首页
                    if (code == 130002) {
						uni.removeStorage({
							key: 'machine_code',
							success: function (res) {
								console.log('success');
							}
						});
						
						// 跳转到首页
						uni.reLaunch({
							url: '/pages/index/index'
						});
						return;
					}

                    const result : ResponseData = {
                        code: (code as number),
                        message: message,
                        data: dataField != null ? (dataField as UTSJSONObject) : null
                    }
					uni.hideLoading()
                    resolve(result)
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: '响应解析失败',
						icon: 'error'
					})
					reject(e as any)
				}
			},
			fail(error_1) {
				uni.hideLoading()
				uni.showToast({
					title: '网络错误',
					icon: 'error'
				})
				reject(error_1)
			}
		})
	})
}

const binds = (params : object) => {
    return request(api.binds as string, 'POST', params)
}

const guestLogin = (params : object) => {
    return request(api.guestLogin as string, 'POST', params)
}

const languages = (params : object) => {
    return request(api.languages as string, 'POST', params)
}

const list = (params : object) => {
    return request(api.list as string, 'POST', params)
}

const category = (params : object) => {
    return request(api.category as string, 'POST', params)
}

const queryRenderResult = (prompt_id : string) => {
    return request(api.queryRenderResult + prompt_id as string, 'GET', {})
}

const goodscategory = (params : object) => {
    return request(api.goodscategory as string, 'POST', params)
}

const creatework = (params : object) => {
    return request(api.creatework as string, 'POST', params)
}

const getmachines = (params : object) => {
    return request(api.getmachines as string, 'POST', params)
}

const getgoods = (params : object) => {
    return request(api.getgoods as string, 'POST', params)
}

const uploadQrcode = (fd : string) => {
    return request(api.uploadQrcode + fd as string, 'POST', {})
}

const uploadurl = (params : object) => {
    return request(api.uploadurl as string, 'POST', params)
}

const getMachineApp = (params : object) => {
    return request(api.getMachineApp as string, 'POST', params)
}

const print = (params : object) => {
    return request(api.print as string, 'POST', params)
}

const createorder = (params : object) => {
    return request(api.createorder as string, 'POST', params)
}

const queryStatus = (params : object) => {
    return request(api.queryStatus as string, 'POST', params)
}

const cancel = (params : object) => {
    return request(api.cancel as string, 'POST', params)
}

const queueList = (params : object) => {
    return request(api.queueList as string, 'POST', params)
}

const ads = (params : object) => {
    return request(api.ads as string, 'POST', params)
}

const shareQrcode = (works_id: number) => {
    return request(api.shareQrcode + '?works_id=' + works_id.toString(), 'GET', {})
}

export { binds, guestLogin, list, category, languages, queryRenderResult, uploadurl, ossUpload, goodscategory, creatework, getmachines, getgoods, uploadQrcode, getMachineApp, print, createorder, queryStatus, cancel, queueList, ads, shareQrcode}
