import type { Effect, Reducer } from 'umi';

import { queryCurrent, query as queryUsers, synchroBehaviorRecord } from '@/services/user';
import session from '@/utils/session';
import globalState from '@/globalState';
import { history } from 'umi';

// import { menuFormatter } from '@/utils/menuformatter'

export type CurrentUser = {
	UserName: string; // 登录帐户 ,
	ID: number; // 帐户内码 ,
	Name: string; // 用户名称 ,
	DepartmentName: string; // 所属部门 ,
	UserMobilephone: string; // 手机号码 ,
	ProvinceCode: string; // 省份编码，如330000 ,
	ProvinceUnit: string; // 业主单位 ,
	OwnerUnitId: number; // 业主单位id ,
	OwnerUnitName: string; // 业主单位 ,
	UserToken: string; // 登录标识 ,
	CityAuthority: string; // 用户服务区权限 ,
	EnabledRepeat: boolean; // 是否允许重复登录 ,
	UserModuleList: [] // 用户模块权限
	ServerpartShopIds: string, // 商户门店权限
	SuperAdmin: string // 是否是超级管理员
	TopSystemRoleId: number // 父级角色id
	UserPattern: number // 账号类型 1000 业主；2000商户
	BusinessManID: number // 归属商户id
	BusinessManName: string // 归属商户名称
	ID_Encrypted: string // 归属商户名称
	HeadImgUrl: string; // 用户头像链接
	ServerpartIds: string; // 服务区ids
	unreadCount: number; // 未读消息数量
	SupplierID: number;
};

export type UserModelState = {
	currentUser?: CurrentUser;
};

export type UserModelType = {
	namespace: 'user';
	state: UserModelState;
	effects: {
		fetch: Effect;
		fetchCurrent: Effect;
		addUserRecord: Effect;
	};
	reducers: {
		saveCurrentUser: Reducer<UserModelState>;
		changeNotifyCount: Reducer<UserModelState>;
	};
};

const UserModel: UserModelType = {
	namespace: 'user',

	state: {
		currentUser: undefined,
	},

	effects: {
		*fetch({ callback }, { call, put, select }) {

			const user = yield select((state: UserModelState) => state.currentUser)

			if (!user) {
				const response = yield call(queryUsers);

				yield put({
					type: 'saveCurrentUser',
					payload: response,
				});
				if (callback && typeof callback === 'function') {
					callback(response)
				}
			}
			return user
		},
		*fetchCurrent({ payload }, { call, put, select }) {
			const user = yield select((state: UserModelState) => state.currentUser)
			if (!user) {
				const response = yield call(queryCurrent, payload);

				yield put({
					type: 'saveCurrentUser',
					payload: response,
				});
				return response;
			}
			return user
		},
		*addUserRecord({ payload }, { call }) {
			const basicInfo: any = session.get('basicInfo')
			yield call(synchroBehaviorRecord, {
				...payload,
				BEHAVIORRECORD_ROUTNAME: payload?.BEHAVIORRECORD_ROUT === '/' ? '首页' : payload?.BEHAVIORRECORD_ROUTNAME,
				USER_LOGINIP: basicInfo?.ip ? basicInfo?.ip : '',
				BEHAVIORRECORD_TYPE: 1000,
				USER_LOGINPLACE: `${basicInfo?.prov ? basicInfo?.prov : ''}${basicInfo?.prov && basicInfo?.city ? '-' : ''}${basicInfo?.city ? basicInfo?.city : ''}`,
				// BrowserVersion: browser || '',
				// OperatingSystem: systemInfo || '',

			});
		}
	},

	reducers: {
		saveCurrentUser(state, action) {
			const user = { ...action.payload };
			//   const menu = menuFormatter([... user.UserModuleList])
			delete user.UserModuleList;
			globalState.set('currentUser', user);
			session.set('currentUser', user);

			return {
				...state,
				currentUser: user || {},
			};
		},
		changeNotifyCount(
			state = {
				currentUser: {},
			},
			action,
		) {
			return {
				...state,
				currentUser: {
					...state.currentUser,
					notifyCount: action.payload.totalCount,
					unreadCount: action.payload.unreadCount,
				},
			};
		},
	},
};

export default UserModel;
