<template>
	<view class="amms-stagin">
		<view class="container">
			<view class="head_information">
				<image v-if="headSrc != ''" :src="headSrc" class="pic"></image>
				<image v-else src="../../../static/img/ammsHome/touxiang.png" class="pic"></image>
				<view class="right">
					<view class="n">{{ usernameCn }}</view>
					<view class="node">员工编号：{{ userNo }}</view>
				</view>
			</view>
			<view class="nav">
				<view class="item">
					<view class="n">{{ userWarehouse || '--' }}</view>
					<view class="s">工作仓库</view>
				</view>
				<view class="item">
					<view class="n">{{ userTerminal || '--' }}</view>
					<view class="s">工作航站</view>
				</view>
				<view class="item">
					<view class="n">{{ userStock || '--' }}</view>
					<view class="s">工作库存地</view>
				</view>
			</view>
			<!--  -->
			<view class="weather" @tap="setWeather">
				<block v-if="weatherObj != null">
					<view class="item">
						<view class="n"></view>
						<view class="s active" @click.stop="toSet">{{ weatherObj.city || '--' }}</view>
					</view>
					<view class="item">
						<view class="n">{{ weatherObj.weather || '--' }}</view>
						<view class="s">天气</view>
					</view>
					<view class="item">
						<view class="n">{{ `${weatherObj.temperature || '--'}℃` }}</view>
						<view class="s">温度</view>
					</view>
					<view class="item">
						<view class="n">{{ `${weatherObj.humidity || '--'}%` }}</view>
						<view class="s">空气湿度</view>
					</view>
					<uni-transition custom-class="transition" :mode-class="modeClass" class="transition" :show="true">
						<image :src="getWeatherPic" class="pic"></image>
					</uni-transition>
				</block>
				<view v-if="area == ''" class="weatherMask" @tap="toSet">——点击前往设置所在城市开启天气——</view>
			</view>
			<!--  -->
			<view class="work_nav">
				<view class="title">
					<view class="left" @tap="footClick">
						<text>我的工作菜单</text>
						<!-- <image src="../../../static/img/ammsHome/more.png" class="pic"></image> -->
					</view>
					<view class="right">
						<button v-show="sortIs" size="mini" @click="edit" hover-class="is-hover"
							type="primary">编辑</button>
						<button v-show="!sortIs" size="mini" @click="save" hover-class="is-hover"
							type="primary">保存</button>
					</view>
				</view>

				<l-drag class="ul" :list="workList" :disabled="sortIs" @change="onMoveCallback" :column="4" gridHeight="188rpx" :longpress="true" after>
					<template #grid="{content}">
						<view class="li-wrap">
							<view class="li" :class="{'liShake': !sortIs}" @tap="path_url(content)">
								<view class="na">
									<image :src="content.imgs" class="pic"></image>
									<view class="n">{{ content.name }}</view>
								</view>
								<image v-show="iconImgShow && content.ifDefault != '1'"
									src="../../../static/img/ammsHome/reduce.png" @tap.stop="iconClick(content)" class="icon">
								</image>
							</view>
						</view>
					</template>
					<template #after>
						<view class="li-wrap">
							<view class="li" @tap="footClick">
								<view class="na">
									<image src="../../../static/img/ammsHome/icon5.png" class="pic"></image>
								</view>
							</view>
						</view>
					</template>
				</l-drag>
			</view>
		</view>
		<q-loading mask="true" click="true" ref="loading"></q-loading>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, getCurrentInstance, computed } from 'vue';
	import { request, requestOutUrl } from '@/utils/request';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	const { proxy } = getCurrentInstance();
	const weatherObj = ref({
		city: '',
		weather: '',
		temperature: '',
		humidity: ''
	});
	const area = ref('');
	const weatherIconObj: any = {
		'晴': '../../../static/img/ammsHome/weather/qingtian.png',
		'多云': '../../../static/img/ammsHome/weather/duoyun.png',
		'雷阵雨': '../../../static/img/ammsHome/weather/leizhenyu.png',
		'暴雪': '../../../static/img/ammsHome/weather/baoxue.png',
		'暴雨': '../../../static/img/ammsHome/weather/baoyu.png',
		'大雪-暴雪': '../../../static/img/ammsHome/weather/dabaoxue.png',
		'大暴雨': '../../../static/img/ammsHome/weather/dabaoyu.png',
		'大雪': '../../../static/img/ammsHome/weather/daxue.png',
		'大雨': '../../../static/img/ammsHome/weather/dayu.png',
		'台风': '../../../static/img/ammsHome/weather/taifeng.png',
		'雾': '../../../static/img/ammsHome/weather/wu.png',
		'霾': '../../../static/img/ammsHome/weather/wumai.png',
		'小雪': '../../../static/img/ammsHome/weather/xiaoxue.png',
		'雪': '../../../static/img/ammsHome/weather/xiaoxue.png',
		'小雨': '../../../static/img/ammsHome/weather/xiaoyu.png',
		'雨': '../../../static/img/ammsHome/weather/xiaoyu.png',
		'阴': '../../../static/img/ammsHome/weather/yintian.png',
		'雨夹雪': '../../../static/img/ammsHome/weather/yujiaxue.png',
		'中雪': '../../../static/img/ammsHome/weather/zhongxue.png',
		'中雨': '../../../static/img/ammsHome/weather/zhongyu.png'
	};
	const modeClass = ref(['fade', 'slide-right']);
	const isVirtual = ref(true);
	const sortIs = ref(true);
	const iconImgShow = ref(false);
	const usernameCn = ref('');
	const userNo: any = ref('');
	const userStock = ref('--');
	const userTerminal = ref('--');
	const userFactory = ref('--');
	const userWarehouse = ref('--');
	const workList = ref([]);
	const headSrc = ref('')

	onMounted(() => {
		
	})
	onShow(() => {
		// 判断登录类型显示id
		if (uni.getStorageSync('loginType') == 'iam') {
			userNo.value = uni.getStorageSync('userAppId');
			headSrc.value = `https://amms.hnatechnic.com/hnahr/image/headimage/emp/${(userNo.value+'').substring(0, 6)}0000/${userNo.value}.jpg`;
		} else {
			userNo.value = uni.getStorageSync('userid');
			headSrc.value = '';
		}
		
		getUserAttributesFun(uni.getStorageSync('username'));
		// 获取天气数据
		area.value = uni.getStorageSync('ammsArea') || '';
		if (!uni.getStorageSync('adcodeAndCityCode')) {
			request({
				method: 'post',
				url: 'adcodeAndCityCode-getInfo',
				data: {}
			})
				.then((res : any) => {
					console.log(res)
					if (res.code == 0) {
						uni.setStorageSync('adcodeAndCityCode', res.data);
						if (area.value) {
							setTimeout(()=> {
								setWeather();
							}, 500)
							
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
				.catch((err : any) => {
					console.log(err);
				});
		} else {
			if (area.value) {
				setTimeout(()=> {
					setWeather();
				}, 500)
			}
		}
	})
	onLoad(() => {
		// 监听站点选择回调
		uni.$off('menuList');
		uni.$on('menuList', () => {
			getMenu()
		});
	})
	
	function setWeather () {
		const adcodeAndCityCode = uni.getStorageSync('adcodeAndCityCode');
		let adcode = '';
		let _area = area.value.split('-')[2]
		adcodeAndCityCode.forEach((ele: any) => {
			if (ele.name.indexOf(_area) > -1) {
				adcode = ele.adcode;
			}
		})
		requestOutUrl({
			method: 'get',
			url: 'weather-weatherInfo',
			data: {
				key: '4801a8ed294e7e691a763b5db19606df',
				city: adcode
			},
		}).then((res2 : any) => {
			console.log(res2)
			if (res2.status == '1') {
				weatherObj.value = res2.lives[0]
			}
		}).catch((err : any) => {
			console.log(err)
			uni.showToast({
				title: err.errMsg,
				icon: 'none'
			});
		});
	}
	
	const getWeatherPic = computed (() => {
		if (weatherObj.value.weather != '') {
			return typeof(weatherIconObj[weatherObj.value.weather]) == 'undefined' ? weatherIconObj['多云'] : weatherIconObj[weatherObj.value.weather]
		} else {
			return ''
		}
	});
	
	function edit() {
		iconImgShow.value = true;
		sortIs.value = false;
		proxy.$emit('recall', 'stagingEdit');
		uni.showToast({
			icon: 'none',
			title: '已锁定当前页面，完成编辑后可解除锁定，长按菜单可拖动进行排序操作。',
			duration: 2000
		})
	}

	function save() {
		iconImgShow.value = false;
		sortIs.value = true;
		proxy.$emit('recall', 'stagingSave');
	}

	function footClick() {
		uni.navigateTo({
			url: '/pages/home/components/menuList'
		});
	}
	
	function toSet() {
		uni.navigateTo({
			url: '/pages/home/components/stagingSettings'
		});
	}

	function init() {
		if (workList.value.length == 0) {
			getMenu();
		} 
		
	}
	// 获取收藏菜单
	function getMenu() {
		proxy.$emit('recall', 'open');
		request({
			method: 'post',
			url: 'appmenu-selectMenuCollectPage',
			data: {
				parentid: uni.getStorageSync('_PARAMETERS_') || '10076',
				page: "1",
				length: "500"
			},
		}).then((res : any) => {
			proxy.$emit('recall', 'close');
			if (res.code == 0) {
				let arr = res.data.records;
				if (arr.length > 0) {
					let initData : any = [];
					arr?.map((item : any) => {
						initData.push({
							active: false,
							name: item.name,
							imgs: 'data:image/png;base64,' + item.iconFileUrl,
							menuId: item.menuId,
							parentId: item.parentId,
							ifDefault: item.ifDefault,
							path: item.path,
							iconImgShow: true,
							isVirtual: false,
						})
					});
					workList.value = [];
					workList.value = initData;
				} else if (arr.length == 0) {
					let initData : any = [];
					workList.value = [];
					workList.value = initData;
				}
			}

		}).catch((err : any) => {
			uni.showToast({
				title: err.errMsg,
				icon: 'none'
			});
			proxy.$emit('recall', 'close');
		});
	}

	const onMoveCallback = (val : any) => {
		if (val.length > 0) {
			let arr : any = []
			val.map((item : any) => {
				arr.push(item.content)
			})
			workList.value = arr;
		}

		sortApi();
	};

	// 获取人员属性
	function getUserAttributesFun(username : String) {
		request({
			method: 'GET',
			url: 'getUserAttributes',
			data: { userName: username }
		})
			.then((res : any) => {
				if (res.code == 0) {
					if (!!res.data && res.data.length > 0) {
						uni.setStorageSync('usernameCn', res.data[0].name);
						usernameCn.value = res.data[0].name;
						uni.setStorageSync('deptName', res.data[0].orgName);
						// 设置工厂
						uni.setStorageSync('factoryList', res.data[0].factoryList);
						if (!!res.data[0].defaultFactory) {
							userFactory.value = res.data[0].defaultFactory;
						} else {
							uni.setStorageSync('userFactory', '');
							uni.setStorageSync('userFactoryId', '');
						}
						// 设置仓库
						setWarehouseList(res.data[0].warehouseList, res.data[0].defaultWarehouse);
						// 设置航站
						uni.setStorageSync('terminalList', res.data[0].terminalList);
						if (!!res.data[0].defaultTerminal) {
							uni.setStorageSync('userTerminal', res.data[0].defaultTerminal.tag);
							uni.setStorageSync('userTerminalName', res.data[0].defaultTerminal.distributionAreaId || res.data[0].defaultTerminal.description);
							uni.setStorageSync('userTerminalValue', res.data[0].defaultTerminal.value);
							userTerminal.value = res.data[0].defaultTerminal.tag;
						} else {
							uni.setStorageSync('userTerminal', '');
							uni.setStorageSync('userTerminalValue', '');
						}
						// 设置库存地
						uni.setStorageSync('stockLocationList', res.data[0].stockLocationList);
						if (!!res.data[0].defaultStockLocation) {
							uni.setStorageSync('userStock', res.data[0].defaultStockLocation.tag);
							uni.setStorageSync('userStockValue', res.data[0].defaultStockLocation.value);
							userStock.value = res.data[0].defaultStockLocation.tag;
						} else {
							uni.setStorageSync('userStock', '');
							uni.setStorageSync('userStockValue', '');
						}
					}
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			})
			.catch((err : any) => {
				console.log(err);
			});
	}
	// 设置工作仓库
	function setWarehouseList(datas : any, defaultWarehouse : String) {
		request({
			method: 'GET',
			url: 'getWarehouseDict'
		})
			.then((res : any) => {
				if (res.code == 0) {
					let warehouseList = [];
					uni.setStorageSync('warehouseList', res.data);
					datas.forEach((ele : any) => {
						let temp = res.data.find((item : any) => item.id == ele);
						warehouseList.push(temp);
					});
					if (!!defaultWarehouse) {
						let ele = res.data.find((item : any) => item.id == defaultWarehouse);
						if (!!ele) {
							uni.setStorageSync('userWarehouse', ele.label);
							uni.setStorageSync('userWarehouseId', defaultWarehouse);
						}
					} else {
						uni.setStorageSync('userWarehouse', '');
						uni.setStorageSync('userWarehouseId', '');
					}
					userWarehouse.value = uni.getStorageSync('userWarehouse');
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			})
			.catch((err : any) => {
				console.log(err);
			});
	}

	// 排序 sort
	function sortApi() {
		workList.value.map((t : any) => {
			if (t.isVirtual) {
				isVirtual.value = false;
			}
		})

		if (isVirtual.value) {
			let initData : any = [];
			let sort = 0;
			workList.value?.map((item : any) => {
				initData.push({
					menuId: item.menuId,
					sort: ++sort
				})
			});
			proxy.$emit('recall', 'open');
			request({
				method: 'post',
				url: 'appmenu-menuResort',
				data: initData,
			}).then((res : any) => {
				proxy.$emit('recall', 'close');
				uni.showToast({
					title: res.msg,
					icon: 'none'
				});
			}).catch((err: any) => {
				uni.showToast({
					title: err.msg || '系统繁忙，请稍后重试',
					icon: 'none'
				});
				proxy.$emit('recall', 'close');
			});
		}
	}

	function iconClick(item : any) {
		uni.showModal({
			title: '确定取消删除？',
			success: function (res) {
				if (res.confirm) {
					if (item.isVirtual) {
						let str = JSON.stringify(item.menuId);
						let arr : any = [];
						JSON.parse(JSON.stringify(workList.value)).map(t => {
							arr.push(t);
						})

						let screenArr = [];
						screenArr = arr.filter((it : any) => {
							return !str.includes(it.menuId)
						});

						workList.value = screenArr;
						return
					} else {
						let obj : any = {};
						obj['menuId'] = item.menuId;
						let arr = [];
						arr.push(obj);
						proxy.$emit('recall', 'open');
						request({
							method: 'post',
							url: 'appmenu-deleteMenuCollect',
							data: arr,
						}).then((res : any) => {
							proxy.$emit('recall', 'close');
							if (res.code == 0) {
								uni.showToast({
									title: "删除成功！",
									icon: 'none'
								});
								getMenu();
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								});
							}
						}).catch((res : any) => {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
							proxy.$emit('recall', 'close');
						});
					}
				}
			}
		})
	}

	function path_url(row : any) {
		hits(row.menuId);
		if (row.path.indexOf('/index') > -1) {
			uni.navigateTo({
				url: `/pages/modules/${row.path}`
			});
		} else {
			uni.navigateTo({
				url: `/pages/modules/${row.path}/index`
			});
		}
	}
	// 记录点击菜单点击量
	function hits(menuId : any) {
		let obj : any = {};
		obj['menuId'] = menuId;
		request({
			method: 'post',
			url: 'appmenu-saveClick',
			data: obj,
		})
	}

	defineExpose({ init })
</script>

<style lang="less" scoped>
	.amms-stagin {
		background-color: #F2F6F9;
		.bj {
			background: linear-gradient(226deg, #168AFF 0%, #0E57FF 100%);
			border-radius: 0rpx 0rpx 32rpx 32rpx;
			padding-bottom: 125rpx;
		}

		.container {
			padding: 0rpx 32rpx;
		}

		.head_information {
			margin-top: 35rpx;
			display: flex;
			align-items: center;

			.pic {
				height: 112rpx;
				width: 112rpx;
				margin: 0;
				border-radius: 50%;
			}

			.right {
				font-family: PingFangSC-Medium, PingFang SC;
				margin-left: 24rpx;
				.n {
					color: #444D54;
					font-size: 32rpx;
					font-weight: 500;
				}
				.node {
					margin-top: 9rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: #808080;
				}
			}
		}
		.nav {
			margin-top: 24rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			font-size: 28rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #444D54;

			.item {
				.s {
					font-size: 24rpx;
					font-weight: 400;
					color: #808080;
					margin-top: 6rpx;
				}
			}
		}

		.weather {
			margin-top: 76rpx;
			position: relative;
			display: flex;
			align-items: flex-end;
			justify-content: space-between;
			background: #166CE5;
			border-radius: 16rpx;
			padding: 38rpx 38rpx 11rpx 38rpx;
			font-size: 28rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			.weatherMask {
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				z-index: 100;
				top: 0;
				left: 0;
				bottom: 0;
				right: 0;
				background-color: rgba(0, 0, 0, 0.7);
				font-size: 28rpx;
				color: #ffffff;
				border-radius: 16rpx;
			}

			.item {
				.s {
					font-size: 24rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #CCCCCC;
					margin-top: 8rpx;
				}

				.active {
					font-weight: 500;
					color: #FFFFFF;
				}
			}

			.transition {
				position: absolute;
				top: -47rpx;
				left: 14rpx;
			}

			.pic {
			
				width: 112rpx;
				height: 112rpx;
			}
		}
 
		/deep/.work_nav {
			margin-top: 40rpx;

			.title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 32rpx;
				font-weight: 500;
				color: #444D54;
				.left {
					display: flex;
					align-items: center;
					.pic {
						width: 32rpx;
						height: 32rpx;
						margin-left: 10rpx;
						position: relative;
						top: -2rpx;
					}
				}

				.right {
					font-size: 28rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFFFFF;

					uni-button {
						border-radius: 28rpx;
					}
				}
			}

			.ul {
				display: flex;
				align-items: flex-start;
				flex-wrap: wrap;
				margin-top: 20rpx;
				height: calc(100vh - 840rpx) !important;
				overflow-y: scroll;
				.li-wrap {
					box-sizing: border-box;
					padding-bottom: 20rpx;
					height: 188rpx;
					.li {
							width: 156rpx;
							height: 100%;
							background-color: #FFFFFF;
							border-radius: 16rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							position: relative;
					
							.na {
								text-align: center;
								
					
								.pic {
									width: 58rpx;
									height: 58rpx;
									margin: 0rpx;
								}
					
								.n {
									display: flex;
									align-items: flex-start;
									justify-content: center;
									margin-top: 16rpx;
									font-size: 24rpx;
									height: 60rpx;
									line-height: 30rpx;
									box-sizing: border-box;
									padding: 0 10rpx;
								}
							}
					
							.active {
								display: flex;
							}
					
							.icon {
								width: 48rpx;
								height: 52rpx;
								margin: 0;
								position: absolute;
								top: 0;
								right: 0;
							}
						}
					}
				}
				
		}

		.is-hover {
			color: #ffffff;
			background-color: #179b16;
			border-color: #179b16;
		}
	}
	.liShake {
		animation: shake 1s infinite linear;
	}
	@keyframes shake {
	
	    0%,
	    100% {
	        transform: rotate(1deg)
	    }
	
	    10% {
	        transform: rotate(-10deg)
	    }
	
	    20% {
	        transform: rotate(9deg)
	    }
	
	    30% {
	        transform: rotate(-8deg)
	    }
	
	    40% {
	        transform: rotate(7deg)
	    }
	
	    50% {
	        transform: rotate(-6deg)
	    }
	
	    60% {
	        transform: rotate(5deg)
	    }
	
	    70% {
	        transform: rotate(-4deg)
	    }
	
	    80% {
	        transform: rotate(3deg)
	    }
	
	    90% {
	        transform: rotate(-2deg)
	    }
	}
</style>