<template>
  <div
    class="login" :style="{
      backgroundImage: `url(${backgroundImageUrl})`,
      backgroundSize: '100%',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: '50% 85%',
    }"
  >
    <div>
      <div class="login_wrapper">
        <div class="login_form">
          <section class="login_content">
            <div class="login-content1">
              <h1>
                <img alt="" :src="logoUrl" style="margin-top: -40px; width: 100px; height: 100px" />
                <!-- src="/static/assets/client-base-v4/image/template-logo.png" -->
                <div class="desc" data-v-7b9d9b52="">
                  Prodog 希望帮助您更好的管理物料
                </div>
              </h1>

              <div>
                <a-input
                  v-model:value="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 class="pass-container">
                <a-input v-model:value="passImageCode" placeholder="验证码" class="form-control" @press-enter="login" />
                <img alt="点击刷新" :src="passImageSrc" class="pass-image" @click="getPassImage" />
              </div>

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

              <div class="div-date">
                <DateTime
                  v-model="accountDateTime" :readonly="false" style="width: 100%;" class="input-password"
                  @keyup.enter="login"
                />
              </div>
              <div>
                <a-select
                  v-model:value="languageSelected" name="language-choice"
                  style="width: 100%;text-align: left;" @change="getLanguageSelected"
                >
                  <a-select-option value="zh-CN">中文</a-select-option>
                  <a-select-option value="en-US">English</a-select-option>
                </a-select>
              </div>
              <div>
                <div
                  style="
                    display: flex;
                    flex-direction: row;
                    flex-wrap: nowrap;
                    justify-content: space-between;
                  "
                >
                  <div>
                    <a-switch v-model:checked="rememberPassword" />
                    <label for="inputPassword2" class="form-control-static remember-password" style="margin-left: 1rem">
                      {{ $t("lang.login.rememberPassword") }}
                    </label>
                  </div>
                  <div>
                    <a class="reset_pass forget-password" @click="toForgetPassword()">{{ $t("lang.login.forgetPassword")
                    }}</a>
                  </div>
                </div>
                <div class="clear" />
              </div>
              <div>
                <div>
                  <a-button style="width: 100%;margin-top: 1rem;" @click="login">
                    {{ $t("lang.login.login") }}
                  </a-button>
                </div>
                <div class="clear" />
              </div>
              <div class="clearfix" />
              <div v-if="authSetting != null && authSetting.length > 0">
                <div class="separator" />
                <div class="other-login-method">其他登录方式</div>
                <div class="login-third-box">
                  <div class="login-third">
                    <div class="login-third-items">
                      <span
                        v-for="item in authSetting" :key="item.id" v-tooltip.top="`${item.authType}-${item.name}`"
                        class="login-third-item" @click="existsServer(item)"
                      >
                        <img :src="getImageSrc(item.className, item.logo)" />
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
      <div v-if="showLeanwoText" style="text-align: center">
        <!-- <p>{{ $t("lang.login.copyright") }}</p> -->
        <div class="copyright">
          <div class="copyright-inner">
            {{ $t("lang.login.copyright") }}
            &nbsp; &nbsp;
            <a href="https://beian.miit.gov.cn/" target="_blank">
              沪ICP备11017244号
            </a>
            &nbsp; &nbsp;
            <a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=31011202004082" target="_blank">
              沪公网安备31011202004082号
            </a>
            &nbsp; &nbsp;
            <a
              href="http://fw.scjgj.sh.gov.cn/lz/licenseLink.do?method=licenceView&amp;entyId=20120314203547743"
              target="_blank"
            >
              工商亮照
            </a>
          </div>
        </div>
      </div>
      <div class="account-name">
        {{ accountItem.accountName }}
      </div>
      <Loading v-if="loading" />
    </div>
  </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';
import { queryLoginAuth } from '.././identity/configData.js';
import { message } from 'ant-design-vue';
import { getImageSrc } from '../common/image-src';
import dayjs from 'dayjs';

export default {
  components: {},
  data: function () {
    return {
      userName: '',
      password: '',
      accountItem: {},
      rememberPassword: false,
      accountDateTime: '',
      showLeanwoText: false,
      languageSelected: 'zh-CN',
      loading: false,
      btntxt: this.$t('lang.login.getVerificationCode'),
      disabledBtn: false,
      verificationCode: '', // 验证码
      time: 60,
      authSetting: [],
      getImageSrc,
      backgroundImageUrl: '/static/assets/client-base-v4/image/background.svg',
      logoUrl: '', // logo路径
      registerToken: '', // 注册token
      passImageSrc: '', // 验证码图片
      passImageCode: '', // 验证码
    };
  },

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

  created: function () { },

  mounted: function () {
    $('body').attr('class', 'body-login');
    $('body').children(':first').attr('class', '');

    this.initView();
    this.queryAllAuthSetting();
    this.unqiueAccountManagementDto();

    this.getLogoName();

    this.getCurrentDate();

    this.getRegisterToken();

    this.showLeanwoText = CustomerEnvironment.LOGIN_SHOW_LEANWO_TEXT;
  },

  methods: {

    // 查询系统logo
    getLogoName: function () {
      const _self = this;
      $.ajax({
        type: 'GET',
        url: Common.getApiURL('clientLogoResource/selectByClientId?logoName=mainLogoName'),
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (res) {
          if (res.errorCode === 0) {
            _self.logoUrl = `/Files/${res.data.filePath}${res.data.imageName}`;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    initView: function () {
      var _self = this;
      const storageInfo = LoginService.restoreFromLocalStorage();
      _self.userName = storageInfo.userName;
      _self.password = storageInfo.password;
      _self.rememberPassword = storageInfo.rememberPassword;
      _self.languageSelected = storageInfo.languageSelected;
    },

    // 查询单点登录认证源信息
    queryAllAuthSetting: function () {
      queryLoginAuth().then(
        success => {
          if (success.errorCode === 0) {
            if (success.datas !== null && success.datas !== undefined) {
              this.authSetting = success.datas;
            }
          }
        },
        error => {
          Common.processException(error);
        },
      );
    },

    /**
     * 根据域名查询账套的信息
     */
    unqiueAccountManagementDto: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL(
          '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);
        },
      });
    },

    // 判断是哪种单点登录方式
    existsServer: function (item) {
      if (item.authType === 'SAML') {
        this.existsSAML(item.no);
      } else if (item.authType === 'CAS') {
        this.existsCAS(item.no);
      }
    },

    // 判断SAML服务器是否存在
    existsSAML: function (no) {
      $.ajax({
        url: Common.getApiURL(
          'SamlLogin/samlServiceProviderCheck?authSettingNo=' + no,
        ),
        type: 'get',
        contentType: 'application/json',
        dataType: 'json',
        success: function (response) {
          if (response.errorCode === 0) {
            let url = '/api/SamlLogin/index?authSettingNo=' + no;
            window.location.href = url;
          } else {
            Notify.error('错误', response.errorMessage);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    // 判断CAS服务器是否存在
    existsCAS: function (no) {
      $.ajax({
        url: Common.getApiURL(
          'CasLogin/casServiceProviderCheck?authSettingNo=' + no,
        ),
        type: 'get',
        contentType: 'application/json',
        dataType: 'json',
        success: function (response) {
          if (response.errorCode === 0) {
            let url = `/casLogin.html?authSettingNo=${no}`;
            window.location.href = url;
            console.log(response);
          } else {
            Notify.error('错误', response.errorMessage);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          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: Common.getApiUrl2(
          '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.passImageCode,
      };
      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.passImageCode.trim() == '') {
        Notify.error(
          _self.$t('lang.login.login'),
          _self.$t('lang.login.pleaseInputVerificationCode'),
        );
        return;
      }

      if (
        _self.accountItem.loginSecondaryAuthentication === 'email' &&
        _self.verificationCode.trim() == ''
      ) {
        Notify.error(
          _self.$t('lang.login.login'),
          _self.$t('lang.login.verificationCodeCannotBeEmpty'),
        );
        return;
      }
      $.ajax({
        url: Common.getApiUrl2('authApi/LoginResource/login'),
        async: true,
        type: 'post',
        data: loginData,
        beforeSend: function (request) {
          request.setRequestHeader('registerToken', _self.registerToken);
        },
        success: function (loginInfo) {
          if (loginInfo.errorCode == 0) {
            loginInfo.accountName = _self.accountItem.accountName;
            LoginService.setLoginInfo(loginInfo.data, _self.$router);
            LoginService.saveLocalStorage(_self);
            _self.setTokenClient();
            localStorage.setItem('allowSound', false);
          } 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);
        }
      });
    },

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

    /**
     * 获取服务端当前时间
     */
    getCurrentDate: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiUrl2('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 = dayjs().format('YYYY-MM-DD HH:mm:ss');
      console.log('自动生成时间成功：' + this.accountDateTime);
    },

    /**
     * 获取验证码registerToken
     */
    getRegisterToken: function () {
      const _self = this;
      TokenClientResource.generateRegisterToken().then(successData => {
        if (successData.errorCode === 0) {
          _self.registerToken = successData.data;
          _self.getPassImage();
        } else {
          Notify.error(_self.$t('lang.Notify.fail'), successData.errorMessage);
        }
      }, error => {
        Common.processException(error);
      });
    },
    // 获取验证码图片地址
    getPassImage: function () {
      const _self = this;
      TokenClientResource.passImage(_self.registerToken).then(successData => {
        if (successData.errorCode === 0) {
          _self.passImageSrc = successData.data;
        } else {
          Notify.error(_self.$t('lang.Notify.fail'), successData.errorMessage);
        }
      }, error => {
        if (error.status == 401) {
          _self.getRegisterToken();
        } else {
          Common.processException(error);
        }
      });
    },
  },
};
</script>

<style scoped>
/* .login { */
/* background-image: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), url('../assets/background.svg'); */
/* background-image: url('../assets/background.svg');
  background-repeat: no-repeat;
  background-position: center 110px;
  background-size: 100%;
  background-position: 50% 85%; */
/* } */
.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: 5px;
}

.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 20px;
}

.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;
}

.separator>p {
  margin-bottom: 0 !important;
}

.login-third-box {
  width: 100%;
  display: flex;
  align-items: center;
  border-bottom-left-radius: 2px;
  border-bottom-right-radius: 2px;
  box-sizing: border-box;
  padding: 0;
  font-size: 12px;
  color: #555666;
}

.login-third {
  margin: 0px 6px 6px 0;
  box-sizing: border-box;
  text-align: center;
  margin-left: 12px;
  font-size: 0;
  position: relative;
  margin-left: 0;
}

.login-third-items {
  font-size: 0;
  position: relative;
  margin-left: 0;
}

.login-third-item img {
  display: inline-block;
  width: 64px;
  height: 64px;
  border-radius: 10% 10%;
  background: #ccc;
  cursor: pointer;
}

.forget-password {
  margin: 0 !important;
  position: relative;
  top: 0.5rem;
}

.copyright {
  font-size: small;
  position: fixed;
  bottom: 0;
  text-align: center;
  width: 100%;
  padding-left: 1rem;
  padding-right: 1rem;
}

.copyright-inner {
  overflow: hidden;
  white-space: nowrap;
}

.copyright a {
  color: #333;
}

.desc {
  margin-top: 12px;
  margin-bottom: 2rem;
  font-size: 14px;
  letter-spacing: 0;
  color: rgba(0, 0, 0, 0.65);
}

.account-name {
  position: fixed;
  top: 1rem;
  right: 1rem;
  color: rgba(0, 0, 0, 0.45);
}

.other-login-method {
  text-align: left;
  font-size: 12px;
  margin-bottom: 0.4rem;
}

.pass-container {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  height: 34px;
}

.pass-image {
  width: 160px;
  cursor: pointer;
}

:deep(.ant-picker) {
  border: none !important;
}
</style>