<!--
 * @Author: euzhi
 * @Description: 描述
-->
<template>
<view class="appCotent">
    <div class="userInfo">
        <div class="info__cover" @click="select">
            <span class="cover__name">头像</span>
            <div class="cover">
                <image v-if="image" :src="image" />
                <image v-else src="@/static/my/my2.jpg" />
                <!-- 此处应该有默认头像 -->
                <!--                <image v-else src="@/static/my/my2.png" />-->
                <span>
                    <image src="@/static/my/my6.png" /></span>
            </div>
        </div>
        <u-popup :show="show" @close="close" closeOnClickOverlay>
            <view class="user__title">
                填写昵称
            </view>
            <div class="user__input"><input v-model="user__nikename" @blur="" placeholder="输入昵称(最多输入20个字符)" type="text">
                <div class="user__name__border"></div>
                <div class="user__save" @click="save">保存</div>
            </div>
        </u-popup>
        <u-popup :show="show__six" @close="close__sex" closeOnClickOverlay>
            <div class="user__input user__sex" @click="select__sex('男')">
                男
            </div>
            <div class="user__input user__sex" @click="select__sex('女')">
                女
            </div>
        </u-popup>


       <!-- <u-datetime-picker :show="show__date" v-model="dateValue" ref='datetimePicker' :minDate="-2209017600000" mode="date" @confirm='confirm' @close='close__date' @cancel='close__date' :formatter="formatter" closeOnClickOverlay>

        </u-datetime-picker> -->
        <view class="info__content">
            <active-form @clickFn='clickFn' :formDate.sync="formData"></active-form>
        </view>
    </div>
</view>
</template>

<script>
export default {
    data() {
        return {
            dateValue: Number(new Date()),
            user__nikename: '',
            show__six: false,
            show: false,
            show__date: false,
            image: '',
            userInfo: {
                nickName: '默认昵称',
            },
            formData: [
				// {
    //                 id: "kjjns", //id必须唯一 可以是数字
    //                 placeholder: "请填写",
    //                 label: "手机号", // 提示输入名
    //                 type: "text", //类型
    //                 disabled: true, //是否禁用
    //                 rules: {
    //                     name: "mobile", //字段名 即提交给后端的字段
    //                     value: "",
    //                     verify: false, //是否开启校验
    //                     errMess: "手机号未填写", //校验不通过的错误提示
    //                 },
    //             },
                {
                    id: "kjjns", //id必须唯一 可以是数字
                    placeholder: "请填写",
                    label: "昵称", // 提示输入名
                    type: "select", //类型
                    rules: {
                        name: "nickName", //字段名 即提交给后端的字段
                        value: "",
                        label: ""
                    },
                },
                {
                    id: "kjjns", //id必须唯一 可以是数字
                    placeholder: "请选择",
                    label: "性别", // 提示输入名
                    type: "select", //类型
                    rules: {
                        name: "sex", //字段名 即提交给后端的字段
                        value: "",
                        verify: false, //是否开启校验
                        label: ''
                    },
                },
                // {
                //     id: "kjjns", //id必须唯一 可以是数字
                //     placeholder: "请选择",
                //     label: "生日", // 提示输入名
                //     type: "select", //类型
                //     rules: {
                //         name: "birthday", //字段名 即提交给后端的字段
                //         value: "",
                //         verify: false, //是否开启校验
                //         label: ''
                //     },
                // },

            ],
        }
    },
    onReady() {
        // 微信小程序需要用此写法
        // this.$refs.datetimePicker.setFormatter(this.formatter)
    },
    methods: {
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            if (type === 'day') {
                return `${value}日`
            }
            return value
        },
        transformTime(timestamp) {
            if (timestamp) {
                var time = new Date(timestamp);
                //console.log(time);
                var y = time.getFullYear(); //getFullYear方法以四位数字返回年份
                var M = time.getMonth() + 1; // getMonth方法从 Date 对象返回月份 (0 ~ 11)，返回结果需要手动加一

                 if(M < 10) {
                    M  = '0' + M;
                 }

                var d = time.getDate(); // getDate方法从 Date 对象返回一个月中的某一天 (1 ~ 31)
                if(d < 10) {
                   d  = '0' + d;
                }
                return y + '-' + M + '-' + d
            } else {
                return '';
            }
        },
        confirm(e) {
            this.formData.forEach(element => {
                if (element.label === '生日') {
                    element.rules.label = this.transformTime(e.value)
                    let opts = {
                        url: '/app/user/update',
                        method: 'post'
                    };
                    let userInfoItem = {
                        type: 4,
                        val: element.rules.label
                    };
                    this.http.httpTokenRequest(opts, userInfoItem).then(response => {
                        if (response.data.code == 200) {

                        }
                    })
                }
            });
            this.show__date = false
        },
        select__sex(val) {
            this.formData.forEach(element => {
                if (element.label === '性别') {
                    element.rules.label = val
                    let opts = {
                        url: '/app/user/update',
                        method: 'post'
                    };
                    let sex = (val == '男' ? "0" : "1")
                    let userInfoItem = {
                        type: 3,
                        val: sex
                    };
                    this.http.httpTokenRequest(opts, userInfoItem).then(response => {
                        if (response.data.code == 200) {

                        }
                    })
                }
            });

            this.show__six = false
        },
        save() {
           let that = this
            this.formData.forEach(element => {
                if (element.label === '昵称') {
                    element.rules.value = this.user__nikename
                    let opts = {
                        url: '/app/user/update',
                        method: 'post'
                    };
                    let userInfoItem = {
                        type: 2,
                        val: this.user__nikename
                    };
                    that.http.httpTokenRequest(opts, userInfoItem).then(response => {
                        if (response.data.code == 200) {
							this.getUserInfo()
                        }
                    })
                }
            });
            this.show = false
        },
        clickFn(e) {
            //console.log(e)
            switch (e) {
                case 0:
                    this.show = true
                    break;
                case 1:
                    this.show__six = true
                    break;
                case 2:
                    this.show__date = true
                    break;
            }
        },
        close() {
            this.show = false;
        },
        close__sex() {
            this.show__six = false;
        },
        close__date() {
            this.show__date = false;
        },
        select() {
            let that = this
			
            uni.chooseImage({
                count: 1, //默认9
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], //从相册选择
                success: function (res) {
					uni.showLoading({
						title:"加载中",
						mask:true
					})
                    const tempFilePaths = res.tempFilePaths;
                    uni.uploadFile({
                        url: that.http.baseUrl + '/app/user/upload',
                        //url: 'http://192.168.2.21:7001/upload',//仅为示例，非真实的接口地址
                        method: 'POST',
                        filePath: tempFilePaths[0],
                        name: 'file',
                        formData: {
                            file: tempFilePaths[0]
                        },
                        // 请求头一定要加，否则 iOS 图片上传会失败
                        header: {
                            'content-type': 'multipart/form-data',
                            'Authorization': 'Bearer ' + uni.getStorageSync('userToken')
                        },
                        success: (res) => {
                            let uploadData = JSON.parse(res.data)
                            let opts = {
                                url: '/app/user/update',
                                method: 'post'
                            };
                            let userInfoItem = {
                                type: 1,
                                val: uploadData.data.url
                            };
                            that.http.httpTokenRequest(opts, userInfoItem).then(response => {
								uni.hideLoading()
                                if (response.data.code == 200) {
                                    that.$nextTick(() => {
                                        that.image = uploadData.data.url
                                    })
                                }else{
									uni.showToast({
										title: response.data.msg,
										icon: "error",
									});
								}
                            })
                        },
						fail() {
                        	uni.hideLoading()
							uni.showToast({
								title: "上传头像失败！",
								icon: "error",
							});
                        }
                    });
                }
            });

        },
        // select() {
        //     let that = this
        //     uni.chooseImage({
        //         count: 1, //默认9
        //         sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        //         sourceType: ['album'], //从相册选择
        //         success: function (res) {
        //             const tempFilePaths = res.tempFilePaths;
        //             uni.uploadFile({
        //                 url: that.http.baseUrl + '/common/upload',
        //                 //url: 'http://192.168.2.21:7001/upload',//仅为示例，非真实的接口地址
        //                 method: 'POST',
        //                 filePath: tempFilePaths[0],
        //                 name: 'file',
        //                 formData: {
        //                     file: tempFilePaths[0]
        //                 },
        //                 success: (res) => {
        //                     let uploadData = JSON.parse(res.data)
        //                     let opts = {
        //                         url: '/app/user/update',
        //                         method: 'post'
        //                     };
        //                     let userInfoItem = {
        //                         type: 1,
        //                         val: uploadData.data.fileName
        //                     };
        //                     //console.log(userInfoItem)
        //                     that.http.httpTokenRequest(opts, userInfoItem).then(response => {
        //                         if (response.data.code == 200) {
        //                             that.userInfo.avatar = res.data.url
        //                         }
        //                     })
        //                 }
        //             });
        //         }
        //     });
        // },
        getUserInfo() {
            let opts = {
                url: '/app/user/info',
                method: 'get'
            };
            this.http.httpTokenRequest(opts, {}).then(res => {
                if (res.data.code == 200) {
                    this.userInfo = res.data.data
                    if(this.userInfo.avatar){
                        this.image = this.userInfo.avatar
                    }
                    this.formData.forEach(element => {
                        if (element.label === '手机号') {
                            element.rules.value = this.userInfo.mobile
                        }
                        if (element.label === '昵称') {
                            element.rules.label = this.userInfo.nickName
                        }
                        if (element.label === '性别') {
                            element.rules.label = this.userInfo.sex == "0" ? "男" : "女"
                        }
                        // if (element.label === '生日') {
                        //     element.rules.label = this.userInfo.birthday
                        // }
                    })
                }else{
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					});
				}
            })
        },
        editUserInfo() {
            let user = {}
            for (let i in this.formData) {
                let name = this.formData[i].rules.name
                this.user[name] = this.formData[i].rules.value
            }
        },
    },
    onShow() {
        this.getUserInfo()
    },

}
</script>

<style lang="scss" scoped>
.userInfo {
    .user__save {
        font-size: 32rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #3A86F7;
        line-height: 42rpx;
        text-align: center;
        padding: 30rpx 0;
    }

    .user__title {
        font-size: 36rpx;
        font-family: PingFang SC;
        font-weight: bold;
        color: #333333;
        line-height: 42rpx;
        text-align: center;
        padding: 30rpx 0;
    }

    /deep/ .u-popup__content {
        border-radius: 20rpx 20rpx 0px 0px;
    }

    .user__input {
        padding: 0 30rpx;
        padding-bottom: 40rpx;
        text-align: center;

        .user__name__border {
            width: 100%;
            height: 2rpx;
            background: url('@/static/my/border.png') no-repeat;
            background-size: contain;
            margin-top: 30rpx;
        }

        .user__name__border__sex {
            margin-bottom: 30rpx;
        }
    }

    .user__sex {
        font-size: 36rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #333333;
        line-height: 42rpx;
        padding: 30rpx 0;
        padding-bottom: 60rpx;
    }

    padding: 40rpx;

	/deep/ .form-container{
		min-height:auto !important;
	}
    /deep/ .form-container .line .input {
        text-align: right !important;
        padding-right: 20rpx;
    }

    .info__cover {
        height: 140rpx;
        background: #FFFFFF;
        box-shadow: 0rpx 0rpx 28rpx 1rpx rgba(232, 232, 232, 0.2);
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30rpx;

        .cover__name {
            font-size: 32fpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #333333;
        }

        .cover {
            display: flex;
            align-items: center;

            image {
                width: 100rpx;
                height: 100rpx;
                border-radius: 50%;
            }

            span {
                margin-left: 10rpx;

                image {
                    width: 11rpx;
                    height: 18rpx;
                }
            }
        }
    }

    .info__content {
        margin-top: 30rpx;
        background: #FFFFFF;
        box-shadow: 0rpx 0rpx 28rpx 1rpx rgba(232, 232, 232, 0.2);
        border-radius: 20rpx;
    }
}
</style>
