<template>
  <div class="detail">
    <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">{{ content.title }}</h3>
        </div>
        <div class="md-toolbar-section-end">
          <md-button class="md-icon-button" @click="turnToEdit()">
            <md-icon>edit</md-icon>
          </md-button>
          <md-button class="md-icon-button" @click="openDelDialog()">
            <md-icon>delete</md-icon>
          </md-button>
        </div>
      </md-app-toolbar>

      <md-app-content>
        <v-touch @swiperight="back()" :swipe-options="{ direction: 'horizontal' }">
          <div ref="list_placeholder" style="height: 54px;"></div>
          <md-list class="md-double-line">
            <md-list-item>
              <label class="md-caption">{{ lang.label[0] }}</label>
              <div class="msg-box">
                <p>{{ content.user_name }}</p>
                <md-button
                  class="md-icon-button"
                  v-clipboard:copy="content.user_name"
                  v-clipboard:success="onCopyUrl"
                  v-clipboard:error="onErrorUrl"
                >
                  <icon
                    class="icon"
                    name="file_copy"
                    :class="settings.is_dark_mode ? 'dark-theme-icon' : ''"
                  ></icon>
                </md-button>
              </div>
            </md-list-item>
            <md-list-item>
              <label class="md-caption">{{ lang.label[1] }}</label>
              <div class="msg-box">
                <p class="password">{{ show_password ? content.password : doitPassword }}</p>
                <md-button class="md-icon-button" @click="show_password = !show_password">
                  <md-icon>remove_red_eye</md-icon>
                </md-button>
                <md-button
                  class="md-icon-button"
                  v-clipboard:copy="content.password"
                  v-clipboard:success="onCopyUrl"
                  v-clipboard:error="onErrorUrl"
                >
                  <icon
                    class="icon"
                    name="file_copy"
                    :class="settings.is_dark_mode ? 'dark-theme-icon' : ''"
                  ></icon>
                </md-button>
              </div>
            </md-list-item>
            <md-list-item>
              <label class="md-caption">{{ lang.label[2] }}</label>
              <div class="msg-box">
                <p>{{ content.web_address ? content.web_address : lang.empty_placeholder }}</p>
                <md-button class="md-icon-button" @click="openUrl()">
                  <md-icon>open_in_new</md-icon>
                </md-button>
              </div>
            </md-list-item>
            <md-list-item>
              <label class="md-caption">{{ lang.label[3] }}</label>
              <div class="msg-box">
                <p class="node">{{ content.node ? content.node : lang.empty_placeholder }}</p>
              </div>
            </md-list-item>
          </md-list>
          <md-dialog-confirm
            :md-active.sync="show_dialog"
            :md-title="lang.dialog.title"
            :md-content="lang.dialog.content"
            :md-confirm-text="lang.dialog.confirm"
            :md-cancel-text="lang.dialog.cancel"
            @md-cancel="onCancel"
            @md-confirm="delCode"
          />
          <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 { lang } from "@/utils/language.js";
import { setHtmlFontSize } from "@/utils/px2rem.js";
import { replaceState } from "@/utils/getStore.js";

export default {
  name: "Add",
  data() {
    return {
      show_snackbar: false,
      snakebar_msg: "",
      content: {},
      show_password: false,
      show_dialog: false,
      lang: "",
      clientHeight: "",
    };
  },
  computed: {
    ...mapState(["row_data", "row_pwd", "settings", "user_infos"]),
    doitPassword() {
      if (this.content.password) {
        let doit = "";
        for (let i = 0; i < this.content.password.length; i++) {
          doit += "*";
        }
        return doit;
      }
    },
  },
  methods: {
    ...mapActions(["setRowData", "setRowPwd", "setSettings", "setUserInfo"]),
    // 修改md-app的最小高度
    changeFixed(clientHeight) {
      //动态修改样式
      // window.document.getElementsByClassName('md-app-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
      console.log(1)
      replaceState.call(this);
      // 判断是否有参数
      if (this.$route.params.code_content) {
        // 判断有无用户密码
        if (Object.keys(this.row_pwd).length != 0) {
          // 有密码，已经输入过了
          let now = new Date().getTime();
          if (now - this.row_pwd.create_time < this.settings.expired_time) {
            // 上次写入时间距离现在在（默认五分钟）之内
            // 刷新重置数据
            this.initLanguage();
            this.content = this.$route.params.code_content;
            this.addCount();
          } else {
            // 密码超时
            this.turnToHome("密码超时");
          }
        } else {
          // 没有密码
          this.turnToHome("无密码");
        }
      } else {
        // 无参跳转
        this.turnToHome("无参跳转");
      }
    },

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

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

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

    // 跳转至编辑
    turnToEdit() {
      this.$router.push({
        name: "Add",
        params: { modify_content: this.content },
      });
    },

    // 复制成功
    onCopyUrl(e) {
      this.snakebar_msg = this.lang.copy.successful;
      this.show_snackbar = true;
    },

    // 复制失败
    onErrorUrl(e) {
      this.snakebar_msg = this.lang.copy.failed;
      this.show_snackbar = true;
    },

    // 打开链接
    openUrl() {
      if (this.content.web_address) {
        window.open(this.content.web_address);
      } else {
        this.snakebar_msg = this.lang.snakebar_msg_empty;
        this.show_snackbar = true;
      }
    },
    // 增加点击
    addCount() {
      // 解密主密码
      let main_code_decrpt = decryptMainCode(this.row_pwd.main_code);
      // 解密密码本
      let data_decrypt = decrypt(main_code_decrpt, this.row_data);
      // json化
      let data_list = JSON.parse(data_decrypt);
      // 遍历所有密码
      for (let i in data_list) {
        // 找到该密码
        if (data_list[i].id == this.content.id) {
          // 覆写
          data_list[i].open_count++;
        }
      }
      let data_list_aes = encrypt(main_code_decrpt, data_list);
      this.setRowData([data_list_aes, this]);
      console.log("新加密信息覆写成功,增加点击完成");
    },

    // 点击取消
    onCancel() {},

    // 打开删除模态框
    openDelDialog() {
      this.show_dialog = true;
    },
    // 删除该密码
    delCode() {
      // 解密主密码
      let main_code_decrpt = decryptMainCode(this.row_pwd.main_code);
      // 解密密码本
      let data_decrypt = decrypt(main_code_decrpt, this.row_data);
      // json化
      let data_list = JSON.parse(data_decrypt);
      // 暂存表
      let data_cache = [];
      // 遍历所有密码
      for (let i in data_list) {
        // 找到该密码
        if (data_list[i].id != this.content.id) {
          // 覆写
          data_cache.push(data_list[i]);
        }
      }
      let data_list_aes = encrypt(main_code_decrpt, data_cache);
      this.setRowData([data_list_aes, this]);
      console.log("新加密信息覆写成功,密码删除完成");
      this.back();
    },
  },
  created() {
    this.lang = lang().detail.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);
    },
  },
  beforeDestroy() {},
  components: {},
};
</script>

<style scoped lang="scss" type="text/scss">
@import "../../style/main";
.detail {
  width: 100%;
  min-height: 100%;
  background: #fff;
  .md-toolbar {
    position: fixed !important;
  }
  .md-list-item-content {
    position: relative;
    label {
      position: absolute;
      top: 0.2rem;
      left: 16px;
    }
    .msg-box {
      margin-top: 0.5rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      border-bottom: 1px #eee solid;
      p {
        word-wrap: break-word;
        word-break: normal;
        white-space: normal;
        width: 80%;
        margin: 0.2rem 0;
      }
      .icon {
        height: 24px;
        width: 24px;
        color: gray;
      }
      .dark-theme-icon {
        color: #fff !important;
      }
      .node {
        width: 100%;
      }
      .password {
        width: 70%;
      }
    }
  }
}
</style>
