<template>
	<view class="main">
		<!-- #ifdef APP-PLUS -->
		<cu-custom bgColor="bg-blue">
			<block slot="content">我的</block>
		</cu-custom>
		<!-- #endif -->
		<view class="person-head">
			<lsj-upload ref="lsjUpload" childId="upload1" width="160rpx" height="140rpx" :option="option" :debug="false"
				:instantly="false" @uploadEnd="onuploadEnd" @change="afterRead">
				<view class="cu-avatar xl round margin-left-sm" :style="`background-image:url('${avatar}')`"></view>
			</lsj-upload>

			<view class="person-head-box">
				<view class="person-head-nickname">{{userInfo.name?userInfo.name:''}}</view>
				<view class="person-head-username">ID：{{userInfo.loginName?userInfo.loginName:''}}</view>
			</view>
		</view>
		<u-cell-group :border="false" customStyle="padding: 5px">
			<u-cell title="签名" icon="home-fill" :iconStyle="{color: '#0081ff'}" isLink
				url="/pages/user/setting/signature/signature"></u-cell>
			<u-cell title="部门" icon="list-dot" :iconStyle="{color: '#0081ff'}"
				:value="userInfo.officeDTO && userInfo.officeDTO.name"></u-cell>
			<!-- <u-cell
		    title="岗位"
			icon="account-fill"
			:iconStyle="{color: '#0081ff'}"
			:value="userInfo.post && userInfo.post.name"
		></u-cell> -->
			<u-cell title="角色" icon="man-add-fill" :iconStyle="{color: '#0081ff'}"
				:value="userInfo.roleNames?userInfo.roleNames:''"></u-cell>
			<u-cell title="电话" icon="phone-fill" :iconStyle="{color: '#0081ff'}"
				:value="userInfo.phone?userInfo.phone:''"></u-cell>
			<u-cell title="手机号" icon="phone-fill" :iconStyle="{color: '#0081ff'}"
				:value="userInfo.mobile?userInfo.mobile:''"></u-cell>
			<!-- <u-cell
		    title="邮箱"
			icon="email-fill"
			:iconStyle="{color: '#0081ff'}"
			:value="userInfo.email"
		></u-cell> -->
			<u-cell title="修改密码" icon="edit-pen" isLink :iconStyle="{color: '#e54d42'}"
				url="/pages/user/setting/password/password"></u-cell>
		</u-cell-group>

		<view class="padding-xl">
			<u-button type="primary" text="退出登录" @click="outlogin"></u-button>
			<!-- <u-gap height="80" bgColor="#fff"></u-gap> -->
		</view>

	</view>

</template>

<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'
	import {
		isImageFormat
	} from "@/common/util.js"
	import BASE_URL from '@/config.js'
	import * as $auth from "@/common/auth.js"
	import userService from "@/api/sys/userService"
	import loginService from "@/api/auth/loginService"
	import fileService from "@/api/file/fileService.js"
	export default {
		name: "person",
		computed: mapState({
			userInfo: (state) => state.user.userInfo,
			avatar: (state) => BASE_URL + state.user.avatar
		}),
		data() {
			return {
				files: [],
				// 上传接口参数
				option: {
					url: BASE_URL + '/gwfile/upload?uploadPath=userdir',
					name: 'file',
					header: {
						"token": $auth.getUserToken()
					},
				},
			}
		},
		methods: {
			...mapActions(['refreshUserInfo']),
			/**
			 * 修改密码
			 */
			toPassword() {
				uni.navigateTo({
					url: '/pages/user/setting/password/password'
				})
			},
			// 新增图片
			afterRead(files) {
				uni.showLoading({
					title: "更新中"
				})
				let lists = [...files.values()]
				this.files = files
				for (let i = 0; i < lists.length; i++) {
					if (lists[i].type == 'success') continue;
					if (!isImageFormat(lists[i].name)) {
						uni.showToast({
							title: '请上传图片',
							icon: 'error'
						})
					} else {
						if (lists[i].size > 200 * 1024) {
							this.compressAPP(lists[i], 150).then(res => {
								this.files.get(lists[i].name).file = res
								this.upload(lists[i].name)
							})
						} else {
							this.upload(lists[i].name)
						}
					}

				}

			},
			// app图片压缩
			compressAPP(urlData, targetSizeKB, initialQuality = 1.0) {
				const maxQuality = 1.0;
				const minQuality = 0.0;
				const tolerance = 0.01; // 根据需要调整公差
				let that = this
				return new Promise((resolve, reject) => {

					let binarySearch = (min, max) => {
						const midQuality = (min + max) / 2;
						uni.getImageInfo({
							src: urlData.path,
							success: function(res) {
								let img = new Image()
								img.src = res.path
								img.onload = function() {
									const canvas = document.createElement('canvas');
									const ctx = canvas.getContext('2d');

									canvas.width = img.width;
									canvas.height = img.height;

									ctx.clearRect(0, 0, canvas.width, canvas.height);
									ctx.drawImage(img, 0, 0, canvas.width, canvas
										.height);

									// 使用异步的 toBlob 方法
									canvas.toBlob(async (blob) => {
										const fileSizeKB = blob.size / 1024;
										if (Math.abs(fileSizeKB -
												targetSizeKB) <
											tolerance || max - min <
											tolerance) {

											// 当前质量足够接近目标大小，使用当前质量解析
											const file = new File([blob], urlData
												.name, {
													type: blob.type,
													lastModified: new Date()
														.getTime(), // 使用当前时间作为最后修改时间
												});
											setTimeout(() => {
												resolve(file)
											}, 300)
										} else if (fileSizeKB >
											targetSizeKB) {
											// 如果文件大小太大，降低质量，继续二分查找
											binarySearch(min, midQuality);
										} else {
											// 如果文件大小太小，增加质量，继续二分查找
											binarySearch(midQuality, max);
										}
									}, urlData.file.type, midQuality);
								};
							},
							fail: function(err) {
								resolve(false);
							}
						});


					}
					// 开始二分查找
					binarySearch(minQuality, maxQuality);
				})
			},
			// APP手动上传
			upload(name) {
				// name=指定文件名，不指定则上传所有type等于waiting和fail的文件
				this.$refs['lsjUpload'].upload(name);
			},
			onuploadEnd(item) {
				console.log(`${item.name}已上传结束，上传状态=${item.type}`);

				// 更新当前窗口状态变化的文件
				this.files.set(item.name, item);
				let file = {
					name: item.name,
					path: item.responseText
				}
				// 微信小程序Map对象for循环不显示，所以转成普通数组，
				// 如果你用不惯Map对象，也可以像这样转普通数组，组件使用Map主要是避免反复文件去重操作
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif

				// 强制更新视图
				this.$forceUpdate();
				userService.saveInfo({
					id: this.userInfo.id,
					photo: item.responseText
				}).then(() => {
					this.refreshUserInfo()
				})
				uni.hideLoading()
				// ---可删除--演示判断是否所有文件均已上传成功
				let isAll = [...this.files.values()].find(item => item.type !== 'success');
				if (!isAll) {

				} else {
					console.log(isAll.name + '待上传');
				}

			},
			// upload(filePath) {
			// 	fileService.upload(filePath).then((data) => {
			// 		userService.saveInfo({
			// 			id: this.userInfo.id,
			// 			photo: data
			// 		}).then(() => {
			// 			this.refreshUserInfo()
			// 		})
			// 	})
			// },
			outlogin() {
				uni.showLoading()
				loginService.logout().then((data) => {
					this.$store.commit('logout');
					// uni.clearStorage();
					uni.removeStorageSync("WMS-userinfo")
					uni.removeStorageSync("WMS-username")
					uni.removeStorageSync("dictList")
					uni.removeStorageSync("__DC_STAT_UUID")
					uni.removeStorageSync("WMS-permission")
					uni.removeStorageSync("token")
					uni.hideLoading()
					uni.reLaunch({
						url: '/pages/login/login'
					})

				})
			}
		}
	}
</script>

<style>
	.person-head {
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 150px;
		padding-left: 20px;
		background: #0081ff;
	}

	.person-head-box {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: flex-start;
		margin-left: 10px;
	}

	.person-head-nickname {
		font-size: 18px;
		font-weight: 500;
		color: #fff;
	}

	.person-head-username {
		font-size: 14px;
		font-weight: 500;
		color: #fff;
	}

	.person-list {
		line-height: 0;
	}

	.cu-list.card-menu {
		overflow: hidden;
		margin-right: 5px;
		margin-left: 5px;
		border-radius: 7px;
	}

	.cu-list.card-menu.margin-top-20 {
		margin-top: -20px;
	}

	.cu-list.menu>.cu-item .content>uni-view:first-child {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		/* -webkit-align-items: center; */
		/* align-items: center; */
		display: inline-block;
		margin-right: 5px;
		width: 1.6em;
		text-align: center;
	}
</style>