import permision from "@/js_sdk/wa-permission/permission.js";
import {
	getMacAddress
} from "../../utils/util";
import {
	systemList
} from "@/utils/commonDicts.js";
export default {
	namespaced: true,
	state: {
		userInfo: {},
		token: "",
		belongSystem: null, // 子系统实体类
		isDS: false, // 是否处于脱敏状态
		path: "", // 请求的前缀
		system: {}, // 当前选择的系统
		abcModel: false,
		spdbModel: false,
		ccbModel: false,
		dfklModel: false,
		publicModel: false,
		cibModel: false,
		icbcHModel: false,
		tjxtModel: false,
		homeOff: false, // 居家
		isOut: false, // 外访
		uuid: null, // 设备id
		netConfig: {
			// http://59.42.9.166:9520/proxy
			// http://10.0.7.100:9500
			// ip: "https://crm.nanjingshiyu.com/prod-api", // ip
			ip: "https://crmtest.nanjingshiyu.com/prod-api", // 测试环境ip
			// ip : "/api", // 测试环境ip
			// ip : "http://47.113.184.101", // 测试环境ip
			// ip: "http://172.16.7.200", // ip
			// port: "9500", // 端口
			isCallOff: "2", // 开关
			folder: "", // 文件夹
			webRtcIp: "", // 呼叫中心的ip
			webRtcPort: "", // 呼叫中心的端口s
		},
		systemList: [],

		redirectUrl: null,
		availableRoles: [], // 可用的角色列表
		currentRoleIndex: 0, // 当前选中的角色索引
		showRoleSwitch: false, // 是否显示切换权限按钮
	},
	mutations: {
		SET_REDIRECTURL(state, data) {
			state.redirectUrl = data;
		},
		SET_USER_ONLINE_STATUS: (state, data) => {
			state.userInfo.onlineStatus = data;
		},
		SET_USERINFO: (state, data) => {
			state.userInfo = data;
			const roles = data.roles || [];
			
			const validRoles = [];
			
			const hasWarehouser = roles.some(role => role.roleKey === 'WAREHOUSER');
			if (hasWarehouser) {
				validRoles.push('WAREHOUSER');
			}
			
			const hasSalesman = roles.some(role => role.roleKey === 'SALESMAN');
			if (hasSalesman) {
				validRoles.push('SALESMAN');
			}
			
			const hasCrmRole = roles.some(role => role.roleKey && role.roleKey.includes('CRM'));
			if (hasCrmRole) {
				validRoles.push('CRM');
			}
			
			const showSwitch = validRoles.length >= 2;
			state.showRoleSwitch = showSwitch;
			state.availableRoles = validRoles;
			state.currentRoleIndex = 0;
			
			setTimeout(() => {
				const allIndices = [0, 1, 2, 3, 4, 5, 6];
				allIndices.forEach(index => {
					uni.setTabBarItem({ index, visible: false });
				});
				
				const currentRole = validRoles[0] || '';
				
				switch (currentRole) {
					case 'SALESMAN':
						// 展示核价中心、询价中心、我的
						uni.setTabBarItem({ index: 3, visible: true }); // 询价中心
						uni.setTabBarItem({ index: 4, visible: true }); // 核价中心
						break;
					case 'WAREHOUSER':
						// 展示仓库中心、我的
						uni.setTabBarItem({ index: 2, visible: true }); // 仓库
						break;
					case 'CRM':
						// 展示首页、线索公海、销售线索、接单中心、我的
						uni.setTabBarItem({ index: 0, visible: true }); // 首页
						uni.setTabBarItem({ index: 1, visible: true }); // 线索公海
						uni.setTabBarItem({ index: 5, visible: true }); // 销售线索
						uni.setTabBarItem({ index: 6, visible: true }); // 接单中心
						break;
				}
				
				uni.setTabBarItem({ index: 7, visible: true }); // 我的
			}, 100);
		},

		SET_TOKEN: (state, data) => {
			state.token = data;
		},
		SET_NETCONFIG: (state, data) => {
			state.netConfig = data;
		},
		SET_BELONGSYSTEM: (state, data) => {
			const system = state.userInfo.subsystemList.find(item => (item.systemCode == data.code));
			if (system) {
				state.belongSystem = system;
				data.callback && data.callback(true);
			} else {
				data.callback && data.callback(false);
			}
		},
		SET_ISDS: (state, value) => {
			state.isDS = value
		},
		SET_HOMEOFF: (state, value) => {
			state.homeOff = value
		},
		SET_ISOUT: (state, value) => {
			state.isOut = value
		},
		SET_SYSTEM(state, data) {
			state.path = data.path;
			state.system = data;
			state.abcModel = data.text == "农行催收";
			state.spdbModel = data.text == "浦发催收";
			state.ccbModel = data.text == "建行催收";
			state.publicModel = data.text == "专业催收";
			state.dfklModel = data.text == "商账催收";
			state.cibModel = data.text == "兴业催收";
			state.icbcHModel = data.text == "工行催收";
			state.tjxtModel = data.text == "调催系统";
		},
		SET_UUID(state, data) {
			state.uuid = data;
		},
		SET_SYSTEM_LIST(state, data) {
			state.systemList = data;
		},
		// 权限相关mutations
		SET_AVAILABLE_ROLES(state, roles) {
			state.availableRoles = roles;
		},
		SET_CURRENT_ROLE_INDEX(state, index) {
			state.currentRoleIndex = index;
		},
		SET_SHOW_ROLE_SWITCH(state, show) {
			state.showRoleSwitch = show;
		},
		SWITCH_ROLE({}, role) {
			setTimeout(() => {
				const allIndices = [0, 1, 2, 3, 4, 5, 6];
				allIndices.forEach(index => {
					uni.setTabBarItem({ index, visible: false });
				});
				switch (role.value) {
					case 'SALESMAN':
						// 展示核价中心、询价中心、我的
						uni.setTabBarItem({ index: 3, visible: true }); // 询价中心
						uni.setTabBarItem({ index: 4, visible: true }); // 核价中心
						break;
					case 'WAREHOUSER':
						// 展示仓库中心、我的
						uni.setTabBarItem({ index: 2, visible: true }); // 仓库
						break;
					case 'CRM':
						// 展示首页、线索公海、销售线索、接单中心、我的
						uni.setTabBarItem({ index: 0, visible: true }); // 首页
						uni.setTabBarItem({ index: 1, visible: true }); // 线索公海
						uni.setTabBarItem({ index: 5, visible: true }); // 销售线索
						uni.setTabBarItem({ index: 6, visible: true }); // 接单中心
						break;
				}
				
				uni.setTabBarItem({ index: 7, visible: true }); // 我的
			}, 100);
		}
	},
	actions: {
		setSystemlist({
			commit,
			state
		}, systemCodeList) {
			state.systemList = systemList.filter(v => systemCodeList.includes(v.value));
		},
		getUserInfo(store) {
			const {
				commit,
				state,
				dispatch
			} = store;
			return new Promise((resolve, reject) => {
				uni.$u.api.getInfo().then(res => {
					commit("SET_USERINFO", res.user);
					commit("SET_BELONGSYSTEM", {
						code: state.system.value,
						callback: (flag) => {
							resolve(res.user);
						}
					});
				});
			})
		},
		login({
			commit,
			dispatch,
			state
		}, form) {
			return new Promise((resolve, reject) => {
				uni.$u.api.login(form).then((loginRes) => {
					const token = loginRes.data.access_token;
					commit("SET_TOKEN", token);
					dispatch("getUserInfo").then((userInfo) => {
						const { userId } = userInfo;
						resolve(userId);
					}).catch(() => {
						commit("SET_TOKEN", "");
						commit("SET_USERINFO", {});
						reject();
					})
				})
			})
		},
		logout({
			commit,
			dispatch
		}) {
			return uni.$u.api.logout().then(() => {
				// 停止电话监听
				dispatch("call/stopPhoneListener", null, { root: true }).catch(error => {
					console.error('退出登录时停止电话监听失败:', error);
				});

				commit("SET_TOKEN", "");
				commit("SET_USERINFO", {});
				dispatch("app/logoutCloseData", null, {
					root: true
				});
				Promise.resolve();
			}).catch(() => {
				Promise.reject();
			})
		},
	}
}

export function setupTabBar(userInfo, availableRoles, currentRoleIndex) {
		// 隐藏所有tabbar项，然后根据当前角色显示对应的项
		// 下标index从0开始
		const allIndices = [0, 1, 2, 3, 4, 5, 6];
		allIndices.forEach(index => {
			uni.setTabBarItem({ index, visible: false });
		});
		
		// 获取当前角色
		const currentRole = availableRoles[currentRoleIndex] || '';
		
		// 根据当前角色显示对应的tabbar
		switch (currentRole) {
			case 'SALESMAN':
				// 展示核价中心、询价中心、我的
				uni.setTabBarItem({ index: 3, visible: true }); // 询价中心
				uni.setTabBarItem({ index: 4, visible: true }); // 核价中心
				break;
			case 'WAREHOUSER':
				// 展示仓库中心、我的
				uni.setTabBarItem({ index: 2, visible: true }); // 仓库
				break;
			case 'CRM':
				// 展示首页、线索公海、销售线索、接单中心、我的
				uni.setTabBarItem({ index: 0, visible: true }); // 首页
				uni.setTabBarItem({ index: 1, visible: true }); // 线索公海
				uni.setTabBarItem({ index: 5, visible: true }); // 销售线索
				uni.setTabBarItem({ index: 6, visible: true }); // 接单中心
				break;
			default:
				// 默认情况，显示CRM相关的tabbar
				uni.setTabBarItem({ index: 0, visible: true }); // 首页
				uni.setTabBarItem({ index: 1, visible: true }); // 线索公海
				uni.setTabBarItem({ index: 5, visible: true }); // 销售线索
				uni.setTabBarItem({ index: 6, visible: true }); // 接单中心
				break;
		}
		
		// "我的"tab默认都展示（假设我的tab是index为7的位置）
		// 注意：这里需要根据实际的tabbar配置来调整index
		// 如果"我的"tab的index不是7，请修改下面的代码
		uni.setTabBarItem({ index: 7, visible: true }); // 我的
}

// 导出切换权限的action
export function switchRole({ commit, state }, currentRole) {
	commit('SWITCH_ROLE', currentRole);
}