<template>
  <div class="login">
    <div>
      <div class="login_wrapper">
        <div class="login_form">
          <section class="login_content">
            <div class="login-content1">
              <h1>
                <img
                  alt=""
                  src="/static/assets/client-base-v4/image/template-logo.png"
                  style="margin-top: -40px; width: 100px; height: 100px"
                  @click="showAccount()"
                />
              </h1>
              <div>
                <input
                  v-model="accountItem.accountName"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  :placeholder="$t('lang.login.accountInfo')"
                  readonly="true"
                  disabled="true"
                />
              </div>
              <div>
                <input
                  v-model="userName"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  :placeholder="$t('lang.login.pleaseInputUserName')"
                  required
                  @keyup.enter="login"
                />
              </div>
              <div>
                <a-input-password
                  v-model:value="password"
                  :placeholder="$t('lang.login.pleaseInputPassword')"
                  class="input-password"
                  style="height: 34px"
                  @press-enter="login"
                />
              </div>

              <div v-if="accountItem.loginSecondaryAuthentication === 'email'">
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    flex-wrap: nowrap;
                    justify-content: space-between;
                  "
                >
                  <div class="input-group" style="margin: 0 0 0px">
                    <input
                      v-model="verificationCode"
                      type="text"
                      class="form-control"
                      autocomplete="off"
                      :placeholder="$t('lang.login.pleaseInputVerificationCode')"
                      style="width: 240px"
                    />
                  </div>
                  <div>
                    <button v-if="disabledBtn == false" class="btn btn-default" :disabled="disabledBtn" style="width: 10rem;" @click="sendUserVerificationCode">
                      {{ $t("lang.login.getVerificationCode") }}
                    </button>
                    <button v-else class="btn btn-default" :disabled="disabledBtn" style="width: 10rem;" @click="sendUserVerificationCode">{{ btntxt }}</button>
                  </div>
                </div>
              </div>

              <div class="div-date">
                <DateTime
                  v-model="accountDateTime"
                  :readonly="false"
                  style="width: 100%"
                  @keyup.enter="login"
                />
              </div>
              <div>
                <select
                  v-model="languageSelected"
                  name="language-choice"
                  class="form-control"
                  @change="getLanguageSelected"
                >
                  <option value="zh-CN">中文</option>
                  <option value="en-US">English</option>
                </select>
              </div>
              <div>
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    flex-wrap: nowrap;
                    justify-content: space-between;
                  "
                >
                  <div>
                    <label
                      for="inputPassword2"
                      class="form-control-static remember-password"
                    >{{ $t("lang.login.rememberPassword") }}</label>
                  </div>
                  <div>
                    <Switches
                      v-model="rememberPassword"
                      :selected="rememberPassword"
                      :show-text="false"
                      style="width: 50px"
                      color="green"
                      :type-bold="true"
                    />
                  </div>
                </div>
                <div class="clear" />
              </div>
              <div>
                <div class="left">
                  <a class="btn btn-default submit" @click="login">{{
                    $t("lang.login.login")
                  }}</a>
                </div>
                <div class="clear" />
              </div>
              <div class="clearfix" />
              <div class="separator">
                <p class="float-left">
                  <a class="reset_pass" @click="toForgetPassword()">{{
                    $t("lang.login.forgetPassword")
                  }}</a>
                </p>
                <p class="float-left">
                  <a
                    v-show="showAccountCount > 15"
                    class="reset_pass"
                    @click="toInitClient()"
                  >{{ $t("lang.login.initClient") }}</a>
                </p>
                <p v-if="allowCreateNewCount" class="change_link float-left">
                  <a class="to_register" @click="toRegister()">{{
                    $t("lang.login.createAccount")
                  }}</a>
                </p>
                <p v-if="allowSystemManagement" class="change_link float-left">
                  <a class="to_register" @click="toSystemMenu()">{{
                    $t("lang.login.systemManagment")
                  }}</a>
                </p>
                <p v-if="showSystemConfigPage" class="change_link float-left">
                  <a @click="toSystemConfigPage()"><i class="glyphicon glyphicon-cog" />{{
                    $t("lang.login.systemConfig")
                  }}</a>
                </p>
                <p v-if="allowDownloadApp" class="float-right">
                  <a
                    class="to_register"
                    style="margin-right: 0px"
                    @click="toDownloadPage()"
                  >{{ $t("lang.login.appDownload") }}</a>
                </p>
                <div class="clearfix" />
                <br />
                <div v-if="showLeanwoText">
                  <p>{{ $t("lang.login.copyright") }}</p>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </div>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../common/Common.js';
import CustomerEnvironment from '../CustomerEnvironment.js';
import TokenClientResource from '../api/base/TokenClientResource.js';
import LoginService from './LoginService.js';
import { Notify, Uuid } from 'pc-component-v3';

export default {
  components: {},
  data: function () {
    return {
      userName: '',
      password: '',
      accountItem: {},
      showAccountCount: 1,
      rememberPassword: false,
      accountDateTime: '',
      allowCreateNewCount: false, // 是否允许创建账户
      allowSystemManagement: false, // 是否允许打开系统管理界面
      allowDownloadApp: false, // 是否允许下载APP
      showSystemConfigPage: false, //显示设置系统参数
      showLeanwoText: false,
      languageSelected: 'zh-CN',
      loading: false,
      btntxt: this.$t('lang.login.getVerificationCode'),
      disabledBtn: false,
      verificationCode: '', // 验证码
      time: 60,
    };
  },

  watch: {
    rememberPassword: function () {
      var _self = this;
      if (!localStorage) {
        alert('浏览器不支持localstorage');
      } else {
        localStorage.setItem('#rememberPassword', _self.rememberPassword);
      }
    },
  },

  created: function () {},

  mounted: function () {
    $('body').attr('class', 'body-login');
    $('body').children(':first').attr('class', '');
    var path = location.href;
    if (path.indexOf('mesapp') > 0) {
      this.showSystemConfigPage = true;
    }
    this.initView();

    this.unqiueAccountManagementDto();

    this.getCurrentDate();

    // this.allowCreateNewCount = CustomerEnvironment.INDEX_SHOW_REGISTER;
    this.showLeanwoText = CustomerEnvironment.LOGIN_SHOW_LEANWO_TEXT;
  },

  methods: {
    initView: function () {
      var _self = this;

      const restoreDate = LoginService.restoreFromLocalStorage();
      if(restoreDate.rememberPassword === true){
        _self.userName = restoreDate.userName;
        _self.password = restoreDate.password;
        _self.rememberPassword = restoreDate.rememberPassword;
        _self.languageSelected = restoreDate.languageSelected;
      }else{
        _self.userName = null;
        _self.password = null;
        _self.rememberPassword = false;
        _self.languageSelected = restoreDate.languageSelected;
      }
    },

    /**
     * 根据域名查询账套的信息
     */
    unqiueAccountManagementDto: function () {
      var _self = this;
      $.ajax({
        url: '/api/AccountManagementResource/unqiueAccountManagementDto',
        type: 'get',
        async: true,
        success: function (response) {
          if(response.errorCode === 0){
            _self.accountItem = response.data;
          }else{
            Notify.error('账套获取失败', response.errorMessage);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          console.log(XMLHttpRequest);
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 发送验证码
     */
    sendUserVerificationCode: function (event) {
      var loginData = {
        userName: this.userName,
        password: this.password,
        accountDateTime: this.accountDateTime,
        languageId: this.languageSelected,
        verificationCodeType: this.accountItem.loginSecondaryAuthentication,
      };
      var _self = this;
      if (_self.userName.trim() == '' || _self.password.trim() == '') {
        Notify.error(
          _self.$t('lang.login.getVerificationCode'),
          _self.$t('lang.login.getVerificationCodeErrorMssage'),
        );
        return;
      }
      $.ajax({
        url: '/authApi/UserVerificationCodeResource/sendUserVerificationCode',
        async: true,
        type: 'post',
        data: loginData,
        success: function (baseObjectResponse) {
          if (baseObjectResponse.errorCode == 0) {
            Notify.success(
              _self.$t('lang.login.getVerificationCode'),
              baseObjectResponse.data,
              false,
            );
            _self.timerStr();
          } else {
            Notify.error(
              _self.$t('lang.login.getVerificationCode'),
              baseObjectResponse.data,
              false,
            );
          }
          console.log(baseObjectResponse);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    timerStr: function () {
      if (this.time > 0) {
        this.disabledBtn = true;
        this.time--;
        this.btntxt = this.time + this.$t('lang.login.second');
        setTimeout(this.timerStr, 1000);
      } else {
        this.time = 60;
        this.btntxt = this.$t('lang.login.getVerificationCode');
        this.disabledBtn = false;
      }
    },

    /**
     * 选择的语言发生改变
     */
    getLanguageSelected: function () {
      this.$i18n.locale = this.languageSelected;
      localStorage.setItem('#languageSelected', this.languageSelected);
    },

    login: function (event) {
      var loginData = {
        userName: this.userName,
        password: this.password,
        accountDateTime: this.accountDateTime,
        languageId: this.languageSelected,
        verificationCode: this.verificationCode,
      };
      var _self = this;
      if (_self.userName.trim() == '' || _self.password.trim() == '') {
        Notify.error(
          _self.$t('lang.login.login'),
          _self.$t('lang.login.getVerificationCodeErrorMssage'),
        );
        return;
      }

      if (
        _self.accountItem.loginSecondaryAuthentication === 'email' &&
        _self.verificationCode.trim() == ''
      ) {
        Notify.error(
          _self.$t('lang.login.login'),
          _self.$t('lang.login.verificationCodeCannotBeEmpty'),
        );
        return;
      }
      $.ajax({
        url: '/authApi/LoginResource/login',
        async: true,
        type: 'post',
        data: loginData,
        success: function (loginInfo) {
          if (loginInfo.errorCode == 0) {
            loginInfo.accountName = _self.accountItem.accountName;
            LoginService.setLoginInfo(loginInfo.data, _self.$router);
            LoginService.saveLocalStorage(_self);
            _self.setTokenClient();
          } else {
            Notify.error(
              _self.$t('lang.login.loginFailure'),
              loginInfo.errorMessage,
            );
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 设置TokenClient
     * @param {Object} TokenClient
     */
    setTokenClient: function () {
      TokenClientResource.saveTokenClient().then(successData => {
        if (successData != null) {
          console.log(successData);
        }
      });
    },

    showAccount: function () {
      var _self = this;
      _self.showAccountCount++;
    },
    /**
     * 跳转到注册页面
     * @return {void}
     */
    toRegister: function () {
      this.$router.push('/register');
    },

    /**
     * 跳转到产品下载页面
     */
    toDownloadPage: function () {
      this.$router.push('/register/app-download');
    },

    toInitClient: function () {
      this.$router.push('/register/register-client');
    },

    toForgetPassword: function () {
      this.$router.push('/retrievePassword');
    },

    /**
     * 跳转到系统管理界面下
     * @author GuoZhiBo 20200420
     */
    toSystemMenu: function () {
      this.$router.push('/dictionary/Login');
    },

    /**
     * 获取服务端当前时间
     */
    getCurrentDate: function () {
      var _self = this;
      $.ajax({
        url: '/authApi/LoginResource/getCurrentDate',
        type: 'get',
        timeout: 2000,
        success: function (data) {
          if (data != undefined && data != '') {
            _self.accountDateTime = data;
            console.log('获取时间成功：' + _self.accountDateTime);
          } else {
            _self.generateCurrentDate();
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.generateCurrentDate();
        },
      });
    },

    /**
     * 生成当前时间
     */
    generateCurrentDate: function () {
      this.accountDateTime = moment().format('YYYY-MM-DD HH:mm:ss');
      console.log('自动生成时间成功：' + this.accountDateTime);
    },

    /**
     * 跳转到系统配置页面
     */
    toSystemConfigPage: function () {
      this.$router.push('/desktop/systemConfig');
    },
  },
};
</script>

<style scoped>
.login_wrapper {
  margin: 0px auto;
  padding-top: 5%;
  max-width: 350px;
  position: relative;
}

.login_form {
  top: 0px;
  width: 100%;
}

.animate {
  -webkit-animation-duration: 0.5s;
  -webkit-animation-timing-function: ease;
  -webkit-animation-fill-mode: both;
  -moz-animation-duration: 0.5s;
  -moz-animation-timing-function: ease;
  -moz-animation-fill-mode: both;
  -o-animation-duration: 0.5s;
  -o-animation-timing-function: ease;
  -o-animation-fill-mode: both;
  -ms-animation-duration: 0.5s;
  -ms-animation-timing-function: ease;
  -ms-animation-fill-mode: both;
  animation-duration: 0.5s;
  animation-timing-function: ease;
  animation-fill-mode: both;
}

/** /login **/

/** signup **/

.login_box {
  padding: 20px;
  margin: auto;
}

.left {
  float: left;
}

.alignleft {
  float: left;
  margin-right: 15px;
}

.alignright {
  float: right;
  margin-left: 15px;
}

.clear {
  clear: both;
}

.clearfix:after,
.login-content1:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

.separator {
  border-top: 1px solid #d8d8d8;
  margin-top: 10px;
  padding-top: 10px;
}

.login_content {
  margin: 0 auto;
  padding: 25px 0 0;
  position: relative;
  text-align: center;
  text-shadow: 0 1px 0 #fff;
  min-width: 280px;
}

.login_content a,
.login_content .btn-default:hover {
  text-decoration: none;
}

.login_content a:hover {
  text-decoration: underline;
}

.login_content h1 {
  font: normal 25px Helvetica, Arial, sans-serif;
  letter-spacing: -0.05em;
  line-height: 20px;
  margin: 10px 0 30px;
}

.login_content h1:before,
.login_content h1:after {
  content: "";
  height: 1px;
  position: absolute;
  top: 10px;
  width: 27%;
}

.login_content h1:after {
  background: #7e7e7e;
  background: linear-gradient(left, #7e7e7e 0%, white 100%);
  right: 0;
}

.login_content h1:before {
  background: #7e7e7e;
  background: linear-gradient(right, #7e7e7e 0%, white 100%);
  left: 0;
}

.login_content h1:before,
.login_content h1:after {
  content: "";
  height: 1px;
  position: absolute;
  top: 10px;
  width: 20%;
}

.login_content h1:after {
  background: #7e7e7e;
  background: linear-gradient(left, #7e7e7e 0%, white 100%);
  right: 0;
}

.login_content h1:before {
  background: #7e7e7e;
  background: linear-gradient(right, #7e7e7e 0%, white 100%);
  left: 0;
}

.login_content .login-content1 {
  margin: 20px 0;
  position: relative;
}

.login_content .login-content1 input[type="text"],
.login_content .login-content1 input[type="email"],
.login_content .login-content1 input[type="password"],
.login_content .login-content1 .input-password,
.login_content .login-content1 select {
  border-radius: 3px;
  -ms-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0, 0, 0, 0.08) inset;
  -o-box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0, 0, 0, 0.08) inset;
  box-shadow: 0 1px 0 #fff, 0 -2px 5px rgba(0, 0, 0, 0.08) inset;
  border: 1px solid #c8c8c8;
  color: #777;
  margin: 0 0 20px;
  width: 100%;
}

.login_content .login-content1 input[type="text"]:focus,
.login_content .login-content1 input[type="email"]:focus,
.login_content .login-content1 input[type="password"]:focus,
.login_content .login-content1 select:focus {
  -ms-box-shadow: 0 0 2px #ed1c24 inset;
  -o-box-shadow: 0 0 2px #ed1c24 inset;
  box-shadow: 0 0 2px #a97aad inset;
  background-color: #fff;
  border: 1px solid #a878af;
  outline: none;
}

.login_content .login-content1 div a {
  font-size: 12px;
  margin: 10px 15px 0 0;
}

.reset_pass {
  cursor: pointer;
}

.login_content .login-content1 input[type="submit"],
#content .login-content1 .submit {
  float: left;
  margin-left: 38px;
}

.remember-password {
  color: #73879c;
  font-size: 13px;
  font-weight: 400;
  line-height: 1.471;
}

.remember-row {
  text-align: left;
}

.to_register {
  cursor: pointer;
}

.div-date {
  margin-bottom: 20px;
}

.float-right {
  float: right;
}

.float-left {
  float: left;
}
</style>