//#ifdef APP-PLUS
import {
	startPhoneListener,
	stopPhoneListener,
	checkIsAutoRecord,
	toCallAutoRecorderPage,
	navigateToCallRecordingSettings,
	jumpToPermissionPage,
	allRecorderFilesAction
} from '@/uni_modules/yao-lister';
// #endif
import permision from "@/js_sdk/wa-permission/permission.js";
import {
	formatPhoneNumber
} from '../../utils/util';

export default {
	namespaced: true,
	state: {
		filelist: [],
		isAutoRecord: false, // 通话自动录音状态
		hasStoragePermission: false, // 文件访问权限状态
		hasReadPhoneStatePermission: false, // 读取手机状态权限
		hasCallPhonePermission: false, // 拨打电话权限
		hasReadCallLogPermission: false, // 读取通话记录权限
		hasReadPhoneNumbersPermission: false, // 读取电话号码权限
		isPhoneListening: false, // 电话监听状态
		form: {
			clueId: undefined,
			fileUrl: undefined,
			fileName: undefined,
			type: '3',
			list: [],
			caller: '',
			callee: ''
		},
	},
	mutations: {
		SET_FILE_LIST: (state, data) => {
			state.filelist = data.data
		},
		SET_AUTO_RECORD: (state, value) => {
			state.isAutoRecord = value;
		},
		SET_STORAGE_PERMISSION: (state, value) => {
			state.hasStoragePermission = value;
		},
		SET_READ_PHONE_STATE_PERMISSION: (state, value) => {
			state.hasReadPhoneStatePermission = value;
		},
		SET_CALL_PHONE_PERMISSION: (state, value) => {
			state.hasCallPhonePermission = value;
		},
		SET_READ_CALL_LOG_PERMISSION: (state, value) => {
			state.hasReadCallLogPermission = value;
		},
		SET_READ_PHONE_NUMBERS_PERMISSION: (state, value) => {
			state.hasReadPhoneNumbersPermission = value;
		},
		SET_PHONE_LISTENING_STATUS: (state, value) => {
			state.isPhoneListening = value;
		},
		SET_CALLER_PHONE: (state, phoneNumber) => {
			state.form.caller = phoneNumber;
		},
		SET_FORM: (state, data) => {
			state.form = data;
		},
	},
	actions: {
		// 获取文件列表 - 返回Promise方式
		getFileList({
			dispatch,
			state,
			commit
		}) {
			return new Promise((resolve, reject) => {
				dispatch("checkStoragePermission").then(() => {
					if (state.hasStoragePermission) {
						allRecorderFilesAction(res => {
							if (res && res.length > 0) {
								// 将文件路径数组转换为包含filePath和fileName的对象数组
								const fileListPromise = res.map(filePath => {
									return new Promise((resolve) => {
										// 从路径中提取文件名
										const fileName = filePath.split('/')
											.pop();

										// 获取文件信息，包括创建时间
										plus.io.resolveLocalFileSystemURL(
											filePath, (entry) => {
												entry.getMetadata((
													metadata) => {
													resolve({
														filePath: filePath,
														fileName: fileName,
														createTime: metadata
															.modificationTime ?
															metadata
															.modificationTime :
															0, // 文件创建时间
													});
												}, (error) => {
													// 如果获取metadata失败，返回基本信息
													resolve({
														filePath: filePath,
														fileName: fileName,
														createTime: 0, // 设为0，排序时会在最前面
													});
												});
											}, (error) => {
												// 如果解析文件路径失败，返回基本信息
												resolve({
													filePath: filePath,
													fileName: fileName,
													createTime: 0,
													size: 0
												});
											});
									});
								});

								// 等待所有文件信息获取完成后进行排序
								Promise.all(fileListPromise).then((fileList) => {
									// 按创建时间排序，最新的文件排在前面（降序）
									fileList.sort((a, b) => {
										return b.createTime - a.createTime;
									});

									// 提交文件列表到state
									commit('SET_FILE_LIST', {
										data: fileList
									});
									// 返回文件列表
									resolve(fileList);
								}).catch((error) => {
									console.error('获取文件列表失败:', error);
									// 即使排序失败，也尝试提交原始列表
									const fallbackFileList = res.map(filePath => {
										const fileName = filePath.split('/')
											.pop();
										return {
											filePath: filePath,
											fileName: fileName
										};
									});
									commit('SET_FILE_LIST', {
										data: fallbackFileList
									});
									resolve(fallbackFileList);
								});
							} else {
								// 没有文件时返回空数组
								commit('SET_FILE_LIST', {
									data: []
								});
								resolve([]);
							}
						})
					} else {
						dispatch("requestStoragePermission");
						reject(new Error('没有文件访问权限'));
					}
				}).catch(error => {
					reject(error);
				});
			});
		},

		// 获取用户手机号码
		getUserPhoneNumber({
			commit
		}) {
			return new Promise((resolve, reject) => {
				// 首先检查权限
				permision.requestAndroidPermission('android.permission.READ_PHONE_NUMBERS')
					.then(result => {
						if (result === 1) {
							// 权限被授予，获取手机号码
							try {
								const main = plus.android.runtimeMainActivity();
								const Context = plus.android.importClass('android.content.Context');
								const TelephonyManager = plus.android.importClass(
									'android.telephony.TelephonyManager');

								const telephonyManager = main.getSystemService(Context.TELEPHONY_SERVICE);
								const phoneNumber = telephonyManager.getLine1Number();

								if (phoneNumber && phoneNumber.trim() !== '') {
									// 移除国际区号，保留手机号码
									const cleanPhoneNumber = formatPhoneNumber(phoneNumber);
									commit('SET_CALLER_PHONE', cleanPhoneNumber);
									resolve(cleanPhoneNumber);
								} else {
									// 获取不到手机号码
									reject(new Error('无法获取手机号码：设备可能不支持'));
								}
							} catch (error) {
								console.error('获取手机号码失败:', error);
								reject(new Error('获取手机号码失败: ' + error.message));
							}
						} else {
							reject(new Error('没有获取手机号码的权限，请前往设置开启权限'));
						}
					})
					.catch(error => {
						console.error('请求权限失败:', error);
						reject(error);
					});
			});
		},

		resetForm({
			commit
		}) {
			commit("SET_FORM", {
				clueId: undefined,
				fileUrl: undefined,
				fileName: undefined,
				type: '3',
				list: [],
				caller: '',
				callee: ''
			})
		},

		// 检查所有权限状态
		checkAllPermissions({
			commit
		}) {
			return new Promise((resolve, reject) => {
				try {
					// 检查通话自动录音状态
					const autoRecordStatus = checkIsAutoRecord();
					commit('SET_AUTO_RECORD', autoRecordStatus);

					// 检查文件访问权限
					this.dispatch('call/checkStoragePermission').then(storagePermission => {
						commit('SET_STORAGE_PERMISSION', storagePermission);

						// 检查其他权限
						const permissions = [{
								id: 'android.permission.READ_PHONE_STATE',
								mutation: 'SET_READ_PHONE_STATE_PERMISSION'
							},
							{
								id: 'android.permission.CALL_PHONE',
								mutation: 'SET_CALL_PHONE_PERMISSION'
							},
							{
								id: 'android.permission.READ_CALL_LOG',
								mutation: 'SET_READ_CALL_LOG_PERMISSION'
							},
							{
								id: 'android.permission.READ_PHONE_NUMBERS',
								mutation: 'SET_READ_PHONE_NUMBERS_PERMISSION'
							}
						];

						const permissionPromises = permissions.map(perm => {
							return permision.requestAndroidPermission(perm.id).then(result => {
								commit(perm.mutation, result === 1);
								return {
									id: perm.id,
									granted: result === 1
								};
							});
						});

						Promise.all(permissionPromises).then(results => {
							resolve({
								autoRecordStatus,
								storagePermission,
								permissions: results
							});
						});
					});
				} catch (error) {
					reject(error);
				}
			});
		},

		// 检查文件访问权限
		checkStoragePermission({
			commit
		}) {
			return new Promise((resolve) => {
				let hasPermission = false;
				try {
					// 获取Android版本号
					let androidVersion = 0;
					uni.getSystemInfo({
						success: (res) => {
							if (res.system && res.system.includes('Android')) {
								const versionMatch = res.system.match(/Android (\d+\.?\d*)/);
								if (versionMatch && versionMatch[1]) {
									androidVersion = parseFloat(versionMatch[1]);
								}
							}

							if (androidVersion >= 11) {
								// Android 11及以上版本，使用MANAGE_EXTERNAL_STORAGE权限
								const Environment = plus.android.importClass(
									'android.os.Environment');
								hasPermission = Environment.isExternalStorageManager();
								commit('SET_STORAGE_PERMISSION', hasPermission);
								resolve(hasPermission);
							} else {
								// Android 11以下版本，使用READ_EXTERNAL_STORAGE权限
								permision.requestAndroidPermission(
										'android.permission.READ_EXTERNAL_STORAGE')
									.then(result => {
										hasPermission = result === 1;
										commit('SET_STORAGE_PERMISSION', hasPermission);
										resolve(hasPermission);
									});
							}
						}
					});
				} catch (e) {
					hasPermission = false;
					commit('SET_STORAGE_PERMISSION', hasPermission);
					resolve(hasPermission);
				}
			});
		},

		// 请求文件访问权限
		requestStoragePermission() {
			jumpToPermissionPage();
		},

		// 跳转到通话录音设置页面
		toCallRecorderSettings() {
			toCallAutoRecorderPage();
		},

		// 跳转到系统通话录音界面
		toSystemRecorderSettings() {
			navigateToCallRecordingSettings();
		},

		// 打开系统设置
		handleOpenSet() {
			permision.gotoAppPermissionSetting('android.permission.RECORD_AUDIO');
		},

		// 启动电话监听
		startPhoneListener({
			commit,
			dispatch,
			state
		}) {
			try {
				if (state.isPhoneListening) {
					// 已经开启监听就不要了
					return;
				}
				// 用于记录上一个状态，检测通话结束
				let previousState = null;
				dispatch("checkAllPermissions").finally(() => {
					startPhoneListener(res => {
						if (state.form.clueId) {
							// 是通过app监听打出去触发;
							dispatch("handleCallBack", {
								currentState: res,
								previousState
							});
						}
						// 更新上一个状态
						previousState = res;
						commit('SET_PHONE_LISTENING_STATUS', true);
					});
				});
			} catch (error) {
				console.error('启动电话监听失败:', error);
				commit('SET_PHONE_LISTENING_STATUS', false);
				throw error;
			}
		},
		handleCallBack({
			dispatch,
			commit,
			state
		}, {
			currentState,
			previousState
		} = {}) {
			if (previousState && currentState) {
				if (previousState === '通话中') {
					if (currentState === '空闲状态') {
						// 延迟一下再获取，确保录音文件已经生成
						setTimeout(() => {
							dispatch('getLatestRecordingFile').then((file) => {
								uni.showModal({
									title: '检测您的拨号行为,是否上传录音？',
									content: '最新一条电话录音：' + file.fileName +",是否前往关联？",
									success: function (res) {
										if (res.confirm) {
											uni.navigateTo({
												url: `/pages/uploadRecord/index?clueId=${state.form.clueId}`
											})
										} else if (res.cancel) {
											dispatch("resetForm");
										}
									}
								});
							}).catch(error => {
								uni.$u.toast('获取录音文件失败:' + error);
							});
						}, 2000); // 延迟1秒获取
					}
				}
			}
		},

		// 获取最新的录音文件并赋值给form
		getLatestRecordingFile({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				// 获取文件列表 - 使用return Promise的方式
				this.dispatch('call/getFileList').then((fileList) => {
					if (fileList && fileList.length > 0) {
						// 获取最新创建的录音文件（索引0是最新的）
						const latestFile = fileList[0];

						// 更新form中的fileUrl和fileName
						const updatedForm = {
							...state.form,
							fileUrl: latestFile.filePath,
							fileName: latestFile.fileName
						};

						commit('SET_FORM', updatedForm);
						resolve(latestFile);
					} else {
						reject(new Error('未找到录音文件'));
					}
				}).catch(error => {
					console.error('获取文件列表失败:', error);
					reject(error);
				});
			});
		},
		// 停止电话监听
		stopPhoneListener({
			commit
		}) {
			try {
				stopPhoneListener(res => {
					commit('SET_PHONE_LISTENING_STATUS', false);
				});
			} catch (error) {
				console.error('停止电话监听失败:', error);
				commit('SET_PHONE_LISTENING_STATUS', false);
				throw error;
			}
		},

		// 切换电话监听状态
		togglePhoneListener({
			state,
			dispatch
		}) {
			if (state.isPhoneListening) {
				return dispatch('stopPhoneListener');
			} else {
				return dispatch('startPhoneListener');
			}
		}
	},
}