<template>

  <div class="login-container">


    <div class="login-weaper animated bounceInDown" style="z-index:100">
      <div class="login-left">
                <div class="login-time">
          {{time}}
        </div>
        <p class="title">{{productName}}</p>

        <el-image src="/static/img/login.png"></el-image>
      </div>
      <div v-if="whichPage === '1'" class="login-border">
        <div class="login-main">

          <h4 class="login-title">
           登录
          </h4>
          <h3 class="login-sub-title">
            请使用账号密码登录
          </h3>
            <el-form size="small" ref="inputForm" :model="inputForm" :rules="rules" class="login-form"  @keyup.enter.native="login()" @submit.native.prevent>

              <el-form-item  prop="username">
                <el-input type="text" placeholder="请输入账号" v-model="inputForm.username">
                   <i slot="prefix" class="el-input__icon el-icon-user-solid"></i>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input type="password" placeholder="请输入密码" v-model="inputForm.password">
                   <i slot="prefix" class="el-input__icon el-icon-female"></i>
                </el-input>
              </el-form-item>
              <el-form-item v-if="this.isShow">
                <el-row :gutter="10">
                  <el-col :span="8"><el-image @click="getCaptcha" :src="captchaImg" style="height:34px"></el-image></el-col>
                  <el-col :span="16">
                    <el-form-item prop="code">
                      <el-input placeholder="请输入验证码" v-model="inputForm.code"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form-item>
              <div style ="margin-left: 5px;margin-bottom: 20px; float: left;height: 40px;line-height:40px;">
                <!-- 记住我 -->
                <el-checkbox v-model="checked" class="rememberMe">记住我</el-checkbox>
              </div>
              <!-- 找回密码 -->
              <div style="float: right;position: relative;z-index:99">
                <el-button type="text" @click="openForgetPassword()" class="forgetPw">忘记密码</el-button>
              </div>
              <el-form-item>
                <el-button type="primary" :loading="loading" class="login-submit" @click="login">登录</el-button>
              </el-form-item>
              <!--<el-form-item>
              <div class="block">

                <el-image class="mobile" src="/static/img/mobile.png"></el-image>
                  <span class="demonstration">H5</span>
              </div>
                  <div class="block">

                <el-image class="mobile" src="/static/img/mobile.png"></el-image>
                  <span class="demonstration">Android</span>
              </div>
                  <div class="block">

                <el-image class="mobile" src="/static/img/mobile.png"></el-image>
                 <span class="demonstration">IOS</span>
              </div>
              </el-form-item>-->
            </el-form>
        </div>
         <el-image class="right" src="/static/img/right.png"></el-image>


      </div>
      <div v-else-if="whichPage === '2'" class="login-border">
        <div class="login-main">

          <h4 class="login-title">
            找回密码
          </h4>
          <h3 class="login-sub-title">
            使用账号绑定的手机号找回密码
          </h3>
          <el-form size="small" ref="inputForm2" :model="inputForm" :loading="loading" :rules="rules" class="login-form"  @keyup.enter.native="saveNewPass()" @submit.native.prevent>

            <el-form-item  prop="phoneNumber">
              <el-input type="text" placeholder="请输入绑定手机号" v-model="inputForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item  prop="phoneCode">
              <el-input type="text" placeholder="请输入验证码" v-model="inputForm.phoneCode" >
                <el-button slot="append" type="primary" @click="pushPhoneCode()" :loading="!showPhoneCode" style="background-color: #3595f9">
                  <span v-if="showPhoneCode" style="color: white">获取验证码</span>
                  <span v-else class="count" style="color: white">请等待 {{count}} s</span>
                </el-button>
              </el-input>
            </el-form-item>
            <el-form-item prop="newPassword">
              <el-input type="password" placeholder="请输入新密码" v-model="inputForm.newPassword"></el-input>
            </el-form-item>
            <el-form-item prop="newPasswordAgain">
              <el-input type="password" placeholder="请再次输入新密码" v-model="inputForm.newPasswordAgain"></el-input>
            </el-form-item>
            <!-- 返回登录页面 -->
            <div style="float: right;position: relative;z-index:99;height: 40px;line-height:40px;">
              <el-button type="text" @click="backLogin()" class="forgetPw">前往登录页面</el-button>
            </div>
            <el-form-item>
              <el-button type="primary" :loading="loading" class="login-submit" @click="saveNewPass()">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-image class="right" src="/static/img/right.png"></el-image>
      </div>
    </div>
  </div>
</template>

<script>
  import ConfigService from '@/api/sys/ConfigService'
  import LoginService from '@/api/auth/LoginService'
  import UserService from '@/api/sys/UserService'
  export default {
    data () {
      return {
        time: '',
        logo: '',
        productName: '',
        loading: false,
        captchaImg: '',
        isShow: false,
        checked: false,
        inputForm: {
          username: '',
          password: '',
          uuid: '',
          code: '',
          phoneNumber: '',
          phoneCode: '',
          newPassword: '',
          newPasswordAgain: ''
        },
        rules: {
          username: [
            {required: true, message: '帐号不能为空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'}
          ],
          code: [
            {required: true, message: '验证码不能为空', trigger: 'blur'}
          ],
          phoneNumber: [
            {required: true, message: '绑定手机号不能为空', trigger: 'blur'}
          ],
          phoneCode: [
            {required: true, message: '验证码不能为空', trigger: 'blur'}
          ],
          newPassword: [
            {required: true, message: '新的密码不能为空', trigger: 'blur'}
          ],
          newPasswordAgain: [
            {required: true, message: '再次输入的新密码不能为空', trigger: 'blur'}
          ]
        },
        captchaPath: '',
        whichPage: '1', // 1为登录页面，2为忘记密码页面
        showPhoneCode: true,
        count: '', // 初始化次数
        timer: null
      }
    },
    configService: null,
    loginService: null,
    userService: null,
    created () {
      this.configService = new ConfigService()
      this.loginService = new LoginService()
      this.userService = new UserService()
      this.getTime()
      setInterval(() => {
        this.getTime()
      }, 1000)
    },
    mounted () {
      this.getCookie()
      this.configService.getConfig().then(({data}) => {
        this.productName = data.productName
      })
      // this.getCaptcha()
      if (this.inputForm.username) {
        this.getLoginCodeNumber(this.inputForm.username)
      }
    },
    methods: {
      // 提交表单
      login () {
        var checked = this.checked
        var password = this.inputForm.password
        var username = this.inputForm.username
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.loginService.login(this.inputForm).then(({data}) => {
              this.$cookie.set('token', data.token)
              this.userService.getMenus().then(({data}) => {
                localStorage.setItem('routerList', JSON.stringify(data.routerList || '[]'))
                localStorage.setItem('allMenuList', JSON.stringify(data.menuList || '[]'))
                localStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
                localStorage.setItem('dictList', JSON.stringify(data.dictList || '[]'))
                this.$router.push({name: 'home'})
              })
              let Base64 = require('js-base64').Base64
              /* ------ 账号密码的存储 ------ */
              if (checked) {
                // eslint-disable-next-line no-undef
                // let password = Base64.encode(passwordLogin) // base64加密
                this.setCookie(Base64.encode(username), Base64.encode(password), 7)
              } else {
                this.setCookie('', '', -1) // 修改2值都为空，天数为负1天就好了
              }
              /* ------ http登录请求 ------ */
              this.$notify({
                title: '登录成功',
                message: `欢迎回来！<br/>你上次的登录IP是 ${data.oldLoginIp}，登录时间是 ${data.oldLoginDate}。`,
                dangerouslyUseHTMLString: true,
                duration: 10000,
                type: 'success'
              })
            }).catch(e => {
              this.loading = false
              this.getLoginCodeNumber(this.inputForm.username)
            })
          }
        })
      },
      getTime () {
        this.time = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      },
      // 获取验证码
      getCaptcha () {
        this.loginService.getCode().then(({data}) => {
          this.captchaImg = 'data:image/gif;base64,' + data.codeImg
          this.inputForm.uuid = data.uuid
        })
      },
      // 获取验证码
      getLoginCodeNumber (username) {
        this.loginService.getLoginCodeNumber(username).then(({data}) => {
          console.log(11111)
          if (data.redisLoginNumber >= data.loginNumber) {
            this.getCaptcha()
            this.isShow = true
          }
        })
      },
      // 设置cookie
      setCookie (username, password, days) {
        let date = new Date() // 获取时间
        date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * days) // 保存的天数
        // 字符串拼接cookie
        window.document.cookie =
          'username' + '=' + username + ';path=/;expires=' + date.toGMTString()
        window.document.cookie =
          'password' + '=' + password + ';path=/;expires=' + date.toGMTString()
      },

      // 读取cookie 将用户名和密码回显到input框中
      getCookie () {
        let Base64 = require('js-base64').Base64
        if (document.cookie.length > 0) {
          let arr = document.cookie.split('; ') // 分割成一个个独立的“key=value”的形式
          for (let i = 0; i < arr.length; i++) {
            let arr2 = arr[i].split('=') // 再次切割，arr2[0]为key值，arr2[1]为对应的value
            if (arr2[0] === 'username') {
              this.inputForm.username = Base64.decode(arr2[1])// base64解密
            } else if (arr2[0] === 'password') {
              // eslint-disable-next-line no-undef
              this.inputForm.password = Base64.decode(arr2[1])// base64解密
              this.checked = true
            }
          }
        }
      },
      openForgetPassword () {
        this.inputForm.username = ''
        this.inputForm.password = ''
        this.inputForm.code = ''
        this.$refs.inputForm.resetFields()
        this.$nextTick(() => {
          this.whichPage = '2' // 打开忘记密码页面
        })
      },
      backLogin () {
        this.inputForm.phoneNumber = ''
        this.inputForm.phoneCode = ''
        this.inputForm.newPassword = ''
        this.inputForm.newPasswordAgain = ''
        this.$refs.inputForm2.resetFields()
        this.whichPage = '1' // 打开登录页面
      },
      saveNewPass () {
        this.loading = true
        this.$refs['inputForm2'].validate((valid) => {
          if (valid) {
            if (this.inputForm.newPassword !== this.inputForm.newPasswordAgain) {
              this.loading = false
              this.$message.error('两次输入的密码不相同，请重新输入!')
              throw new Error('两次输入的密码不相同，请重新输入!')
            }
            this.loginService.saveNewPassword(this.inputForm).then(({data}) => {
              if (data.success) {
                this.$message.success(data.message)
                this.inputForm.username = this.inputForm.phoneNumber
                this.inputForm.password = this.inputForm.newPassword
                this.backLogin() // 修改密码成功后返回登录页面
                this.loading = false
              } else {
                this.$message.error(data.message)
                this.loading = false
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        })
      },
      pushPhoneCode () {
        // 验证手机号码格式是否正确
        if (this.commonJS.isNotEmpty(this.inputForm.phoneNumber) && this.validateXG.isMobile(this.inputForm.phoneNumber)) {
          // 向手机号发送验证码
          this.loginService.getPhoneCode(this.inputForm.phoneNumber).then(({data}) => {
            if (data.success) {
              this.$message.success(data.message)
              // ‘发送验证码’按钮倒计时
              const TIME_COUNT = 60 // 更改倒计时时间
              if (!this.timer) {
                this.count = TIME_COUNT
                this.showPhoneCode = false
                this.timer = setInterval(() => {
                  if (this.count > 0 && this.count <= TIME_COUNT) {
                    this.count--
                  } else {
                    this.showPhoneCode = true
                    clearInterval(this.timer) // 清除定时器
                    this.timer = null
                  }
                }, 1000)
              }
            } else {
              this.$message.error(data.message)
            }
          })
        } else {
          this.$message.error('请填写正确的手机号')
        }
      }
    }
  }
</script>

<style lang="scss">
@import '~@/assets/scss/login.scss';
</style>
