<template>
  <view class="bigBox">
    <view class="topBar" :style="{'padding-top':systemBarHeight.statusBarHeight+'px','height':systemBarHeight.navigationBarHeight+'px'}">
    	<u-icon @click="Utils.goBack()" name="arrow-left" color="#000000" size="20"></u-icon>
    	<view class="tabTitle" :style="{'line-height':systemBarHeight.navigationBarHeight+'px'}">个人信息</view>
    </view>
    <view class="page"  :style="{'padding-top':(systemBarHeight.statusBarHeight+systemBarHeight.navigationBarHeight)+'px'}">
        <view class="avatarBox">
            <image class="avatar" @click="editAvatar" :src="userInfo.avatarUrl"/>
        </view>
        <view class="infoBox">
            <view class="infoItem name">
                <view class="label">昵称</view>
                <view class="input"><input type="text" v-model="userInfo.name"></view>
                <view class="tip" v-if="valate">{{valateText}}</view>
            </view>
            <view class="infoItem phone">
                <view class="label">手机</view>
                <view class="input">{{userInfo.phone}}</view>
            </view>
            <view class="infoItem sex">
                <view class="label">性别</view>
                <view class="input">
                    <view class="sexBox">
                        <view class="sex" v-for="(item,index) in sexList" :key="index" @click="selectedSex(item)">
                            <view :class="item.value===userInfo.sex?'checked':'nochecked'"></view>
                            <view class="checkLabel">{{item.label}}</view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="infoItem birthday">
                <view class="label">生日</view>
                <view class="input">
                    <view class="birthdayBox">
                        <view :class="canEditBirthday?'text':'textDisabled'">{{birthdayComuted}}</view>
                        <view class="btn" v-if="canEditBirthday" @click="changeBirthday">修改</view>
                    </view>
                </view>
            </view>
        </view>
        <view class="saveBtn">
            <button class="btn" @click="save">保存</button>
        </view>
    </view>

    <show-toast ref="toast"/>
    <!-- <button @click="exit">退出</button> -->

    <u-datetime-picker
      :show="timerShow"
      :maxDate="(new Date()).valueOf()"
      :minDate="-631094400"
      @close="timerShow = false"
      @confirm="choseTime"
      v-model="userInfo.birthday"
      mode="date"
    ></u-datetime-picker>

    <Modal 
        class="modal" 
        title="确认更换生日日期？" 
        content="生日只可修改一次，是否想要修改？" 
        :show="birthdayModalShow"
        @close="birthdayModalShow = false"
        @ok="openTimer"
    />
  </view>
</template>

<script>
import Modal from '@/components/Modal/index.vue'
import Mine from '@/request/mine'
import Utils from '@/utils/utils'
import Store from '@/store';
export default {
    components: { Modal },
    computed:{
        birthdayComuted(){
            const {birthday} = this.userInfo
            const date = new Date(birthday)
            const years = date.getFullYear()
            const month = date.getMonth()+1
            const days = date.getDate()

            return years+'.'+month+'.'+days
        },
        userInfoStorage() {
			return uni.getStorageSync('UserInfo');
		},
        systemBarHeight(){
          return  this.$store.state.user.systemBarHeight
        }
    },
    watch:{
        'userInfo.name':{
            handler(val){
                console.log(val)
                 if(!/^[0-9a-zA-z\u4e00-\u9fa5]{0,7}$/.test(val)){
                    this.valateText = '最多7个字符，不可输入标点符号及特殊字符'
                    this.valate = true
                }else{
                     if(!val){
                        this.valateText = '请输入昵称'
                        this.valate = true
                    }else{
                        this.valateText = ''
                        this.valate = false
                    }
                }
            }
        }
    },
    data() {
        return {
            Utils,
            valateText:'',
            canEditBirthday:true,
            valate:false,
            rules:{
                name:[
                    {
					    required: true,
					    errorMessage: '请输入姓名'
                    }
                ]
			},
            timerShow: false,
            birthdayModalShow:false,
            value1: Number(new Date()),
            userInfo: {
                avatarUrl:'../../../static/touxiang.png',
                name:'脸脸',
                phone:'152****8932',
                sex:0,
                birthday:1658679810130,
                id:''
            },
            sexList:[
                {
                    'label':'男',
                    'value':0
                },
                {
                    'label':'女',
                    'value':1
                },
            ]
        }
    },
    async onLoad(option) {
        const {info} = option
        if(info){
            const {avatarUrl,gender=0,nickName='点点'} = info?JSON.parse(decodeURIComponent(info)):{}
            const {data} = await Mine.getUserInfo()
            const { birthday, createTime, id, phone, sex, userName } = data.data
            this.userInfo.id = id
            this.canEditBirthday = !birthday
            if(!birthday){
                this.userInfo.birthday = new Date(createTime.replace(/-/g,'/')).valueOf()
            }else{
                this.userInfo.birthday = Date.parse(birthday)
            }

            this.userInfo.avatarUrl = avatarUrl
            this.userInfo.sex = sex?sex?1:0:gender
            this.userInfo.name = userName?userName:nickName
            this.userInfo.phone = phone.substr(0,3) + "****" + phone.substr(7)

            const {...result} = this.userInfoStorage
            const sendData  ={
                ...result,
                avatarUrl,
                canEditBirthday:this.canEditBirthday
            }
            Store.commit('setUserInfo', sendData);
            this.save(false)
        }else{
            const { avatarUrl,birthday, id, phone, sex, customerName, canEditBirthday } = this.userInfoStorage
            this.canEditBirthday = canEditBirthday
            this.userInfo.avatarUrl = avatarUrl
            this.userInfo.sex = sex?1:0
            this.userInfo.name = customerName
            this.userInfo.birthday = birthday
            this.userInfo.id = id
            this.userInfo.phone = phone
        }

    },
    methods:{
        async choseTime(e) {
            const sendDate = {
                birthday:this.userInfo.birthday,
                id:this.userInfo.id
            }
            const {data} = await Mine.editBirthdat(sendDate)
            const {code} = data
            if(code===200){
                this.canEditBirthday = false
                this.showToast({ title: '修改成功'})
                this.userInfo.birthday = e.value
            }
            this.timerShow = false
        },
        editAvatar(e) {
            wx.getUserProfile({
          	    desc:'用于完善用户资料',
          	    success:(res)=>{
					const {userInfo} = res
					const Info = {
						avatarUrl:userInfo.avatarUrl,
                        // nickName:userInfo.nickName
					}
                     this.userInfo.avatarUrl = Info.avatarUrl
                    //  this.userInfo.name = Info.nickName
                     this.save(false)
          	    }
          	})
        },
        openTimer() {
            this.birthdayModalShow = false
            this.timerShow = true
        },
        changeBirthday(){
            this.birthdayModalShow = true
        },
        selectedSex(val){
            console.log(val)
            this.userInfo.sex = val.value
        },
        exit(){
            wx.exitMiniProgram({
                success:()=>{
                    console.log(123)
                }
            })
        },
        async save(isReturn = true) {
            const {customerName,...result} = this.userInfoStorage
            if(!this.valate){
                const {sex,name,id,avatarUrl} = this.userInfo
                const sendData = {
                    sex: Number(sex)===0?false:true,
                    userName: name,
                    id
                }
                console.log(sendData)
                await Mine.editUserAvatar({avatarUrl:avatarUrl,id})
                const { data } = await Mine.editUserInfo(sendData)
                console.log(data)
                const {code = 0} = data
                if(code===200){
                    this.showToast({ title: '保存成功'})
                    const data = {
                        ...result,
                        customerName:name,
                        avatarUrl,
                        canEditBirthday:this.canEditBirthday,
                        sex
                    }
                    Store.commit('setUserInfo', data);
                    uni.setStorage({ key: 'userInfo', data: data });
                    uni.setStorageSync('UserInfo',data)
                    if(isReturn){
                        wx.navigateBack({
    		            	delta: 1
  			            });
                    }
                }
            }
        }
    }
}
</script>

<style scoped lang="less">
.bigBox {
  .topBar{
		position: fixed;
		width: 100%;
		background: white;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		z-index: 9999;
		padding-left: 34rpx;
		.tabTitle{
			font-size: 32rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 600;
			text-align: center;
			width: 79%;
			color: #333333
		}
	}

}


.page{
    background: #F8F8F8;
    height: 100vh;
}
    .avatarBox {
        z-index: 1;
        width: 100%;
        height: 320rpx;
        display: flex;
        align-items: center;
        background: #FFFFFF;

        .avatar {
            width: 200rpx;
            height: 200rpx;
            border-radius: 50%;
            margin: 0 auto;
        }
    }

    .infoBox {
        z-index: 1;
        background: #FFFFFF;
        overflow: hidden;
        padding: 0rpx 38rpx 0rpx 40rpx;
        margin-top: 24rpx;

        .name {
            position: relative;

            .tip {
                position: absolute;
                font-size: 18rpx;
                color: red;
                bottom: 9rpx;
                left: 190rpx;
            }
        }

        .infoItem {
            height: 99rpx;
            border-bottom: 1rpx solid #ECECEC;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            box-sizing: border-box;
            padding-top: 7rpx;

            .label {
                font-size: 28rpx;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #333333;
            }

            .input {
                font-size: 28rpx;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #333333;
                margin-left: 136rpx;

                .sexBox {
                    display: flex;
                    align-items: center;
                    justify-content: flex-start;

                    .sex {
                        display: flex;
                        align-items: center;
                        justify-content: flex-start;
                        margin-right: 64rpx;

                        .checked {
                            width: 24rpx;
                            height: 24rpx;
                            background: url('../../../static/imgs/duigouxuanzhong.png') center center no-repeat;
			        		background-size:100% 100%;
                            margin-right: 16rpx;
                        }

                        .nochecked {
                            width: 24rpx;
                            height: 24rpx;
                            background: url('../../../static/imgs/weixuanzhong.png') center center no-repeat;
			        		background-size:100% 100%;
                            margin-right: 16rpx;
                        }

                        .checkLabel {
                            font-size: 28rpx;
                            font-family: PingFangSC-Regular, PingFang SC;
                            font-weight: 400;
                            color: #333333;
                        }
                    }
                }
                
                .birthdayBox {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    .textDisabled {
                        color: #999999;
                    }
                    .btn {
                        width: 96rpx;
                        height: 48rpx;
                        border-radius: 2rpx;
                        border: 2rpx solid #0050F6;
                        font-size: 24rpx;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        text-align: center;
                        color: #0050F6;
                        line-height: 48rpx;
                        margin-left: 192rpx;

                    }
                }


            }
        }

        .infoItem:last-child {
            border: 0rpx;
        }
    }

    .saveBtn {
        width: 670rpx;
        height: 98rpx;
        margin: 0 auto;
        margin-top: 32rpx;

        .btn {
           background: #0050F6;
           border-radius: 2px;
           font-size: 32rpx;
           height: 98rpx;
           line-height: 98rpx;
           font-family: PingFangSC-Regular, PingFang SC;
           font-weight: 400;
           color: #FFFFFF;
        }
        .btn::before {
           background: #0050F6;
           border-radius: 2px;
           font-size: 32rpx;
           height: 98rpx;
           line-height: 98rpx;
           font-family: PingFangSC-Regular, PingFang SC;
           font-weight: 400;
           color: #FFFFFF;
        }
    }
</style>