{% load static %}
<style>
    .editAvatar{
        position: absolute;
        bottom: 0;
        left: 0;
        /* line-height: 64px; */
        width: 64px;
        text-align: center;
        /* color: brown; */
        /* font-size: small; */
    }
</style>
<div class="column" id="userinfo">
    <div class="columns is-align-items-center is-marginless">
        <div class="column is-2 has-text-grey-light">头像</div>
        <div class="column">
            <div class="is-flex is-justify-content-space-between is-align-items-center">
                <b-upload v-model="file" class="file-label" rounded accept=".jpg,.png,gif" @input="avatarInput">
                    <figure class="image is-64x64 is-relative" @mouseover="editAvatar=true" @mouseout="editAvatar=false">
                        <img class="is-rounded" :src="avatarSrc">
                        <div class="editAvatar has-background-primary-light">
                            <b-tag type="is-primary is-light" v-show="editAvatar">修改</b-tag>
                        </div>
                    </figure>
                </b-upload>
                
                <button class="button is-success is-outlined is-small" v-if="file.name" @click="saveAvatar">
                    <span class="icon"><i class="mdi mdi-image-edit"></i></span> 
                    <span class="text">保存</span>
                </button>
            </div>
            
        </div>
    </div>
    <div class="dropdown-divider is-marginless"></div>
    <div class="columns is-align-items-center is-marginless">
        <div class="column is-2 has-text-grey-light">用户名</div>
        <div class="column">{{ request.user.username }}</div>
    </div>
    <div class="dropdown-divider is-marginless"></div>
    <div class="columns is-align-items-center is-marginless">
        <div class="column is-2 has-text-grey-light">手机号</div>
        <div class="column is-flex is-justify-content-space-between is-align-items-center">
            <p>{$ phone $}</p>
            <button class="button is-primary is-small is-outlined" @click="updateUserPhone">
                <span class="icon"><i class="mdi mdi-phone-settings-outline"></i></span> 
                <span class="text">修改</span>
            </button>
        </div>
    </div>
    <div class="dropdown-divider is-marginless"></div>
    <div class="columns is-align-items-center is-marginless">
        <div class="column is-2 has-text-grey-light">邮箱</div>
        <div class="column is-flex is-justify-content-space-between is-align-items-center">
            <p>{$ email $}</p>
            <button class="button is-primary is-small is-outlined" @click="isEmailModalActive=true">
                <span class="icon"><i class="mdi mdi-email-edit-outline"></i></span> 
                <span class="text">修改</span>
            </button>
            <b-modal v-model="isEmailModalActive" 
                :width="350" 
                scroll="keep" 
                :destroy-on-hide="true">
                <div class="modal-card" style="width: auto">
                    <header class="modal-card-head">
                        <p class="modal-card-title">修改邮箱</p>
                        <button
                            type="button"
                            class="delete"
                            @click="isEmailModalActive=false" />
                    </header>
                    <section class="modal-card-body">
                        <b-field label="邮箱">
                            <b-input
                                type="email"
                                v-model="email"
                                placeholder="请输入新的邮箱地址！"
                                required>
                            </b-input>
                        </b-field>
                        <b-field grouped label="验证码">
                            <b-input 
                                placeholder="验证码" 
                                v-model="code" 
                                maxlength="4" 
                                :has-counter="false" 
                                expanded
                                required>
                            </b-input>
                            <p class="control">
                                <b-button :label="codeBtnText" type="is-primary" @click="sendCode" :disabled="codeDisabled" />
                            </p>
                        </b-field>
                    </section>
                    <footer class="modal-card-foot">
                        <b-button
                            label="保存"
                            expanded
                            :disabled="email && code ? false : true"
                            @click="updateUserEmail"
                            type="is-primary" />
                    </footer>
                </div>
            </b-modal>
        </div>
    </div>
    <div class="dropdown-divider is-marginless"></div>
    <div class="columns is-align-items-center is-marginless">
        <div class="column is-2 has-text-grey-light">余额</div>
        <div class="column is-flex is-justify-content-space-between is-align-items-center">
            <p>¥ {$ balance $}</p>
            <p>
                <button class=" button is-primary is-outlined is-small" @click="isBanlanceModalActive=true">
                    <span class="icon"><i class="mdi mdi-credit-card-settings-outline"></i></span> 
                    <span class="text">充值</span> 
                </button>
            </p>
            <b-modal v-model="isBanlanceModalActive" 
                :width="350" 
                scroll="keep" 
                :destroy-on-hide="true">
                <div class="modal-card" style="width: auto">
                    <header class="modal-card-head">
                        <p class="modal-card-title">充值</p>
                        <button
                            type="button"
                            class="delete"
                            @click="isBanlanceModalActive=false" />
                    </header>
                    <section class="modal-card-body">
                        <b-field label="充值金额">
                            <b-input
                                type="number"
                                v-model="add_balance"
                                placeholder="充值金额仅支持整数！"
                                required>
                            </b-input>
                        </b-field>
                    </section>
                    <footer class="modal-card-foot">
                        <b-button
                            label="保存"
                            expanded
                            @click="addUserBanlance"
                            type="is-primary" />
                    </footer>
                </div>
            </b-modal>
        </div>
    </div>
    <div class="dropdown-divider is-marginless"></div>
    
    <div class="columns is-align-items-center is-marginless">
        <div class="column is-2 has-text-grey-light">个人简介</div>
        <div class="column is-flex is-justify-content-space-between is-align-items-center">
            <p v-if="!editedesc">{$ about $}</p>
            <div class=" is-flex-grow-1 mr-5">
                <b-input type="textarea"
                    v-if="editedesc"
                    size="is-small"
                    v-model="about"
                    :has-counter="false"
                    @blur="updateUserAbout"
                    maxlength="150">
                </b-input>
            </div>
            <button class="button is-primary is-small is-outlined" @click="editedesc=true">
                <span class="icon"><i class="mdi mdi-account-cog-outline"></i></span> 
                <span class="text">修改</span>
            </button>

        </div>
    </div>
    <div class="dropdown-divider is-marginless"></div>
</div>

<script>
    var userinfo = new Vue({
        el: '#userinfo',
        delimiters: ['{$', '$}'],
        data: {
            phone: '{{ request.user.baykeuser.phone }}' || "暂未设置",
            email: '{{ request.user.email }}' || "暂未设置",
            about: '{{ request.user.baykeuser.about }}' || "暂未设置",
            balance: parseFloat('{{ request.user.baykeuser.balance }}') || 0,
            code: '',
            isEmailModalActive: false,
            editedesc: false,
            editAvatar: false,
            file: {},
            avatarSrc: "{% if request.user.baykeuser.avatar %}{{ request.user.baykeuser.avatar.url }}{% else %}{% static 'img/wx.jpg' %}{% endif %}",
            remainingTime: 60,
            codeBtnText: '发送验证码',
            codeDisabled: false,
            isBanlanceModalActive: false,
            add_balance: 0
        },

        beforeDestroy() {
            clearInterval(this.timerId);
        },
        methods:{
            // 修改用户简介
            updateUserAbout(){
                fetch("{% url 'user:userapi:update-user-about' %}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': bayke.getCookie('csrftoken'),
                    },
                    body: JSON.stringify({about: this.about}),
                }).then(response => bayke.handleJSONResponse(response)).then(data => {
                    // 处理响应数据
                    this.editedesc = false
                    location.reload()
                }).catch(error => {
                    // 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
                });
            },
            // 修改邮箱
            updateUserEmail(){
                fetch("{% url 'user:userapi:update-user-email' %}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': bayke.getCookie('csrftoken'),
                    },
                    body: JSON.stringify({email: this.email, code: this.code}),
                }).then(response => bayke.handleJSONResponse(response)).then(data => {
                    // 处理响应数据
                    this.isEmailModalActive = false
                    location.reload()
                }).catch(error => {
                    // 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
                });
            },
            // 获取验证码
            sendCode(){
                this.timerId = setInterval(() => this.startCountdown(), 1000);
                // 获取验证码
                fetch("{% url 'user:userapi:send-email' %}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': bayke.getCookie('csrftoken'),
                    },
                    body: JSON.stringify({email: this.email}),
                }).then(response => bayke.handleJSONResponse(response)).then(data => {
                    // 处理响应数据
                    bayke.toastMessage('is-success', '验证码已发送，请尽快验证！')
                }).catch(error => {
                    // 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
                });
            },
            // 定时60秒倒计时
            startCountdown() {
                if (this.remainingTime > 0) {
                    this.remainingTime--;
                    this.codeDisabled = true
                    this.codeBtnText = `${this.remainingTime}s 后获取`
                } else {
                    clearInterval(this.timerId);
                    this.remainingTime = 60
                    this.codeDisabled = false
                    this.codeBtnText = '重新发送验证码'
                }
            },      

            // 余额充值
            addUserBanlance(){
                fetch("{% url 'user:userapi:push-balance' %}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': bayke.getCookie('csrftoken'),
                    },
                    body: JSON.stringify({add_balance: this.add_balance}),
                }).then(response => bayke.handleJSONResponse(response)).then(data => {
                    // 处理响应数据
                    bayke.toastMessage('is-success', '正在跳转至充值页面！')
                    location.replace(data.payurl)
                }).catch(error => {
                    // 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
                });
            },

            // 修改头像
            avatarInput(){
                let avatarUrl = URL.createObjectURL(new Blob([this.file], { type: "image/png" }))
                this.avatarSrc = avatarUrl
            },
            // 保存头像
            saveAvatar(){
                let sendData = new FormData();
                sendData.append('avatar', this.file)
                fetch("{% url 'user:userapi:update-user-avatar' %}", {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': bayke.getCookie('csrftoken'),
                    },
                    body: sendData,
                }).then(response => bayke.handleJSONResponse(response)).then(data => {
                    // 处理响应数据
                    location.reload()
                }).catch(error => {
                    // 处理错误
					let message = Object.values(error).join()
					bayke.toastMessage('is-danger', message)
                });
            },
            // 修改手机号
            updateUserPhone(){
                bayke.toastMessage('is-danger', '暂不支持修改！')
            }
        }
    })
</script>