<template>
  <div class="login-container bg">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      size="medium"
      label-width="2px"
      class="login-form"
      auto-complete="on"
      label-position="left">
      <h3 class="title">数据门户</h3>

      <el-form-item prop="username" style="margin-left: 50%;">
        <div class="flex-center">
          <span class="svg-container w-20">
            <svg-icon icon-class="ic_username"/>
            帐号
          </span>
          <el-input
            v-model="loginForm.username"
            :placeholder="$t('login.username')"
            name="username"
            type="text"
            auto-complete="on"
          />
        </div>

      </el-form-item>

      <el-form-item prop="password" style="margin-left: 50%;margin-top: -2px">
        <div class="flex-center">
          <span class="svg-container w-20">
            <svg-icon icon-class="ic_password"/>
            密码
          </span>
          <el-input
            v-model="loginForm.password"
            :placeholder="$t('login.password')"
            name="password"
            auto-complete="on"
            show-password
            @keyup.enter.native="handleLogin"
          />
        </div>
      </el-form-item>
      <el-form-item style="margin-left: 50%;margin-top: 18px">
        <div class="flex-center">
          <el-input v-model="loginForm.code" placeholder="验证码" @keyup.enter.native="handleLogin" />
          <img :src="codeUrl" class="login-code-img gesture" @click="getCode">
        </div>
        <div class="mt-20"/>
        <el-row>
          <el-col :span="24">
            <el-button :loading="loading" type="primary" class="p-10" style="width:100%;" @click.native.prevent="handleLogin">
              {{ $t('login.logIn') }}
            </el-button>
          </el-col>
        </el-row>
        <!--        <div class="flex-between p-20">-->
        <!--          <el-button type="text">-->
        <!--            <router-link :to="{path:'/resetpw'}" tag="a"><span class="blue">忘记密码</span></router-link>-->
        <!--          </el-button>-->
        <!--          <router-link :to="{path:'/register'}" tag="a">-->
        <!--            <el-button style="width:100%;float: right" type="text">注册开发者</el-button>-->
        <!--          </router-link>-->
        <!--        </div>-->
      </el-form-item>

    </el-form>

    <el-dialog :visible.sync="registerFormVisible" title="注册开发者">
      <el-form :model="registerForm" :rules="rules" :label-width="formLabelWidth">
        <el-form-item label="帐号" prop="account">
          <el-input
            v-model="registerForm.account"
            placeholder="请输入帐号"
            maxlength="32"
            readonly
            onfocus="this.removeAttribute('readonly');"
            @blur="checkLength"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            placeholder="请输入密码，最小长度为8，包含大小写字母和数字"
            type="password"
            minlength="8"
            readonly
            onfocus="this.removeAttribute('readonly');"/>
        </el-form-item>
        <el-form-item label="账号名称" prop="name">
          <el-input v-model="registerForm.name" maxlength="32" placeholder="请输入账号名称"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-row>
            <el-col :span="12">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号码" type="number"/>
            </el-col>
            <el-col :span="12">
              <el-button v-show="sendAuthCode" class="auth_text auth_text_blue" @click="getAuthCode">获取验证码
              </el-button>
              <el-button v-show="!sendAuthCode" class="auth_text"><span class="auth_text_blue">{{ auth_time }} </span>
                秒之后可重新发送验证码
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="短信验证码" prop="validCode">
          <el-input v-model="registerForm.validCode" placeholder="请输入验证码" type="number"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="registerForm.companyName" placeholder="请输入公司名称"/>
        </el-form-item>
        <el-form-item label="公司介绍">
          <el-input v-model="registerForm.companyInfo" placeholder="请输入公司介绍"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <input v-model="agreeLicense" type="checkbox">
        <span>阅读并接受</span>
        <span class="blueText" @click="userAgreementVisible = true">《xx用户协议》</span>
        <span>及</span>
        <span class="blueText" @click="userPrivateVisible = true">《xx隐私权保护声明》</span>
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="btnSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="userAgreementVisible" title="xx用户协议">
      <span>用户协议详情</span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userAgreementVisible = false">返回</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="userPrivateVisible" title="xx隐私权保护声明">
      <span>隐私权保护声明详情</span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userPrivateVisible = false">返回</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="changePwDialogVisible" title="找回密码/修改密码">
      <el-form>
        <el-form-item label="手机号码">
          <el-input v-model="mobilePhone" placeholder="请输入手机号码" type="number"/>
          <el-button v-show="sendAuthCode" class="auth_text auth_text_blue" @click="getChangePwSms">获取验证码
          </el-button>
          <el-button v-show="!sendAuthCode" class="auth_text"><span class="auth_text_blue">{{ auth_time }} </span>
            秒之后可重新发送验证码
          </el-button>
        </el-form-item>
        <el-form-item label="短信验证码">
          <el-input v-model="pwValidCode" placeholder="请输入验证码" type="number"/>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="resetPw" placeholder="请输入新密码" type="password"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changePwDialogVisible = false">返回</el-button>
        <el-button type="primary" @click="submitChangePw">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import md5 from 'js-md5'
import { getCodeImg } from '@/api/login'

export default {
  name: 'Login',
  data() {
    return {
      rules: {
        account: [{ required: true, message: '请输入帐号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入账号名称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号码', length: 11, trigger: 'blur' }],
        validCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
      },
      codeUrl: '',
      loginForm: {
        username: '',
        password: '',
        code: '',
        uuid: ''
      },
      loginRules: {
        username: [{ required: true, message: '请输入帐号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      passwordType: 'password',
      loading: false,
      showDialog: false,
      redirect: undefined,
      agreeLicense: false,
      formLabelWidth: '150px', // 弹出框form宽
      registerFormVisible: false,
      userAgreementVisible: false,
      userPrivateVisible: false,
      registerForm: {
        account: '',
        password: '',
        name: '',
        phone: '',
        validCode: '',
        email: '',
        companyName: '',
        companyInfo: '',
        status: ''
      },
      sendAuthCode: true, /* 布尔值，通过v-show控制显示‘获取按钮’还是‘倒计时’ */
      auth_time: 0, /* 倒计时 计数器*/
      changePwDialogVisible: false,
      mobilePhone: '',
      resetPw: '',
      pwValidCode: '',
      loginCode: '' /* process.env.BASE_API + '/user/gencode?=' + Math.random()*/
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('hashchange', this.afterQRScan)
    this.startTimer()
    this.getCode()
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  },
  methods: {
    getCode() {
      this.loginForm.code = ''
      getCodeImg().then(res => {
        this.codeUrl = 'data:image/gif;base64,' + res.img
        this.loginForm.uuid = res.uuid
      })
    },
    startTimer() {
      console.log('start timer')
      this.timer = setInterval(this.gencode, 60000)
    },
    getAuthCode() {
      if (this.registerForm.phone === '' || this.registerForm.phone === undefined) {
        this.$message.info('手机号码不能为空')
        return
      }
      if (this.registerForm.phone.length !== 11) {
        this.$message.info('请输入正确手机号码')
        return
      }
      var reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
      if (!reg.test(this.registerForm.phone)) {
        this.$message.error('手机号码格式不对')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('phone', vm.registerForm.phone)
      axios.post(process.env.BASE_API + '/user/getsms', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          // vm.$message(obj.message)
          vm.sendAuthCode = false
          vm.auth_time = 60
          var auth_timetimer = setInterval(() => {
            vm.auth_time--
            if (vm.auth_time <= 0) {
              vm.sendAuthCode = true
              clearInterval(auth_timetimer)
            }
          }, 1000)
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    checkLength() {
      var reg = /^[A-Za-z0-9-_]{8,32}$/
      if (!reg.test(this.registerForm.account)) {
        this.$message.info('请输入字母或数字组成的账号，长度8-32位')
      }
    },
    getChangePwSms() {
      if (this.mobilePhone === '' || this.mobilePhone === undefined) {
        this.$message.info('手机号码不能为空')
        return
      }
      if (this.mobilePhone.length !== 11) {
        this.$message.info('请输入正确手机号码')
        return
      }
      var reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
      if (!reg.test(this.mobilePhone)) {
        this.$message.error('手机号码格式不对')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('phone', vm.mobilePhone)
      axios.post(process.env.BASE_API + '/user/getpwsms', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          // vm.$message(obj.message)
          vm.sendAuthCode = false
          vm.auth_time = 60
          var auth_timetimer = setInterval(() => {
            vm.auth_time--
            if (vm.auth_time <= 0) {
              vm.sendAuthCode = true
              clearInterval(auth_timetimer)
            }
          }, 1000)
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    submitChangePw() {
      if (this.mobilePhone === '' || this.mobilePhone === undefined) {
        this.$message.info('手机号码不能为空')
        return
      }
      if (this.mobilePhone.length !== 11) {
        this.$message.info('请输入正确手机号码')
        return
      }
      var reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
      if (!reg.test(this.mobilePhone)) {
        this.$message.error('手机号码格式不对')
        return
      }
      if (this.pwValidCode === '' || this.pwValidCode === undefined) {
        this.$message.info('请输入手机验证码，不能为空')
        return
      }
      if (this.resetPw === '' || this.resetPw === undefined) {
        this.$message.info('请输入新密码，不能为空')
        return
      }
      if (this.resetPw.length < 6) {
        this.$message.info('新密码长度不能少于6位')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('phone', vm.mobilePhone)
      params.append('pwValidCode', vm.pwValidCode)
      params.append('resetPw', md5(vm.resetPw))
      axios.post(process.env.BASE_API + '/user/resetpw', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.changePwDialogVisible = false
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    registerBtnClick() {
      this.registerFormVisible = true
      this.registerForm.account = ''
      this.registerForm.password = ''
    },
    btnCancel() {
      this.registerFormVisible = false
    },
    btnSubmit() {
      if (this.registerForm.account === '' || this.registerForm.account === undefined) {
        this.$message.info('请输入账号，账号不能为空')
        return
      }
      var reg = /^[A-Za-z0-9-_]{8,32}$/
      if (!reg.test(this.registerForm.account)) {
        this.$message.error('请输入字母或数字组成的账号，长度8-32位')
        return
      }
      var re = /select|update|delete|truncate|join|union|exec|insert|drop|count|sql|'|"|;|>|<|%/i
      if (re.test(this.registerForm.account)) {
        this.$message.info('账号名异常，请勿输入非法字符')
        return
      }
      if (this.registerForm.password === '' || this.registerForm.password === undefined) {
        this.$message.info('请输入密码，不能为空')
        return
      }
      if (this.registerForm.password.length < 8) {
        this.$message.info('密码需是8-32位的英文大小写加数字组合')
        return
      }
      if (this.registerForm.phone === '' || this.registerForm.phone === undefined) {
        this.$message.info('请输入手机号码，不能为空')
        return
      }
      if (this.registerForm.phone.length !== 11) {
        this.$message.info('请输入正确手机号码')
        return
      }
      var regPhone = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
      if (!regPhone.test(this.registerForm.phone)) {
        this.$message.error('手机号码格式不对')
        return
      }
      if (this.registerForm.validCode === '' || this.registerForm.validCode === undefined) {
        this.$message.info('请输入手机验证码，不能为空')
        return
      }
      if (this.registerForm.name === '' || this.registerForm.name === undefined) {
        this.$message.info('请输入账号名称，不能为空')
        return
      }
      if (this.registerForm.email === '' || this.registerForm.email === undefined) {
        this.$message.info('请输入email，不能为空')
        return
      }
      var regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
      if (this.registerForm.email === '') {
        this.$message.info('请输入邮箱')
        return
      } else if (!regEmail.test(this.registerForm.email)) {
        this.$message.info('邮箱格式不正确')
        return
      }
      if (this.agreeLicense !== true) {
        this.$message.info('请勾选“阅读并接受用户协议”')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      params.append('account', vm.registerForm.account)
      params.append('password', md5(vm.registerForm.password))
      params.append('email', vm.registerForm.email)
      params.append('name', vm.registerForm.name)
      params.append('phone', vm.registerForm.phone)
      params.append('validCode', vm.registerForm.validCode)
      params.append('companyName', vm.registerForm.companyName)
      params.append('companyInfo', vm.registerForm.companyInfo)
      axios.post(process.env.BASE_API + '/user/insert', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.clearRegisterForm()
          vm.registerFormVisible = false
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('LoginByUsername', this.loginForm).then((res) => {
            this.loading = false
            this.$router.push({ path: this.redirect || '/' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
        this.getCode()
      })
    },
    clearRegisterForm() {
      this.registerForm.account = ''
      this.registerForm.password = ''
      this.registerForm.email = ''
      this.registerForm.name = ''
      this.registerForm.phone = ''
      this.registerForm.validCode = ''
      this.registerForm.companyName = ''
      this.registerForm.companyInfo = ''
    },
    gencode() {
      if (this.loginForm.username !== '') {
        this.loginCode = process.env.BASE_API + '/user/gencode?username=' + this.loginForm.username + '&=' + Math.random()
      }
    }
  }
}
</script>

<style scoped>
.login-form {
  position: absolute;
  left: 0;
  right: 0;
  width: 770px;
  height: 420px;
  padding: 35px 35px 15px 35px;
  margin: 15% auto;
  background-position: center 0;
  background-image: url(../../assets/sub.png);
}

.title {
  font-size: 24px;
  font-weight: 400;
  margin: 0px auto 35px auto;
  text-align: center;
  font-weight: bold;
}

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

.blueText {
  color: #409EFF;
}

.checklicense {
  width: 30px;
  height: 30px;
}

.is-hidden {
  position: absolute;
  left: -10000px;
  top: -10000px;
}

.bg {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  min-width: 1000px;
  zoom: 1;
  background-color: #fff;
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  -o-background-size: cover;
  background-position: center 0;
  background-image: url(../../assets/bg.png);
}

.login-code-img {
  height: 35px;
  margin-left: 10px;
}
</style>
