<template>
  <div class="login-page">
    <div class="login_bg">
      <div class="logo">
        <a href="/">
          <span class="logo_text">
            <img src="../assets/logo1.png" height="40px" v-if="$isMobile" />
            <img src="../assets/logo.png" height="40px" v-else />
          </span>
        </a>
      </div>
    </div>
    <div :class="$isMobile ? 'login-mobile' : ''">
      <div :class="$isMobile ? 'login-content-mobile' : 'login_content'">
        <el-radio-group v-model="labelPosition" class="radioGroup" size="small">
          <el-radio-button label="passwordLogin">密码登录</el-radio-button>
          <el-radio-button label="verificationLogin">验证码登录</el-radio-button>
        </el-radio-group>
        <el-form
          size="medium"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="login_form">
          <el-form-item v-if="labelPosition==='passwordLogin'" prop="email">
            <el-input
              prefix-icon="el-icon-message"
              style="background: #fff"
              v-model="ruleForm.email"
              placeholder="请输入手机号或者邮箱"></el-input>
          </el-form-item>
          <el-form-item  v-if="labelPosition==='passwordLogin'" prop="password" style="margin-bottom: 20px">
            <el-input
              :type="showPwd ? 'text' : 'password'"
              prefix-icon="el-icon-lock"
              style="background: #fff"
              v-model="ruleForm.password"
              placeholder="请输入密码"
              @keyup.enter.native="submitForm">
              <i
                @click="showPwd = !showPwd"
                slot="suffix"
                :class="{ eyes: true, open: !showPwd, close: showPwd }"></i>
            </el-input>
          </el-form-item>
          <el-form-item v-if="labelPosition==='verificationLogin'" prop="phone">
            <el-input
              prefix-icon="el-icon-phone"
              style="background: #fff"
              v-model="ruleForm.phone"
              placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item v-if="labelPosition==='verificationLogin'" prop="verifyKey" label="">
            <div style="display: flex; gap: 20px; margin-bottom: -10px;">
              <div style="flex: 1">
                <el-input
                  v-model="ruleForm.verifyKey"
                  prefix-icon="el-icon-postcard"
                  placeholder="请输入验证码,区分大小写">
                </el-input>
              </div>
              <div @click="getVerifycode">
                <img
                  style="width: 100px; height: 80%"
                  :src="VerifyUrl">
                </img>
              </div>
            </div>
          </el-form-item>
          <el-form-item  v-if="labelPosition==='verificationLogin'" prop="code" label="">
            <div style="display: flex; gap: 20px">
              <div style="flex: 1">
                <el-input
                  v-model="ruleForm.code"
                  prefix-icon="el-icon-message"
                  placeholder="请输入短信验证码"></el-input>
              </div>
              <div>
                <el-button
                  class="get-code-button"
                  style="width: 112px"
                  :disabled="getCodeDisabled"
                  :class="getCodeDisabled ? 'disabled' : 'code-btn'"
                  @click="verPhonecode">
                  {{
                    codeCountDown === 0 ? '获取验证码' : `${codeCountDown}秒`
                  }}
                </el-button>
              </div>
            </div>
          </el-form-item>
          <div class="forget-password">
            <span style="cursor: pointer" @click="forgetPassword">
              忘记密码?
            </span>
          </div>
          <div style="text-align: center">
            <button class="login-btn" @click="submitForm">登录</button>
          </div>
          <div style="margin-top: 40px; font-size: 14px; text-align: center">
            还没有账号？
            <router-link class="link" to="register">马上注册</router-link>
          </div>
        </el-form>
      </div>
    </div>

    <div
      class="modal"
      :style="isShowModal ? 'display: block' : 'display: none'">
      <div class="forget-form">
        <div class="forget-title">忘记密码</div>
        <el-form size="medium" :model="forgetForm" ref="forgetForm">
          <el-form-item
            v-if="labelPosition==='passwordLogin'"
            prop="email"
            label=""
            :rules="[{ required: true, message: '请输入邮箱地址', type: 'email' }]">
            <el-input
              v-model="forgetForm.email"
              prefix-icon="el-icon-postcard"
              style="background: #fff"
              placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item
            v-if="labelPosition==='passwordLogin'"
            prop="code"
            label=""
            :rules="[{ required: true, message: '请输入验证码' }]">
            <div style="display: flex; gap: 20px">
              <div style="flex: 1">
                <el-input
                  v-model="forgetForm.code"
                  style="background: #fff"
                  prefix-icon="el-icon-message"
                  placeholder="请输入验证码"></el-input>
              </div>
              <div>
                <el-button
                  class="get-code-button"
                  :disabled="getCodeDisabled"
                  :class="getCodeDisabled ? 'disabled' : 'code-btn'"
                  @click="verCode">
                  {{
                    codeCountDown === 0 ? '获取验证码' : `${codeCountDown}秒`
                  }}
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            v-if="labelPosition==='verificationLogin'"
            prop="phone"
            :rules="[{ required: true, message: '请输入手机号'}]">
            <el-input
              prefix-icon="el-icon-phone"
              style="background: #fff"
              v-model="forgetForm.phone"
              placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item
            v-if="labelPosition==='verificationLogin'"
            prop="verifyKey"
            label=""
            :rules="[{ required: true, message: '请输入验证码'}]">
            <div style="display: flex; gap: 20px; margin-bottom: -10px;">
              <div style="flex: 1">
                <el-input
                  v-model="forgetForm.verifyKey"
                  prefix-icon="el-icon-postcard"
                  placeholder="请输入验证码,区分大小写">
                </el-input>
              </div>
              <div @click="getVerifycode">
                <img
                  style="width: 100px; height: 80%"
                  :src="VerifyUrl">
                </img>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            v-if="labelPosition==='verificationLogin'"
            prop="code"
            label=""
            :rules="[{ required: true, message: '请输入短信验证码'}]">
            <div style="display: flex; gap: 20px">
              <div style="flex: 1">
                <el-input
                  v-model="forgetForm.code"
                  prefix-icon="el-icon-message"
                  placeholder="请输入短信验证码"></el-input>
              </div>
              <div>
                <el-button
                  class="get-code-button"
                  style="width: 112px"
                  :disabled="getCodeDisabled"
                  :class="getCodeDisabled ? 'disabled' : 'code-btn'"
                  @click="forgetPhonecode">
                  {{
                    codeCountDown === 0 ? '获取验证码' : `${codeCountDown}秒`
                  }}
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            prop="password"
            :rules="[{ required: true, message: '请输入新密码' }]">
            <el-input
              v-model="forgetForm.password"
              placeholder="请输入新密码"
              :type="showNewPwd ? 'text' : 'password'"
              prefix-icon="el-icon-lock"
              style="background-color: #fff">
              <i
                @click="showNewPwd = !showNewPwd"
                slot="suffix"
                :class="{
                  eyes: true,
                  open: !showNewPwd,
                  close: showNewPwd,
                }"></i>
            </el-input>
          </el-form-item>
          <el-form-item
            prop="confirmNewPassword"
            :rules="[
              {
                validator: validatePass,
                trigger: 'blur',
              },
            ]">
            <el-input
              v-model="forgetForm.confirmNewPassword"
              placeholder="请再次输入新密码"
              :type="showAgNewPwd ? 'text' : 'password'"
              prefix-icon="el-icon-lock"
              style="background-color: #fff">
              <i
                @click="showAgNewPwd = !showAgNewPwd"
                slot="suffix"
                :class="{
                  eyes: true,
                  open: !showAgNewPwd,
                  close: showAgNewPwd,
                }"></i>
            </el-input>
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <el-button class="reset-password" round @click="resetPassword">
              重置密码
            </el-button>
          </el-form-item>
          <div style="font-size: 14px">
            <span>无需重置</span>
            <span
              style="margin-left: 20px; color: #2f97f1; cursor: pointer"
              @click="isShowModal = false">
              登录
            </span>
          </div>
        </el-form>
        <i
          class="el-icon-circle-close close-icon"
          @click="isShowModal = false"></i>
      </div>
    </div>
  </div>
</template>

<script>
import { post, get } from '../utils/axios'
import md5 from 'js-md5'
import {mapMutations, mapState} from 'vuex'
export default {
  name: 'login',
  components: {},
  data() {
    return {
      validatePass: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.forgetForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      VerifyUrl:'',
      labelPosition: 'passwordLogin',
      isShowModal: false,
      ruleForm: {
        password: '',
        email: '',
        checked: false,
      },
      codeCountDown: 0,
      forgetForm: {},
      rules: {
        email: [{ required: true, message: '请输入邮箱或手机号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3,4,5,6,7,8,9][0-9]{9}$/,
            message: "请输入正确手机号码",
            trigger: ['blur', 'change'],
          }
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        verifyKey: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
      showPwd: false,
      showNewPwd: false,
      showAgNewPwd: false,
    }
  },
  computed: {
    getCodeDisabled() {
      return this.codeCountDown > 0
    },
  },
  mounted(){
    this.getVerifycode()
  },
  methods: {
    ...mapMutations(['setUserInfo']),
    async verCode() {
      try {
        await new Promise((resolve, reject) => {
          this.$refs.forgetForm.validateField('email', (m) => {
            m ? reject() : resolve()
          })
        })
      } catch {
        return
      }
      try {
        const res = await get('business/user/emailcode', {
          email: this.forgetForm.email,
        })
        this.codeCountDown = 60
        this.timer = setInterval(() => {
          this.codeCountDown--
          if (this.codeCountDown <= 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        this.$message.success(res.message)
      } catch (e) {
        console.error(e)
      }
    },
    async verPhonecode(){
      try {
        await new Promise((resolve, reject) => {
          this.$refs.ruleForm.validateField('phone', (m) => {
            m ? reject() : resolve()
          })
        })
      } catch {
        return
      }
      try {
        const res = await post('business/user/phonecode', {
          account: this.ruleForm.phone,
          verifyKey: this.verifyKeyTime,
          verifyCode: this.ruleForm.verifyKey
        })
        this.codeCountDown = 60
        this.timer = setInterval(() => {
          this.codeCountDown--
          if (this.codeCountDown <= 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        this.$message.success(res.message)
      } catch (e) {
        this.getVerifycode()
        console.error(e)
      }
    },
    async forgetPhonecode(){
      try {
        await new Promise((resolve, reject) => {
          this.$refs.forgetForm.validateField('phone', (m) => {
            m ? reject() : resolve()
          })
        })
      } catch {
        return
      }
      try {
        const res = await post('business/user/phonecode', {
          account: this.forgetForm.phone,
          verifyKey: this.verifyKeyTime,
          verifyCode: this.forgetForm.verifyKey
        })
        this.codeCountDown = 60
        this.timer = setInterval(() => {
          this.codeCountDown--
          if (this.codeCountDown <= 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        this.$message.success(res.message)
      } catch (e) {
        this.getVerifycode()
        console.error(e)
      }
    },
    forgetPassword() {
      this.getVerifycode()
      this.isShowModal = true
      this.forgetForm = {}
      this.codeCountDown = 0
      this.$nextTick(() => {
        this.$refs.forgetForm.clearValidate()
      })
    },
    // 重置密码
    resetPassword() {
      try {
        this.$refs.forgetForm.validate()
      } catch {
        return
      }
      try {
        const hash = md5.create()
        hash.update(this.forgetForm.password)

        const passwordHash = hash.hex()
        post('business/user/restPassword', {
          password: passwordHash,
          account: this.forgetForm.email ? this.forgetForm.email : this.forgetForm.phone,
          code: this.forgetForm.code
        }).then((res) => {
          if (res.code === 200) {
            this.$message.success('密码修改成功')
            this.isShowModal = false
          }
        })
      } catch (e) {
        console.error(e)
      }
    },
    submitForm(e) {
      e.preventDefault()
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let parmes = {}
          if(this.ruleForm.password){
            const hash = md5.create()
            hash.update(this.ruleForm.password)
            const passwordHash = hash.hex()
            parmes = {
              account: this.ruleForm.email ? this.ruleForm.email : this.ruleForm.phone,
              password: passwordHash,
            }
          }else{
            parmes = {
              account: this.ruleForm.email ? this.ruleForm.email : this.ruleForm.phone,
              code: this.ruleForm.code
            }
          }
          
          let url = `business/user/login`
          post(url, parmes).then((res) => {
            if (res.code === 200) {
              localStorage.setItem('userInfo', JSON.stringify(res.data))
              this.setUserInfo(JSON.parse(JSON.stringify(res.data)))
              this.ruleForm = {}
              this.$router.push('/contact')
            }
          })
        }
      })
    },
    getVerifycode(){
      this.verifyKeyTime = new Date().getTime();
      get('business/user/verifycode',{
        verifyKey: this.verifyKeyTime
      }).then((res)=>{
        if(res.code === 200){
          this.VerifyUrl = res.message
        }
      })
    }
  },
}
</script>
<style scoped>
.login-mobile {
  margin: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
  top: 50%;
  left: 0;
  right: 0;
  position: absolute;
  transform: translateY(-50%);
}

.login-content-mobile {
  padding: 20px;
}
.login-page {
  position: relative;
  width: 100%;
  height: 100vh;
  image-rendering: -webkit-optimize-contrast;
  background: url(../assets/banner.jpg) left / cover no-repeat;
}
.reset-password {
  width: 100%;
  background-image: linear-gradient(
    to right,
    #5192e1 0%,
    #23ced5 51%,
    #5192e1 100%
  );
  color: #fff;
}

.login_form::v-deep .el-form-item {
  margin-bottom: 40px;
}

.login_form::v-deep .el-input__inner {
  height: 42px;
  line-height: 42px;
}

.get-code-button:disabled:hover {
  background-color: #d0d2d8;
  color: #666;
}

.disabled {
  background-color: #d0d2d8;
  color: #666;
  margin-left: 10px;
}

.code-btn {
  background: linear-gradient(180deg, #319af2 0%, #2386ee 100%);
  color: #fff;
}

.forget-title {
  text-align: center;
  margin-bottom: 26px;
  font-size: 26px;
  font-weight: 400;
  letter-spacing: 2px;
}
.modal {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: #252d40;
  z-index: 3;
  transition: all 0.3s;
}

.forget-form {
  position: fixed;
  width: 36%;
  padding: 50px 60px;
  box-sizing: border-box;
  border-radius: 6px;
  top: 50%;
  left: 50%;
  background-color: #fff;
  transform: translate(-50%, -50%);
}

.forget-form .close-icon {
  position: fixed;
  top: -30px;
  right: -28px;
  font-size: 30px;
  color: #fff;
  cursor: pointer;
}
.logo {
  display: flex;
  align-items: center;
}
.logo_text {
  display: inline-block;
}
.banner_text {
  font-size: 28px;
  color: #fff;
  letter-spacing: 4px;
  display: flex;
  margin-left: 40px;
}
.login_bg {
  position: absolute;
  left: 7%;
  top: 7%;
}
.login_content {
  padding: 70px 40px;
  background: rgba(255, 255, 255, 1);
  position: absolute;
  top: 50%;
  left: 60%;
  border-radius: 10px;
  transform: translateY(-50%);
  box-sizing: border-box;
  box-shadow: 0 2px 4px rgb(0 0 0 / 12%), 0 0 6px rgb(0 0 0 / 4%);
}

.login_form {
  width: 330px;
  border-radius: 6px;
}

.forget-password {
  margin-bottom: 40px;
  text-align: right;
  font-size: 14px;
  color: #006eff;
}

.login-btn {
  width: 100%;
  height: 42px;
  display: block;
  margin: 0 auto;
  background: #006eff;
  box-shadow: 0 4px 8px 0 rgb(26 90 216 / 32%);
  border-radius: 4px;
  font-size: 18px;
  color: #fff;
  cursor: pointer;
}

.eyes {
  display: inline-block;
  height: 14px;
  width: 18px;
  margin-top: 11px;
  margin-right: 5px;
  cursor: pointer;
}
.eyes.open {
  background: url('../assets/eyes-open.png') no-repeat center / cover;
}
.eyes.close {
  background: url('../assets/eyes-closed.png') no-repeat center / cover;
}
.login-page::v-deep .el-input__inner::-ms-reveal,
.login-page::v-deep .el-input__inner::-ms-clear {
  display: none;
}
.radioGroup{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

@media screen and (max-width: 1100px) {
  .login-page {
    background: none;
    background-color: #edf0f5;
    height: 100vh;
    width: 100vw;
    overflow: hidden;
  }

  .login_bg {
    position: unset;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .login_form {
    width: unset;
    border-radius: 0;
  }

  .forget-form {
    width: 84vw;
    padding: 20px;
  }
}
</style>
