<template>
  <div class="login-container f-sb-fs f-col">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">幼享乐</h3>
        <p class="title-tip">管理后台</p>
      </div>

      <el-form-item prop="phone">
        <el-input
          ref="phone"
          v-model="loginForm.phone"
          placeholder="请输入手机号"
          name="phone"
          type="text"
          tabindex="1"
          auto-complete="on"
          prefix-icon="el-icon-phone"
        >
          <el-button
            slot="suffix"
            class="inline-btn"
            type="primary"
            :disabled="!canBtn"
            @click="handlerGetCode"
          >
            {{btnTxt}}
          </el-button>
        </el-input>
      </el-form-item>

      <el-form-item prop="code">
        <el-input
          ref="code"
          v-model="loginForm.code"
          placeholder="请输入手机验证码"
          name="code"
          type="text"
          tabindex="1"
          prefix-icon="el-icon-chat-dot-round"
          @keyup.enter.native="handleLogin"
        >
        </el-input>
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-bottom:30px;font-size: 20px;"
        @click.native.prevent="handleLogin"
      >
        登录
      </el-button>
    </el-form>
    <div class="footer">
      copyright @ {{ new Date().getFullYear() }}
      广东帕斯融媒体科技有限公司
    </div>

    <el-dialog
      title="真人验证"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="20%"
    >
      <div class="f-c-c f-col">
        <img :src="info.base64Img" class="info-img" @click="loadCheckImg" />
        <el-input v-model="point" placeholder="请输入验证码" clearable />
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleGetSMS"
          >获取短信验证码</el-button
        >
      </span> -->
    </el-dialog>
  </div>
</template>

<script>
import { validPhone } from '@/utils/validate';
import { getImgCode, getSMSCode } from '@/api/user';


export default {
  name: 'Login',
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的电话号码'));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value.length !== 6) {
        callback(new Error('请输入正确电话验证码'));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        phone: '',
        code: ''
      },
      loginRules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        code: [{ required: true, trigger: 'blur', validator: validateCode }]
      },
      validPhone,
      loading: false,
      redirect: undefined,

      dialogVisible: false,
      info: {},
      point: '',

      time: 60,
      timer: null
    };
  },

  computed: {
    canBtn() {
      const { time, loginForm}= this
      let b = validPhone(loginForm.phone) && this.timer === null
      return b
    },
    btnTxt() {
      if (this.timer !== null) {
        return `${this.time}秒`
      }
      return '获取验证码'
    }
  },

  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    },
    dialogVisible: {
      handler(b) {
        if (b) {
          this.loadCheckImg();
          this.point = '';
        }
      },
      immediate: true
    },
    point: {
      handler(str) {
        if (str.length >= 4) {
          this.handleGetSMS();
          this.$nextTick(() => {
            this.point = '';
          });
        }
      },
      immediate: true
    }
  },

  beforeDestroy() {
      if (this.timer) { clearInterval(this.timer); this.timer= null}

    },

  methods: {
    handlerGetCode() {
      if (this.timer) { clearInterval(this.timer); this.timer= null}
      this.timer = setInterval(() => {
        if (this.time > 0) {
          this.time -= 1;
        }
        if (this.time <= 0) {
          this.time = 60;
          clearInterval(this.timer);
          this.timer = null
        }
      }, 1000);
      this.dialogVisible = true
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch(
              'user/login',
              Object.assign({ uuid: this.info.uuid }, this.loginForm)
            )
            .then(() => {
              this.$router.push({ path: this.redirect || '/' });
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          this.$error('尚未填写完成');
          return false;
        }
      });
    },

    async loadCheckImg() {
      const { success, msg, data } = await getImgCode();
      if (success) {
        this.info = data;
      } else {
        this.$error('加载失败，请稍后重试~');
      }
    },

    async handleGetSMS() {
      const { success, msg } = await getSMSCode({
        code: this.point,
        mobileNumber: this.loginForm.phone,
        uuid: this.info.uuid
      });
      if (success) {
        this.$success('短信已发出请稍等...');
        this.dialogVisible = false;
      }
    }
  }
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #aaa;
$cursor: #666;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: #666;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 100%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 0 12px 40px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(255, 255, 255, 0.6);
    border-radius: 5px;
    color: #454545;
  }

  .el-input__prefix {
    font-size: 20px;
  }
  .el-input__inner {
    font-size: 16px;
  }
  .el-input__suffix {
    right: 0;
  }
}
</style>

<style lang="scss" scoped>
// @import url('?@/styles/index.scss');
$bg: #f0f2f5;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background: #f0f2f5;
  // background-color: $bg;
  background-image: url(~@/assets/images/loginBg.svg);
  background-repeat: no-repeat;
  background-position: center 110px;
  background-size: 100%;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

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

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 30px;
      color: #362b2f;
      margin: 0px auto;
      text-align: center;
      font-weight: bold;
    }
    .title-tip {
      font-style: 20px;
      margin-bottom: 60px;
      color: #999;
      text-align: center;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

.footer {
  width: 100%;
  text-align: center;
  padding-bottom: 20px;
  font-size: 18px;
  color: rgba(0, 0, 0, 0.45);
}

.inline-btn {
  width: 120px;
  height: 100%;
  border: none;
}

.info-img {
  width: 130px;
  height: 48px;
}
</style>
