// api/modules/user.ts
import { mainClient, skeletonClient } from '@/api/clients'
import { paymentClient } from '@/api/clients/payment'
import type { IApiResponse } from '@/api/types'
import type { 
  IUserInfo, 
  IVipInfo,
  IOrder,
  IVipPackage,
  ITransaction,
  IFeedbackForm,
  IPageData
} from '@/types/user'
import { SERVICE_MAP } from '@/api/config'

/**
 * 获取用户信息
 */
export async function getUserInfo() {
  const res = await skeletonClient.request<IApiResponse<{ user: IUserInfo }>>({
    url: 'common/user/getUserInfo',
    method: 'POST'
  })
  return res
}

/**
 * 获取VIP信息
 */
export async function getVipInfo() {
  const res = await mainClient.request<IApiResponse<{ vipInfo: IVipInfo }>>({
    url: 'bookAbroad/home/getVipInfo',
    method: 'POST'
  })
  return res
}

/**
 * 获取订单列表
 * @param current 当前页码
 * @param limit 每页数量
 */
export async function getOrderList(page: number, limit: number, orderStatus: string) {
  const res = await mainClient.request<IApiResponse<{ orders: IPageData<IOrder> }>>({
    url: 'common/buyOrder/commonBuyOrderList',
    method: 'POST',
    data: { page, limit, orderStatus, come: '10', userId: uni.getStorageSync('userInfo').id }
  })
  return res
}

/**
 * 获取VIP套餐列表
 */
export async function getVipPackages() {
  const res = await mainClient.request<IApiResponse<{ sysDictDatas: IVipPackage[] }>>({
    url: 'book/sysdictdata/getData',
    method: 'POST',
    data: { dictLabel: 'googleVip' }
  })
  return res
}

/**
 * 创建订单
 * @param data 订单数据
 */
export async function createOrder(data: any) {
  const res = await mainClient.request<IApiResponse<{ orderSn: string }>>({
    url: 'bookAbroad/order/placeOrder',
    method: 'POST',
    data
  })
  return res
}

/**
 * 获取交易记录列表
 * @param userId 用户ID
 */
export async function getTransactionList(userId: number) {
  const res = await mainClient.request<IApiResponse<{ transactionDetailsList: ITransaction[] }>>({
    url: 'common/transactionDetails/getTransactionDetailsList',
    method: 'POST',
    data: { userId }
  })
  return res
}

/**
 * 更新用户基本信息
 * @param data 用户信息
 */
export async function updateUserInfo(data: Partial<IUserInfo>) {
  const res = await mainClient.request<IApiResponse>({
    url: 'book/user/update',
    method: 'POST',
    data
  })
  return res
}

/**
 * 更新用户邮箱
 * @param id 用户ID
 * @param email 邮箱地址
 * @param code 验证码
 */
export async function updateEmail(id: number, email: string, code: string) {
  const res = await mainClient.request<IApiResponse>({
    url: 'common/user/updateUserEmail',
    method: 'POST',
    data: { id, email, code }
  })
  return res
}

/**
 * 更新用户密码
 * @param id 用户ID
 * @param password 新密码
 */
export async function updatePassword(id: number, password: string) {
  const res = await mainClient.request<IApiResponse>({
    url: 'common/user/setPasswordById',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: { id, password }
  })
  return res
}

/**
 * 发送邮箱验证码
 * @param email 邮箱地址
 */
export async function sendEmailCode(email: string) {
  const res = await mainClient.request<IApiResponse>({
    url: 'common/user/getMailCaptcha',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: { email }
  })
  return res
}

/**
 * 上传图片
 * @param filePath 本地文件路径
 * @returns 图片URL
 */
export function uploadImage(filePath: string): Promise<string> {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${SERVICE_MAP.MAIN}oss/fileoss`,
      filePath,
      name: 'file',
      success: (res: any) => {
        try {
          const data = JSON.parse(res.data)
          if (data.url) {
            resolve(data.url)
          } else {
            reject(new Error('上传失败'))
          }
        } catch (error) {
          reject(error)
        }
      },
      fail: reject
    })
  })
}

/**
 * 提交问题反馈
 * @param data 反馈表单数据
 */
export async function submitFeedback(data: IFeedbackForm) {
  const res = await mainClient.request<IApiResponse>({
    url: 'common/sysFeedback/addSysFeedback',
    method: 'POST',
    data
  })
  return res
}

/**
 * 验证Google支付
 * @param purchaseToken 购买令牌
 * @param orderSn 订单号
 * @param productId 产品ID
 */
export async function verifyGooglePay(productId: number, purchaseToken: string, orderSn: string) {
	console.log(productId, purchaseToken, orderSn);
  const res = await paymentClient.request<IApiResponse>({
    url: 'pay/googlepay/googleVerify',
    method: 'POST',
    data: { productId, purchaseToken, orderSn }
  })
  return res
}

/**
 * 验证IAP支付
 * @param data 支付数据
 */
export async function verifyIAP(data: any) {
  const res = await mainClient.request<IApiResponse>({
    url: 'Ipa/veri',
    method: 'POST',
    data
  })
  return res
}

/**
 * 获取充值列表
 * @param type 固定值 point
 * @param qudao 支付类型 
 */
export async function getBookBuyConfigList(type: string, qudao: string) {
  const res = await mainClient.request<IApiResponse>({
    url: 'common/bookBuyConfig/getBookBuyConfigList',
    method: 'POST',
    data: {type, qudao}
  })
  return res
}

/**
 * 获取隐私协议
 * @param id 101众妙之门隐私政策
 */
export async function getAgreement(id: string) {
  const res = await mainClient.request<IApiResponse>({
    url: '/sys/agreement/getAgreement',
    method: 'POST',
    data: {id}
  })
  return res
}

/**
 * 获取活动说明
 */
export async function getActivityDescription() {
  const res = await mainClient.request<IApiResponse>({
    url: 'common/bookBuyConfig/getRechargeActivity',
    method: 'POST'
  })
  return res
}

/**
 * 充值记录列表
 * @param current 当前页码
 * @param limit 每页数量
 * @param userId 用户id
 * @return 
 */ 
export async function getTransactionDetailsList(current : number, limit : number, userId : string) {
	const res = await mainClient.request<IApiResponse>({
		url: 'common/transactionDetails/getTransactionDetailsList',
		method: 'POST',
		data: { current, limit, userId, }
	})
	return res
}

/**
 * 获取订单编号
 * @return 
 */ 
export async function getPlaceOrder(data: object) {
	
	const res = await paymentClient.request<IApiResponse>({
		url: '/book/buyOrder/placeOrder',
		method: 'POST',
		data: data
	})
	return res
}

/**
 * 获取积分数据
 * @return 
 */ 
export async function getPointsData(current : number, limit : number, userId : string,) {
	
	const res = await mainClient.request<IApiResponse>({
		url: 'common/jfTransactionDetails/getJfTransactionDetailsList',
		method: 'POST',
		data: { current, limit, userId, }
	})
	return res
}

/**
 * 迁移用户数据
 * @param tel 旧账号
 * @param code 迁移验证码
 * @param type 未迁移数据类型
 * @return 
 */ 
export async function migrateUserData(data: { tel: string, code: string, type: string }) {
	const res = await mainClient.request<IApiResponse>({
		url: 'common/user/migrationWumenData',
		method: 'POST',
		data
	})
	return res
}

/**
 * 获取用户迁移信息
 * @return {
 * 	alreadyMigration: 已迁移用户数
 * 	notMigration: 未迁移用户数
 * }
 */ 
export async function getUserMigrateInfo() {
	const res = await skeletonClient.request<IApiResponse>({
		url: 'common/user/getMigrationList',
		method: 'POST',
	})
	return res
}

/**
 * 我的湖分
 * @return 
 */ 
export async function getUserContributionData() {
	const res = await skeletonClient.request<IApiResponse>({
		url: 'common/userContribution/getUserContribution',
		method: 'POST'
	})
	return res
}

/**
 * 湖分列表
 * @param current 当前页码
 * @param limit 每页数量
 * @param type 湖分类型
 * @return 
 */ 
export async function getUserContributionByTypeList(current : number, limit : number, type : string,) {
	const res = await mainClient.request<IApiResponse>({
		url: 'common/userContribution/getUserContributionByType',
		method: 'POST',
		data: { current, limit, type, }
	})
	return res
}

/**
 * ios支付
 * @param transactionId 支付交易id
 * @param productId 商品id
 * @param orderId 订单id
 * @param receiptData 苹果返回收据
 * @param customerOid 用户id
 * @return 
 */ 
export async function getIosPayment(transactionId : string, productId : string, orderId : string, receiptData : string, customerOid : string) {
	const res = await mainClient.request<IApiResponse>({
		url: 'Ipa/veri',
		method: 'POST',
		data: { transactionId, productId, orderId, receiptData, customerOid}
	})
	return res
}

/**
 * 我的课程
 * @param page 当前页码
 * @param limit 每页数量
 * @param title 课程名称
 * @param medicalId 商品id
 * @return 
 */
export async function getUserCourseBuyList(page : number, limit : number, title : string, medicalId: string) {
	const res = await mainClient.request<IApiResponse>({
		url: 'medical/course/getUserCourseBuy',
		method: 'POST',
		data: { page, limit, title, medicalId }
	})
	return res
}

/**
 * 正在学习
 * @param page 当前页码
 * @param limit 每页数量
 * @param userId 用户id
 * @return 
 */
export async function getUserCourseStudyingList(page : number, limit : number, userId : string) {
	const res = await mainClient.request<IApiResponse>({
		url: 'medical/course/getUserCourseStudying',
		method: 'POST',
		data: { page, limit, userId }
	})
	return res
}

/**
 * 已过期
 * @param page 当前页码
 * @param limit 每页数量
 * @param userId 用户id
 * @return 
 */
export async function getCourseExpireList(page : number, limit : number, userId : string) {
	const res = await mainClient.request<IApiResponse>({
		url: 'medical/course/getCourseExpire',
		method: 'POST',
		data: { page, limit, userId }
	})
	return res
}

/**
 * 加入学习
 * @param courseId 商品id
 * @param userId 用户id
 * @return 
 */
export async function addUserCourseStudyingList(userId : string, courseId : string) {
	const res = await skeletonClient.request<IApiResponse>({
		url: 'medical/course/addUserCourseStudying',
		method: 'POST',
		data: { userId, courseId }
	})
	return res
}

/**
 * 取消学习
 * @param courseId 商品id
 * @return 
 */
export async function delUserCourseStudyingList(courseId : string) {
	const res = await skeletonClient.request<IApiResponse>({
		url: 'medical/course/delUserCourseStudying',
		method: 'POST',
		data: { courseId }
	})
	return res
}

/**
 * 分类标签数
 * @return 
 */
export async function getCourseMedicalTreeList() {
	const res = await mainClient.request<IApiResponse>({
		url: 'medical/home/getCourseMedicalTree',
		method: 'POST'
	})
	return res
}

/**
 * 续费课程
 * @param catalogueId 商品id
 * @return 
 */
export async function getRelearnShopProductList(catalogueId : string) {
	const res = await skeletonClient.request<IApiResponse>({
		url: 'common/courseRelearn/relearnShopProductList',
		method: 'POST',
		data: { catalogueId }
	})
	return res
}