import {
	registerPush,
	getRegistrationID,
	setRegistrationID,
	EVENT,
	addPushListener
} from '@/uni_modules/TencentCloud-Push';
import request from '@/utils/request'
import store from '@/store/index.js'
/**
 * 当前通知权限开启查询
 * @returns {Boolean} true：已开启   false：未开启
 */
export const isNotificationsEnabled = () => {
	// #ifdef APP-PLUS
	if (plus.os.name == 'Android') {
		// 判断是Android
		var main = plus.android.runtimeMainActivity()
		var NotificationManagerCompat = plus.android.importClass(
			'android.support.v4.app.NotificationManagerCompat'
		)
		if (NotificationManagerCompat == null) {
			NotificationManagerCompat = plus.android.importClass(
				'androidx.core.app.NotificationManagerCompat'
			)
		}

		// 返回是否有权限
		return NotificationManagerCompat.from(main).areNotificationsEnabled()
	} else if (plus.os.name == 'iOS') {
		// 判断是iOS
		var isOn = undefined
		var types = 0
		var app = plus.ios.invoke('UIApplication', 'sharedApplication')
		var settings = plus.ios.invoke(app, 'currentUserNotificationSettings')
		if (settings) {
			types = settings.plusGetAttribute('types')
			plus.ios.deleteObject(settings)
		} else {
			types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes')
		}
		plus.ios.deleteObject(app)
		isOn = 0 != types
		// 返回是否有权限
		return isOn
	}
	// #endif
}

/**
 * 前往系统设置的功能
 * @param {Boolean} type  true：开启		false：关闭
 * @returns
 */
export const permissions = (type) => {
	// #ifdef APP-PLUS
	if (plus.os.name == 'Android') {
		// 判断是Android
		var main = plus.android.runtimeMainActivity()
		var pkName = main.getPackageName()
		var uid = main.getApplicationInfo().plusGetAttribute('uid')

		uni.showModal({
			title: `通知权限${type ? '开启' : '关闭'}提醒`,
			content: `是否前往设置${type ? '开启' : '关闭'}通知权限？`,
			success: res => {
				if (res.confirm) {
					var Intent = plus.android.importClass('android.content.Intent')
					var Build = plus.android.importClass('android.os.Build')
					//android 8.0引导
					if (Build.VERSION.SDK_INT >= 26) {
						var intent = new Intent(
							'android.settings.APP_NOTIFICATION_SETTINGS'
						)
						intent.putExtra('android.provider.extra.APP_PACKAGE', pkName)
					} else if (Build.VERSION.SDK_INT >= 21) {
						//android 5.0-7.0
						var intent = new Intent(
							'android.settings.APP_NOTIFICATION_SETTINGS'
						)
						intent.putExtra('app_package', pkName)
						intent.putExtra('app_uid', uid)
					} else {
						//(<21)其他--跳转到该应用管理的详情页
						intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
						var uri = Uri.fromParts(
							'package',
							mainActivity.getPackageName(),
							null
						)
						intent.setData(uri)
					}
					// 跳转到该应用的系统通知设置页
					main.startActivity(intent)
				} else if (res.cancel) {
					console.log('点击了取消')
				}
			}
		})
	} else if (plus.os.name == 'iOS') {
		// 判断是iOS
		var app = plus.ios.invoke('UIApplication', 'sharedApplication')
		plus.ios.deleteObject(app)

		uni.showModal({
			title: `通知权限${type ? '开启' : '关闭'}提醒`,
			content: `是否前往设置${type ? '开启' : '关闭'}通知权限？`,
			success: res => {
				if (res.confirm) {
					var app = plus.ios.invoke('UIApplication', 'sharedApplication')
					var setting = plus.ios.invoke(
						'NSURL',
						'URLWithString:',
						'app-settings:'
					)
					plus.ios.invoke(app, 'openURL:', setting)
					plus.ios.deleteObject(setting)
					plus.ios.deleteObject(app)
				} else if (res.cancel) {
					console.log('点击了取消')
				}
			}
		})
	}
	// #endif
}

export const formatParams = (params) => {
	let paramStr = '';
	for (let key in params) {
		if (params.hasOwnProperty(key)) {
			// 对参数值进行编码，避免特殊字符导致的问题
			paramStr += `${key}=${encodeURIComponent(params[key])}&`;
		}
	}
	// 去除最后一个&符号
	return paramStr.slice(0, -1);
}


/**
 * 注册推送
 */
export const registPush = () => {
	// #ifdef APP-PLUS
	request.post('/sj/push/getPushUserId').then(result => {

		if (result.code == 200) {
			let isNotifications = isNotificationsEnabled()
			const SDKAppID = 1600130322; // 您的 SDKAppID
			const appKey =
				'5IrByLsKWJhbbNKIKEy2sZRIcQX6omnhMEUoA6zexuLCOsJ33mprqKs9T36Eg8ZZ'; // 客户端密钥
			const registrationID = result.data.push_user_id; // 客户端密钥
			setRegistrationID(registrationID, (id) => {
				console.log('setRegistrationID ok', id);
			});
			registerPush(SDKAppID, appKey, (data) => {
				console.log('registerPush ok', data);

				getRegistrationID((id) => {
					console.log('getRegistrationID ok', id);
					request.post('/sj/push/setPushUserId', {
						push_user_id: id || registrationID
					}).then(result2 => {

						if (result2.code == 200) {
							uni.setStorageSync("isPushUserId", true)
						}

					})

				});
			}, (errCode, errMsg) => {
				console.error('registerPush failed', errCode, errMsg);
			});

			// 监听通知栏点击事件，获取推送扩展信息
			addPushListener(EVENT.NOTIFICATION_CLICKED, (res) => {
				// res 为推送扩展信息
				console.log('notification clicked', res);
				try {
					// 核心步骤：解析嵌套的JSON字符串
					// 第一步：取出res.data中的转义JSON字符串
					const innerJsonStr = res.data;
					// 第二步：将转义字符串解析为JavaScript对象
					const parsedData = JSON.parse(innerJsonStr);

					// 解析后的结构化数据，可直接使用各个字段
					console.log('解析后的订单数据：', parsedData);
					if (parsedData.path) {
						uni.navigateTo({
							// 拼接路径和参数（uniapp中参数需要通过url拼接传递）
							url: `${parsedData.path}?${formatParams(parsedData.data)}`,
							// 跳转成功的回调
							success: (res) => {
								console.log('页面跳转成功', res);
							},
							// 跳转失败的回调
							fail: (err) => {
								console.error('页面跳转失败', err);
							}
						});
					}

				} catch (error) {
					// 异常处理：防止JSON格式错误导致程序崩溃
					console.error('JSON解析失败：', error);
				}
			});



			// 监听在线推送
			addPushListener(EVENT.MESSAGE_RECEIVED, (res) => {
				// res 为消息内容
				request.post("/sj/push/messageUnreadNum").then(res => {
					console.log('111111111', res);
					if (res.code == 200) {
						store.commit("setMessageNum", res.data.count)
					}
				})
				console.log('message received111111111', res);

			});

			// 监听在线推送被撤回
			addPushListener(EVENT.MESSAGE_REVOKED, (res) => {
				// res 为被撤回的消息 ID
				console.log('message revoked', res);
			});

			//当前系统通知状态
			let isSatae = isNotifications ? 1 : 2

			request.post('/sj/push/getReceiveState', {
				message_type_id: -1
			}).then(result2 => {
				//如果系统通知状态和后台通知状态不一致
				console.log("state", result2.data.list[0].state, isSatae)
				if (result2.data.list[0].state != isSatae && isSatae == 1) {
					request.post('/sj/push/setReceiveState', {
						message_type_id: -1,
						message_kind_id: 0,
						state: isSatae
					}).then(result3 => {
						console.log("setReceiveState", result3)
					})
				}

			})


		}
	}).catch(err => {

	})
	// #endif
}