<template>
  <div class="login-container">
    <img
      style="position: fixed; width: 100%; height: 100%; z-index: -1; left: 0; top: 0; object-fit: cover; object-position: center"
      src="../../assets/images/background.png"
    />
    <h1 class="main-title">天津市林草资源专项调查管理平台</h1>
    <el-form
      autocomplete="on"
      :model="loginForm"
      :rules="loginRules"
      ref="loginForm"
      label-position="left"
      label-width="0px"
      class="card-box login-form"
    >
      <p class="title">任务调度系统</p>
      <el-form-item prop="username">
        <el-input
          name="username"
          type="text"
          v-model="loginForm.username"
          autocomplete="on"
          placeholder="用户名"
          prefix-icon="el-icon-user"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          name="password"
          :type="pwdType"
          @keyup.enter.native="handleLogin"
          v-model="loginForm.password"
          autocomplete="on"
          placeholder="密码"
          prefix-icon="el-icon-lock"
        >
          <i
            slot="suffix"
            :class="pwdType === 'password' ? 'el-icon-view' : 'el-icon-hide'"
            @click="showPwd"
            style="cursor: pointer;"
          ></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login-button"
          :loading="loading"
          @click.native.prevent="handleLogin"
          >登录</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button class="register-button" @click.native.prevent="toRegister"
          >注册</el-button
        >
      </el-form-item>
      <div class="extra-text">
        <router-link
          :to="{ path: '/modifypassword' }"
          class="login-text1"
          title="修改密码"
          >修改密码</router-link
        >
        <router-link
          :to="{ path: '/forgetpassword' }"
          class="login-text"
          title="忘记密码"
          >忘记密码</router-link
        >
      </div>
    </el-form>
    <span style="position: fixed; bottom: 10px; left: 10px; color: lightgray"
      >v20251006</span
    >
    
    <!-- 数据初始化失败提示对话框 -->
    <el-dialog
      title="数据初始化失败"
      :visible.sync="initErrorVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="400px"
    >
      <div style="text-align: center; padding: 20px 0;">
        <i class="el-icon-warning" style="font-size: 48px; color: #E6A23C; margin-bottom: 16px;"></i>
        <p style="font-size: 16px; color: #606266; margin-bottom: 20px;">{{ initErrorMessage }}</p>
      </div>
      <div slot="footer" style="text-align: center;">
        <el-button type="primary" @click="retryInit" :loading="loading">重试</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ajax as request } from "@/request.js";
import md5 from "js-md5";
import { store } from "@/components/vuex/store.js";
export default {
  name: "login",
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能小于6位"));
      } else {
        callback();
      }
    };
    return {
      myname: myname,
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          // { min: 5, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePass },
        ],
      },
      loading: false,
      pwdType: "password",
      initErrorVisible: false,
      initErrorMessage: "",
    };
  },
  methods: {
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          let that = this;
          that.loading = true;

          // sessionStorage.setItem("access-user", "Admin");
          // that.$router.push({ path: "/view" });
          request({
            url: "/user/login",
            method: "post",
            params: {
              username: that.loginForm.username,
              password: md5(md5(that.loginForm.password)),
            },
          }).then(function (response) {
            //获取数据存入config
            if (response.data.success == true) {
              sessionStorage.setItem("access-user", response.data.data.role);
              sessionStorage.setItem("access-id", response.data.data.id);
              
              // 初始化任务数据
              that.initTaskData();
            } else if (response.data.status == "204") {
              that
                .$confirm("用户信息不完善，是否去完善信息？", "提示", {
                  cancelButtonText: "取消",
                  confirmButtonText: "确定",
                  type: "warning",
                })
                .then(() => {
                  that.loading = false;
                  that.$router.push({ path: "/addinfo" });
                })
                .catch(() => {
                  that.loading = false;
                  that.$notify.error({
                    title: "提示",
                    message: "登录失败",
                  });
                });
            } else {
              that.$notify.error({
                title: "提示",
                message: response.data.message,
              });
              that.loading = false;
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    toRegister() {
      this.$router.push({ path: "/register" });
    },
    // 初始化任务数据
    async initTaskData() {
      let that = this;
      const result = await store.dispatch('initTaskData');
      
      if (result.success) {
        // 初始化成功，根据用户角色跳转
        that.loading = false;
        if (
          sessionStorage.getItem("access-user") == "Admin" ||
          sessionStorage.getItem("access-user") == "SuperAdmin" ||
          sessionStorage.getItem("access-user") == "Leader"
        ) {
          // 检查当前路径，避免重复导航
          if (that.$route.path !== "/view") {
            that.$router.push({ path: "/view" }).catch(err => {
              // 忽略 NavigationDuplicated 错误
              if (err.name !== 'NavigationDuplicated') {
                console.error('路由导航错误:', err)
              }
            })
          }
        } else if (sessionStorage.getItem("access-user") == "Operator") {
          // 检查当前路径，避免重复导航
          if (that.$route.path !== "/main") {
            that.$router.push({ path: "/main" }).catch(err => {
              // 忽略 NavigationDuplicated 错误
              if (err.name !== 'NavigationDuplicated') {
                console.error('路由导航错误:', err)
              }
            })
          }
        } else {
          that.$notify.error({
            title: "提示",
            message: "用户不可登录该系统！",
          });
        }
      } else {
        // 初始化失败，显示错误提示
        that.loading = false;
        that.initErrorMessage = result.error || "数据初始化失败，请重试";
        that.initErrorVisible = true;
      }
    },
    // 重试初始化
    retryInit() {
      this.initErrorVisible = false;
      this.loading = true;
      this.initTaskData();
    },
  },
};
</script>

<style scoped rel="stylesheet/scss" lang="scss">
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  overflow: hidden;
}
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background: linear-gradient(160deg, rgba(232, 245, 233, 0.95), rgba(248, 253, 249, 0.9));
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 80px 20px 40px;
  overflow-y: auto;
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
  }
  .title {
    font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
    font-size: 24px;
    font-weight: 650;
    color: #1b5e20;
    background: linear-gradient(135deg, rgba(129, 199, 132, 0.2) 0%, rgba(200, 230, 201, 0.2) 100%);
    width: 100%;
    height: 70px;
    line-height: 70px;
    margin: 0;
    padding: 0;
    text-align: center;
    border-radius: 16px 16px 0 0;
    border-bottom: 1px solid rgba(129, 199, 132, 0.25);
  }
  .el-form-item {
    margin-left: 30px;
    margin-right: 30px;
    margin-top: 0;
    margin-bottom: 0;
    width: calc(100% - 60px);
    height: auto;
    min-height: 50px;
    background: transparent !important;
    border: none !important;
    border-radius: 0 !important;
    transition: all 0.3s ease;
    &:hover {
      background: transparent !important;
      border: none !important;
    }
    &:focus-within {
      background: transparent !important;
      border: none !important;
    }
    &:first-of-type {
      margin-top: 24px;
    }
    &:not(:first-of-type):not(:nth-of-type(3)):not(:nth-of-type(4)) {
      margin-top: 14px;
    }
  }
  .el-form-item__content {
    background: transparent !important;
    border: none !important;
    display: flex;
    align-items: center;
    width: 100%;
    position: relative;
  }
  .el-form-item__error {
    padding-left: 32px !important;
    margin-left: 32px !important;
    
  }
  .el-input {
    display: inline-block;
    height: 50px;
    width: 100%;
    flex: 1;
    min-width: 0;
  }
  input {
    background: rgba(255, 255, 255, 0.85) !important;
    border: 1px solid rgba(129, 199, 132, 0.4) !important;
    padding: 14px 12px;
    font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
    font-size: 15px;
    color: #1b5e20;
    border-radius: 12px;
    transition: all 0.3s ease;
    height: 50px;
    line-height: 50px;
  }
  .el-input__inner {
    background: transparent !important;
    border: none !important;
    &::placeholder {
      color: #4e7d4f;
      font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
      font-size: 15px;
      opacity: 0.7;
    }
    &:focus {
      border: none !important;
    }
  }
  .main-title {
    margin: 0 0 32px 0;
    font-family: "PingFang SC", "Microsoft YaHei", "SimHei", "STHeiti", "Helvetica Neue", Arial, sans-serif;
    font-size: 60px;
    font-weight: 700;
    color: #1b5e20;
    text-align: center;
    width: 100%;
    z-index: 1;
    text-shadow: 0 8px 30px rgba(27, 94, 32, 0.2);
    letter-spacing: 4px;
    line-height: 1.4;
    padding: 0 30px 120px 30px;
    box-sizing: border-box;
    animation: titleFadeIn 0.8s ease-out;
    &::after {
      content: '';
      position: absolute;
      left: 50%;
      bottom: -6px;
      transform: translateX(-50%);
      width: 150px;
      height: 4px;
      background: linear-gradient(90deg, transparent 0%, rgba(129, 199, 132, 0.6) 20%, #4caf50 50%, rgba(129, 199, 132, 0.6) 80%, transparent 100%);
      border-radius: 2px;
      box-shadow: 0 2px 8px rgba(76, 175, 80, 0.35);
    }
  }
  @keyframes titleFadeIn {
    from {
      opacity: 0;
      transform: translateY(-30px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }
  .login-form {
    margin: 0 auto 40px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(18px);
    -webkit-backdrop-filter: blur(18px);
    box-shadow: 0 12px 36px rgba(76, 175, 80, 0.18),
                0 4px 12px rgba(0, 0, 0, 0.08),
                inset 0 1px 0 rgba(255, 255, 255, 0.7);
    border-radius: 24px;
    border: 1px solid rgba(129, 199, 132, 0.35);
    width: 420px;
    min-height: 450px;
    padding-bottom: 20px;
    transition: all 0.3s ease;
    animation: slideUp 0.6s ease-out;
  }
  @keyframes slideUp {
    from {
      opacity: 0;
      transform: translateY(30px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  // 按钮容器的间距调整
  .el-form-item:nth-of-type(3) {
    margin-top: 24px !important;
  }
  .el-form-item:nth-of-type(4) {
    margin-top: 12px !important;
  }
  .login-button {
    width: 100%;
    height: 46px;
    margin: 0;
    background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%) !important;
    border: none !important;
    border-radius: 12px !important;
    font-family: PingFangSC-Regular;
    font-size: 16px;
    font-weight: 600;
    color: #ffffff !important;
    letter-spacing: 1px;
    text-align: center;
    box-shadow: 0 4px 14px rgba(76, 175, 80, 0.35),
                0 2px 4px rgba(76, 175, 80, 0.2);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(76, 175, 80, 0.45),
                  0 4px 8px rgba(76, 175, 80, 0.25);
      background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%) !important;
    }
    &:active {
      transform: translateY(0);
      box-shadow: 0 3px 10px rgba(76, 175, 80, 0.35),
                  0 1px 3px rgba(76, 175, 80, 0.18);
    }
  }
  .register-button {
    width: 100%;
    height: 46px;
    margin: 0;
    background: rgba(255, 255, 255, 0.95) !important;
    border: 1.5px solid #4caf50 !important;
    border-radius: 12px !important;
    font-family: PingFangSC-Regular;
    font-size: 16px;
    font-weight: 600;
    color: #2e7d32 !important;
    letter-spacing: 1px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(76, 175, 80, 0.25),
                0 1px 3px rgba(76, 175, 80, 0.12);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    cursor: pointer;
    &:hover {
      transform: translateY(-2px);
      background: rgba(76, 175, 80, 0.08) !important;
      border-color: #66bb6a !important;
      border-width: 1.5px !important;
      box-shadow: 0 4px 14px rgba(76, 175, 80, 0.3),
                  0 2px 6px rgba(76, 175, 80, 0.15);
      color: #2e7d32 !important;
    }
    &:active {
      transform: translateY(0);
      box-shadow: 0 2px 6px rgba(76, 175, 80, 0.25),
                  0 1px 2px rgba(76, 175, 80, 0.15);
    }
  }
  .login-text1 {
    position: absolute;
    left: 30px;
    font-size: 13px;
    color: #4e7d4f;
    font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
    text-decoration: none;
    transition: all 0.3s ease;
    &:hover {
      color: #1b5e20;
      text-decoration: underline;
    }
  }
  .login-text {
    position: absolute;
    right: 30px;
    font-size: 13px;
    color: #4e7d4f;
    font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
    text-decoration: none;
    transition: all 0.3s ease;
    &:hover {
      color: #1b5e20;
      text-decoration: underline;
    }
  }
  // Element UI 输入框图标样式
  .el-input__prefix,
  .el-input__suffix {
    color: #6f946f;
    transition: all 0.3s ease;
  }
  .el-form-item:focus-within .el-input__prefix,
  .el-form-item:focus-within .el-input__suffix {
    color: #1b5e20;
  }
  .el-input__suffix {
    cursor: pointer;
    &:hover {
      color: #1b5e20;
    }
  }
  .extra-text {
    position: relative;
    margin: 16px 30px 0 30px;
    padding: 0;
    width: calc(100% - 60px);
  }
}
@media all and (max-width: 480px) {
  .main-title {
    font-size: 28px;
    letter-spacing: 2px;
    padding: 0 20px 12px 20px;
    line-height: 1.4;
  }
  .login-form {
    width: 90% !important;
    max-width: 340px !important;
    margin: 0 auto 40px;
    border-radius: 16px;
  }
  .login-container .login-button,
  .login-container .register-button {
    width: 100% !important;
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  .login-container .login-button {
    margin-top: 32px !important;
    margin-bottom: 0 !important;
    height: 46px !important;
    font-size: 16px !important;
  }
  .login-container .register-button {
    margin-top: 16px !important;
    margin-bottom: 0 !important;
    height: 46px !important;
    font-size: 16px !important;
  }
  .login-container .el-form-item {
    width: calc(100% - 40px) !important;
    margin-left: 20px !important;
    margin-right: 20px !important;
  }
  .login-container .extra-text {
    margin-left: 20px !important;
    margin-right: 20px !important;
    width: calc(100% - 40px) !important;
  }
  .title {
    border-radius: 16px 16px 0 0;
  }
}
</style>