<template>
	<view class="page-container">
		<helang-compress ref="helangCompress"></helang-compress>
		<view class="mine-header">
			<view class="user-info-box">
				<view class="info-box" v-if="userInfo">
					<!-- <image v-if="!userInfo.avatar" src="/static/images/default-avatar.png" class="avatar"
						@click="handleEditAvatar"></image> -->
					<image v-if="faceImg" :src="faceImg" class="avatar" @error="imgLoadFail" @click="handleEditAvatar"></image>
					<view class="name-class">
						<view class="name">{{userInfo.nickName}}</view>
						<view class="class-name">{{userInfo.dept.deptName}}</view>
					</view>
					<image src="/static/images/mine/detail-icon-white.png" class="more"></image>
				</view>
			</view>
			<view class="stastics-data-box" v-if="analysisData">
				<view class="item">
					<view class="num">{{analysisData.momentCount || 0}}</view>
					<view class="label">动态</view>
				</view>
				<view class="item">
					<view class="num">{{analysisData.commentCount || 0}}</view>
					<view class="label">评论</view>
				</view>
				<view class="item">
					<view class="num">{{analysisData.likeCount || 0}}</view>
					<view class="label">点赞数</view>
				</view>
			</view>
		</view>

		<!-- 我发的动态 -->
		<scroll-view class="my-dynamics" scroll-y :show-scrollbar="false" v-if="list.length >0"
			@scrolltolower="loadMore">
			<template v-for="(item,index) in list">
				<dynamic-item :form="item" @refresh="handleRefresh" @deleteSuccess="handleRefresh" :deleteable="true"></dynamic-item>
			</template>
		</scroll-view>
		<scroll-view class="my-dynamics" scroll-y :show-scrollbar="false" v-if="list.length==0">
			<list-empty></list-empty>
		</scroll-view>
	</view>
</template>

<script>
	import DynamicItem from '@/components/Dynamic-Item.vue';
	import ListEmpty from '@/components/ListEmpty.vue';
	import config from '@/config/index.config.js';
	import {
		getToken
	} from '@/utils/auth.js';
	import $modal from '@/utils/modal.js'
	import {
		getInfo
	} from '@/api/login.js';
	import {
		getDynamicStastics,
		userDynamics,
		updateUserInfo
	} from '@/api/api.js';
	import HelangCompress from '@/components/HelangCompress.vue';
	import {generateSignature} from '@/utils/common.js';
	import defalutAvatar from '/static/images/default-avatar.png'
	export default {
		data() {
			return {
				userInfo: undefined,
				analysisData: undefined,
				list: [],
				queryParams: {
					pageNum: 1,
					pageSize: 10
				},
				total: 0,
				uploadUrl: '/bbs/mobile/common/upload', //上传地址
				baseUrl: config.requestUrl,
				faceImg:''
			}
		},
		components: {
			DynamicItem,
			ListEmpty,
			HelangCompress
		},
		onLoad() {
			this.getUserInfo();
		},
		onShow() {
			this.getStatistics();
			this.list = [];
			this.queryParams.pageNum = 1;
			this.getList()
		},
		methods: {
			// 当前用户信息
			getUserInfo() {
				getInfo().then(res => {
					this.userInfo = res.data
					this.faceImg = generateSignature(this.userInfo.userName)
				})
			},
			// 统计数据
			getStatistics() {
				getDynamicStastics().then(res => {
					console.log(res)
					this.analysisData = res.data
				})
			},
			handleRefresh() {
				this.getStatistics();
				this.list = [];
				this.queryParams.pageNum = 1;
				this.getList()
			},
			// 获取当前用户动态列表
			getList() {
				uni.showLoading({
					title: '加载中...'
				})
				userDynamics(this.queryParams).then(res => {
					this.list = [...this.list, ...res.rows];
					this.total = res.total;
				}).finally(() => {
					uni.hideLoading()
				})
			},
			loadMore() {
				if (this.list.length < this.total) {
					this.queryParams.pageNum += 1;
					this.getList()
				}
			},
			// 修改头像
			handleEditAvatar() {
				const _this = this;
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					sizeType: ['original', 'compressed'],
					success(res) {
						const tempFilePaths = JSON.parse(JSON.stringify(res.tempFilePaths));
						$modal.loading('上传中...');
						_this.$refs.helangCompress.compress({
							src: tempFilePaths,
							maxSize: 800,
							fileType: 'jpg',
							quality: 0.80,
							progress: (res) => {
								// console.log('压缩进度');
								// console.log(res);
							}
						}).then((res) => {
							let tempFile = res.map(item => _this.dataURLtoBlob(item));
							if (tempFile.length <= 0) {
								uni.hideLoading();
								uni.showToast({
									title: '未识别到图片'
								})
								return;
							}
							_this.handleUploadPic(tempFile);
						}).catch((err) => {
							uni.hideLoading();
							uni.showToast({
								title: err
							})
						})

					}
				});
			},
			imgLoadFail() {
				this.faceImg = defalutAvatar
			},
			//将base64转换为blob
			dataURLtoBlob(dataurl) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			
			handleUploadPic(fileList) {
				const _this = this;
				let uploadTasks = fileList.map((item, index) => {
					return uni.uploadFile({
						url: _this.baseUrl + _this.uploadUrl,
						file: item,
						name: 'file',
						formData: {},
						header: {
							Authorization: 'Bearer ' + getToken()
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							if (data.code === 401) {
								uni.reLaunch({
									url: '/pages/login/login'
								});
							} else if (data.code === 200) {
								// 上传成功
								_this.userInfo.avatar = data.url;
								_this.uploadSuccess(data)
							} else if (data.code === 500) {
								$modal.msg(data.msg || '上传失败');
							}
						},
						fail: (error) => {
							console.log('上传失败：', error);
						},
						// 接口调用结束的回调函数（调用成功、失败都会执行）
						complete: () => {
							console.log('上传完成',new Date())
							uni.hideLoading();
						}
					});
				})
			
				Promise.all(uploadTasks).then((res) => {
					// console.log('所有图片上传完成'); // 所有图片上传成功后执行的逻辑
				}).catch(err => {
					console.error('有图片上传失败', err); // 如果有上传失败的情况处理的逻辑
				});
			},
			
			
			// 上传成功之后调用更新信息接口
			uploadSuccess(info){
				let _this = this;
				let data = {
					avatar:info.url,
				}
				updateUserInfo(data).then(res=>{
					_this.$store.dispatch('GetInfo');
					uni.$emit('hanldeDynamicRefresh')
					this.list = [];
					this.queryParams.pageNum = 1;
					this.getList()
				})
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/styles/common.scss';

	.mine-header {
		height: 410rpx;

		.user-info-box {
			height: 300rpx;
			background-color: #4873C0;
			background-image: url('/static/images/mine/bg-dec.png');
			background-size: contain;
			background-repeat: no-repeat;
			background-position: bottom;

			.info-box {
				height: 226rpx;
				display: flex;
				padding: 0 36rpx;
				box-sizing: border-box;
				align-items: center;
				justify-content: space-between;

				.avatar {
					width: 112rpx;
					height: 112rpx;
					border-radius: 50%;
				}

				.name-class {
					width: calc(100% - 184rpx);
					color: white;

					.name {
						font-size: 32rpx;
					}

					.class-name {
						font-size: 24rpx;
						margin-top: 10rpx;
					}
				}

				.more {
					width: 32rpx;
					height: 32rpx;
				}
			}
		}

		.stastics-data-box {
			height: 184rpx;
			width: 92vw;
			margin-top: -74rpx;
			background-color: white;
			border-radius: 12rpx;
			margin-left: 4vw;
			display: flex;
			justify-content: space-evenly;
			align-items: center;

			.item {
				.num {
					color: rgba(0, 0, 0, 1);
					font-size: 32rpx;
					text-align: center;
				}

				.label {
					color: rgba(148, 148, 150, 1);
					font-size: 28rpx;
				}
			}
		}
	}

	.my-dynamics {
		margin-top: 40rpx;
		height: calc(100vh - 570rpx);
	}
</style>