/**
 * 用户相关API接口
 */

import httpRequest from './request.js';
import {
	generateRfm
} from '@/utils/common.js';

class UserApi {
	constructor() {
		this.baseUrl = '/kyhl-weixin-1.0';
		this.cardBaseUrl = '/cm-api/v1'
	}

	// 检查是否有公众号OpenId（获取Cookie的关键接口）
	async getCookie() {
		try {
			const fullUrl = `${this.cardBaseUrl}/auth/get-auth`;

			const response = await httpRequest.post(fullUrl);

			return response;
		} catch (error) {
			console.error('checkHasGzhOpenId请求失败:', error);
			throw error;
		}
	}

	// 获取设备信息(管理平台)
	async getDeviceInfoAdmin(device_id) {
		try {
			const fullUrl = `${this.cardBaseUrl}/device/query`;

			const response = await httpRequest.post(fullUrl, {
				page: 1,
				page_size: 1,
				device_id
			});

			return response;
		} catch (error) {
			console.error('获取设备信息(管理平台):', error);
			throw error;
		}
	}

	// 获取WXUrl
	/* 
	 {
	   "code": "0",
	   "current_session_user_resource_ids_index": "",
	   "app_result_key": "0",
	   "wxAuthUrl": "",
	   "system_result_key": "0"
	 }
	 */
	async getWxUrl() {
		try {
			const params = {
				responseFunction: 'checkHasGzhOpenId',
				needGzhOpenId: true,
				currentPageUrl: 'https://m1.whjhft.com/pages/index/index',
				checkFrom: 'cardlogin',
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/wxauth/checkHasGzhOpenId.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('登录请求失败:', error);
			throw error;
		}
	}


	// 用户登录接口
	async login(iccidMark) {
		try {
			console.log(iccidMark);
			const params = {
				responseFunction: 'findByiccidMarkCallback',
				iccidMark,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/card/login.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('登录请求失败:', error);
			throw error;
		}
	}

	// 判断是否实名接口
	async getRealNameInfo() {
		try {
			const params = {
				iccidOrPhone: "",
				responseFunction: "getRealNameInfoCallback",
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/user/getRealNameInfo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取实名信息失败:', error);
			throw error;
		}
	}


	// 获取用户信息接口
	async getUserInfo() {
		try {
			const params = {
				responseFunction: 'findByOpenIdCallback',
				DoNotGetRealNameInfo: true,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/user/findByOpenId.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取用户信息失败:', error);
			throw error;
		}
	}

	// 切换运营商 1: 电信 2: 联通  3: 移动  esim参数值
	async changeOperator(esim, iccidMark) {
		try {
			const params = {
				responseFunction: 'updateWifi',
				optwifi: "esim",
				esim,
				iccidMark,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/card/updateWifi.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('切换运营商失败:', error);
			throw error;
		}
	}

	// 进入实名是否只显示主卡
	async getIsOnlyMainCard(iccidMark) {
		try {
			const fullUrl = `${this.cardBaseUrl}/call/device/${iccidMark}/exists`;

			const response = await httpRequest.get(fullUrl);

			return response;
		} catch (error) {
			console.error('进入实名是否只显示主卡请求失败:', error);
			throw error;
		}
	}

	// 获取openId接口
	async getOpenId() {
		try {
			const params = {
				responseFunction: 'getUserCardInfo',
				DoNotGetRealNameInfo: true,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/usercard/getUserCardInfo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取openId失败:', error);
			throw error;
		}
	}

	// 进行授权
	async getAuthorize(code) {
		try {
			const params = {
				origin_html_url: 'https://m1.whjhft.com/pages/index/index',
				code: code,
				state: null
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/wxauth/recvCode.do?${queryString}`;

			const response = await httpRequest.get(fullUrl);

			return response;
		} catch (error) {
			console.error('获取授权失败:', error);
			throw error;
		}
	}

	// 获取微信支付签名
	/* 
	 {
	   "code": "0",
	   "signature": "3771f2fce5802b3630377e7d2618a7195d136007",
	   "current_session_user_resource_ids_index": "",
	   "appId": "wxea8c599fe100ce8a",
	   "nonceStr": "31565688940e48cb91827adbf6aeb499",
	   "system_result_key": "0",
	   "timestamp": 1766209145,
	   "isSuccess": "0"
	 }
	 */
	async getWxPaySign() {
		try {
			const fullUrl = `${this.baseUrl}/weixinPay/getWxSign.do`;

			const response = await httpRequest.get(fullUrl);

			return response;
		} catch (error) {
			console.error('获取微信支付签名失败:', error);
			throw error;
		}
	}

	getCurrentPageUrl() {
		try {
			// #ifdef H5
			if (typeof window !== 'undefined' && window.location) {
				const currentUrl = window.location.href;
				console.log('当前页面URL:', currentUrl);
				return encodeURIComponent(currentUrl);
			}
			// #endif

			const defaultUrl = "https://m1.whjhft.com/pages/index/index";
			console.log('使用默认URL:', defaultUrl);
			return encodeURIComponent(defaultUrl);
		} catch (error) {
			console.error('获取当前页面URL失败:', error);
			return encodeURIComponent('https://m1.whjhft.com/pages/index/index');
		}
	}

	// 获取套餐列表 smList
	async getPackageList() {
		try {
			const params = {
				responseFunction: 'findByCardNoCallback',
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}//setmeal/findByCardNo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取套餐列表失败:', error);
			throw error;
		}
	}


	// 1. checkHasGzhOpenId 判断当前用户是否已经绑定了微信公众号的 OpenId
	/*
	 {
	   "code": "0",
	   "current_session_user_resource_ids_index": "",
	   "app_result_key": "0",
	   "wxAuthUrl": "", 
	   "system_result_key": "0"
	 }
	 */
	// 如果返回的wxAuthUrl: 是空的就表示已经授权了, 没有就需要再来一次授权流程
	async checkHasGzhOpenId() {
		try {
			const params = {
				responseFunction: 'checkHasGzhOpenId',
				needGzhOpenId: true,
				currentPageUrl: "https://m1.whjhft.com/pages/package-order/package-order",
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}//wxauth/checkHasGzhOpenId.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('checkHasGzhOpenId:', error);
			throw error;
		}
	}

	// 2. checkYgosWxInfo 检查当前用户是否具有与微信支付相关的特定信息
	async checkYgosWxInfo() {
		try {
			const params = {
				responseFunction: 'checkYgosWxInfo',
				hasYgGzhPm: false,
				currentPageUrl: "https://m1.whjhft.com/pages/package-order/package-order",
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}//weixinPay/checkYgosWxInfo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('checkYgosWxInfo:', error);
			throw error;
		}
	}

	// 3. checkXwzfWxInfo 检查微信信息
	async checkXwzfWxInfo() {
		try {
			const params = {
				responseFunction: 'checkXwzfWxInfo',
				hasXwzfPm: false,
				zwxMchId: "",
				currentPageUrl: "https://m1.whjhft.com/pages/package-order/package-order",
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}//weixinPay/checkXwzfWxInfo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('checkXwzfWxInfo:', error);
			throw error;
		}
	}



	// 4. 获取支付方式
	/* 
	 {
	   "onlyWalletRechargeCard": false,
	   "code": "0",
	   "walletBalance": 0.0,
	   "current_session_user_resource_ids_index": "",
	   "payMethodList": [
	     {
	       "mybatisRecordCount": 0,
	       "orderNo": "",
	       "jsonUpdateFlag": "0",
	       "id": "a333",
	       "createDate": "",
	       "createUserId": "",
	       "createUserName": "",
	       "payMethod": 2,
	       "showStatus": "",
	       "selectStatus": 2,
	       "sortNum": 44,
	       "showName": "余额支付",
	       "showIconUrl": "http://jh.whjhft.com/kyhl-weixin-1.0/img/yezf.png",
	       "appId": "",
	       "appSecret": "",
	       "gzhId": "",
	       "gzhName": "",
	       "gzhUsername": "",
	       "gzhPassword": "",
	       "mchId": "",
	       "mchKey": "",
	       "systemDomain": "",
	       "mchCertUrl": "",
	       "notifyUrl": "",
	       "returnUrl": "",
	       "profitSharingConfigNo": "",
	       "createDateStr": "",
	       "showApp": true,
	       "needOpenId": false,
	       "payMethodStr": "余额支付",
	       "showStatusStr": "",
	       "selectStatusStr": "否"
	     },
	     {
	       "mybatisRecordCount": 0,
	       "orderNo": "",
	       "jsonUpdateFlag": "0",
	       "id": "4F31156EE9654A35B16CF0E3A6569F53",
	       "createDate": "",
	       "createUserId": "",
	       "createUserName": "",
	       "payMethod": 1,
	       "showStatus": "",
	       "selectStatus": 1,
	       "sortNum": "",
	       "showName": "微信支付",
	       "showIconUrl": "http://jhft.whjhft.com/kyhl-weixin-1.0/img/wx.png",
	       "appId": "",
	       "appSecret": "",
	       "gzhId": "",
	       "gzhName": "",
	       "gzhUsername": "",
	       "gzhPassword": "",
	       "mchId": "",
	       "mchKey": "",
	       "systemDomain": "",
	       "mchCertUrl": "",
	       "notifyUrl": "",
	       "returnUrl": "",
	       "profitSharingConfigNo": "",
	       "createDateStr": "",
	       "showApp": false,
	       "needOpenId": true,
	       "payMethodStr": "微信支付",
	       "showStatusStr": "",
	       "selectStatusStr": "是"
	     }
	   ],
	   "app_result_key": "0",
	   "buyMealMealPrice": 29.0,
	   "pwdEmpty": false,
	   "system_result_key": "0",
	   "isSuccess": "1"
	 }
	 */
	async getPayList(mealId) {
		try {
			const params = {
				responseFunction: 'getNeedPayMoneyAndWalletBalance',
				mealId,
				getMealPrice: true,
				allowWalletPay: true,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}//cardwallet/getNeedPayMoneyAndWalletBalance.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取支付方式失败:', error);
			throw error;
		}
	}
	/*
	{
	  "code": "0",
	  "current_session_user_resource_ids_index": "",
	  "wp": {
	    "appId": "wxea8c599fe100ce8a",
	    "timeStamp": "1766388518476",
	    "nonceStr": "1d64e63b37f349cfb3699643757268a3",
	    "prepayId": "prepay_id=wx2215283841316122e94a592ddd8e7f0000",
	    "paySign": "FDCD3D358E55C568725A10B4E7BC4F5B",
	    "signType": ""
	  },
	  "system_result_key": "0",
	  "isSuccess": "0"
	} 
	 */
	// 5. 调用 orderPayPageUse.do 创建订单 并拉起支付 我只要微信支付即可
	async createOrder(data) {
		try {
			const fullUrl = `${this.baseUrl}/weixinPay/orderPayPageUse.do`;

			// 将数据转换为 URL 编码格式
			const p = new URLSearchParams(data).toString();

			// 确保 header 中的 Content-Type 为 x-www-form-urlencoded
			const response = await httpRequest.post(fullUrl, p, {
				header: {
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
				}
			});
			
			return response;
		} catch (error) {
			console.error('创建订单失败', error);
			throw error;
		}
	}

	// 获取切卡列表-设备流量-WIFI信息-连接数
	async getSwitchCardList() {
		try {
			const params = {
				responseFunction: 'findNetWorkInfo',
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/card/findCardMchInfo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取切卡列表-设备流量-WIFI信息-连接数异常:', error);
			throw error;
		}
	}

	// 获取卡信息(过期时间expireDate-状态statusStr)
	async getCardInfo() {
		try {
			const params = {
				iccidOrPhone: '',
				responseFunction: 'findCardInfoCallback',
				skipGift: true,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/card/findCardInfo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取切卡列表-设备流量-WIFI信息-连接数异常:', error);
			throw error;
		}
	}


	// 修改WiFi信息
	async modifyWifi({
		cardNo,
		ssid,
		password
	}) {
		try {
			const fullUrl = `${this.cardBaseUrl}/device/wifi-config`;

			const response = await httpRequest.post(fullUrl, {
				cardNo,
				ssid,
				password
			});

			return response;
		} catch (error) {
			console.error('修改WiFi信息失败:', error);
			throw error;
		}
	}

	// 重启设备
	async restartDevice(deviceId) {

		try {
			const fullUrl = `${this.cardBaseUrl}/device/restart`;

			const response = await httpRequest.post(fullUrl, {
				cardNo: deviceId
			});

			return response;
		} catch (error) {
			console.error('重启设备失败:', error);
			throw error;
		}
	}

	// 恢复出厂设置
	async restDevice(deviceId) {
		try {
			const fullUrl = `${this.cardBaseUrl}/device/factory-reset`;

			const response = await httpRequest.post(fullUrl, {
				cardNo: deviceId
			});

			return response;
		} catch (error) {
			console.error('恢复出厂设置失败:', error);
			throw error;
		}
	}

	// 获取实名地址
	async getRealNameAddress(iccidMark) {
		try {
			const params = {
				iccidOrPhone: "",
				responseFunction: "getRealNameInfoCallback",
				force: true,
				iccidMark,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/user/getRealNameInfo.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取实名地址异常:', error);
			throw error;
		}
	}

	// 智能诊断
	/* 
	 {
	   "internalRetMsg": "",
	   "code": "0",
	   "current_session_user_resource_ids_index": "",
	   "app_result_key": "0",
	   "retMsg": "已提交复机申请，预计1小时内复机。",
	   "system_result_key": "0",
	   "isSuccess": "0"
	 }
	 */
	async intelligentDiagnosis(iccidMark) {
		try {
			const params = {
				responseFunction: "intelliDiagnose"
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/card/intelliDiagnose.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('智能诊断异常:', error);
			throw error;
		}
	}

	// 获取设备绑定的手机号
	async getDeviceBindPhone() {
		try {
			const params = {
				responseFunction: 'findMyBindRecord',
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/phonebindrecord/findMyBindRecord.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取设备绑定的手机号异常:', error);
			throw error;
		}
	}

	// 获取短信验证码
	async getSmsNumber(mobile) {
		try {
			const params = {
				responseFunction: 'sendSms',
				mobile,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/phonebindrecord/sendSms.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('获取短信验证码异常:', error);
			throw error;
		}
	}

	// 绑定手机号
	async bindCardPhone(mobile, code) {
		try {
			const params = {
				responseFunction: 'saveBind',
				mobile,
				code,
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/phonebindrecord/saveBind1.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('绑定手机号异常:', error);
			throw error;
		}
	}

	// 退出登录
	async logout() {
		try {
			const params = {
				responseFunction: 'logoutCallback',
				rfm: generateRfm()
			};

			const queryString = this.buildQueryString(params);
			const fullUrl = `${this.baseUrl}/card/logout.do?${queryString}`;

			const response = await httpRequest.post(fullUrl, null);

			return response;
		} catch (error) {
			console.error('退出登录异常:', error);
			throw error;
		}
	}

	buildQueryString(params) {
		return Object.keys(params)
			.filter(key => params[key] !== undefined && params[key] !== null)
			.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
			.join('&');
	}
}

const userApi = new UserApi();

export default userApi;