<template>
  <div v-loading="loading"
       class="login-bodyBox">
    <div class="login-header">
      <div class="header-box">
        <!-- <span class="iconfont icon-yiliangyiyun"></span> -->
        <p>管理后台</p>
      </div>
    </div>
    <div class="login-center">
      <img class="login-left"
           src="../../assets/images/page/login/logoSpace.png">
      <div class="login-right">
        <!--登录-->
        <div class="login-box">
          <div>
            <img class="company-image"
                 src="../../assets/images/page/login/logo.png">
            <el-form ref="login"
                     :model="loginForm"
                     :rules="loginRule">
              <el-form-item prop="username">
                <el-input ref="username"
                          prefix-icon="el-icon-user"
                          v-model="loginForm.username"
                          placeholder="请输入用户名"
                          size="small"
                          name="username"
                          type="text" />
              </el-form-item>

              <el-form-item prop="password">
                <el-input size="small"
                          prefix-icon="el-icon-lock"
                          ref="password"
                          show-password
                          v-model="loginForm.password"
                          placeholder="请输入密码"
                          name="password"
                          @keyup.enter.native="handleLogin" />
              </el-form-item>
            </el-form>
            <div class="fr pointer forget-pwd"
                 @click="getForgetBox">忘记密码</div>
          </div>
          <el-button size="small"
                     type="primary"
                     @click.native.prevent="handleLogin">登录</el-button>
        </div>
      </div>
    </div>
    <div class="login-footer">
      <!-- <p class="copyright">Copyright © 大连海大赢海科技有限公司版权所有 CP备案号 : 辽ICP备13007766号-6</p> -->
    </div>

    <!--忘记密码消息弹框盒子-->
    <el-dialog class="dialog"
               v-if="messageBox"
               title="找回密码"
               :visible.sync="messageBox"
               width="500px"
               top="20vh"
               center>
      <!--弹框主体-->
      <el-form ref="forgetDate"
               :model="forgetDate"
               :rules="loginRule"
               label-width="120px"
               label-position="right">
        <el-form-item label="手机号">
          <el-input v-model="forgetDate.mobilePhone"
                    style="width:200px"
                    size="small"
                    placeholder="请输入手机号" />
          <div style="display: inline-block;margin-left:4px;"
               class="sendverificatin">
            <el-button v-show="showVerification"
                       size="small"
                       type="primary"
                       @click="sendVerification">发送验证码</el-button>
            <el-button v-show="!showVerification"
                       size="small"
                       class="retry">重试({{ count }})s</el-button>
          </div>
        </el-form-item>
        <el-form-item label="验证码"
                      prop="veriCode">
          <el-input v-model="forgetDate.veriCode"
                    size="small"
                    class="dialog-form-input"
                    placeholder="请输入验证码" />
        </el-form-item>
        <el-form-item label="新密码"
                      prop="password">
          <el-input v-model="forgetDate.password"
                    size="small"
                    class="dialog-form-input"
                    placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码"
                      prop="againPassword">
          <el-input v-model="forgetDate.againPassword"
                    size="small"
                    class="dialog-form-input"
                    placeholder="再次输入新密码" />
        </el-form-item>
      </el-form>
      <!--弹框底部-->
      <span slot="footer"
            class="dialog-footer">
        <el-button size="small"
                   @click="resetForm">取 消</el-button>
        <el-button size="small"
                   type="primary"
                   @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  retrievePassword,
  getCompanyInfo,
  checkPassword,
  getLoginInfo
} from '../../api/login/login'
import {
  sendMsg,
  checkMsg
} from '../../api/businessSettings/businessSettings'
export default {
  name: 'Login',
  data () {
    return {
      showVerification: true,
      disabledButton: true,
      count: '',
      companyLogo: '',
      timer: null,
      loading: false,
      messageBox: false,
      companyName: localStorage.getItem('companyName'),
      passwordType: 'password',
      userCellPhone: '',
      // userKind: 'OPERATOR',
      loginRule: {
        username: [{
          required: true,
          message: '请输入正确的用户名',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '密码为6到20位数字、大小写字母任意组合',
          trigger: 'blur'
        }]
      },
      forgetDate: {
        password: '',
        againPassword: '',
        veriCode: ''
      },
      loginForm: {
        username: '',
        password: '',
        userKind: 'OPERATOR'
      }
    }
  },
  created () {
    /* 初始化时通过域名获取公司信息*/
    this.getCompInfo()
  },
  methods: {
    handleLogin () {
      this.loginForm.domainName = 'YLYY'
      this.$refs.login.validate(valid => {
        if (valid) {
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              getLoginInfo().then((response) => {
                //将登录人id 名称放到localStorage中
                localStorage.setItem('ws-pf_userId', response.data.userInfo.userId)
                localStorage.setItem('ws-pf_userName', response.data.userInfo.loginName)
              })
              this.$router.push({
                path: this.redirect || '/'
              })
            })
        }
        return false
      })
    },
    /* 忘记密码*/
    getForgetBox () {
      this.showVerification = true
      this.messageBox = true
    },
    /* 点击取消*/
    resetForm () {
      this.messageBox = false
      this.$refs.forgetDate.resetFields()
    },
    /* 点击保存*/
    submitForm () {
      this.$refs.forgetDate.validate(valid => {
        if (valid) {
          this.checkPwd(this.forgetDate.password)
        } else {
          this.$message({
            message: '保存失败',
            type: 'error',
            showClose: true
          })
          return false
        }
      })
    },
    saveNewPassword () {
      // this.saveVerification()
      const againPasswordState =
        this.forgetDate.againPassword !== '' &&
        this.forgetDate.againPassword !== undefined &&
        this.forgetDate.againPassword != null
      const passwordState =
        this.forgetDate.password !== '' &&
        this.forgetDate.password !== undefined &&
        this.forgetDate.password != null
      const veriCodeState =
        this.forgetDate.veriCode !== '' &&
        this.forgetDate.veriCode !== undefined &&
        this.forgetDate.veriCode != null
      if (againPasswordState && passwordState && veriCodeState) {
        // this.saveVerification()
        this.checkPwd(this.forgetDate.password)
      } else {
        if (
          this.forgetDate.againPassword === '' ||
          this.forgetDate.againPassword === undefined ||
          this.forgetDate.againPassword === null
        ) {
          this.$message({
            message: '保存失败',
            type: 'error',
            showClose: true
          })
        } else if (
          this.forgetDate.password === '' ||
          this.forgetDate.password === undefined ||
          this.forgetDate.password === null
        ) {
          this.$message({
            message: '保存失败',
            type: 'error',
            showClose: true
          })
        } else if (
          this.forgetDate.veriCode === '' ||
          this.forgetDate.veriCode === undefined ||
          this.forgetDate.veriCode === null
        ) {
          this.$message({
            message: '保存失败',
            type: 'error',
            showClose: true
          })
        }
      }
    },
    /* 在忘记密码时检测验证码*/
    saveVerification () {
      const data = {
        mobilePhone: this.userCellPhone,
        veriCode: this.forgetDate.veriCode
      }
      checkMsg(data)
        .then(response => {
          const checkState = response.data
          if (checkState) {
            this.checkPwd(this.forgetDate.password)
          } else {
            this.$message({
              message: '验证码无效',
              type: 'error',
              showClose: true
            })
            this.forgetDate.veriCode = ''
          }
        })
    },
    /* 在忘记密码时找回密码*/
    getNewPassword () {
      const data = {
        mobilePhone: this.forgetDate.mobilePhone,
        veriCode: this.forgetDate.veriCode,
        password: this.forgetDate.againPassword,
        userKind: "OPERATOR"
      }
      retrievePassword(data)
        .then(response => {
          if (response.code === '200') {
            this.$message({
              message: '修改成功',
              type: 'success',
              showClose: true
            })
            this.messageBox = false
          } else if (response.code === 'AUTH-004') {
            this.$message({
              message: '验证码无效',
              type: 'error',
              showClose: true
            })
            this.forgetDate.veriCode = ''
          } else if (response.code === 'AUTH-006') {
            this.$message({
              message: '新密码与原始密码相同',
              type: 'error',
              showClose: true
            })
            this.forgetDate.againPassword = ''
            this.forgetDate.password = ''
          }
        })
    },
    /* 检查输入密码的规则*/
    checkPwd (pwd) {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
      const re = new RegExp(reg)
      if (re.test(pwd)) {
        if (this.forgetDate.againPassword !== this.forgetDate.password) {
          this.$message({
            message: '输入的密码不一致，请重新输入',
            type: 'error',
            showClose: true
          })
          this.forgetDate.againPassword = ''
        } else {
          this.getNewPassword()
        }
      } else {
        this.$message({
          message: '密码不符合规则，请重新输入',
          type: 'error',
          showClose: true
        })
      }
    },
    /* 通过域名获取公司信息*/
    getCompInfo () {
      getCompanyInfo()
        .then(response => {
          if (response.data && response.data) {
            this.companyLogo = response.data.compHeadimg
            this.userCellPhone = response.data.managerInfo.userCellPhone
            localStorage.setItem('companyLogo', this.companyLogo)
            localStorage.setItem('companyName', response.data.compName)
            localStorage.setItem('companyId', response.data.compId)
            localStorage.setItem(
              'userRealName',
              response.data.managerInfo.userRealName
            )
            this.userKind = response.data.managerInfo.userKind
          } else {
            this.companyLogo = require('../../assets/images/page/login/defaultLogo.png')
          }
        })
    },
    /* 点击发送验证码*/
    sendVerification () {
      clearInterval(this.timer)
      this.timer = null
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT
        this.showVerification = false
        this.postVerification()
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.showVerification = true
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },
    /* 发送验证码*/
    postVerification () {
      const data = {
        mobilePhone: this.forgetDate.mobilePhone,
        userKind: this.userKind
      }
      sendMsg(data)
        .then(response => {
          const codeState = response.code
          if (codeState === 'AUTH-003') {
            this.$message({
              message: '该手机号不存在',
              type: 'error',
              showClose: true
            })
            this.loginBox = true
          } else {
            this.disabledButton = false
          }
        })
    },
    /* 检测验证码*/
    checkVerification () {
      const date = {
        mobilePhone: this.userCellPhone,
        veriCode: this.formData.veriCode,
      }
      this.loginForm = date
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', date)
            .then(() => {
              this.$router.push({
                path: this.redirect || '/'
              })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    /* 验证密码*/
    getLoginBox () {
      if (
        this.formData.password === '' ||
        this.formData.password === undefined ||
        this.formData.password === null
      ) {
        this.$message({
          message: '密码不能为空',
          type: 'warning',
          showClose: true
        })
      } else {
        const data = {
          password: this.formData.password
        }
        checkPassword(data)
          .then(response => {
            const loginState = response.data
            if (loginState === null) {
              this.$message({
                message: '密码错误，请重新输入',
                type: 'error',
                showClose: true
              })
              this.formData.password = ''
            } else {
              this.loginBox = false
              this.showVerification = true
              this.userCellPhone = response.data.userCellPhone
            }
          })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.icon-yiliangyiyun{
color:#fff;
font-size:36px;
}
.login-bodyBox {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  background-color: #001529;
  width: 100%;
  height: 100%;
  overflow-y: hidden;
  display: flex;
  flex-direction: column;
  .show-pwd {
    position: absolute;
    right: 14px;
    top: 2px;
    font-size: 16px;
    color: #a6a7a8;
    cursor: pointer;
    user-select: none;
  }
  .forget-pwd {
    color: #a6a7a8;
    line-height: 20px;
  }
  .el-dialog {
    .company-name {
      width: 208px;
      display: inline-block;
      height: 30px;
      line-height: 30px;
      padding-bottom: 5px;
    }
    .password-prompt {
      font-size: 12px;
      line-height: 16px;
      position: absolute;
      width: 300px;
      display: inline-block;
      color: #999;
      bottom: -20px;
      left: 1px;
    }
  }
  .login-header {
    background: #000;
    .header-box {
      height: 60px;
      max-width: 800px;
      margin: 0 auto;
      width: 100%;
      display: flex;
      align-items: center;
      p {
        color: #909090;
        padding-left: 10px;
        font-size: 16px;
      }
    }
  }

  .login-center {
    flex: 1 0 auto;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
    .login-left {
      box-shadow: -12px -6px 20px 0 #0e0e0e94;
    }
    .login-right {
      width: 400px;
      height: 400px;
      background: #fff;
      .login-box {
        height: 340px;
        padding: 30px 50px 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .title-text {
          color: #333;
          font-size: 14px;
          text-align: center;
        }
        .company-image {
          display: block;
          margin: 20px auto;
          width: 150px;
          border-radius: 6px;
        }
        .company-name {
          font-size: 14px;
          color: #707070;
          text-align: center;
          display: block;
          padding-bottom: 30px;
        }
        .forget-password {
          color: #0560f5;
          text-align: center;
          cursor: pointer;
          font-size: 13px;
          font-weight: 500;
        }
      }
    }
  }
  .login-footer {
    text-align: center;
    color: #999;
    position: absolute;
    width: 100%;
    bottom: 30px;
    .copyright {
      padding: 5px 0;
    }
  }
  .retry {
    height: 32px;
    line-height: 30px;
    width: 85px;
    margin: 0;
    padding: 0 14px !important;
    font-size: 13px;
    display: inline-block;
    background-color: #eeeeee;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    color: #666;
  }
}
.dialog-form-input {
  width: 320px !important;
}
</style>
