<template>
    <div class="user-center-container">
        <div v-show="editAttr == 'none'" class="user-info-box">
            <!-- 头像设置 -->
            <div class="avatar-wrap">
                <div class="badge-wrap">
                    <img class="user-badge" :src="userInfo.picture || defBadge">
                    <div class="upd-mask">
                        <Upload :headers="updHeader" action="/blob/public-upload" class="upd-badge" :before-upload="customUpload" :on-error="handleUpdErr" :show-upload-list="false">
                            <Icon type="md-create" :title="$t('user.updAvatar')" color="white" />
                        </Upload>
                    </div>
                </div>
                <p class="id-info">{{`ID:${userInfo.id}`}}</p>
            </div>
            <!-- 基础信息区域 -->
            <div class="base-info-item">
                <Icon type="ios-person" class="info-label-icon" />
                <div class="base-value-wrap">
                    <p class="info-label">{{$t('user.name')}}:</p>
                    <p class="info-value" :style="{color:userInfo.name ? '' : '#ed4014'}">
                        {{userInfo.name || $t('user.noSet')}}
                    </p>
                </div>
                <span :class="['edit-btn', userInfo.name ? '' : 'set-btn']" @click="editInfo('name')">
                    {{userInfo.name ? $t('user.edit') : $t('user.setting')}}
                </span>
            </div>
            <div class="base-info-item">
                <Icon type="md-key" class="info-label-icon" />
                <div class="base-value-wrap">
                    <p class="info-label">{{$t('user.psw')}}</p>
                    <p class="info-value" :style="{color:userInfo.is_set_pw ? '' : '#ed4014'}">
                        {{userInfo.is_set_pw ? '********' : $t('user.noSet')}}
                    </p>
                </div>
                <span :class="['edit-btn', userInfo.is_set_pw ? '' : 'set-btn']" @click="editInfo('password')">
                    {{userInfo.is_set_pw ? $t('user.edit') : $t('user.setting')}}
                </span>
            </div>
            <div class="base-info-item">
                <Icon type="md-phone-portrait" class="info-label-icon" />
                <div class="base-value-wrap">
                    <p class="info-label">{{$t('user.mobile')}}:</p>
                    <p class="info-value" :style="{color:userInfo.mobile ? '' : '#ed4014'}">
                        {{userInfo.mobile || $t('user.noSet')}}
                    </p>
                </div>
                <span :class="['edit-btn', userInfo.mobile ? '' : 'set-btn']" @click="editInfo('mobile')">
                    {{userInfo.mobile ? $t('user.edit') : $t('user.setting')}}
                </span>
            </div>
            <div class="base-info-item">
                <Icon type="ios-mail" class="info-label-icon" />
                <div class="base-value-wrap">
                    <p class="info-label">{{$t('user.email')}}:</p>
                    <p class="info-value" :style="{color:userInfo.mail ? '' : '#ed4014'}">
                        {{userInfo.mail || $t('user.noSet')}}
                    </p>
                </div>
                <span :class="['edit-btn', userInfo.mail ? '' : 'set-btn']" @click="editInfo('mail')">
                    {{userInfo.mail ? $t('user.edit') : $t('user.setting')}}
                </span>
            </div>
            <!-- <div class="base-info-item">
                <Icon type="md-link" class="info-label-icon" />
                <div class="base-value-wrap">
                    <p class="info-label">账号绑定:</p>
                    <p class="info-value">
                        - -
                    </p>
                </div>
                <span class="edit-btn">编辑</span>
            </div> -->
        </div>
        <div v-show="editAttr !== 'none'" class="user-info-box light-iview-input">
            <!-- <Icon type="md-close" class="close-edit-info" @click="editAttr = 'none'" /> -->
            <!-- 编辑名称 -->
            <div v-show="editAttr == 'name'" style="margin:auto;width:fit-content" :class="nameErr ? 'error-input' : ''">
                <span style="margin-right:10px">{{$t('user.name')}}</span>
                <Input v-model="eName" :placeholder="userInfo.name" style="width: 260px" />
                <p v-show="nameErr" class="error-tips">
                    {{$t('user.nameWarning')}}
                </p>
            </div>
            <!-- 修改密码 -->
            <div v-show="editAttr == 'password'" style="margin:auto;width:fit-content">
                <Form ref="password" :model="pw" :rules="pwValidate" :label-width="80" label-position="left">
                    <FormItem prop="original">
                        <span slot="label" class="form-label">{{$t('user.oldPsw')}}</span>
                        <Input v-model="pw.original" placeholder="" class="edit-pw-input" type="password" password />
                    </FormItem>
                    <FormItem prop="newPw">
                        <span slot="label" class="form-label">{{$t('user.newPsw')}}</span>
                        <Input v-model="pw.newPw" placeholder="" class="edit-pw-input" type="password" password />
                    </FormItem>
                    <FormItem prop="confirm">
                        <span slot="label" class="form-label">{{$t('user.newPsw1')}}</span>
                        <Input v-model="pw.confirm" placeholder="" class="edit-pw-input" type="password" password />
                    </FormItem>
                </Form>
            </div>
            <!-- 修改手机号 -->
            <div v-show="editAttr == 'mobile'" style="margin:auto;width:fit-content">
                <Form ref="mobile" :model="mobile" :rules="mobileValidate" :label-width="80" label-position="left">
                    <FormItem prop="number" class="custom-radirs">
                        <span slot="label" class="form-label">{{$t('user.mobile')}}</span>
                        <Select v-model="mobile.area" style="width:130px">
                            <Option v-for="item in areaList" :value="item.code" :key="item.area">
                                {{ `+${item.code}(${item.name})` }}
                            </Option>
                        </Select>
                        <Input v-model="mobile.number" placeholder="" class="edit-pw-input" style="width:160px" />
                    </FormItem>
                    <FormItem prop="code" class="custom-radirs">
                        <span slot="label" class="form-label">{{$t('user.code')}}</span>
                        <Button :disabled="!mobile.number || hasSend" @click="sendMsgCode" style="width:130px">
                            {{$t('user.sendCode')}}
                            {{hasSend ? `(${countdown})` : ''}}
                        </Button>
                        <Input v-model="mobile.code" placeholder="" class="edit-pw-input" style="width:160px" />
                    </FormItem>
                </Form>
            </div>
            <!-- 编辑邮箱 -->
            <div v-show="editAttr == 'mail'" style="margin:auto;width:fit-content">
                <Form ref="mail" :model="mail" :rules="mailValidate" :label-width="80" label-position="left">
                    <FormItem prop="mail">
                        <span slot="label" class="form-label">{{$t('user.email')}}</span>
                        <Input v-model="mail.mail" placeholder="" class="edit-pw-input" />
                    </FormItem>
                    <FormItem prop="code" class="custom-radirs">
                        <span slot="label" class="form-label">{{$t('user.code')}}</span>
                        <Button :disabled="!mail.mail || hasSend" @click="sendMailCode" style="width:130px">
                            {{$t('user.sendCode1')}}
                            {{hasSend ? `(${countdown})` : ''}}
                        </Button>
                        <Input v-model="mail.code" placeholder="" class="edit-pw-input" style="width:100px" />
                    </FormItem>
                </Form>
            </div>
            <div class="submit-btn-wrap">
                <Button type="primary" style="width:150px;margin-right:10px" @click="submit">{{$t('user.confirm')}}</Button>
                <Button style="width:150px" @click="editAttr = 'none'">{{$t('user.cancel')}}</Button>
            </div>
        </div>
    </div>
</template>
<script>
import jwtDecode from 'jwt-decode'
import countryCode from '@/static/countryCodeData.js'
export default {
    data() {
        const confirm = (rule, value, callback) => {
            if (value !== this.pw.newPw) {
                callback(new Error(this.$t('user.pswErr1')))
            } else {
                callback()
            }
        }
        return {
            updHeader: {},
            timer: undefined,
            countdown: 60, //倒计时
            userInfo: {},
            defBadge: undefined,
            editAttr: 'none',
            eName: '',//修改名称
            nameErr: false,
            hasSend: false,
            pw: {
                original: '',
                newPw: '',
                confirm: ''
            },
            pwValidate: {
                original: [
                    { required: true, message: this.$t('user.oldErr'), trigger: 'change' }
                ],
                newPw: [
                    { required: true, message: this.$t('user.pswErr2'), trigger: 'change' }
                ],
                confirm: [
                    { required: true, message: this.$t('user.pswErr3'), trigger: 'blur' },
                    { validator: confirm, trigger: 'blur' }
                ],
            },
            mobile: {
                number: '',
                code: '',
                area: 86
            },
            mobileValidate: {
                number: [
                    { required: true, message: this.$t('user.mobileErr'), trigger: 'change' }
                ],
                code: [
                    { required: true, message: this.$t('user.codeWarning'), trigger: 'change' }
                ],
                area: [
                    { required: true, message: this.$t('user.areaErr'), trigger: 'change' }
                ]
            },
            mail: {
                mail: '',
                code: ''
            },
            mailValidate: {
                mail: [
                    { required: true, message: this.$t('user.emailErr'), trigger: 'change' }
                ],
                code: [
                    { required: true, message: this.$t('user.codeWarning'), trigger: 'change' }
                ]
            },
            areaList: []
        }
    },
    created() {
        if (localStorage.getItem('auth_token')) {
            this.updHeader['x-auth-authtoken'] = localStorage.getItem('auth_token')
        } else {
            this.$Message.error(this.$t('login.loginErr'))
            this.$router.push({
                name: 'login'
            })
        }
        //默认头像
        this.defBadge = require('@/assets/icon/default_school.png')
        this.getIdInfo()
        //处世化地区数据
        console.log(countryCode)
        let curLocal = localStorage.getItem('local')
        let attr = 'CountryEn'
        if (curLocal.includes('cn') || curLocal.includes('CN')) {
            attr = 'CountryCn'
        } else if (curLocal.includes('tw') || curLocal.includes('TW')) {
            attr = 'CountryTw'
        }
        for (const key in countryCode) {
            this.areaList.push(
                {
                    code: countryCode[key].Code,
                    area: key,
                    name: countryCode[key][attr],
                    local: countryCode[key].Culture
                }
            )
        }
        this.areaList.sort((a, b) => {
            return a.code - b.code
        })
        console.log(this.areaList)
    },
    methods: {
        //发送短信验证码
        sendMsgCode() {
            let srvAdr = this.$store.state.config.srvAdr
            let host = srvAdr == 'Global' ? this.$store.state.config.Global.coreAPIUrl : this.$store.state.config.China.coreAPIUrl
            let params = {
                country: this.mobile.area + '',
                to: this.mobile.number,
                lang: localStorage.getItem('local'),
                HasUser: false
            }
            this.$api.service.sandMsgCode(host, params).then(
                res => {
                    if (!res.error) {
                        this.$Message.success(this.$t('user.msgOk'))
                        this.hasSend = true
                        this.timer = setInterval(() => {
                            this.countdown--
                        }, 1000)
                    } else {
                        if (res.error == 1) {
                            this.$Message.error(this.$t('user.noMobile'))
                        } else if (res.error == 2) {
                            this.$Message.error(this.$t('user.hasReg'))
                        } else {
                            this.$Message.error(this.$t('user.msgErr'))
                        }
                    }
                },
                err => {
                    this.$Message.error(this.$t('user.msgErr'))
                }
            )
        },
        //发送邮件验证码
        sendMailCode() {
            let srvAdr = this.$store.state.config.srvAdr
            let host = srvAdr == 'Global' ? this.$store.state.config.Global.coreAPIUrl : this.$store.state.config.China.coreAPIUrl
            let params = {
                to: this.mail.mail,
                lang: localStorage.getItem('local'),
                HasUser: false
            }
            this.$api.service.sandMailCode(host, params).then(
                res => {
                    if (!res.error) {
                        this.$Message.success(this.$t('user.emailOk'))
                        this.hasSend = true
                        this.timer = setInterval(() => {
                            this.countdown--
                        }, 1000)
                    } else if (res.error == 2) {
                        this.$Message.error(this.$t('user.emailHasReg'))
                    } else {
                        this.$Message.error(this.$t('user.emailErr'))
                    }
                },
                err => {
                    this.$Message.error(this.$t('user.emailErr'))
                }
            )
        },
        //保存信息
        submit() {
            let srvAdr = this.$store.state.config.srvAdr
            let host = srvAdr == 'Global' ? this.$store.state.config.Global.coreAPIUrl : this.$store.state.config.China.coreAPIUrl
            let clientId = srvAdr == 'Global' ? this.$store.state.config.Gloabl.clientID : this.$store.state.config.China.clientID
            let idToken = localStorage.getItem('id_token')
            let tokenData = jwtDecode(idToken)
            let nonce = tokenData ? tokenData.nonce : ''

            let params = {
                "nonce": nonce,
                "client_id": clientId,
                "id_token": idToken
            }
            switch (this.editAttr) {
                case 'name':
                    if (this.eName) {
                        params.grant_type = 'name'
                        params.name = this.eName
                        this.nameErr = false
                    } else {
                        this.nameErr = true
                    }
                    break
                case 'password':
                    this.$refs['password'].validate((valid) => {
                        if (valid) {
                            params.grant_type = 'password'
                            params.old_pw = this.pw.original
                            params.new_pw = this.pw.newPw
                        } else {
                            this.$Message.error(this.$t('user.checkTips'))
                        }
                    })
                    break
                case 'mobile':
                    this.$refs['mobile'].validate((valid) => {
                        if (valid && this.mobile.area) {
                            params.grant_type = 'mobileOrMail'
                            params.mobile_mail = `+${this.mobile.area}-${this.mobile.number}`
                            params.pin_code = this.mobile.code
                        } else {
                            this.$Message.error(this.$t('user.checkTips'))
                        }
                    })
                    break
                case 'mail':
                    this.$refs['mail'].validate((valid) => {
                        if (valid) {
                            params.grant_type = 'mobileOrMail'
                            params.mobile_mail = this.mail.mail
                            params.pin_code = this.mail.code
                        } else {
                            this.$Message.error(this.$t('user.checkTips'))
                        }
                    })
                    break
                default:
                    break
            }
            if (params.grant_type) {
                this.updateUserInfo(host, params)
            }
        },
        updateUserInfo(host, params) {
            this.$api.service.getIdProfile(host, params).then(
                res => {
                    if (!res.error) {
                        this.$Message.success(this.$t('user.updOk'))
                        console.log(this.editAttr)
                        switch (this.editAttr) {
                            case 'name':
                                this.userInfo.name = this.eName
                                this.$store.commit('setUserName', this.eName)
                                this.$EventBus.$emit('freshUserInfo')
                                this.eName = ''
                                break
                            case 'mobile':
                                this.userInfo.mobile = this.mobile.number
                                this.mobile.number = ''
                                this.mobile.code = ''
                                this.mobile.area = 86
                                break
                            case 'mail':
                                this.userInfo.mail = this.mail.mail
                                this.mail.mail = ''
                                this.mail.code = ''
                                break
                            case 'none':
                                if (params.picture) {
                                    let r = jwtDecode(res.id_token)
                                    let p = r.picture || this.userInfo.picture
                                    this.$set(this.userInfo, 'picture', '')
                                    setTimeout(() => {
                                        this.$set(this.userInfo, 'picture', p)
                                    })
                                    let userInfo = JSON.parse(decodeURIComponent(localStorage.getItem('userInfo') || '{}', "utf-8"))
                                    userInfo.picture = p
                                    localStorage.setItem('userInfo', encodeURIComponent(JSON.stringify(userInfo)))
                                    this.$EventBus.$emit('freshUserInfo', {
                                        picture: p
                                    })
                                }
                                break
                            default:
                                break
                        }
                        this.editAttr = 'none'
                    } else {
                        if (res.error == 3) {
                            this.$Message.error(this.$t('user.codeErr'))
                        } else {
                            this.$Message.error('API Error')
                        }
                    }
                },
                err => {
                    console.log(err)
                }
            )
        },
        editInfo(attr) {
            this.editAttr = attr
        },
        //上传头像
        customUpload(file) {
            let format = ['png', 'jpg', 'jpeg'] //头像文件格式
            let extension = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length)
            extension = extension.toLowerCase()
            if (format.length > 0 && format.indexOf(extension) == -1) {
                this.$Message.error({
                    content: this.$t('updModal.typeErr'),
                    duration: 3
                })
                return false
            }
            let _this = this
            let reader = new FileReader(); //实例化文件读取对象
            reader.readAsDataURL(file); //将文件读取为 DataURL,也就是base64编码
            reader.onload = function (ev) { //文件读取成功完成时触发
                let dataURL = ev.target.result; //获得文件读取成功后的DataURL,也就是base64编码
                console.log(dataURL);
                //更新头像
                let srvAdr = _this.$store.state.config.srvAdr
                let host = srvAdr == 'Global' ? _this.$store.state.config.Global.coreAPIUrl : _this.$store.state.config.China.coreAPIUrl
                let clientId = srvAdr == 'Global' ? _this.$store.state.config.Gloabl.clientID : _this.$store.state.config.China.clientID
                let idToken = localStorage.getItem('id_token')
                let tokenData = jwtDecode(idToken)
                let nonce = tokenData ? tokenData.nonce : ''
                let params = {
                    "nonce": nonce,
                    "client_id": clientId,
                    "id_token": idToken,
                    'grant_type': 'picture',
                    'picture': dataURL
                }
                _this.updateUserInfo(host, params)
            }
            return false
        },
        handleUpdErr() {
            this.$Message.error(this.$t('updModal.updErr'))
        },
        // 获取账号详细信息
        getIdInfo() {
            let srvAdr = this.$store.state.config.srvAdr
            let host = srvAdr == 'Global' ? this.$store.state.config.Global.coreAPIUrl : this.$store.state.config.China.coreAPIUrl
            let clientId = srvAdr == 'Global' ? this.$store.state.config.Global.clientID : this.$store.state.config.China.clientID
            let idToken = localStorage.getItem('id_token')
            let tokenData = jwtDecode(idToken)
            let nonce = tokenData ? tokenData.nonce : ''
            let params = {
                "grant_type": "get",
                "nonce": nonce,
                "client_id": clientId,
                "id_token": idToken
            }
            this.$api.service.getIdProfile(host, params).then(
                res => {
                    console.log(res)
                    if (!res.error) {
                        this.userInfo = res
                    } else {
                        this.$Message.error('API Error')
                    }
                },
                err => {
                    console.log(err)
                }
            )
        }
    },
    watch: {
        countdown(n, o) {
            if (n <= 0) {
                clearInterval(this.timer)
                this.timer = undefined
                this.hasSend = false
                this.countdown = 60
            }
        }
    }
}
</script>
<style lang="less" scoped>
.edit-pw-input {
    display: inline-block;
    width: 230px;
}
.form-label {
    // color: white;
}
.error-tips {
    color: #ed4014;
    text-align: left;
    margin-left: 40px;
    margin-top: 2px;
}
.submit-btn-wrap {
    margin-top: 20px;
    text-align: center;
}
.close-edit-info {
    color: white;
    position: absolute;
    right: 10px;
    top: 8px;
    cursor: pointer;
}
.info-label {
    color: #a5a5a5;
}
.info-value {
    // color: white;
}
.id-info {
    // color: white;
    text-align: center;
    margin-top: 10px;
}
.avatar-wrap {
    margin-bottom: 25px;
}
.user-center-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    // align-items: center;
}
.user-info-box {
    margin-top: 120px;
    padding: 50px 50px;
    height: -moz-fit-content;
    height: fit-content;
    border-radius: 30px;
    box-shadow: 0 0 10px 5px #e9e9e9;
    position: relative;
    // color: white;
    width: 700px;
}
.base-info-item {
    width: 600px;
    margin: 0px auto;
    padding: 15px 25px 15px 5px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid transparent;
    &:hover {
        // border-color: var();
        background: var(--hover-text-color);
    }
    .info-label-icon {
        font-size: 24px;
        color: var(--normal-icon-color);
        width: 60px;
    }
    .base-value-wrap {
        flex: 1;
    }
    .edit-btn {
        background: #eee;
        padding: 2px 6px;
        font-size: 12px;
        border-radius: 4px;
        color: #303030;
        cursor: pointer;
        user-select: none;
    }
    .set-btn {
        background: #ed4014;
        color: white;
    }
}
.badge-wrap {
    position: relative;
    width: 70px;
    margin: auto;
    &:hover {
        .upd-mask {
            opacity: 1;
        }
    }
    .upd-mask {
        position: absolute;
        left: 0px;
        top: 0px;
        bottom: 0px;
        width: 70px;
        border-radius: 50%;
        display: flex;
        background: rgba(68, 68, 68, 0.5);
        justify-content: center;
        align-items: center;
        opacity: 0;
        .upd-badge {
            cursor: pointer;
            text-align: center;
            font-size: 20px;
        }
    }
}
.user-badge {
    vertical-align: middle;
    width: 70px;
    border-radius: 50%;
}
</style>
<style lang="less">
.custom-radirs {
    .ivu-select-selection,
    .ivu-btn {
        border-radius: 4px 0px 0px 4px;
    }
    .ivu-input {
        border-radius: 0px 4px 4px 0px;
    }
}
.error-input {
    .ivu-input {
        border-color: #ed4014;
    }
}
</style>