<template>
	<view class="edit">
	<!-- 	<view class="head-box">
			<image @click="chooseHead" class="head" :src="headImg||defaultImg" mode=""></image>
			<image class="icon" src="../../static/take_photo.png" mode=""></image>
		</view> -->
		<view class="content">
			<u-cell size="large" title="头像" :border="false" isLink>
				<image @click="chooseHead" slot="value" class="head" :src="headImg||defaultImg" mode=""></image>
			</u-cell>
			<u-cell size="large" title="修改昵称" :border="false" :isLink="true" url="/my/edit/editName"></u-cell>
			<u-cell size="large" title="退订移动套餐" :border="false" :isLink="true" url="/my/edit/unSubscribe"></u-cell>
		</view>
		<button class="login-out" @click="loginOut">退出当前账号</button>
	</view>
</template>

<script>
	import {
		uploadImg,finishUploadImg
	} from '@/api/common.js';
	import crypto from 'crypto-js';
	import { Base64 } from 'js-base64';

	export default {
		data() {
			return {
				headImg: '',
				defaultImg: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fci.xiaohongshu.com%2Fc34b7b74-ba38-0456-982a-43c0f97522fe%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fci.xiaohongshu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1693532127&t=a2e186c12aecaab7723611cb52a6778f',
				userId: '',
				userInfo: null
			}
		},
		methods: {
			chooseHead() {
				let that = this
				uni.chooseImage({
					count: 1,
					success(r) {
						console.log(r);
						uploadImg({
							 "fineName": r.tempFilePaths[0].substr(r.tempFilePaths[0].lastIndexOf('/')+1) 
						}).then(res => {
							if (res.state == 'Success') {

								// that.headImg = r.tempFilePaths[0]
								// uni.showToast({
								// 	title: '上传成功',
								// });

								// that.userInfo.imgPath = r.tempFilePaths[0]
								// uni.setStorageSync('userInfo',JSON.stringify(this.userInfo))
								const date = new Date();
								date.setHours(date.getHours() + 1);
								const policyText = {
								  expiration: date.toISOString(), // 设置policy过期时间。
								  conditions: [
								    // 限制上传大小。
								    ["content-length-range", 0, 1024 * 1024 * 1024],
								  ],
								};
								
								
								
								let fileName = r.tempFilePaths[0].substr(r.tempFilePaths[0].lastIndexOf('/')+1);
								const host = 'https://' + res.content.bucket + '.'+ res.content.endPoint;
								const policy = Base64.encode(JSON.stringify(policyText));
								const signature = crypto.enc.Base64.stringify(crypto.HmacSHA1(policy, res.content.token.accessKeySecret));;
								const filePath = r.tempFilePaths[0]; // 待上传文件的文件路径。
								let paths = res.content.paths[0]
								// paths.pop()
								uni.uploadFile({
								  url: host, // 开发者服务器的URL。
								  filePath: filePath,
								  name: 'file', // 必须填file。
								  formData: {
								    key:paths.join('/'),
								    policy,
									success_action_status: '200', //让服务端返回200,不然，默认会返回204
								    OSSAccessKeyId: res.content.token.accessKeyId,
								    signature,
								    'x-oss-security-token': res.content.token.securityToken // 使用STS签名时必传。
								  },
								  success: (res1) => {
								    if (res1.statusCode === 200) {
								      console.log('上传成功');
									  // 告知服务器上传成功地址
									  finishUploadImg(
									  [{
										   path:res.content.paths[0]
									  }]).then(msg=>{
										  that.headImg = host + '/' + paths.join('/')
										  let userInfo = JSON.parse(uni.getStorageSync('userInfo'))
										  userInfo.imgPath = that.headImg
										  uni.getStorageSync('userInfo',JSON.stringify(userInfo))
									  })
								    }
								  },
								  fail: err => {
								    console.log(err);
								  }
								});


							}
						})
					}
				})
			},
			loginOut() {
				// 保存部分信息
				let location = uni.getStorageSync('location')
				let goodsTypeObj = uni.getStorageSync('goodsTypeObj')
				let inviteCode = uni.getStorageSync('inviteCode')
				uni.clearStorageSync()
				uni.setStorageSync('location',location)
				uni.setStorageSync('goodsTypeObj',goodsTypeObj)
				uni.setStorageSync('inviteCode',inviteCode)
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		created() {
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			this.headImg = this.userInfo.imgPath || ''
			this.userId = this.userInfo.userId || ''

		}
	}
</script>

<style lang="scss" scoped>
	.edit {
		padding: 20rpx 24rpx ;
		background: #F9F9F9;
		min-height: 100vh;
		.content{
			background: #fff;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
		}
		.head{
			width: 60rpx;
			height: 60rpx;
			border-radius: 50%;
		}
		.head-box {
			margin: 80rpx auto 50rpx;
			width: 150rpx;
			height: 150rpx;
			position: relative;

			.head {
				width: 150rpx;
				height: 150rpx;
				border-radius: 50%;
			}

			.icon {
				position: absolute;
				width: 44rpx;
				height: 44rpx;
				bottom: 0%;
				right: 0;
			}
		}

		.login-out {
			position: fixed;
			bottom: 150rpx;
			left: 50%;
			width: 400rpx;
			line-height: 110rpx;
			text-align: center;
			color: #fff;
			background: rgb(164, 173, 179);
			border-radius: 55rpx;
			transform: translateX(-50%);
			font-size: 30rpx;
		}
	}
</style>