import axios from "@/utils/axios";
import { get } from "@/utils/cookie";

import { getSectionInfo, getOrg } from "@/api/curingManage";

export interface State {
	roadBase: Array<any>;
	gantryBase: Array<any>;
	evtSrc: Array<any>;
	checkedLayers: Array<any>;
	evtList: Array<any>;
	camaras: Array<any>;
	loadings: any;
	informationBoards: Array<any>;

	allRoads: Array<any>; // 写死的路段数据
	selectRoadId: Array<any>;
	selectLevel: any;
	selectCode: any;
	eventSelected: any;
	selectAllRoad: Array<any>;
	selectProvince: any;
	orgInfo: any;
}

const state: State = {
	roadBase: [],
	evtSrc: [],
	camaras: [],
	checkedLayers: [],
	evtList: [],
	loadings: {},
	informationBoards: [],
	gantryBase: [],

	selectRoadId: [],
	allRoads: [],
	selectLevel: 0,
	selectCode: 0,
	eventSelected: {}, // 选中事件
	selectAllRoad: [],
	selectProvince: "", // 选中省份
	orgInfo: {}, // 组织架构信息
};

// getters
const getters = {};

// actions
const actions = {
	// 获取所有路段
	async getAllRoads({ state, commit }: any): Promise<void> {
		// if (state.allRoads?.length > 0) {
		//   return;
		// }
		try {
			// const res: any = await getSectionInfo();
			const res: any = await getOrg();
			console.log("51获取全部组织接口", res);
			// console.log('获取所有组织', res);
			if (res.msgState === "SUCCESS") {
				// let newmsgContent: any = []
				// res.msgContent.forEach((ele: any )=> {
				//   if(ele.organizationId == 'SC' || ele.pnode == 'SC' || ele.provinceId == 'SC') {
				//     newmsgContent.push(ele)
				//   }
				// });
				// 记录所有的一级组织架构
				let level1_arr: any = [];
				let orgInfo: object = {};
				res.msgContent.forEach((ele: any) => {
					if (ele.level == "1") {
						level1_arr.push(ele);
						orgInfo = ele;
					}
				});
				// 如果用户的权限只有某个省，那就展示第一个省，否则展示所有省 用于头部标题
				if (level1_arr.length >= 2) {
					orgInfo = {};
				}
				// 如果用户的权限是所有省份(目前是5个省，后面根据需求改), 就优先展示重庆。
				// 如果用户的权限只有某个省，那就展示第一个省
				// let orgId: any = level1_arr.length < 5 ? level1_arr[0].organizationId : 'CQ'
				let orgId: any = ""; // 默认展示全国
				localStorage.setItem("orgId", orgId);
				localStorage.setItem("orglen", level1_arr.length);
				localStorage.setItem("orgInfo", JSON.stringify(orgInfo));
				const arr = [].concat(res.msgContent);
				commit("setAllRoads", arr);
				commit("setOrgInfo", orgInfo);
			} else {
				throw res.msgDes;
			}
		} catch (error) {
			console.log("获取路段列表信息失败");
		}
	},
	async getRoadBase({ state, commit }: any): Promise<void> {
		if (state.roadBase?.length > 0) {
			return;
		}
		try {
			const res: any = await axios.get(
				"/http-server-yygl/publish/jsc/roadbase"
			);

			if (res.msgState === "SUCCESS") {
				commit("setRoadBase", res.msgContent);
			} else {
				throw res.msgDes;
			}
		} catch (error) {
			console.log("获取路段信息失败");
		}
	},
	async getEvtList({ state, commit }: any): Promise<void> {
		if (state.evtList?.length > 0) {
			return;
		}
		commit("setLoading", {
			key: "EVENT_POINT",
			value: true,
		});
		try {
			const res: any = await axios.get(
				"/external/event/cockpit-event-list?pageNo=1&pageSize=1000"
			);
			if (res?.data?.result) {
				commit("setEvtList", res?.data?.result);
			} else {
				throw res.msgDes;
			}
			commit("setLoading", {
				key: "EVENT_POINT",
				value: false,
			});
		} catch (error) {
			console.log("获取事件信息失败");
			commit("setLoading", {
				key: "EVENT_POINT",
				value: false,
			});
			commit("removeLayer", "EVENT_POINT");
		}
	},
	async getGantryBase({ state, commit }: any): Promise<void> {
		if (state.gantryBase?.length > 0) {
			return;
		}
		commit("setLoading", {
			key: "GANTRY_POINT",
			value: true,
		});
		try {
			const res: any = await axios.get(
				"/http-server-yygl/publish/jsc/gantrybase?com=list"
			);
			if (res.msgState === "SUCCESS") {
				commit("setGantryBase", res.msgContent);
			} else {
				throw res.msgDes;
			}
			commit("setLoading", {
				key: "GANTRY_POINT",
				value: false,
			});
		} catch (error) {
			console.log("获取门架信息失败");
			commit("setLoading", {
				key: "GANTRY_POINT",
				value: false,
			});
			commit("removeLayer", "GANTRY_POINT");
		}
	},
	async getEvtSrc({ state, commit }: any): Promise<void> {
		if (state.roadBase?.length > 0) {
			return;
		}
		try {
			const res: any = await axios.get("/sys/bm/findEventSource");
			if (res.success) {
				const list = res.data;
				const target: any = [];
				list?.forEach(({ name, code, children }: any) => {
					target.push({ name, code });
					if (children?.length > 0) {
						children.forEach((e: any) => {
							const { name: cName, code: cCode } = e;
							target.push({
								name: name + "-" + cName,
								code: cCode,
							});
						});
					}
				});
				commit("setEvtSrc", target);
			} else {
				throw "failed";
			}
		} catch (error) {
			console.log("获取事件来源信息失败");
		}
	},
	// 情报板
	async getAllInformationBoards({ state, commit }: any): Promise<void> {
		if (state.informationBoards?.length > 0) {
			return;
		}
		commit("setLoading", {
			key: "INFOMATION_BOARD_POINT",
			value: true,
		});
		try {
			const res: any = await axios.get(
				"/manage/getDeviceInfoList?typeCode=TY003&page=1&pageSize=1000"
			);
			if (res.result && res.datas) {
				commit("setInformationBoards", res.datas);
			} else {
				throw "获取情报板数据失败";
			}
			commit("setLoading", {
				key: "INFOMATION_BOARD_POINT",
				value: false,
			});
		} catch (error) {
			commit("setLoading", {
				key: "INFOMATION_BOARD_POINT",
				value: false,
			});
			console.log("获取情报板数据失败");
			commit("removeLayer", "INFOMATION_BOARD_POINT");
		}
	},
	// 视频
	async getAllCameras({ state, commit }: any): Promise<void> {
		if (state.camaras?.length > 0) {
			return;
		}
		commit("setLoading", {
			key: "CAMERA_POINT",
			value: true,
		});
		try {
			const res: any = await axios.get("/video/getVideoDeviceList");
			if (res.result && res.datas) {
				commit("setCamaras", res.datas);
			} else {
				throw "获取摄像头数据失败";
			}
			commit("setLoading", {
				key: "CAMERA_POINT",
				value: false,
			});
		} catch (error) {
			commit("setLoading", {
				key: "CAMERA_POINT",
				value: false,
			});
			console.log("获取摄像头失败");
			commit("removeLayer", "CAMERA_POINT");
		}
	},
	setEventSelected({ state, commit }: any, data: any) {
		commit("setEventSelected", data);
	},
};

// mutations
const mutations = {
	setOrgInfo: (state: State, orgInfo: any) => {
		state.orgInfo = orgInfo;
	},
	setAllRoads: (state: State, allRoads: any) => {
		state.allRoads = allRoads;
	},
	setRoadBase: (state: State, roadBase: any) => {
		state.roadBase = roadBase;
	},
	setGantryBase: (state: State, gantryBase: any) => {
		state.gantryBase = gantryBase;
	},
	setEvtSrc: (state: State, evtSrc: any) => {
		state.evtSrc = evtSrc;
	},
	setCheckedLayers: (state: State, checked: any) => {
		state.checkedLayers = checked;
	},
	setLoading: (state: State, { key, value }: any) => {
		state.loadings[key] = value;
	},
	setInformationBoards: (state: State, list: any) => {
		state.informationBoards = list;
	},
	setCamaras: (state: State, list: any) => {
		state.camaras = list;
	},
	setEvtList: (state: State, list: any) => {
		state.evtList = list;
	},
	removeLayer: (state: State, name: any) => {
		state.checkedLayers = state.checkedLayers.filter(
			(e: any) => e !== name
		);
	},
	setSelectRoadId: (state: State, selectRoadId: any) => {
		state.selectRoadId = selectRoadId;
	},
	setSelectLevel: (state: State, selectLevel: any) => {
		state.selectLevel = selectLevel;
	},
	//code
	setSelectCode: (state: State, selectCode: any) => {
		state.selectCode = selectCode;
	},
	//设置选中事件经纬度
	setEventSelected: (state: State, eventSelected: any) => {
		state.eventSelected = eventSelected;
	},
	setSelectAllRoad: (state: State, ids: any) => {
		state.selectAllRoad = ids;
	},
	// 设置选中省份
	setSelectProvince: (state: State, ids: any) => {
		state.selectProvince = ids;
	},
};

export default {
	namespaced: true,
	state,
	getters,
	actions,
	mutations,
};
