<template>
	<view>
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="content">
				我的账号
			</block>
		</cu-custom>

		<view class="flex  align-center justify-between" style="margin-top: 15rpx; background-color: white;"
			@tap="chooseImage()">
			<view class=""
				style="border-bottom: #EEEEEE 1rpx; padding-left: 40rpx;padding-top: 30rpx; padding-bottom: 30rpx;font-size: 30rpx;">
				头像
			</view>
			<view class="flex align-center">
				<view class="">
					<image :src="userInfo.avatar" mode="" v-if="userInfo.avatar"
						style="border-radius: 100rpx;width: 80rpx;height: 80rpx;margin-right: 10rpx;"></image>
					<image src="../../../static/avatar_icon.png" mode="" v-else
						style="border-radius: 100rpx;width: 80rpx;height: 80rpx;margin-right: 10rpx;"></image>
				</view>
				<view class="">
					<u-icon name='arrow-right' class="right_icon" style="margin-right: 20rpx;"> </u-icon>
				</view>
			</view>
		</view>

		<view class="flex  align-center justify-between" style="background-color: white; " @tap="jumpUpdateUserName()">
			<view class=""
				style="border-bottom: #EEEEEE 1rpx;padding-left: 40rpx;padding-top: 30rpx;padding-bottom: 30rpx; font-size: 30rpx;">
				用户名
			</view>
			<view class="flex align-center">
				<view class="">
					{{userInfo.nikeName}}
				</view>
				<view class="">
					<u-icon name='arrow-right' class="right_icon" style="margin-right: 20rpx;"> </u-icon>
				</view>
			</view>
		</view>

		<view class="flex  align-center justify-between" style="background-color: white; ">
			<view class=""
				style="border-bottom: #EEEEEE 1rpx;padding-left: 40rpx;padding-top: 30rpx;padding-bottom: 30rpx;font-size: 30rpx;">
				手机号
			</view>
			<view class="flex align-center">
				<view class="">
					
					{{$formatPhone( userInfo.phone)}}
				</view>
				<view class="">
					<u-icon class="" style="margin-right: 20rpx;"> </u-icon>
				</view>
			</view>
		</view>
		<view class="" v-if="userInfo!=''" style="position: fixed;bottom: 50rpx;left: 45rpx;">
			<view class=""
			 @click="goOut"
			 style="width: 660rpx; color: #fc6035;border: 1rpx solid #fc6035; border-radius: 30rpx;padding: 20rpx;text-align: center;">
				退出当前账号
			</view>
		</view>
		<u-modal v-model="show" :show-cancel-button="true" confirm-color='#fc6035'
			confirm-text="确认" cancel-text="取消" :content="content" @confirm="seting"></u-modal>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				content:'',
				show:false,
				userInfo: '',
				memberId: uni.getStorageSync('userInfo').memberId,
                fileObj: {},
                expire: 0,
			}
		},
		onShow() {
			this.getUserInfo()
		},
		methods: {
			seting(){
				uni.clearStorageSync()
				uni.switchTab({
					url:'../../index/index'
				})
			},
			goOut(){
				this.content='您确认要退出登录吗?'
				this.show=true
			},
			getUserInfo() {
				this.$u.api.getUserInfo(this.memberId).then(res => {
					// console.log(res)
					if (res.code === 200) {
						this.userInfo = res.data
					}
				})
			},
			///1.底部弹出相机和相册
			chooseImage() {
				var that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择、摄像头
					success: function(res) {
						// console.log(res)
						// let uploadUrl = `${that.$u.http.config.ossUrl}/common/uploadImage`;
                        let igmFile = res.tempFiles;
                        igmFile.map((item) => {
                    
                            let fileName = ""
                            let date = new Date()
                            let time = date.getTime()
                            
                            // 获取图片类型，拼接时间戳作为文件名称（H5直接获取，app另外获取）
                            // #ifdef H5
                            // console.log("h5");
                            fileName = that.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+item.type.substring(item.type.lastIndexOf('/')+1) || 'jpg'
                            // #endif

                            // #ifdef APP-PLUS
                            // console.log("App");
                            uni.getImageInfo({
                                src: item.path,
                                success: function (image) {
                                    //    console.log( image.type,'image.typeimage.type')
                                    fileName = that.$timefilter('YY/MM/DD',date) +'/'+ time+'.'+image.type
                                }
                            });
                            // #endif

                            // console.log(fileName)

                            that.getAliOssInfo(item.path,fileName)
                        });

					}
				});
			},
            //获取oss信息
            async getAliOssInfo(path,fileName,type) {
                // console.log(fileName,'fileName')
                let that = this
                let time = new Date().getTime()
                let resultUrl = ""
                let zip = "";
                try {
                    if(time > Number(that.expire)) {
                        const res = await that.$u.api.ossInfo()
                        // console.log(res)
                        if(res.code==200) {
                            that.fileObj.dir = res.data.dir
                            that.fileObj.host = res.data.host
                            // that.fileObj.host = 'https://fresh-life.oss-cn-shanghai.aliyuncs.com'
                            that.fileObj.policy = res.data.policy
                            that.fileObj.signature = res.data.signature
                            that.fileObj.accessid = res.data.accessid
                            that.expire = res.data.expire * 1000
                            // console.log(that.$timefilter('YY-MM-DD HH:MM:SS',that.expire))
                            // console.log(that.fileObj,'pppoooo')
                        } else {
                            that.$api.msg('获取上传信息失败')
                        }
                    }

                    if (that.uploadFileType == "image") {
                        // #ifdef APP-PLUS
                        // console.log("App压缩");
                        zip = await that.compress(path);
                        // #endif
                    } else if (that.uploadFileType == "video") {
                        // #ifdef APP-PLUS
                        // console.log("App压缩");
                        zip = await that.videoCompress(path); // await--上传图片之前先压缩，否则上传会比压缩先执行
                        // #endif
                    }

                    let filePath = "";
                    // #ifdef H5
                    // console.log("h5");
                    filePath = path;
                    // #endif

                    // #ifdef APP-PLUS
                    // console.log("App");
                    filePath = zip;

                    // #endif

                    uni.showLoading({
                        mask: true,
                        title: "上传中...",
                    });
                    resultUrl = await that.uploadOss(filePath,fileName);
                    const param = {
                        memberId: uni.getStorageSync('userInfo').memberId, //会员id
                        avatar: resultUrl //头像
                    }
                    that.$u.api.changeUserInfo(param).then(res => {
                        // console.log(res)
                        if (res.code == 200) {
                            that.$api.msg('头像修改成功')
                            that.getUserInfo()

                        }
                    }).catch(error => {
                        console.log(error)
                    })
                    uni.hideLoading();
                } catch (error) {
                    uni.hideLoading();
                    that.$refs.uToast.show({
                        title: "上传失败",
                        duration: 1000,
                    })
                }
                
            },

            //直接上传oss
            async uploadOss(filePath,fileName) {
                let that = this
                let claims = uni.getStorageSync("claims");
                // console.log(that.fileObj,'mmmmmmm')
                // console.log(fileName,'+fileName')
                let [err, result] = await uni.uploadFile({
                    url: that.fileObj.host, //阿里云的存储地址，可以后端返回给你，也可以前端自己写上
                    filePath:filePath, //要上传的临时文件路径
                    name: 'file',
                    header:{
                        Authorization: claims
                    },
                    formData: {
                        key: that.fileObj.dir+'/'+fileName, //文件名
                        policy: that.fileObj.policy, //后台获取超时时间
                        OSSAccessKeyId: that.fileObj.accessid, //后台获取临时ID
                        success_action_status: '200', //让服务端返回200,不然，默认会返回204
                        signature: that.fileObj.signature //后台获取签名
                    },
                })
                if (err) {
                    //  上传错误了。。。可以做点什么
                } else {
                    let url = that.fileObj.host+'/'+that.fileObj.dir+'/'+fileName
                    // console.log(url)
                    return url //上传成功后，将我们所自定义的key（文件路径名）返回出去
                }
            },

			///2.进入修改用户名称页面
			jumpUpdateUserName() {
				uni.navigateTo({
					url: "/pages/mine/minePage/updateUserName?name=" + this.userInfo.nikeName,
				});
			}
		}
	}
</script>

<style>

</style>
