import {
	selectMerchant,
	queryStoreBranch,
	getImUser
} from '@/commit/api.js'
import {
	emConnect,
} from '@/EaseIM/emApis';
import loginStore from '@/store/modules/login.js';


const {
	loginWithPassword
} = emConnect();

const setEMUserLoginInfosToStorage = (userId, token) => {
	const params = {
		key: `EM_LOGIN_INFOS`,
		data: {
			userId: userId,
			token: token
		},
	};
	uni.setStorage({
		...params
	});
}

const loginWithUserId = async () => {
	let loginEaseIMId = uni.getStorageSync('im_userid')
	try {
		const res = await loginWithPassword(
			loginEaseIMId,
			uni.getStorageSync('im_pass')
		);
		loginStore.mutations['SET_LOGIN_USER_BASE_INFOS']({
			loginUserId: loginEaseIMId,
		});
		setEMUserLoginInfosToStorage(
			loginEaseIMId.toLowerCase(),
			res.accessToken
			//注意：res.accessToken
		);
	} catch (error) {
		console.log('>>>>>>', error);
		uni.showToast({
			title: '登录失败',
			icon: 'none',
		});
	} finally {
		loginEaseIMId = '';
	}
}

const llwFunc = async () => {
	//lww
	let storeStaff = uni.getStorageSync('storeStaff')
	if (storeStaff != null) {
		const res = await queryStoreBranch({
			id: storeStaff.department
		})
		if (res.data.status == 200) {
			uni.setStorageSync('jurisdiction', paramsData.jurisdiction);
		}
	} else {
		uni.setStorageSync('jurisdiction', [7, 9, 5, 3]);
	}

	// TODO 需要明确含义，目前逻辑是undifined
	let type;

	if (type == 1) {
		console.log('返回上一页')
		uni.navigateBack({
			delta: 1
		})
	} else {
		uni.switchTab({
			url: '../pages/cashier/index'
		});
	}
}

const readQuery = () => {
	const hash = window.location.hash; // 例如：#/?param1=value1&param2=value2

	// 检查 hash 是否为空
	if (hash) {
		// 创建一个 URLSearchParams 实例
		const queryString = hash.split('?')[1]; // 获取 '?' 后面的部分
		const params = new URLSearchParams(queryString);

		return JSON.parse(decodeURIComponent(params.get('data')))
	}
}

const func = async () => {
	try {
		const paramsData = readQuery()
		if(!paramsData) {
			return;
		}

		const paramsData1 = {
			"storeStaff": null,
			"x_token": "MTYzMzYxODYzMjY4MTA0NTIwMjUtMDEtMDYgYXQgMjI6MDA6MDkgQ1NU",
			"user": {
				"uid": 16336,
				"wechat_user_id": "0",
				"ali_user_id": "0",
				"account": "18632681045",
				"real_name": "",
				"label_id": null,
				"group_id": "11",
				"nickname": "用户1045",
				"avatar": "https://app.bjtdba.com/uploads/logo.jpg",
				"phone": "18632681045",
				"now_score": null,
				"score": 0,
				"now_money": 0,
				"brokerage_price": 0,
				"admin_agent_rate": null,
				"locktime": null,
				"user_number": null,
				"im": 0,
				"im_uuid": null,
				"last_ip": "20.100.5.11",
				"identity": 5,
				"spreadUid": null,
				"user_type": "MP",
				"pwd": "$2y$10$XARVMD82YRAl9NMwzLcrKeSozdzlnUj7IXp2dvPGYGobzYFlf0j5K",
				"mer_id": 0,
				"spread_count": 0,
				"first_sign": 0
			}
		}

		uni.setStorageSync('userinfo', paramsData.user);
		uni.setStorageSync('authorization', paramsData.x_token);
		uni.setStorageSync('storeStaff', paramsData.storeStaff);

		// 用户状态判断
		const userInfoData = await selectMerchant({
			uid: paramsData.user.uid
		});
		console.log(userInfoData)

		const {
			merchantIntention = {},
		} = userInfoData.data.data || {};

		uni.setStorage({
			key: 'myUsername',
			data: JSON.stringify(uni.getStorageSync('userinfo').uid),
		});
		uni.setStorage({
			key: 'mer_id',
			data: merchantIntention.mer_id,
		});

		if (userInfoData.data.status == 200) {
			uni.setStorageSync('selectmerchant', userInfoData.data.data);

			const imUserData = await getImUser({
				mer_id: uni.getStorageSync('mer_id'),
			});
			// actionEMReconnect();
			const {
				loginWithPassword
			} = emConnect();
			uni.setStorage({
				key: 'im_userid',
				data: imUserData.data.data.im_userid
			})
			uni.setStorage({
				key: 'im_pass',
				data: imUserData.data.data.im_pass
			})
			uni.setStorage({
				key: 'im_uuid',
				data: imUserData.data.data.im_uuid
			})
			//环信注册成功 登录
			if (imUserData.data.status == 200) {
				console.log('>>>>>>>>环信注册成功 登录')
				await loginWithUserId()
			}



			await llwFunc();

		}
	} catch (error) {
		console.error(error);
		//TODO handle the exception
	}



}
export default func;