<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <lottie-web-cimo
        ref="lottie_web"
        animation-name="meeting"
        style="width: 85%; max-width: 95%; height: 12%; margin: auto"
      />
      <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"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip
        v-model="capsTooltip"
        content="Caps lock is On"
        placement="right"
        manual
      >
        <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="Password"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
      >登录组内系统</el-button>

      <div style="position: relative">
        <el-button type="primary" @click="registerDialogVisible = true">
          没有账号？立即注册
        </el-button>

        <el-button type="primary" @click="showDialog = true">
          使用第三方账号登录
        </el-button>
      </div>
    </el-form>

    <!-- 第三方登录弹窗 -->
    <el-dialog
      title="或者使用第三方账号登录"
      :visible.sync="showDialog"
      width="400px"
      class="register-dialog"
    >
      后续使用微信或者qq扫码登录
      <br>
      <br>
      <br>
      <social-sign />
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
      title="用户注册"
      :visible.sync="registerDialogVisible"
      width="400px"
      class="register-dialog"
      :before-close="handleClose"
    >
      <el-form
        ref="registerForm"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            :type="registerPasswordType"
            placeholder="请输入密码"
          >
            <i
              slot="suffix"
              :class="
                registerPasswordType === 'password'
                  ? 'el-icon-view'
                  : 'el-icon-view'
              "
              style="cursor: pointer; padding: 8px"
              @click="toggleRegisterPasswordVisibility"
            />
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            :type="confirmPasswordType"
            placeholder="请再次输入密码"
          >
            <i
              slot="suffix"
              :class="
                confirmPasswordType === 'password'
                  ? 'el-icon-view'
                  : 'el-icon-view'
              "
              style="cursor: pointer; padding: 8px"
              @click="toggleConfirmPasswordVisibility"
            />
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="registerDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="registerLoading"
          @click="handleRegister"
        >注 册</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SocialSign from './components/SocialSignin'
import LottieWebCimo from '@/components/LottieWeb/lottie-web-cimo'
import { post } from '@/boot/axios_request'

export default {
  name: 'Login',
  components: { SocialSign, LottieWebCimo },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'))
      } else {
        callback()
      }
    }

    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '用户名长度在1到15个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ]
      },

      // 注册相关数据
      registerDialogVisible: false,
      registerLoading: false,
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '用户名长度在1到15个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      registerPasswordType: 'password',
      confirmPasswordType: 'password',

      // 其他数据保持不变
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    // 注册相关方法
    toggleRegisterPasswordVisibility() {
      this.registerPasswordType =
        this.registerPasswordType === 'password' ? 'text' : 'password'
    },
    toggleConfirmPasswordVisibility() {
      this.confirmPasswordType =
        this.confirmPasswordType === 'password' ? 'text' : 'password'
    },
    handleClose(done) {
      this.$refs.registerForm.resetFields()
      done()
    },
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.registerLoading = true

          // 模拟注册请求
          post('register/', {
            name: this.registerForm.username,
            password1: this.registerForm.password,
            password2: this.registerForm.confirmPassword
          })
            .then((res) => {
              if (res.code === '200') {
                this.registerLoading = false
                this.$notify({
                  title: '注册成功',
                  message: '账号已成功创建，请使用新账号登录',
                  type: 'success'
                })
                this.registerDialogVisible = false
                localStorage.setItem('openid', res.data.openid)
                // 自动填充注册信息到登录表单
                this.loginForm.username = this.registerForm.username
                this.loginForm.password = this.registerForm.password
                this.$nextTick(() => {
                  this.$refs.password.focus()
                })
              } else {
                this.registerLoading = false
                this.$notify({
                  title: '注册失败',
                  message: res.msg,
                  type: 'error'
                })
              }
            })
            .finally(() => {
              this.registerLoading = false
            })
        } else {
          this.registerLoading = false
          console.log('表单验证不通过')
          return false
        }
      })
    },

    // 原有方法保持不变
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true

          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              // 登录成功后获取用户信息
              return this.$store.dispatch('user/getInfo')
            })
            .then(() => {
              // 跳转到首页
              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery
              })
            })
            .catch((error) => {
              // 显示错误通知
              this.$notify({
                title: '登录失败',
                message: error.message || '用户名或密码错误',
                type: 'error',
                duration: 5000
              })
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
$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;
  }
}

/* 注册弹窗样式 */
.register-dialog {
  .el-dialog {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);

    &__header {
      background-color: #409eff;
      padding: 15px 20px;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;

      .el-dialog__title {
        color: #fff;
        font-weight: bold;
      }

      .el-dialog__headerbtn {
        top: 15px;
        .el-dialog__close {
          color: #fff;
        }
      }
    }

    &__body {
      padding: 20px 25px;

      .el-form-item {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-input__inner {
          height: 38px;
          line-height: 38px;
          color: #000; /* 设置输入框文字颜色为黑色 */
        }

        .el-form-item__error {
          padding-top: 4px;
        }
      }
    }

    &__footer {
      padding: 10px 20px 20px;
      text-align: center;

      .el-button {
        width: 100px;
        margin: 0 10px;
      }
    }
  }
}
</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;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
