import { getClinicAdminMyInfo } from '@/api/clinicAdmin.js';
import { getClinicSalespersonMyInfo } from '@/api/clinicSalesperson.js';
import { getPlatformAdminMyInfo } from '@/api/platformAdmin.js';
import { getSalespersonMyInfo } from '@/api/salesperson.js';
import { getUserInfo } from '@/api/all.js';
import {
	resolveActiveAdminLoginMode,
	getCurrentLoginContext,
	resolveDoctorWxAuthToken,
} from '@/utils/doctorWxAuthToken.js';

export { getCurrentLoginContext, resolveDoctorWxAuthToken };

const ADMIN_HOME = {
	platform_admin: '/subPackages/sub_platform_admin/home/index',
	salesperson: '/subPackages/sub_salesperson/home/index',
	clinic_salesperson: '/subPackages/sub_clinic_salesperson/home/index',
	clinic_admin: '/subPackages/sub_clinic_admin/home/index',
};

function applyServiceUserProfile(user) {
	if (!user || !user.id) return;
	uni.setStorageSync('loginInfo', user);
	uni.setStorageSync('role', user.role);
	uni.setStorageSync('login_id', user.id);
	uni.setStorageSync('login_status', user.status);
}

function clearBusinessAdminStorage() {
	uni.removeStorageSync('clinic_admin_token');
	uni.removeStorageSync('clinic_admin_user');
	uni.removeStorageSync('platform_admin_token');
	uni.removeStorageSync('platform_admin_user');
	uni.removeStorageSync('salesperson_token');
	uni.removeStorageSync('salesperson_user');
	uni.removeStorageSync('clinic_salesperson_token');
	uni.removeStorageSync('clinic_salesperson_user');
}

function clearServiceUserStorage() {
	uni.removeStorageSync('token');
	uni.removeStorageSync('loginInfo');
	uni.removeStorageSync('logInfo');
	uni.removeStorageSync('identity');
	uni.removeStorageSync('role');
	uni.removeStorageSync('store_id');
	uni.removeStorageSync('doctor_id');
	uni.removeStorageSync('user_id');
	uni.removeStorageSync('login_id');
	uni.removeStorageSync('login_status');
	uni.removeStorageSync('doctorInfo');
}

/** 清除全部登录态（医生/药师 + 各角色管理员） */
export function clearAllLoginStorage() {
	clearBusinessAdminStorage();
	clearServiceUserStorage();
	uni.removeStorageSync('loginMode');
	uni.removeStorageSync('qr_preview_payload');
}

function inferLoginMode() {
	return resolveActiveAdminLoginMode();
}

/** 已登录时返回应跳转的首页，否则 null */
export function resolveLoggedInTarget() {
	const mode = inferLoginMode();
	if (mode && ADMIN_HOME[mode]) {
		return { url: ADMIN_HOME[mode] };
	}
	const token = uni.getStorageSync('token');
	if (!token) return null;
	const role = Number(uni.getStorageSync('identity') || uni.getStorageSync('role') || 0);
	if (role === 2) {
		return { url: '/pages/pharmacist/index' };
	}
	return { url: '/pages/workbench/index' };
}

export function redirectIfLoggedIn() {
	const target = resolveLoggedInTarget();
	if (target && target.url) {
		uni.reLaunch({ url: target.url });
		return true;
	}
	return false;
}

export function saveLoginSession(result) {
	if (!result) return;

	clearAllLoginStorage();

	const token = result.token ? String(result.token).trim() : '';
	const hint = result.redirect_hint || '';

	if (result.account_type === 'admin') {
		if (hint === 'platform_admin_home') {
			uni.setStorageSync('loginMode', 'platform_admin');
			uni.setStorageSync('platform_admin_token', token);
			uni.setStorageSync('platform_admin_user', result.user || {});
			return;
		}
		if (hint === 'salesperson_home') {
			uni.setStorageSync('loginMode', 'salesperson');
			uni.setStorageSync('salesperson_token', token);
			uni.setStorageSync('salesperson_user', result.user || {});
			return;
		}
		if (hint === 'clinic_salesperson_home') {
			uni.setStorageSync('loginMode', 'clinic_salesperson');
			uni.setStorageSync('clinic_salesperson_token', token);
			uni.setStorageSync('clinic_salesperson_user', result.user || {});
			return;
		}
		uni.setStorageSync('loginMode', 'clinic_admin');
		uni.setStorageSync('clinic_admin_token', token);
		uni.setStorageSync('clinic_admin_user', result.user || {});
		return;
	}

	uni.setStorageSync('token', token);

	const user = result.user || {};
	const storeDoctor = result.store_doctor || {};
	uni.setStorageSync('identity', user.role);
	uni.setStorageSync('logInfo', user);
	uni.setStorageSync('store_id', storeDoctor.store_id || '11001');
	if (user.id) {
		uni.setStorageSync('doctor_id', user.id);
		uni.setStorageSync('user_id', user.id);
	}
}

export async function fetchProfileAfterLogin(result) {
	if (result.account_type === 'admin') {
		const hint = result.redirect_hint || '';
		if (hint === 'platform_admin_home') {
			const wrap = await getPlatformAdminMyInfo();
			if (wrap && wrap.ok) {
				uni.setStorageSync('platform_admin_user', wrap.data);
			}
			return;
		}
		if (hint === 'salesperson_home') {
			const wrap = await getSalespersonMyInfo();
			if (wrap && wrap.ok) {
				uni.setStorageSync('salesperson_user', wrap.data);
			}
			return;
		}
		if (hint === 'clinic_salesperson_home') {
			const wrap = await getClinicSalespersonMyInfo();
			if (wrap && wrap.ok) {
				uni.setStorageSync('clinic_salesperson_user', wrap.data);
			}
			return;
		}
		const wrap = await getClinicAdminMyInfo();
		if (wrap && wrap.ok) {
			uni.setStorageSync('clinic_admin_user', wrap.data);
		}
		return;
	}

	if (result.user && result.user.id) {
		applyServiceUserProfile(result.user);
		return;
	}

	const data = {
		store_id: uni.getStorageSync('store_id') || '11001',
	};
	const res = await getUserInfo(data);
	if (res && res.errcode != -1) {
		applyServiceUserProfile(res.data);
	}
}

export function navigateAfterLogin(result) {
	const hint = result.redirect_hint;
	const role = Number(result.role || 0);
	const status = Number(result.status ?? result.user?.status ?? 0);

	if (hint === 'platform_admin_home') {
		uni.reLaunch({ url: '/subPackages/sub_platform_admin/home/index' });
		return;
	}
	if (hint === 'salesperson_home') {
		uni.reLaunch({ url: '/subPackages/sub_salesperson/home/index' });
		return;
	}
	if (hint === 'clinic_salesperson_home') {
		uni.reLaunch({ url: '/subPackages/sub_clinic_salesperson/home/index' });
		return;
	}
	if (result.account_type === 'admin' || hint === 'clinic_admin_home') {
		uni.reLaunch({ url: '/subPackages/sub_clinic_admin/home/index' });
		return;
	}

	if (hint === 'complete_profile' || status === 0) {
		uni.showToast({ title: '您还没有完善信息，请先完善信息', icon: 'none' });
		setTimeout(() => {
			uni.navigateTo({ url: '/subPackages/sub_workbench/workbench_upInfo/index' });
		}, 600);
		return;
	}

	if (hint === 'examine' || status === 1) {
		uni.showToast({ title: '您的账号还在审核中', icon: 'none' });
		setTimeout(() => {
			uni.reLaunch({ url: '/pages/workbench/examine' });
		}, 600);
		return;
	}

	if (status === 3) {
		setTimeout(() => {
			uni.reLaunch({ url: '/pages/workbench/examine' });
		}, 600);
		return;
	}

	if (hint === 'pharmacist_home' || role === 2) {
		setTimeout(() => {
			uni.reLaunch({ url: '/pages/pharmacist/index' });
		}, 400);
		return;
	}

	setTimeout(() => {
		uni.reLaunch({ url: '/pages/workbench/index' });
	}, 400);
}

export function clearLoginStorage() {
	clearAllLoginStorage();
	uni.$emit('user-logout');
}
