<template>
    <div class="page">
        <div class="portrait" @click="upload">
            <my-image
                class="portrait__img"
                :src="userInfo.avatarUrl || '/static/user/portrait.jpg'"
            ></my-image>
            <div class="portrait__text">更换头像</div>
        </div>
        <ul class="list">
            <li class="list__item">
                <div class="list__left">
                    <div class="list__title">用户名：</div>
                    <input class="list__input" type="text" v-model="nickName" />
                </div>
                <div class="list__right">
                    <div class="list__btn" @click="setNickName">保存</div>
                </div>
            </li>
            <li class="list__item">
                <div class="list__left">
                    <div class="list__title">手机号：</div>
                    <input class="list__input" type="text" v-model="phone" />
                </div>
                <div class="list__right">
                    <div class="list__btn" @click="setPhone">保存</div>
                </div>
            </li>
            <li class="list__item" @click="setSex">
                <div class="list__left">
                    <div class="list__title">性别：</div>
                </div>
                <div class="list__right">
                    <div class="list__text2">
                        {{
                            userInfo.gender === 1
                                ? "男"
                                : userInfo.gender === 2
                                ? "女"
                                : "保密"
                        }}
                    </div>
                    <i class="iconfont iconarrow list__icon"></i>
                </div>
            </li>
            <picker
                mode="date"
                :end="endDate"
                :value="birthday"
                @change="setBirthday"
            >
                <li class="list__item">
                    <div class="list__left">
                        <div class="list__title">生日：</div>
                    </div>
                    <div class="list__right">
                        <div class="list__text2">{{ birthday || "" }}</div>
                    </div>
                </li>
            </picker>
            <li class="list__item" @click="jumpHandle('/pages/user/vip-code')">
                <div class="list__left">
                    <div class="list__title">会员码：</div>
                </div>
                <div class="list__right">
                    <my-image
                        class="vip-code"
                        src="/static/user/qr-code2.png"
                    ></my-image>
                    <i class="iconfont iconarrow list__icon"></i>
                </div>
            </li>
        </ul>
        <canvas
            class="canvas-ele"
            style="width: 220px; height: 220px"
            canvas-id="myQrcode"
        ></canvas>
    </div>
</template>

<script>
import MyImage from "../../components/image/index";
import drawQrcode from "../../common/js/weapp.qrcode.esm";

export default {
    name: "",
    components: { MyImage },
    // 数据
    data() {
        return {
            nickName: "", // 昵称
            birthday: "", //生日
            phone: "", // 手机号
            endDate: "",
            vipCodeImg: "",
        };
    },

    onShow() {
        const self = this;

        let nowDate = new Date();
        let year = nowDate.getFullYear();
        let month = nowDate.getMonth() + 1;
        let day = nowDate.getDate();

        if (month < 10) {
            month = "0" + month;
        }

        if (day < 10) {
            day = "0" + day;
        }

        self.endDate = year + "-" + month + "-" + day;
        self.birthday = self.userInfo.birthday;
    },

    // 函数
    methods: {
        // 上传头像
        upload() {
            const self = this;
            let list = ["拍照", "我的相册"];
            self.fn.showActionSheet(list).then((index) => {
                uni.chooseImage({
                    count: 1,
                    sizeType: ["original", "compressed"],
                    sourceType: index === 0 ? ["camera"] : ["album"],
                    success(res) {
                        const filePaths = res.tempFilePaths;

                        filePaths.forEach((item) => {
                            uni.uploadFile({
                                header: {
                                    appId: self.config.appId,
                                    companyId: self.$store.state.user.companyId,
                                    userId: self.$store.state.user.userId,
                                    Authorization: "Bearer " + self.token,
                                },
                                url: self.config.apiBaseUrl + "/Upload/Image",
                                filePath: item,
                                name: "file",
                                formData: {},
                                success: function (res) {
                                    let data = JSON.parse(res.data);

                                    uni.hideLoading();

                                    self.api
                                        .post("/User/UpdateHeadIcon", {
                                            userId: self.user.userId,
                                            headIcon: data.data,
                                        })
                                        .then(() => {
                                            self.fn.showToast("修改成功");
                                            self.getUserInfo();
                                        });
                                },
                            }).onProgressUpdate((res) => {
                                if (res.progress < 100) {
                                    uni.showLoading({
                                        title: "上传中 " + res.progress,
                                        mask: true,
                                    });
                                }
                            });
                        });
                    },
                });
            });
        },

        // 修改昵称
        setNickName() {
            const self = this;

            if (!self.nickName) {
                self.fn.showToast("请输入用户名");
            } else if (self.nickName.length > 10) {
                self.fn.showToast("用户名不合法");
            } else {
                self.api
                    .post("/User/UpdateNickName", {
                        userId: self.user.userId,
                        nickName: self.nickName,
                    })
                    .then(() => {
                        self.fn.showToast("修改成功");
                        self.getUserInfo();
                    });
            }
        },

        // 修改手机号
        setPhone() {
            const self = this;
            let phoneReg = /^[1][1-9][0-9]{9}$/;

            if (!self.phone) {
                self.fn.showToast("请输入手机号");
            } else if (!phoneReg.test(self.phone)) {
                self.fn.showToast("手机号码不正确");
            } else {
                self.api
                    .post("/User/UpdateMobile", {
                        userId: self.user.userId,
                        mobile: self.phone,
                    })
                    .then((res) => {
                        if (res.data) {
                            self.fn.showToast("修改成功");
                            self.getUserInfo();
                        } else {
                            self.fn.showToast(res.message);
                        }
                    });
            }
        },
        // 未登录跳转处理
        jumpHandle(option) {
            const self = this;

            if (self.user.login) {
                self.router.push(option);
            } else {
                self.router.push("/pages/login/index");
            }
        },

        // 设置性别
        setSex() {
            const self = this;
            let list = ["保密", "男", "女"];

            self.fn.showActionSheet(list).then((index) => {
                self.api
                    .post("/User/UpdateGender", {
                        userId: self.user.userId,
                        gender: index,
                    })
                    .then(() => {
                        self.fn.showToast("修改成功");
                        self.getUserInfo();
                    });
            });
        },

        // 设置生日
        setBirthday(e) {
            const self = this;

            self.birthday = e.detail.value;
            self.api
                .post("/User/UpdateBirthday", {
                    userId: self.user.userId,
                    birthday: self.birthday,
                })
                .then(() => {
                    self.fn.showToast("修改成功");
                    self.getUserInfo();
                });
        },

        // 获取用户信息
        getUserInfo() {
            const self = this;

            self.api.get("/User/GerUserInfo").then((res) => {
                self.$store.commit("user/update", {
                    userInfo: res.data,
                });
            });
        },
        viewVipCode() {
            var self = this;
            if (this.vipCodeImg) {
                uni.previewImage({
                    urls: [self.vipCodeImg],
                    longPressActions: true,
                });
            } else {
                this.api.get("/My/GetVipCode").then((res) => {
                    let code = res.data;
                    let ctx = wx.createCanvasContext("myQrcode");
                    drawQrcode({
                        width: 200,
                        height: 200,
                        ctx,
                        text: code,
                        x: 10,
                        y: 10,
                        foreground: "#333333",
                    });
                    setTimeout(() => {
                        // 生成临时路径
                        uni.canvasToTempFilePath({
                            canvasId: "myQrcode",
                            fileType: "jpg",
                            success: function (res) {
                                self.vipCodeImg = res.tempFilePath;
                                uni.previewImage({
                                    urls: [self.vipCodeImg],
                                    longPressActions: true,
                                });
                            },
                        });
                    }, 100);
                });
            }
        },
    },

    // 数据计算
    computed: {
        user() {
            return this.$store.state.user || "";
        },
        userInfo() {
            const self = this;

            self.nickName = this.$store.state.user.userInfo.nickName || "";
            self.phone = this.$store.state.user.userInfo.mobile || "";

            return this.$store.state.user.userInfo || "";
        },
        token() {
            return this.$store.state.user.token;
        },
    },

    // 数据监听
    watch: {},
};
</script>

<style>
page {
    background-color: #fff;
}
</style>

<style lang="scss" scoped>
.page {
    padding-top: px(40);
}

.portrait {
    position: relative;
    width: px(200);
    height: px(200);
    overflow: hidden;
    margin: 0 auto;
    border-radius: 50%;

    &__img /deep/ img {
        width: px(200);
        height: px(200);
    }

    &__text {
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: px(70);
        font-size: px(30);
        color: #fff;
        background-color: rgba(0, 0, 0, 0.4);
    }
}

.list {
    margin-top: px(40);
    border-top: solid px(3) #eaeaea;

    &__item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: px(135);
        padding: 0 px(45);
        border-bottom: solid px(3) #eaeaea;
    }

    &__content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 100%;
    }

    &__left {
        display: flex;
        align-items: center;
    }

    &__right {
        display: flex;
        align-items: center;
    }

    &__title {
        font-size: px(38);
        color: #000;
    }

    &__text {
        font-size: px(38);
        color: #9e9e9e;
    }

    &__input {
        font-size: px(38);
        color: #9e9e9e;
    }

    &__btn {
        display: flex;
        justify-content: center;
        align-items: center;
        height: px(55);
        padding: 0 px(15);
        font-size: px(36);
        color: #fff;
        background-color: #f8662a;
        border-radius: px(5);
    }

    &__text2 {
        font-size: px(38);
        color: #000;
    }

    &__icon {
        font-size: px(38);
        color: #000;
    }
}
.vip-code {
    width: px(50);
    height: px(50);
    /deep/ img {
        width: px(50);
        height: px(50);
    }
}
.canvas-ele {
    position: fixed;
    top: -100%;
    left: -100;
    z-index: -10;
}
</style>