<template>
  <div class="modefy-avatar">
    <img class="avatar" :src="avatar" alt />
    <div class="btn">
      <van-uploader
        :max-count="1"
        :before-delete="onDeleteAvatar"
        :after-read="onRead"
      >
        <van-button type="primary">上传新头像</van-button>
      </van-uploader>
      <van-button type="primary" plain @click="checkBtn">确定</van-button>
    </div>
  </div>
</template>

<script>
import { setAvatar } from "@/api/user";
import { uploadImage } from "@/api/base";
export default {
  name: "ModefyAvatar",
  data() {
    return {
      avatar: "",
      imageUrl: ""
    };
  },
  mounted() {
    console.log("123");
    if (!this.avatar) {
      this.avatar = require("@/assets/images/no_avatar.png");
    }
  },
  methods: {
    checkBtn() {
      const params = {
        headImage: this.imageUrl,
        userId: this.$userId
      };
      setAvatar(params).then(res => {
        if (res.code === 0) {
          this.$toast.success("头像设置成功");
          this.$router.go(-1);
        }
      });
    },
    onRead(file) {
      this.avatar = file.content;
      console.log("file", file);
      const params = {
        inviteCode: "bbbbbb"
      };
      const fd = new FormData();
      fd.append("files", file.file);
      uploadImage(params, fd).then(res => {
        console.log(res);
        this.imageUrl = res.zxUrl;
      });
    },
    onDeleteAvatar(file, detail) {
      return new Promise((resolve, reject) => {
        this.$dialog
          .confirm({
            message: "确认删除图片？"
          })
          .then(() => {
            this.fileList.splice(detail.index, 1);
            this.$toast.success("删除成功");
            resolve();
          })
          .catch(error => {
            this.$toast.fail("已取消");
            reject(error);
          });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.modefy-avatar {
  box-sizing: border-box;
  text-align: center;
  padding-top: 25px;
}
.avatar {
  width: 345px;
  height: 345px;
  margin-bottom: 52px;
  border-radius: 4px;
}
.van-uploader {
  font-size: 0;
}
.btn {
  display: flex;
  justify-content: space-around;
  .van-button {
    width: 165px;
  }
}
</style>
