<template>
  <div class="account">
    <md-app md-waterfall md-mode="fixed">
      <md-app-toolbar class="md-primary toolbar">
        <div class="md-toolbar-section-start">
          <md-button class="md-icon-button" @click="back()">
            <md-icon>arrow_back</md-icon>
          </md-button>
          <h3 class="md-title" style="flex: 1">{{ lang.title }}</h3>
        </div>
      </md-app-toolbar>

      <md-app-content>
        <v-touch @swiperight="back()" :swipe-options="{ direction: 'horizontal' }">
          <div ref="list_placeholder" style="height: 54px;"></div>
          <icon class="logo" name="canary"></icon>
          <template v-if="page_type == 'login'">
            <md-field :class="cid_verify ? '' : 'md-invalid'">
              <label>{{ lang.login.input_placeholder[0] }}</label>
              <md-input v-model="cid" required></md-input>
              <span class="md-error">{{ cid_errmsg }}</span>
            </md-field>

            <md-field :class="password_verify ? '' : 'md-invalid'">
              <label>{{ lang.login.input_placeholder[1] }}</label>
              <md-input v-model="password" required type="password"></md-input>
              <span class="md-error">{{ lang.login.password_errmsg }}</span>
            </md-field>
            <md-button
              class="md-raised md-primary expand"
              @click="judgeLogin()"
              :disabled="login_loading"
            >
              {{ lang.login.submit }}
              <div class="loading-box">
                <md-progress-spinner
                  v-if="login_loading"
                  :md-diameter="22"
                  :md-stroke="3"
                  md-mode="indeterminate"
                ></md-progress-spinner>
              </div>
            </md-button>
          </template>

          <template v-if="page_type == 'account'">
            <md-list>
              <md-list-item>
                <span class="md-list-item-text">{{ user_infos.cid }} | {{ user_infos.user_name }}</span>
              </md-list-item>

              <md-divider></md-divider>

              <md-list-item>
                <span class="md-list-item-text">{{ lang.account.label[0] }}</span>
                <span class="time-content">{{ update_time }}</span>
              </md-list-item>

              <md-list-item>
                <span class="md-list-item-text">{{ lang.account.label[1] }}</span>
                <span class="time-content">{{ user_infos.cloud_drivce }}</span>
              </md-list-item>

              <md-list-item>
                <span class="md-list-item-text">{{ lang.account.label[2] }}</span>
                <md-button
                  @click="syncCloudStart()"
                  v-if="!sync_cloud_loading"
                  class="md-icon-button md-list-action"
                >
                  <md-icon>cloud_upload</md-icon>
                </md-button>
                <md-progress-spinner
                  v-else
                  :md-diameter="22"
                  :md-stroke="3"
                  md-mode="indeterminate"
                ></md-progress-spinner>
              </md-list-item>

              <md-list-item>
                <span class="md-list-item-text">{{ lang.account.label[3] }}</span>
                <md-button
                  @click="syncLocalStart()"
                  v-if="!sync_local_loading"
                  class="md-icon-button md-list-action"
                >
                  <md-icon>cloud_download</md-icon>
                </md-button>
                <md-progress-spinner
                  v-else
                  :md-diameter="22"
                  :md-stroke="3"
                  md-mode="indeterminate"
                ></md-progress-spinner>
              </md-list-item>

              <md-button
                @click="startLogout()"
                class="md-raised md-primary expand"
                :disabled="sync_local_loading || sync_cloud_loading"
              >{{ lang.account.logout }}</md-button>
            </md-list>
          </template>
          <md-snackbar md-position="center" :md-active.sync="show_snackbar" md-persistent>
            <span>{{ snakebar_msg }}</span>
          </md-snackbar>
        </v-touch>
      </md-app-content>
    </md-app>
  </div>
</template>

<script>
// @ is an alias to /src
import { mapState, mapActions } from "vuex";
import {
  encrypt,
  decrypt,
  encryptMainCode,
  decryptMainCode,
} from "@/utils/aes.js";
import { syncLocal, syncCloud } from "@/axios/api.js";
import { lang } from "@/utils/language.js";
import { setHtmlFontSize } from "@/utils/px2rem.js";
import { replaceState } from "@/utils/getStore.js";

export default {
  name: "Add",
  data() {
    return {
      page_type: "login", // login account
      cid: "",
      cid_verify: true,
      cid_errmsg: "",
      password: "",
      password_verify: true,
      sync_local_loading: false,
      sync_cloud_loading: false,
      login_loading: false,
      show_snackbar: false,
      snakebar_msg: "",
      lang: "",
      clientHeight: "",
    };
  },
  computed: {
    ...mapState(["user_infos", "row_data", "row_pwd", "settings"]),
    update_time: function () {
      return this.formatDateTime(
        new Date(parseInt(this.user_infos.update_time))
      );
    },
  },
  methods: {
    ...mapActions(["setRowData", "setRowPwd", "setSettings", "setUserInfo"]),
    // 修改md-app的最小高度
    changeFixed(clientHeight) {
      //动态修改样式
      // console.log(clientHeight);
      // window.document.getElementsByClassName('md-content')[0].style.minHeight = clientHeight + 'px';
      this.$refs.list_placeholder.parentNode.parentNode.style.maxHeight =
        clientHeight + "px";
      this.$refs.list_placeholder.parentNode.style.minHeight =
        clientHeight - 32 + "px";
      window.document.documentElement.setAttribute(
        "data-theme",
        this.settings.is_dark_mode ? "dark" : "light"
      );
    },
    // 初始化
    init() {
      // 刷新本页vuex
      replaceState.call(this);
      this.initLanguage();
      // 判断页面类型
      if (
        this.user_infos &&
        this.user_infos.cid &&
        this.user_infos.row_login_pwd
      )
        this.page_type = "account";
      else this.page_type = "login";
      console.log("当前用户状态为" + this.page_type);
    },

    // 配置语言
    initLanguage() {
      if (this.settings.is_chinese) {
        this.lang = lang().account.CHS;
      } else {
        this.lang = lang().account.EN;
      }
      console.log("语言配置完成");
    },

    //返回上一页
    back() {
      this.$router.go(-1);
    },

    // 强制返回Home
    turnToHome(msg) {
      console.log(msg);
      this.$router.replace("/");
    },

    // 点击上传
    judgeLogin() {
      // 设置flag
      let can_continue = true;

      // 处理mail_addr
      if (!(this.cid = this.cid.trim())) {
        can_continue = false;
        this.cid_verify = false;
        this.cid_errmsg = this.lang.cid_errmsg[0];
      }
      // 处理password
      if (!(this.password = this.password.trim())) {
        can_continue = false;
        this.password_verify = false;
      }
      // 根据flag判断是否提交
      if (can_continue) this.startLogin();
    },

    // 开始上传信息
    startLogin() {
      this.login_loading = true;
      let data = {
        cid: this.cid,
        pwd: this.password,
      };
      syncLocal(data)
        .then((res) => {
          // console.log(res.data)
          this.manageLoginRes(res.data);
        })
        .catch((err) => {
          console.log(err);
          this.login_loading = false;
          if (!err.response) {
            this.snakebar_msg = this.lang.snakebar_msg[0];
          } else if (err.response.status == 512) {
            this.snakebar_msg = this.lang.snakebar_msg[1];
          } else if (err.response.status == 510) {
            this.snakebar_msg = this.lang.snakebar_msg[2];
          } else {
            this.snakebar_msg = this.lang.snakebar_msg[3] + err.response.status;
          }
          this.show_snackbar = true;
        });
    },

    // 处理登录后端返回的信息
    manageLoginRes(data) {
      // 登录成功
      let user_infos = {
        ...this.user_infos,
        cid: this.cid,
        row_login_pwd: encryptMainCode(this.password),
        user_name: data.username,
        update_time: data.modified,
        cloud_drivce: this.settings.is_chinese ? "暂无" : "unknown",
      };
      this.setUserInfo([user_infos, this]);
      console.log("正常用户登录，用户信息覆写完成");
      this.snakebar_msg = this.lang.snakebar_msg[4];
      this.show_snackbar = true;
      this.page_type = "account";
      this.login_loading = false;
    },

    // 处理时间
    formatDateTime(inputTime) {
      var date = new Date(inputTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      var second = date.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute;
      // return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
      // return y + "-" + m + "-" + d;
    },

    // 更新本地密码本
    syncLocalStart() {
      this.sync_local_loading = true;
      let data = {
        cid: this.user_infos.cid,
        pwd: decryptMainCode(this.user_infos.row_login_pwd),
      };
      syncLocal(data)
        .then((res) => {
          let data = res.data;
          // 获取成功
          let content = "";
          try {
            content = JSON.parse(data.content);
            if (typeof content == "string") throw new Error();
            if (!content || !content.codebook) {
              // 无数据自动初始化
              content = {
                codebook: "",
                drivce: content.drivce
                  ? content.drivce
                  : this.settings.is_chinese
                  ? "暂无"
                  : "unknown",
              };
            }
            if (
              content.drivce &&
              content.drivce != "暂无" &&
              content.drivce != "unknown"
            )
              content.drivce = decodeURIComponent(content.drivce);
            else content.drivce = this.settings.is_chinese ? "暂无" : "unknown";
            this.setRowData([content.codebook, this]);
            console.log("数据获取成功，密码本覆写成功");
            let user_infos = this.user_infos;
            user_infos.update_time = data.modified - 1000 * 60 * 4;
            user_infos.user_name = data.username;
            user_infos.cloud_drivce = content.drivce;
            this.setUserInfo([user_infos, this]);
            console.log("数据获取成功，用户信息覆写成功");
            this.snakebar_msg = this.lang.snakebar_msg[6];
            this.show_snackbar = true;
          } catch (e) {
            console.log(e);
            console.log("数据获取成功，内容有误");
            this.snakebar_msg = this.lang.snakebar_msg[5];
            this.show_snackbar = true;
          } finally {
            setTimeout(
              function () {
                this.sync_local_loading = false;
              }.bind(this),
              1000
            );
          }
        })
        .catch((err) => {
          console.log(err);
          this.sync_local_loading = false;
          if (!err.response) {
            this.snakebar_msg = this.lang.snakebar_msg[0];
          } else if (err.response.status == 512) {
            this.snakebar_msg = this.lang.snakebar_msg[1];
          } else if (err.response.status == 510) {
            this.snakebar_msg = this.lang.snakebar_msg[2];
          } else {
            this.snakebar_msg = this.lang.snakebar_msg[3] + err.response.status;
          }
          this.show_snackbar = true;
        });
    },

    // 更新云端密码本
    syncCloudStart() {
      this.sync_cloud_loading = true;
      let content = {
        codebook: this.row_data,
        drivce: encodeURIComponent(this.user_infos.drivce),
      };
      let data = {
        cid: this.user_infos.cid,
        pwd: decryptMainCode(this.user_infos.row_login_pwd),
        content: JSON.stringify(content),
      };
      console.log(data);
      syncCloud(data)
        .then((res) => {
          let user_infos = this.user_infos;
          user_infos.update_time = new Date().getTime();
          user_infos.cloud_drivce = user_infos.drivce
            ? user_infos.drivce
            : this.settings.is_chinese
            ? "暂无"
            : "unknown";
          this.setUserInfo([user_infos, this]);
          console.log("数据上传成功，用户信息覆写成功");
          this.snakebar_msg = this.lang.snakebar_msg[7];
          this.show_snackbar = true;
          setTimeout(
            function () {
              this.sync_cloud_loading = false;
            }.bind(this),
            1000
          );
        })
        .catch((err) => {
          console.log(err);
          this.sync_cloud_loading = false;
          if (!err.response) {
            this.snakebar_msg = this.lang.snakebar_msg[0];
          } else if (err.response.status == 512) {
            this.snakebar_msg = this.lang.snakebar_msg[1];
          } else if (err.response.status == 510) {
            this.snakebar_msg = this.lang.snakebar_msg[2];
          } else {
            this.snakebar_msg = this.lang.snakebar_msg[3] + err.response.status;
          }
          this.show_snackbar = true;
        });
    },

    // 退出登录
    startLogout() {
      // 初始化用户信息
      let user_infos = {
        ...this.user_infos,
        user_name: "A Little Canary",
        cid: "Codebook",
        row_login_pwd: "",
        cloud_drivce: this.settings.is_chinese ? "暂无" : "unknown",
        update_time: new Date().getTime(),
      };
      this.setUserInfo([user_infos, this]);
      console.log("用户信息覆写完成");
      this.back();
    },
  },
  created() {
    this.lang = lang().account.CHS;
    console.log("临时语言系统加载完成");
    this.init();
  },
  mounted() {
    // 获取浏览器可视区域高度
    this.clientHeight = `${document.documentElement.clientHeight}`;
    //document.body.clientWidth;
    window.onresize = function temp() {
      this.clientHeight = `${document.documentElement.clientHeight}`;
      setHtmlFontSize();
    }.bind(this);
  },
  watch: {
    // 如果 `clientHeight` 发生改变，这个函数就会运行
    clientHeight: function () {
      this.changeFixed(this.clientHeight);
    },
    // 如果 `cid` 发生改变，就会清空错误状态
    cid: function () {
      this.cid_verify = true;
    },
    // 如果 `password` 发生改变，就会清空错误状态
    password: function () {
      this.password_verify = true;
    },
    // 如果 `activation_code` 发生改变，就会清空错误状态
    activation_code: function () {
      this.activation_code_verify = true;
    },
  },
  beforeDestroy() {},
  components: {},
};
</script>

<style scoped lang="scss" type="text/scss">
@import "../../style/main";
.account {
  width: 100%;
  min-height: 100%;
  background: #fff;
  .expand {
    width: 100%;
    margin: 0 !important;
    min-height: 1.2rem !important;
    margin-top: 0.5rem !important;
  }
  .logo {
    margin: 0 auto;
    display: block;
    height: 5rem;
    width: 5rem;
  }
  .time-content {
    text-align: right !important;
  }
  .loading-box {
    position: absolute;
    right: 50%;
    top: 50%;
    margin-right: -11px;
    margin-top: -11px;
  }
  .toolbar {
    position: fixed !important;
  }
}
</style>
