<template>
    <div class="edit">
        <headNav @rightClick="rightClick" RText="保存" title="编辑个人资料"></headNav>
        <van-cell-group>
            <van-cell title="" is-link center>
                <template #title>
                    <van-image
                        round
                        width="1.5rem"
                        height="1.5rem"
                        :src="headerUrl"
                    />
                </template>
                <template>
                    <van-uploader :preview-image="false" v-model="fileList" :max-count="1" :before-read="beforeAvatarUpload" :after-read="afterRead">
                        <span>修改头像</span>
                    </van-uploader>
                </template>
            </van-cell>
        </van-cell-group>
        <van-cell-group>
            <van-cell title="姓名" :value="userInfo && userInfo.name" />
            <van-cell title="账号" :value="userInfo && userInfo.account" />
            <van-cell title="部门" :value="userInfo && userInfo.enforce_org_name" />
            <van-cell title="手机号" :value="userInfo && userInfo.phone_num" />
        </van-cell-group>
        <van-cell-group>
            <van-field v-model="email" label="邮箱" input-align="right" placeholder="请输入邮箱" />
            <van-field v-model="cardNo" label="身份证号" input-align="right" placeholder="请输入身份证号" />
            <van-cell title="生日" is-link :value="date?date:'请选择'" @click="showDatePicker=true" />
            <van-cell title="性别" is-link :value="sex?sex:'请选择'" @click="showSexPicker=true" />
        </van-cell-group>

        <van-popup v-model="showSexPicker" round position="bottom">
            <van-picker
                show-toolbar
                title="选择性别"
                :columns="sexColumns"
                @cancel="showSexPicker = false"
                @confirm="onSexConfirm"
            />
        </van-popup>
        <van-popup v-model="showDatePicker" position="bottom">
            <van-datetime-picker
                type="date"
                title="选择出生日期"
                v-model="currentDate"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="onDateConfirm"
                @cancel="showDatePicker = false"
            />
        </van-popup>

        <v-mask :showOverLay="showOverLay" :tipMsg="tipMsg"></v-mask>
    </div>
</template>

<script>
import headNav from '@/components/headNav.vue';
import mask_overLay from "@/components/overLay_xy.vue";

import { dateFormat, notEmpty, formatYYYYMMDD } from '@/utils/tool';
import { getInfo, saveInfo } from '@/utils/auth';
import { post, postImg, put, get } from '@/utils/http.js';
import { compressAccurately } from "image-conversion";

export default {
    components: {
        "v-mask": mask_overLay,
        headNav
    },
    data () {
        return {
            headerUrl: 'https://img2.baidu.com/it/u=1915165029,2595650850&fm=26&fmt=auto',
            email: '',
            cardNo: '',
            showSexPicker: false,
            sexColumns: ['男', '女'],
            sex: null,
            showDatePicker: false,
            date: null,
            currentDate: new Date(),
            minDate: new Date(1949, 0, 1),
            maxDate: new Date(2025, 11, 31),
            fileList: [],
            tipMsg: '保存中...',
            showOverLay: false,
        }
    },
    computed: {
        userInfo() {
            return getInfo();
        },
    },
    mounted () {
        if (this.userInfo) {
            if (this.userInfo.sex == '0') {
                this.sex = '男';
            }
            else {
                this.sex = '女';
            }
            this.email = this.userInfo.email;
            this.cardNo = this.userInfo.cardId;
            this.date = this.userInfo.birthday;
            this.resetHeaderUrl();
        }
    },
    methods: {
        onSexConfirm(v) {
            this.sex = v;
            this.showSexPicker = false;
        },
        onDateConfirm(v) {
            this.date = dateFormat('YYYY-mm-dd', v);
            this.showDatePicker = false;
        },
        beforeAvatarUpload(file) {
			const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
			if (!isJpgOrPng) {
				this.$toast.fail("图片只能是 JPG 或 PNG 格式!");
				return false;
			}
			this.showOverLay = true;
			this.tipMsg = '图片处理中';
			return new Promise((resolve) => {
				compressAccurately(file, {
					size: 100,
				})
				.then((res) => {
					this.showOverLay = false;
					resolve(res);
				});
			});
		},
        afterRead(file) {
            this.showOverLay = true;
			this.tipMsg = '保存头像中...';
            post('/v1/api/user_user/editUserInfo', {
                userHeadportrarit: file.content,
                userId: this.userInfo.id
            }).then(res => {
                if (res.status == 200) {
                    this.headerUrl = file.content;
                    this.fileList = [];
                    this.loadUserInfo();
                }
                else {
                    this.showOverLay = false;
                    this.$toast.fail(res.msg || '头像保存失败');
                }
            }).catch(err => {
                this.showOverLay = false;
            })
        },
        resetHeaderUrl() {
            let str = 'https://img2.baidu.com/it/u=1915165029,2595650850&fm=26&fmt=auto';
            if (this.userInfo) {
                const url = this.userInfo.avatar;
                if (notEmpty(url)) {
                    str = url;
                }
            }
            this.headerUrl = str;
        },
        rightClick() {
            this.showOverLay = true;
            this.tipMsg = '保存中...';
            const params = {
                sex: this.sex == '女' ? 1 : 0,
            };
            if (notEmpty(this.cardNo)) {
                params.cardId = this.cardNo.trim();
            }
            if (notEmpty(this.email)) {
                params.email = this.email.trim();
            }
            if (notEmpty(this.date)) {
                params.birthday = this.date;
            }
            this.showOverLay = true;
            put(`/v2/api/sys_user/${this.userInfo.id}`, params).then(res => {
                this.loadUserInfo();
            }).catch(err => {
                this.showOverLay = false;
                this.$toast.fail('保存失败');
            })
        },
        loadUserInfo() {
            get(`/v2/api/sys_user/${this.userInfo.id}`).then(res => {
                if (res) {
                    saveInfo(res);
                }
                this.showOverLay = false;
                this.$toast.success('保存成功');
            });
        },
    }
}
</script>

<style lang="scss">
.edit {
    .van-cell-group {
        margin-top: 15px;
    }
    .van-uploader {
        width: 100%;
    }
    .van-uploader__input-wrapper {
        width: 100%;
    }
}
</style>

<style lang="scss" scoped>
.edit {
    padding-top: 57px;
}
</style>