<template>
  <div
    class="page-account"
    :style="
      backgroundImages
        ? { backgroundImage: 'url(' + backgroundImages + ')' }
        : { backgroundImage: 'url(' + backgroundImageMo + ')' }
    "
  >
    <div class="container" :class="[fullWidth > 768 ? 'containerSamll' : 'containerBig']">
      <template v-if="fullWidth > 768">
        <div class="swiperPic">
          <img :src="leftLogo" />
        </div>
      </template>
      <div class="index_from">
        <div class="login-form-container">
          <div class="title">账号登录</div>
          <div :class="['form-item', inputType === 'account' ? 'form-item-input' : '', inputError === 'account' ? 'form-item-error' : '']" style="margin-top: 40px;" @click="onFocus('account')">
            <div :class="['tip', inputType === 'account' || loginForm.account ? 'tip-input' : '']">账号</div>
            <input :class="['input-block', inputType === 'account' || loginForm.account ? 'input-focus' : '']" ref="account" v-model.trim="loginForm.account" name="username" tabindex="1" autocomplete="on" @blur="onBlur" />
          </div>
          <div :class="['form-item', inputType === 'pwd' ? 'form-item-input' : '', inputError === 'pwd' ? 'form-item-error' : '']" style="margin-top: 60px;" @click="onFocus('pwd')">
            <div class="left">
              <div :class="['tip', inputType === 'pwd' || loginForm.pwd ? 'tip-input' : '']">密码</div>
              <input :class="['input-block', inputType === 'pwd' || loginForm.pwd ? 'input-focus-in' : '']" :key="passwordType" ref="pwd" v-model.trim="loginForm.pwd" :type="passwordType" name="pwd" tabindex="2" auto-complete="on" @blur="onBlur" />
            </div>
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </div>
          <div :class="['form-item', inputType === 'code' ? 'form-item-input' : '', inputError === 'code' ? 'form-item-error' : '']" style="margin-top: 60px;" @click="onFocus('code')">
            <div class="left">
              <div :class="['tip', inputType === 'code' || loginForm.code ? 'tip-input' : '']" style="width: 50px;">验证码</div>
              <input :class="['input-block', inputType === 'code' || loginForm.code ? 'input-focus-in' : '']" ref="code" v-model.trim="loginForm.code" tabindex="3" autocomplete="on" name="username" @blur="onBlur" />
            </div>
            <div class="imgs" @click.stop="getCaptcha()">
                <img :src="captchatImg" />
                <span v-show="showCaptchatImg">已失效</span>
              </div>
          </div>
          <div class="acea-row">
            <el-button
              :loading="loading"
              type="primary"
              style="width: 100%; margin-bottom: 30px"
              @click.native.prevent="handleLogin"
              :disabled="disabled"
              >登录
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <img src="../../assets/imgs/plat_logo.png" class="plat-logo" />
  </div>
</template>

<script>
// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------
import { validUsername } from '@/utils/validate';
import '@/assets/js/canvas-nest.min.js';
import { getLoginPicApi, captchaApi } from '@/api/user';
import { frontDomainApi } from '@/api/systemConfig';
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length > 12) {
        callback(new Error('密码位数为6-12位'));
      } else {
        callback();
      }
    };
    return {
      showCaptchatImg: false,
      captchatImg: '',
      leftLogo: '',
      loginLogo: '',
      backgroundImages: '',
      backgroundImageMo: require('@/assets/imgs/bg.jpg'),
      fullWidth: document.body.clientWidth,
      swiperOption: {
        pagination: {
          el: '.pagination',
        },
        autoplay: {
          enabled: true,
          disableOnInteraction: false,
          delay: 3000,
        },
      },
      loginForm: {
        account: '', // admin
        pwd: '',
        key: '',
        code: '',
        captcha: {
          captchaVerification: '',
          secretKey: '',
          token: '',
        },
      },
      loginRules: {
        account: [{ required: true, trigger: 'blur', message: '请输入用户名' }], // validator: validateUsername
        pwd: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        code: [{ required: true, message: '请输入正确的验证码', trigger: 'blur' }],
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      disabled: false,
      isWeixin: this.$wechat.isWeixin(),

      // modify
      inputType: '',
      inputError: ''
    };
  },
  components: {},
  watch: {
    fullWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val;
        this.timer = true;
        const that = this;
        setTimeout(function () {
          // 打印screenWidth变化的值
          that.timer = false;
        }, 400);
      }
    },
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    const _this = this;
    document.onkeydown = function (e) {
      if (_this.$route.path.indexOf('login') !== -1) {
        const key = window.event.keyCode;
        if (key === 13) {
          _this.handleLogin();
        }
      }
    };
    window.addEventListener('resize', this.handleResize);
  },
  mounted() {
    // this.getInfo();
    this.$nextTick(() => {
      if (this.screenWidth < 768) {
        // document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg');
      } else {
        // document.getElementsByTagName('canvas')[0].className = 'index_bg';
      }
    });
    if (this.loginForm.account === '') {
      this.$refs.account.focus();
    } else if (this.loginForm.pwd === '') {
      this.$refs.pwd.focus();
    }
    this.getCaptcha();
  },
  beforeCreate() {
    if (this.fullWidth < 768) {
      // document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg');
    } else {
      // document.getElementsByTagName('canvas')[0].className = 'index_bg';
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize);
    // document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg');
  },
  methods: {
    // 获取移动端域名
    getUrl() {
      frontDomainApi().then((res) => {
        this.$store.commit('settings/SET_FrontDomain', res);
      });
    },
    handleResize(event) {
      this.fullWidth = document.body.clientWidth;
      if (this.fullWidth < 768) {
        document.getElementsByTagName('canvas')[0].removeAttribute('class', 'index_bg');
      } else {
        // document.getElementsByTagName('canvas')[0].className = 'index_bg';
      }
    },
    getInfo() {
      // getLoginPicApi().then((res) => {
      //   this.leftLogo = res.leftLogo;
      //   this.loginLogo = res.loginLogo;
      //   this.backgroundImages = res.backgroundImage;
      // });
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z';
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.pwd.focus();
      });
    },

    validateParam(params) {
      if (!params.account) {
        this.$message({
          message: '用户名不能为空',
          type: 'error',
          showClose: true
        });
        this.inputError = 'account';

        return false;
      }

      if (!params.pwd) {
        this.$message({
          message: '密码不能为空',
          type: 'error',
          showClose: true
        });
        this.inputError = 'pwd';

        return false;
      }

      if (!params.code) {
        this.$message({
          message: '验证码不能为空',
          type: 'error',
          showClose: true
        });
        this.inputError = 'code';
        
        return false;
      }

      return true;
    },

    handleLogin() {
      if (!this.validateParam(this.loginForm)) {
        return;
      }

      this.success(null);
    },
    success(params) {
      this.loginForm.captcha = this.$store.state.user.captcha;
      const loading = this.$loading({
        lock: true,
        text: '正在登录中.',
      });
      this.$store
        .dispatch('user/login', this.loginForm)
        .then(() => {
          this.getUrl();
          this.$router.push({ path: this.redirect || '/dashboard', query: this.otherQuery });
          this.$store.commit('product/SET_AdminProductClassify', []);
          this.$store.commit('product/SET_ProductBrand', []);
          this.$store.commit('merchant/SET_MerchantClassify', []);
          this.$store.commit('merchant/SET_MerchantType', []);

          loading.close();
          this.disabled = true;
        })
        .catch((err) => {
          loading.close();
          this.disabled = false;
          if (this.$wechat.isPhone()) this.$dialog.error(err.message);
          this.getCaptcha();
        });
    },
    getCaptcha() {
      // captchaApi()
      //   .then((data) => {
      //     this.captchatImg = data.code;
      //     this.loginForm.key = data.key;
      //     this.showCaptchatImg = false;
      //     setTimeout(() => {
      //       this.showCaptchatImg = true;
      //     }, 270000);
      //   })
      //   .catch(({ message }) => {
      //     this.$message.error(message);
      //   });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },

    // modify
    onFocus(type) {
      this.inputError = '';
      this.inputType = type;
      type === 'account' ? this.$refs.account.focus() : type === 'pwd' ? this.$refs.pwd.focus() : this.$refs.code.focus();
    },

    onBlur() {
      this.inputType = '';
      this.inputError = '';
    },

    onError(type) {
      this.inputError = type;
    }
  },
};
</script>

<style lang="scss" scoped>
$screen-md: 768px;
$font-size-base: 14px;
$animation-time: 0.3s;
$animation-time-quick: 0.15s;
$transition-time: 0.2s;
$ease-in-out: ease-in-out;
$subsidiary-color: #808695;
.footer {
  align-items: center;
  justify-content: center;
  width: 50%;
  height: 36px;
  cursor: pointer;
}
.wechat {
  width: 26px;
  height: 26px;
  img {
    width: 100%;
    height: 100%;
  }
}

.page-account {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  overflow: auto;

  &-container {
    flex: 1;
    padding: 32px 0;
    text-align: center;
    width: 384px;
    margin: 0 auto;

    &-result {
      width: 100%;
    }
  }

  &-tabs {
    .ivu-tabs-bar {
      border-bottom: none;
    }
    .ivu-tabs-nav-scroll {
      text-align: center;
    }
    .ivu-tabs-nav {
      display: inline-block;
      float: none;
    }
  }
  &-top {
    padding: 32px 0;
    &-logo {
      img {
        max-height: 75px;
      }
    }
    &-desc {
      font-size: $font-size-base;
      color: $subsidiary-color;
    }
  }

  &-auto-login {
    margin-bottom: 24px;
    text-align: left;
    a {
      float: right;
    }
  }

  &-other {
    margin: 24px 0;
    text-align: left;
    span {
      font-size: $font-size-base;
    }
    img {
      width: 24px;
      margin-left: 16px;
      cursor: pointer;
      vertical-align: middle;
      opacity: 0.7;
      transition: all $transition-time $ease-in-out;
      &:hover {
        opacity: 1;
      }
    }
  }

  .ivu-poptip,
  .ivu-poptip-rel {
    display: block;
  }

  &-register {
    float: right;
    &-tip {
      text-align: left;
      &-title {
        font-size: $font-size-base;
      }
      &-desc {
        white-space: initial;
        font-size: $font-size-base;
        margin-top: 6px;
      }
    }
  }

  &-to-login {
    text-align: center;
    margin-top: 16px;
  }

  &-header {
    text-align: right;
    position: fixed;
    top: 16px;
    right: 24px;
  }
}

@media (min-width: $screen-md) {
  .page-account {
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
  }
  .page-account-container {
    padding: 32px 0 24px 0;
    position: relative;
  }
}
.page-account {
  display: flex;
}

.page-account .code {
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-account .code .pictrue {
  height: 40px;
}

.swiperPross {
  border-radius: 6px 0px 0px 6px;
  overflow: hidden;
}

// .swiperPross,
// .swiperPic,
// .swiperPic img {
//   width: 286px;
//   height: 100%;
// }

.swiperPic img {
  width: 100%;
  height: 100%;
}





.containerBig {
  width: auto !important;
  background: #f7f7f7 !important;
}

.btn {
  background: linear-gradient(90deg, rgba(25, 180, 241, 1) 0%, rgba(14, 115, 232, 1) 100%) !important;
}
</style>

<style lang="scss" scoped>
.captcha {
  display: flex;
  align-items: flex-start;
}
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.imgs {
  position: relative;
  height: 36px;
  cursor: pointer;
  img {
    height: 100%;
  }
  span {
    width: 84px;
    line-height: 36px;
    display: inline-block;
    background: rgba(0, 0, 0, 0.4);
    position: absolute;
    left: 0;
    color: #fff;
  }
}
.login-form {
  position: relative;
  max-width: 100%;
  margin: 0 auto;
  overflow: hidden;
}
.tips {
  font-size: 14px;
  color: #fff;
  margin-bottom: 10px;

  span {
    &:first-of-type {
      margin-right: 16px;
    }
  }
}


// update
.container {
  // height: 400px !important;
  padding: 0 !important;
  border-radius: 6px;
  z-index: 1;
  display: flex;
}

.containerSamll {
  display: flex;
  flex-direction: row;
  width: 1240px;
  /*width: 56% !important;*/
  // width: 670px;

  .swiperPic img {
    width: 800px;
    height: 548px;
  }

  .index_from {
    // width: 338px;
    // height: 400px;
    box-sizing: border-box;
    margin-top: 20px;
  }
}

.page-account-container {
  border-radius: 0px 6px 6px 0px;
}

.login-form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 338px;
  height: 440px;
  background: #FFFFFF;
  box-shadow: 0px 4px 10px 0px rgba(0,0,0,0.16);
  border-radius: 16px;

  .title {
    font-size: 20px;
    font-family: Microsoft YaHei-Bold, Microsoft YaHei;
    font-weight: 700;
    color: #3D3D3D;
    letter-spacing: 1px;
    margin-top: 40px;
  }

  .form-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: calc(100% - 50px);
    position: relative;
    border-bottom: 1px solid #DCDFE6;
    padding-bottom: 10px;

    .tip {
      width: 30px;
      font-size: 14px;
      font-family: Microsoft YaHei-Regular, Microsoft YaHei;
      color: #666666;
      letter-spacing: 1px;
    }

    .tip-input {
      position: absolute;
      animation: move 1s ease-in-out;
      animation-fill-mode: forwards
    }

    .input-block {
      width: calc(100% - 50px);
      border: none;
      margin-left: 20px;
    }

    .input-focus {
      width: 100%;
      margin-left: 0px;
    }
    
    .left {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: calc(100% - 50px);

      .input-block {
        width: calc(100% - 50px);
        border: none;
        margin-left: 20px;
      }

      .input-focus-in {
        width: 100%;
        margin-left: 0px;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
      ::v-deepsvg-icon {
        vertical-align: 0.3em;
      }
    }

    
    .imgs {
      position: relative;
      height: 36px;
      cursor: pointer;
      text-align: center;
      caret-color: rgba(0,0,0,0);

      img {
        height: 100%;
      }

      span {
        width: 84px;
        line-height: 36px;
        display: inline-block;
        background: rgba(0, 0, 0, 0.4);
        position: absolute;
        left: 0;
        color: #fff;
      }
    }
  }

  .form-item-input {
    border-bottom: 1px solid #409EFF;
  }

  .form-item-error {
    border-bottom: 1px solid #F56C6C;
  }

  .acea-row {
    width: calc(100% - 50px);
    margin-top: 60px;
  }
}

.plat-logo {
  position: fixed;
  top: 30px;
  left: 30px;
}

@keyframes move {
  0% {
    top: 0px;
    left: 0px;
  }

  100% {
    top: -20px;
    left: 0px;
    font-size: 12px;
  }
}
</style>
