<template>
  <div class="login-container">
    <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>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="username" v-model="loginForm.username" placeholder="请输入您的账号" name="username" type="text"
          maxlength="11" tabindex="1" auto-complete="on" />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
          placeholder="请输入登录密码" name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-form-item prop="code">
        <el-row :span="24" style="display: flex; align-items: center">
          <el-col :span="20">
            <el-input v-model="loginForm.code" auto-complete="off" placeholder="请输入验证码" size=""
              @keyup.enter.native="submitForm('loginForm')"></el-input>
          </el-col>
          <el-col :span="4" style="display: flex; justify-content: flex-end">
            <div class="login-code" @click="refreshCode">
              <!--验证码组件-->
              <s-identify :identifyCode="identifyCode"></s-identify>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- <el-form-item prop="checkCode">
        <el-row :span="24" style="display: flex; align-items: center">
          <el-col :span="20">
            <el-input v-model="loginForm.checkCode" auto-complete="off" placeholder="请输入手机验证码"></el-input>
          </el-col>
          <el-col :span="4" style="display: flex; justify-content: flex-end">
            <div class="login-code" @click="checkClick">
              <el-button type="primary" style="width: 112px">{{
                codeText
              }}</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <div class="tips">手机验证码五分钟内有效</div> -->
      <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="nextLogin">进入</el-button>
      <!-- handleLogin -->

      <!-- <div class="tips">
        <span style="margin-right:20px;">username: admin</span>
        <span>password: any</span>
      </div> -->
    </el-form>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import {
    mapActions
  } from 'vuex';
  import {
    validUsername,
    isLoginName
  } from '@/utils/validate';
  import {
    getVerifyCode,
    getCheckInfo,
    getlogin
  } from '@/api/user'
  import SIdentify from './sidentify';
  export default {
    name: 'Login',
    components: {
      SIdentify,
    },
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error('请输入正确的账号'));
        } else {
          callback();
        }
      };
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('请输入正确的密码'));
        } else {
          callback();
        }
      };
      const validateCode = (rule, value, callback) => {
        if (this.identifyCode !== value) {
          this.loginForm.code = '';
          this.refreshCode();
          callback(new Error('请输入正确的验证码'));
        } else {
          callback();
        }
      };
      const checkCode = (rule, value, callback) => {
        if (this.identifyCode !== value || value.length != 6) {
          this.loginForm.checkCode = '';
          this.refreshCode();
          callback(new Error('请输入正确的手机验证码'));
        } else {
          callback();
        }
      };
      return {
        isDebugLogin: false,
        loginForm: {
          username: '',
          password: '',
          code: '',
        },
        identifyCodes: '1234567890',
        identifyCode: '',
        loginRules: {
          username: [{
              required: true,
              trigger: 'blur',
              message: '请输入账号',
            },
            {
              min: 11,
              max: 11,
              message: '请输入11位手机号',
              trigger: 'blur',
            },
            {
              validator: isLoginName,
              trigger: 'blur',
            },
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur',
            },
            {
              min: 1,
              max: 100,
              message: '长度在1-100字符之间',
              trigger: 'blur',
            },
          ],
          code: [{
              required: true,
              message: '请输入验证码',
              trigger: 'blur',
            },
            {
              validator: validateCode,
              trigger: 'blur',
            },
          ],
          // checkCode: [{
          //     required: true,
          //     message: "请输入手机验证码",
          //     trigger: "blur",
          //   },
          //   {
          //     min: 6,
          //     max: 6,
          //     message: "请输入6位手机验证码",
          //     trigger: "blur",
          //   },
          // ],
        },
        loading: false,
        rememberMe: true,
        passwordType: 'password',
        redirect: undefined,
        codeText: '获取验证码',
      };
    },
    watch: {
      $route: {
        handler: function(route) {
          console.log('route',route)
          this.redirect = route.query && route.query.redirect;
          console.log('this.redirect,this.redirect')
        },
        immediate: true,
      },
      isDebugLogin(v) {
        if (v) {
          this.loginForm.password = '123';
          this.refreshCode();
        }
      },
      identifyCode(v) {
        this.isDebugLogin && (this.loginForm.code = v);
      },
    },
    methods: {
      nextLogin() { //校验验证码
        this.$refs.loginForm.validate(async (valid) => {
          if (valid) {
            // getCheckInfo({
            //   phone: this.loginForm.username,
            //   verifyCode: this.loginForm.checkCode
            // }).then(response => {
            //   if (response.code == 200) { //验证码校验成功   登录
            //     this.handleLogin()
            //   }
            // })
            this.handleLogin()
          }
        })
      },
      checkClick() { //获取验证码
        let that = this;
        if (that.identifyCode !== that.loginForm.code) {
          this.loginForm.code = '';
          that.$message.error('请输入正确的图片验证码')
          return
        }
        if (/^0?1[3|4|5|6|7|8][0-9]\d{8}$/.test(that.loginForm.username)) {
          if (that.codeText == '获取验证码' || that.codeText == '重新发送') {
            getVerifyCode({
              phone: that.loginForm.username,
              identification: 3
            }).then(response => {
              if (response.code == 200) {
                that.codeText = 60;
                setInterval(() => {
                  if (that.codeText > 0) {
                    that.codeText -= 1;
                  } else {
                    that.codeText = '重新发送';
                  }
                }, 1000);
              } else {
                that.$message.error(response.message)
              }
            })
          }
        } else {
          that.$message.error('请输入正确的手机')
        }
      },
      ...mapActions('user', ['login']),
      randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
      },
      refreshCode() {
        this.identifyCode = '';
        this.makeCode(this.identifyCodes, 4);
      },
      makeCode(o, l) {
        for (let i = 0; i < l; i++) {
          this.identifyCode +=
            this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
        }
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = '';
        } else {
          this.passwordType = 'password';
        }
        this.$nextTick(() => {
          this.$refs.password.focus();
        });
      },
      // handleLogin() {
      //   this.$refs.loginForm.validate(async (valid) => {
      //     if (valid) {
      //       this.loginForm.companyName = '黑龙江中天昊元贸易有限公司'
      //       this.loading = true
      //       // this.$store.dispatch('user/login', this.loginForm)
      //       // const res = await this.$store.dispatch('user/login', this.loginForm)
      //       const res = await this.login(this.loginForm)
      //       localStorage.setItem('ws_login_type', 2)
      //       Cookies.set('ws_login_companyShortName', this.loginForm.companyName, {
      //         expires: 365,
      //       })
      //       Cookies.set('ws_login_account', this.loginForm.username, {
      //         expires: 365,
      //       })
      //       if (this.rememberMe) {
      //         Cookies.set('ws_login_pwd', this.loginForm.password, {
      //           expires: 365,
      //         })
      //         Cookies.set('ws_login_rememberMe', 1, {
      //           expires: 365
      //         })
      //       } else {
      //         Cookies.remove('ws_login_companyShortName')
      //         Cookies.remove('ws_login_account')
      //         Cookies.remove('ws_login_pwd')
      //         Cookies.set('ws_login_rememberMe', 0, {
      //           expires: 365
      //         })
      //       }
      //       const redirect = this.$route.query.redirect
      //       if (redirect) {
      //         this.$router.push(redirect)
      //       } else {
      //         this.$router.push('/')
      //       }
      //       // .then(response => {
      //       //   localStorage.setItem('UserInfo', JSON.stringify(response.data))
      //       //   this.$router.push({
      //       //     path: this.redirect || '/'
      //       //   })
      //       //   this.loading = false
      //       // })
      //       // .catch(() => {
      //       //   this.loading = false
      //       // })
      //     } else {
      //       console.log('error submit!!')
      //       return false
      //     }
      //   })
      // },



      handleLogin() {
        let that = this
        this.$refs.loginForm.validate(async (valid) => {
          if (valid) {
            this.loginForm.companyName = '黑龙江中天昊元贸易有限公司';
            this.loading = true;
            // this.$store.dispatch('user/login', this.loginForm)
            // const res = await this.$store.dispatch('user/login', this.loginForm)、
           const res = await getlogin({
              loginName: this.loginForm.username,
              loginPassword: this.loginForm.password,
              compId: '2710b21efc1e4393930c5dc800010dc4',
            })
            
              if (res.code == 200) {
                const res1 = await this.$store.dispatch('user/login', this.loginForm)
                localStorage.setItem('UserInfo', JSON.stringify(res1.data))
                localStorage.setItem('ws_login_type', 2);
                Cookies.set('ws_login_companyShortName', this.loginForm.companyName, {
                  expires: 365,
                });
                Cookies.set('ws_login_account', this.loginForm.username, {
                  expires: 365,
                });
                if (this.rememberMe) {
                  Cookies.set('ws_login_pwd', this.loginForm.password, {
                    expires: 365,
                  });
                  Cookies.set('ws_login_rememberMe', 1, {
                    expires: 365,
                  });
                } else {
                  Cookies.remove('ws_login_companyShortName');
                  Cookies.remove('ws_login_account');
                  Cookies.remove('ws_login_pwd');
                  Cookies.set('ws_login_rememberMe', 0, {
                    expires: 365,
                  });
                }
                const redirect = this.$route.query.redirect;
                if (redirect) {
                  this.$router.push(redirect);
                } else {
                  this.$router.push('/');
                }
              } else {
                this.$message.error(response.message)
              }
            // .then(response => {
            //   localStorage.setItem('UserInfo', JSON.stringify(response.data))
            //   this.$router.push({
            //     path: this.redirect || '/'
            //   })
            //   this.loading = false
            // })
            // .catch(() => {
            //   this.loading = false
            // })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    },
    created() {
      this.refreshCode();
    },
  };
</script>

<style lang="scss">
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: #fff;
  $cursor: #fff;

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

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

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        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(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    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: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

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

  .login-code {
    cursor: pointer;
    margin-right: 5px;

    .login-code-img {
      width: 100px;
      height: 38px;
      background-color: #eee;
      border: 1px solid #f0f0f0;
      color: #333;
      font-size: 18px;
      font-weight: bold;
      letter-spacing: 2px;
      text-indent: 2px;
      text-align: center;
    }
  }

  .tips {
    width: 100%;
    text-align: right;
    color: #a1a3a6 !important;
  }
</style>
