<template>
  <div class="settings">
    <van-cell-group class="group-1">
      <van-cell title="用户名" :value="userName" />
      <!--is-link @click="onModefy" -->
      <van-cell center title="头像">
        <img class="avatar-img" :src="imageBaseUrl + avatar" alt="头像" />
      </van-cell>
    </van-cell-group>
    <van-cell-group>
      <van-cell
        class="van-less"
        is-link
        title="推荐人邀请码"
        :value="inviteeCode"
        @click="fillInviterCode"
      />
      <van-cell
        is-link
        title="软件更新"
        :value="version"
        @click="updateVersion"
      />
      <van-cell is-link title="用户协议" @click="jumpToInstructions" />
    </van-cell-group>

    <a href="redirect://xts.com/login_activity?hideBack=true">
      <van-button size="large" class="logout-btn" @click="logout"
        >退出登录</van-button
      >
    </a>

    <base-dialog
      base-dialog-title="推荐人邀请码"
      base-dialog-btn="提交"
      :base-dialog-show="inviteeCodeDialog"
      :base-dialog-show-close="true"
      @onClose="onCloseDialog"
      @onClick="onFillInviteeCode"
    >
      <div slot="content">
        <p class="content-tip">请输入您的推荐人邀请码</p>
        <van-field
          v-model="fillCode"
          maxlength="6"
          class="validCodeInput"
          placeholder="请输入"
        />
      </div>
    </base-dialog>

    <base-dialog
      base-dialog-title="版本更新"
      :base-dialog-show="versionShow"
      :base-dialog-btn="updateBtn"
      @onClick="onUpdateVersion"
    >
      <div slot="content" class="update-content">
        <span class="update-tip">{{ updateResult }}</span>
      </div>
    </base-dialog>
  </div>
</template>

<script>
import { versionUpdate } from "@/api/base";
import { getUserInfo2 } from "@/api/user";
import { logout } from "@/api/user";
import { fillInviteCode } from "@/api/user";
import BaseDialog from "../components/BaseDialog.vue";
export default {
  components: { BaseDialog },
  name: "Settings",
  data() {
    return {
      downAppUrl: "",
      needUpdate: false,
      updateBtn: "关闭",
      updateResult: "",
      versionShow: false,
      version: "",
      userName: "",
      imageBaseUrl: "",
      headImage: "",
      avatar: "",
      fileList: [],
      fillCode: "",
      inviteeCode: "未填写",
      inviteeCodeDialog: false
    };
  },
  mounted() {
    console.log("读取用户信息");
    this.imageBaseUrl = process.env.VUE_APP_BASE_URL;
    this.getUser();
    this.getAppVersion();
  },
  methods: {
    onUpdateVersion() {
      if (this.needUpdate) {
        location.href = this.downAppUrl;
      } else {
        this.versionShow = false;
      }
    },
    updateVersion() {
      const params = {
        type: this.$bridgeToAppFun.userAgent === "ios" ? 1 : 2,
        version: this.version.substr(2)
      };
      versionUpdate(params).then(res => {
        this.versionShow = true;
        if (res.code == 1) {
          this.updateResult = res.message;
          this.needUpdate = false;
        } else if (res.code == 0) {
          this.downAppUrl = res.data;
          this.updateResult = "最新版App下载地址：" + res.data;
          this.updateBtn = "下载最新版App";
          this.needUpdate = true;
        }
      });
    },
    getAppVersion() {
      this.version = "版本" + this.$bridgeToAppFun.getAppVersion();
    },
    getUser() {
      const params = {
        userId: JSON.parse(localStorage.getItem("user")).userId
      };
      console.log("setting-userId", params);
      getUserInfo2(params)
        .then(res => {
          if (res.userId) {
            localStorage.setItem("user", JSON.stringify(res));
            this.$nextTick(() => {
              this.userName = res.userId;
              this.inviteeCode =
                res.beInvitedCode == 1
                  ? "请填写推荐人邀请码"
                  : res.beInvitedCode;
              this.avatar = res.headImage;
              this.headImage = res.headImage;
            });
          }
        })
        .catch(err => {
          if (err.response.status === 502) {
            this.$toast("服务在升级，请稍后重试");
          }
        });
    },
    logout() {
      localStorage.clear();
      logout().then();
      this.$bridgeToAppFun.logoutToApp();
    },
    jumpToInstructions() {
      this.$router.push("/instructions");
    },
    onModefy() {
      this.$router.push({
        path: "/modefy-avatar",
        query: {
          headImage: this.headImage
        }
      });
    },
    onCloseDialog() {
      this.inviteeCodeDialog = false;
    },
    onFillInviteeCode() {
      if (!this.fillCode) {
        this.$toast.fail("请填写推荐人邀请码");
        return;
      }
      if (!/^[A-z|\d]{6}$/.test(this.fillCode)) {
        this.$toast.fail("邀请码只支持6位数字+字母的组合");
        return;
      }
      this.inviteeCodeDialog = false;
      const params = {
        inviteCode: this.fillCode,
        userId: JSON.parse(localStorage.getItem("user")).userId
      };
      fillInviteCode(params)
        .then(res => {
          if (res.code == 0) {
            // console.log('成功');
            this.inviteeCode = this.fillCode;
          } else {
            this.$toast.fail(res.message);
          }
        })
        .catch(err => {
          console.log(err);
          this.$toast.fail(err);
        });
    },
    fillInviterCode() {
      if (
        this.inviteeCode === "请填写推荐人邀请码" ||
        this.inviteeCode == "1"
      ) {
        this.inviteeCodeDialog = true;
        this.fillCode = "";
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.settings {
  box-sizing: border-box;
  padding: 10px 16px;
  .van-less {
    .van-cell__right-icon {
      display: none;
    }
  }
}
.group-1 {
  margin-bottom: 10px;
  .avatar-img {
    width: 37px;
    height: 37px;
    border-radius: 50%;
  }
}
.logout-btn {
  margin: 10px 0;
}
.content-tip {
  text-align: center;
  font-size: 14px;
  color: #333333;
}
.validCodeInput {
  width: 245px;
  margin: 35px auto;
  background-color: #f9f9f9;
  border-radius: 20px;
}
.update-content {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.update-tip {
  width: 90%;
  font-size: 18px;
  word-break: break-all;
  text-align: center;
}
</style>
