import { getIn } from "herculex/dist/utils/manipulate";
import {
	getSilentAuthCode,
	getAuthUser,
	getOpenUserInfo,
	getPhoneNumber,
	getIDNumber,
} from "../../utils/jsapi";
import request from "../../utils/request";
import { ywtAuth } from "../../utils/ywtService";
import { setStorage } from "../../utils";
import { userInfoUrl, loginUrl, gwAppId } from "../../utils/constants";

export default {
	async checkUserLogin({ commit }) {
		const [authcodeErr, authcodeRes] = await getSilentAuthCode();
		if (authcodeErr) return [authcodeErr, null];
		const [err, res] = await request({
			url: userInfoUrl,
			data: { authCode: authcodeRes.authCode },
		});
		if (err) return [err, null];
		if (res) {
			// eslint-disable-next-line no-undef
			const app = getApp();
			if (res.ticket) {
				app.globalData.ticketData.ticket = res.ticket;
				app.globalData.ticketData.expiresTime = res.expiresTime;
			}
			app.globalData.isUserLogin = true;
			commit("updateUserInfo", {
				...res,
				isLogin: true,
			});
		}
	},

	async doLogin({ state, commit }, payload) {
		const { scopesList = "", scopes = state.scopes || "auth_user" } =
			payload || {};
		let isLoginSuccess = false;
		let data = { formId: state.formId };
		const url = loginUrl[scopes] || "";
		/*
		 * 静默授权
		 * */
		if (scopes === "auth_user") {
			const [err, res] = await getAuthUser(scopesList);
			if (err) return isLoginSuccess;
			data = {
				...data,
				authCode: getIn(res, ["authCode"]),
			};
		} else if (scopes === "userInfo") {
			const [err, res] = await getOpenUserInfo();
			if (err) {
				console.error("获取用户公开信息异常:", err);
				return isLoginSuccess;
			}
			data = {
				...data,
				city: res.city,
				gender: res.gender,
				avatar: res.avatar,
				nickName: res.nickName,
				province: res.province,
			};
		} else if (scopes === "phoneNumber") {
			const [err, res] = await getPhoneNumber();
			if (err) return isLoginSuccess;
			data = {
				...data,
				encryptedData: res,
				scope: "phoneNumber",
			};
		} else if (scopes === "IDNumber") {
			const [err, res] = await getIDNumber();
			if (err) return isLoginSuccess;
			data = {
				...data,
				encryptedData: res,
				scope: "IDNumber",
			};
		}
		my.showLoading({
			content: "登录中...",
		});
		const [err, res] = await request({
			url,
			data,
		});
		const $pageAfter = getCurrentPages();
		$pageAfter.forEach((element) => {
			my.hideLoading({
				page: element,
			});
		});
		if (err) return isLoginSuccess;
		// eslint-disable-next-line no-undef
		const app = getApp();
		if (res && res.ticket) {
			app.globalData.ticketData.ticket = res.ticket;
			app.globalData.ticketData.expiresTime = res.expiresTime;
		}
		app.globalData.isUserLogin = true;
		app.globalData.userInfo = res;
		if (res) {
			const [ywtErr, ywtResult] = await ywtAuth({
				ticket: res.ticket,
				gwAppId,
			});
			if (!ywtErr && ywtResult && ywtResult.token) {
				app.globalData.ywtToken = "Bearer " + ywtResult.token;
				app.globalData.ywtUserId = ywtResult.userId;
			}
		}
		commit({
			userInfo: {
				isLogin: true,
				...res,
			},
		});
		await setStorage("logout", false);
		isLoginSuccess = true;
		return isLoginSuccess;
	},
};
