import {
	callFunction,
} from "../../utils/common.js";
import permision from "@/js_sdk/wa-permission/permission.js";

export default {
	namespaced: true,
	state: {
		dragOption: {
			x: uni.getSystemInfoSync().windowWidth,
			y: 200
		},
		currentVersion: "1.0.0",
		lastVersion: "1.0.0",

		callAccount: null,

		callSystem: null,

		currentPhone: "",

		recordId: undefined,

		signInState: false, // 是否签入成功

		redisStatus: false, // redis中的状态

		registerInfo: null, // 分机的注册信息

		dialing: false, // 拨号中

		incomingCallPhone: "",

		incomingCallId: null,

		lineList: [],
		
		phoneStatus : {
			isRing: false, // 外呼振铃
			isBusy: false, // 通话(来电外呼通用)
			isIncoming: false, // 来电振铃
			isEnd: false, // 挂断
			isLeisure: true // 空闲
		},
		isNotificationEnabled : false,
		isAlwaysAsk : false,
	},
	mutations: {
		SET_CALL_ACCOUNT(state, data) {
			state.callAccount = data;
		},
		SET_DRAGOPTION_Y(state, data) {
			state.dragOption.y = data;
		},
		SET_CURRENTVERSION(state, data) {
			state.currentVersion = data;
		},
		SET_LASTVERSION(state, data) {
			state.lastVersion = data;
		},
		SET_CALLSYSTEM(state, data) {
			state.callSystem = data;
		},
		SET_RECORDID(state, data) {
			state.recordId = data;
		},
		SET_CURRENTPHONE(state, data) {
			state.currentPhone = data;
		},
		SET_SIGNINSTATE(state, data) {
			state.signInState = data;
		},
		SET_DIALING(state, data) {
			state.phoneStatus = data;
			state.dialing = !data.isLeisure;
		},
		SET_INCOMINGCALLPHONE(state, data) {
			state.incomingCallPhone = data;
		},
		SET_INCOMINGCALLID(state, data) {
			state.incomingCallId = data;
		},
		SET_LINE_LIST(state, data) {
			state.lineList = data;
		},
		SET_REDIS_INFO(state, data) {
			state.redisStatus = data != null
			state.registerInfo = data;
		},
	},
	actions: {
		// 创建Wv的实例
		createWv({
			commit,
			state,
			rootState
		}) {
			if(state.callSystem != null){
				state.callSystem.close();
			}
			const wv = plus.webview.create("", "custom-webview", {
				'uni-app': 'none'
			});
			const data = state.callAccount;
			const {
				ip,
				port,
				folder,
				webRtcIp,
				webRtcPort
			} = rootState.user.netConfig;
			const baseURL = ip + ":" + port + folder; /* 根域名 */
			
			wv.loadURL("/static/call/index.html?extension=" + data.extenNum + "&password=" + data.pwd +
				"&user_agent=app_" + data.userId + "&baseURL=" + baseURL + "&ip=" + webRtcIp + ":" + webRtcPort);
				
			// wv.loadURL("/static/call/index.html?extension=" + "yxx" + "&password=" + "1234" +
			// 	"&user_agent=app_" + data.userId + "&baseURL=" + baseURL + "&ip=" + webRtcIp + ":" + webRtcPort);
				
			// wv.loadURL("/static/call/index.html?extension=" + data.extenNum + "&password=" + data.pwd +
			// 				"&user_agent=app_" + data.userId + "&baseURL=" + "http://10.0.100.230:9500" + "&ip=" + "10.0.100.230" + ":9504");
			// wv.loadURL("/static/call/index.html?extension=" + data.extenNum + "&password=" + data.pwd +
							// "&user_agent=app_" + data.userId + "&baseURL=" + "http://59.42.9.166:9520/wfhl28gz_getwfxt0817" + "&ip=" + "59.42.9.166" + ":7564");
				
			// console.log("/static/call/index.html?extension=" + data.extenNum + "&password=" + data.pwd +
			// 	"&user_agent=app_" + data.userId + "&baseURL=" + baseURL + "&ip=" + ip.split("//")[1])
				
			// wv.loadURL("/static/call/index.html?extension=cyid1&password=1234&user_agent=app_1&baseURL=http://10.0.23.253:9500");
			// 设置线路
			wv.evalJS(`setLineList(${ JSON.stringify(state.lineList) })`);
			commit("SET_CALLSYSTEM", wv);
		},
		register({ state , dispatch , rootState}){
			if(rootState.user.userInfo.userId && rootState.user.netConfig.isCallOff === '1'){
				// 重新签出注册
				if(state.callSystem != null && state.phoneStatus.isLeisure){
					callFunction("unReg");
				}
				if(state.callSystem === null){
					dispatch("getExtensionByUserId", {
						userId: rootState.user.userInfo.userId
					}).then((res) => {
						Promise.all([permision.requestAndroidPermission("android.permission.RECORD_AUDIO"),permision.requestAndroidPermission('android.permission.MODIFY_AUDIO_SETTINGS')]).then(result=>{
							const flag = result.every(v=>v == 1);
							if(flag){
								dispatch("createWv");
							}
						})
					});
				}
			}
		},
		getExtensionByUserId({
			commit,
			dispatch
		}, params) {
			return new Promise((resolve, reject) => {
				uni.$u.api.getExtensionByUserId(params).then(({
					data
				}) => {
					if (data && data.length > 0) {
						commit("SET_CALL_ACCOUNT", data[0]);
						dispatch("getLineByIds", {
							extenId: data[0].id
						}).then(() => {
							resolve(data[0]);
						})
					} else {
						uni.$u.toast("检测到您未配置分机号");
						reject();
					}
				})
			})
		},
		getLineByIds({
			commit,
			state
		}, params) {
			return new Promise((resolve, reject) => {
				uni.$u.api.getLineByIds(params).then((lineRes) => {
					if (lineRes.data && lineRes.data.length === 0) {
						uni.$u.toast('检测到' + state.callAccount.extenNum + '没有配置线路');
						reject();
					} else {
						commit('SET_LINE_LIST', lineRes.data);
						resolve();
					}
				})
			})
		},
	 	call({ state, commit, rootState, dispatch }, { lineData, phoneId, caseId, caseDetail }){
			return new Promise(async (resolve,reject)=>{
				const { dialStr: dialer, phone: linePhone, type, callPhone } = lineData;
				
				if (!callPhone) {
					uni.$u.toast('没有外显号码，请前往呼叫中心补充')
					return
				}
				
				let flag = false
				if (type !== 'ip') {
				    flag = true
				} else {
				    const { code } = await uni.$u.api.setEffectiveCallerIdNumber({ extension: state.callAccount.extenNum, phone: linePhone });
				    flag = code === 200
				}
				
				if (flag) {
				    const { data } =  await uni.$u.api.getJsSipExtra({ caller : linePhone, phoneId , callPhone , caseId , type : "2" });
					const { callee: x_callee, caller: x_caller, orgId, recordingId, base64P, callPhone: x_callPhone } = data;
					
					const afterPhone = new Buffer(base64P, 'base64').toString('utf8');
					
					const phone = afterPhone.replace('-', '').trim();
					
					const callParams = {
						replacedContact : dialer.replace('${destination_number}',phone),
						bankCode : caseDetail.bankCode , 
						bankBatchCode : caseDetail.bankBatchCode,
						userId : rootState.user.userInfo.userId, 
						nickName : rootState.user.userInfo.nickName, 
						deptId: rootState.user.userInfo.deptId, 
						recordingId : recordingId,
						x_callee : x_callee,
						x_caller : x_caller,
						orgId : orgId,
						systemCode : rootState.user.system.value,
						extension : state.callAccount.extenNum,
						x_callPhone : x_callPhone,
						callPhone : callPhone,
						phone : phone,
						caseId : caseId
					}
					callFunction("handleCall",callParams);
				}
			})
		},
		saveUnionAppCall({
			commit
		}, params) {
			return new Promise((resolve, reject) => {
				uni.$u.api.saveUnionAppCall(params, {
					custom: {
						loading: false
					}
				}).then(({
					data
				}) => {
					if (params.action === "outbound") {
						commit("SET_RECORDID", data);
						commit("SET_CURRENTPHONE", params.phone);
					}else if (params.action === "incoming"){
						commit("SET_INCOMINGCALLPHONE",params.phone);
						commit("SET_INCOMINGCALLID",data)
					}
					resolve(data);
				}).catch(() => {
					reject();
				})
			})
		},
		logoutCloseData(store) {
			store.state.callAccount = null;
			store.commit("SET_CURRENTPHONE", "");
			store.commit("SET_RECORDID", undefined);
			store.state.dialing = false; // 拨号中
			store.state.incomingCallPhone = "";
			store.state.incomingCallId = null;
			store.rootState.user.userInfo = {};
			store.state.signInState = false;
			if(store.state.callSystem){
				store.state.callSystem.close();
				store.commit("SET_CALLSYSTEM", null);
			}
		},
		getIsUseCallSystem(store, action) {
			return new Promise((resolve, reject) => {
				const {
					signInState,
					callSystem,
					callAccount
				} = store.state;
				Promise.all([permision.requestAndroidPermission("android.permission.RECORD_AUDIO"), permision
					.requestAndroidPermission('android.permission.MODIFY_AUDIO_SETTINGS')
				]).then(result => {
					const flag = result.every(v => v == 1);
					if (flag) {
						if (!callAccount) {
							uni.$u.toast("检测到您的账号未配置分机号");
							store.commit("SET_DIALING", false);
							reject()
						} else if (!callSystem) {
							uni.$u.toast("检测到呼叫系统被销毁,将为您重新创建,请稍等几秒后操作");
							store.dispatch("createWv");
							store.commit("SET_DIALING", false);
							reject();
						} else if (callSystem) {
							resolve();
						}
					} else {
						store.commit("SET_DIALING", false);
						uni.$u.toast("请提供录音权限");
						reject();
					}
				})
			})
		}
	},
}