import { Module } from 'vuex';
import { Session, Local } from '/@/utils/storage';
import {getuserinfo} from '/@/api/login/index';
// 此处加上 `.ts` 后缀报错，具体原因不详
import { UserInfosState, RootStateTypes } from '/@/store/interface/index';
import { getClientVsResourceListApi } from '/@/api/client_vs_resource';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { scheduleGetConfig } from '/@/api/scheduling/HemoMedSchedule';

const userInfosModule: Module<UserInfosState, RootStateTypes> = {
	namespaced: true,
	state: {
		userInfos: {},
		paibanConfig:{scheduleIsEnablePlusSlot:0,schedulePlusSlotName:''}, // 排班配置项
		clientVsUser: [],
		// selectedFieldsInMedStat2: Local.get("selectedFieldsInMedStat2") || "", // 药品统计2页面,自定义显示的药品字段  该字段已废弃，转入printSetting下面
		selectFieldsInTodayOrderPage: Local.get("selectFieldsInTodayOrderPage") || "", // 今日医嘱页面，自定义医嘱显示的列名
		printSetting: Local.get("printSetting") || { selectFieldsInShangjiCanshuPage: "" }, // 用户设置的相关参数，药品统计2不在其中
		selectedFieldsInInventory2QueryPage: Local.get('selectedFieldsInInventory2QueryPage') || '', // 二级库房查询页面自定义显示字段
		selectedFieldsInInventory2OutPage: Local.get('selectedFieldsInInventory2OutPage') || '', // 二级出库的自定义打印列
		selectedFieldsInCleanStatPage: Local.get('selectedFieldsInCleanStatPage') || '', // 消毒统计页面的自定义打印列
 		// 下面这两个id和code是当前账号的id和code，不是客户
		id: Local.get("uId") || "",
		code: Local.get("uCode") || "",
		patientIsAlive:1,
		// 选择的排班天数查看
		ShowWeeksData:Local.get('ShowWeeksData') || [],
		signedInCountByDa: Local.get('signedInCountByDa') || '1', // 是否只统计已签到的透析单-今日医嘱
		patientIsAliveTrigger: null, // 这个只用来更新左上角的患者列表，传时间戳
		notBasicDictTyHisTypes: ['康博佳', '骆工His', '新安国际HIS', '天津长康HIS'], // 对应his设置的类型，不需要合并字典等等的，禅道id2257
	},
	mutations: {
		// 设置用户信息
		getUserInfos(state: any, data: object) {
			console.log('设置用户信息---------------',data)
			state.userInfos = data;
		},
		getUserInfoCilent(state: any, data: object) {
			state.userInfos.client = data;
		},
		// 设置客户下用户信息
		getClientUser(state: any, data: object) {
			state.clientVsUser = data;
		},
		SET_PaibanConfig(state: any, data: object) {
			state.paibanConfig = data;
		},
		SET_ShowWeeksData(state:any,list:[]){
			Local.set('ShowWeeksData', list);
			state.ShowWeeksData= list
		},
		// 设置二级出库页面自定义打印列
		SET_SELECTFIELDSININVENTORYOUTPAGE(state: any, str: string) {
			Local.set('selectedFieldsInInventory2OutPage', str);
			state.selectedFieldsInInventory2OutPage = str;
		},
		// 设置药品统计2页面,自定义显示的药品字段
		// SET_SELECTFIRLDSINMEDSTAT2(state: any, str: string) {
		// 	Local.set("selectedFieldsInMedStat2", str);
		// 	state.selectedFieldsInMedStat2 = str;
		// },
		// 今日医嘱页面，自定义医嘱显示的列名
		SET_SELECTFIELDSINTODAYORDERPAGE(state: any, str: string) {
			Local.set("selectFieldsInTodayOrderPage", str);
			state.selectFieldsInTodayOrderPage = str;
		},
		// 二级库房查询页面自定义显示字段的列名selectedFieldsInInventory2QueryPage
		SET_SELECTFIELDSINVENTORY2QUERYPAGE: (state: any, str: string) => {
			Local.set('selectedFieldsInInventory2QueryPage', str);
			state.selectedFieldsInInventory2QueryPage = str;
		},
		SET_SELECTDFIELDSINCLEANSTATPAGE: (state: any, str: string) => {
			Local.set('selectedFieldsInCleanStatPage', str);
			state.selectedFieldsInCleanStatPage = str;
		},
		// 用户的相关参数，如果key不传，则认为修改的是全部的
		SET_PRINTSETTING(state: any, settingObj: { val: string | object; key?: string }) {
			const { val, key } = settingObj;
			if(key) {
				const obj = JSON.parse(JSON.stringify(state.printSetting));
				obj[key] = val;
				Local.set("printSetting", obj);
				console.log("obj", obj)
				state.printSetting = obj;
			} else {
				Local.set("printSetting", val);
				state.printSetting = val;
			}
		},
		SET_UID(state: any, id: string) {
			Local.set("uId", id);
			state.id = id;
		},
		SET_UCODE(state: any, code: string) {
			Local.set("uCode", code);
			state.code=code
			// state.uCode = code;
		},
		SET_patientIsAlive(state: any, type: number) {
			console.log('type: ', type)
			state.patientIsAlive = type;
		},
		// signedInCountByDa
		SET_SIGNEDINCOUNTBYDA(state: any, val: string) {
			Local.set('signedInCountByDa', val);
			state.signedInCountByDa = val;
		},
		SET_PATIENTISALIVETRIGGER(state: any, val: number) {
			state.patientIsAliveTrigger = val;
		}
	},
	actions: {
		// 设置用户信息
		async setUserInfos({ commit }) {
			if (Session.get('userInfo')) {
				console.log('更具本地存储读取用户信息')
				commit('getUserInfos', Session.get('userInfo'));
				const data=Session.get('userInfo');
				if(data.client?.code){
					const datamode= await scheduleGetConfig({ clientCode: data.client?.code })
					console.log('获取排班配置项',datamode)
					commit('SET_PaibanConfig',datamode.data);
				}
				
			} else {
				/** 设置用户相关自定义设置 */
				const setUserSetting = (data: any) => {
					const printSetting = {
						selectFieldsInShangjiCanshuPage: data.selectFieldsInShangjiCanshuPage || '', // 上机参数页面, 自定义显示字段
						selectedFieldsInMedStat2: data.selectedFieldsInMedStat2 || '', // 药品准备2自定义显示字段
						listReadyRows: data.listReadyRows || '', // 透析耗材准备自定义显示字段
						listStatInfo: data.listStatInfo || '', // 透析耗材统计自定义显示字段
						prepareWorkMedicine: data.prepareWorkMedicine || '', // 药品准备自定义显示字段
						prepareWorkMedicineStat: data.prepareWorkMedicineStat || '', // 药品准备自定义显示字段
						排班时段选择项: data.排班时段选择项, // 患者排班的排班时段选项
						隐藏自备药: data.隐藏自备药, // 今日医嘱页面展示
						是否自动出库至二级默认仓库: data.是否自动出库至二级默认仓库 || 0, // 一级出库是否自动出库至二级默认仓库
					};
					// store.commit("userInfos/SET_PRINTSETTING", { val: printSetting });
					commit('SET_PRINTSETTING', { val: printSetting });
					// 二级库存查询的自定义打印列设置
					// store.commit('userInfos/SET_SELECTFIELDSINVENTORY2QUERYPAGE', data.selectedFieldsInInventory2QueryPage);
					commit('SET_SELECTFIELDSINVENTORY2QUERYPAGE', data.selectedFieldsInInventory2QueryPage);
					// 二级出库的自定义打印列设置
					// store.commit('userInfos/SET_SELECTFIELDSININVENTORYOUTPAGE', data.selectedFieldsInInventory2OutPage);
					commit('SET_SELECTFIELDSININVENTORYOUTPAGE', data.selectedFieldsInInventory2OutPage);
					// 消毒统计的自定义打印列设置
					// store.commit('userInfos/SET_SELECTDFIELDSINCLEANSTATPAGE', data.selectedFieldsInCleanStatPage);
					commit('SET_SELECTDFIELDSINCLEANSTATPAGE', data.selectedFieldsInCleanStatPage);
					// 今日医嘱-是否只统计已签到的透析单
					// store.commit('userInfos/SET_SIGNEDINCOUNTBYDA', data.signedInCountByDa || '1');
					commit('SET_SIGNEDINCOUNTBYDA', data.signedInCountByDa || '1');
					
					// 当前账号的id和code
					// store.commit("userInfos/SET_UID", data.id);
					commit('SET_UID', data.id);
					// store.commit("userInfos/SET_UCODE", data.code);
					commit('SET_UCODE', data.code);
				}

				/** 
				 * 设置用户信息
				 *  type 0超级管理员 1含有多家客户 2独家
				*/
				const setUserInfo = async (data: any, defaultRoles: any[], defaultMenus: any[], defaultAuthBtnList: any[], type: 0 | 1 | 2) => {
					const clients = type === 0 ? data?.管理员能看到的客户列表 : data.clientInfos;
					const clinetCode = data?.currentClientInfo?.code;
					let menus = defaultMenus;
					if (type === 2) {
						menus = await filterClientDisablePermission(defaultMenus, clinetCode);
					}

					return {
						userCode: data.code,
						userName: data.userName,
						photo: data.userAvatar,
						time: new Date().getTime(),
						roles: defaultRoles,
						meuns: menus,
						client: data.currentClientInfo,
						authBtnList: defaultAuthBtnList,
						clients: clients
					}
				}

				/** 过滤当前选中客户已经禁用掉的权限菜单 */
				const filterClientDisablePermission = async (meuns: any[], clientCode: string) => {
					const { data } = await getClientVsResourceListApi({
						page: 0,
						size: 0,
						wherecondition: `client_code='${clientCode}' AND is_deleted=0`,
						ordercondition: '',
					});
					const disablePermission = data.list.map(v => v.resourceCode);
					const menuRes = meuns.filter(v => !disablePermission.includes(v.resourceCode));
					return menuRes;
				}
				// 通过接口获取用户信息
				const { data: userData } = await getuserinfo();
				console.log('通过接口获取用户信息-----')
				console.log('通过接口获取用户信息-----')
				console.log('通过接口获取用户信息-----')
				console.log('通过接口获取用户信息-----')
				console.log('通过接口获取用户信息-----')

				console.log('通过接口获取用户信息-----')
				console.log('通过接口获取用户信息',userData)
				setUserSetting(userData);
				let defaultRoles: Array<string> = [];
				let defaultMenus =[]; // 这里是路由
				let defaultAuthBtnList: Array<string> = [];
				// admin 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
				// let adminRoles: Array<string> = ['admin'];
				// admin 按钮权限标识
				let adminAuthBtnList: Array<string> = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
				// test 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
				let testRoles: Array<string> = ['common'];
				// test 按钮权限标识
				let testAuthBtnList: Array<string> = ['btn.add', 'btn.link'];
				// 如果用户权限为空
				if (userData.roles.length <= 0) {
					defaultRoles = testRoles;
					defaultAuthBtnList = testAuthBtnList;
					Session.set('token', '');
					return false;
				}

				// 如果用户权限不为空
				const menuMap = new Map<string, any>();

				for (const ro of userData.roles) {
				defaultRoles.push(ro.roleName);

				for (const e of ro.roleVsResourceList) {
					const existing = menuMap.get(e.resourceName);

					if (!existing || e.grantPrivilege === 'RW') {
					menuMap.set(e.resourceName, e);
					}
				}
				}

				defaultMenus = Array.from(menuMap.values());
				defaultAuthBtnList = adminAuthBtnList;

				if(defaultRoles.indexOf('admin')>-1){ 
					const userInfos = await setUserInfo(userData, defaultRoles, defaultMenus, defaultAuthBtnList, 0);
					// 存储用户信息到浏览器缓存
					Session.set('userInfo', userInfos);
					Local.set('client_'+userData.userName,userData.currentClientInfo.code);
					commit('getUserInfos', userInfos)
					if(userInfos.client?.code){
						const datamode= await scheduleGetConfig({ clientCode: userInfos.client?.code })
						console.log('获取排班配置项',datamode)
						commit('SET_PaibanConfig',datamode.data);
					}
					// 1、请注意执行顺序(存储用户信息到vuex)
					// store.dispatch('userInfos/setUserInfos');
					// await initFrontEndControlRoutes();
				} else {
					const userInfos = await setUserInfo(userData, defaultRoles, defaultMenus, defaultAuthBtnList, 2);
					// 存储用户信息到浏览器缓存
					Session.set('userInfo', userInfos);
					Local.set('client_'+userData.userName,userData.currentClientInfo.code);
					commit('getUserInfos', userInfos)
					if(userInfos.client?.code){
						const datamode= await scheduleGetConfig({ clientCode: userInfos.client?.code })
						console.log('获取排班配置项',datamode)
						commit('SET_PaibanConfig',datamode.data);
					}
					// 1、请注意执行顺序(存储用户信息到vuex)
					// store.dispatch('userInfos/setUserInfos');
					// await initFrontEndControlRoutes();
				}
			}
		},
		
		async setClientVsUser ({ commit }, userList) {
			// store 赋值
			commit('getClientUser', userList)
		}
	},
};

export default userInfosModule;
