<template>
  <div class="login-container">
    <!-- 背景装饰元素 -->
    <div class="login-bg-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>

    <!-- 主登录卡片 -->
    <div class="login-card">
      <!-- 系统logo和标题 -->
      <div class="login-header">
        <div class="logo">
          <svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
            <path d="M32 0C14.3 0 0 14.3 0 32s14.3 32 32 32 32-14.3 32-32S49.7 0 32 0zm0 60C16.5 60 4 47.5 4 32S16.5 4 32 4s28 12.5 28 28-12.5 28-28 28z" fill="#1890ff"/>
            <path d="M32 12c-11 0-20 9-20 20s9 20 20 20 20-9 20-20-9-20-20-20zm0 36c-8.8 0-16-7.2-16-16s7.2-16 16-16 16 7.2 16 16-7.2 16-16 16z" fill="#1890ff"/>
            <path d="M32 20c-6.6 0-12 5.4-12 12s5.4 12 12 12 12-5.4 12-12-5.4-12-12-12zm0 20c-4.4 0-8-3.6-8-8s3.6-8 8-8 8 3.6 8 8-3.6 8-8 8z" fill="#1890ff"/>
            <path d="M32 28c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4z" fill="#1890ff"/>
          </svg>
        </div>
        <h1 class="system-name">政策沟通交流系统</h1>
        <p class="system-description">Integrated Operations Management System</p>
      </div>

      <!-- 登录表单 -->
      <div class="login-form">
        <el-form ref="loginForm" :model="loginForm" :rules="LoginRules" class="form-content">
          <!-- 租户输入框 -->
          <el-form-item prop="tenantName" v-if="tenantEnable">
            <el-input
              v-model="loginForm.tenantName"
              type="text"
              auto-complete="off"
              placeholder="请输入租户名称"
              prefix-icon="el-icon-office-building">
            </el-input>
          </el-form-item>

          <!-- 账号密码登录 -->
          <div v-if="loginForm.loginType === 'uname'">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="请输入账号"
                prefix-icon="el-icon-user">
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="请输入密码"
                @keyup.enter.native="getCode"
                prefix-icon="el-icon-lock">
                <i slot="suffix" class="el-icon-view password-eye" @click="togglePasswordVisibility"></i>
              </el-input>
            </el-form-item>

            <div class="form-options">
              <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
<!--              <el-link type="primary" class="forget-password" @click="showForgetDialog">忘记密码?</el-link>-->
            </div>
          </div>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              class="login-btn"
              @click.native.prevent="getCode">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>

          <!-- 底部链接 -->
          <div class="form-footer">
            <a
              href="#"
              class="btn-trsids"
              @click.prevent="loginWithTRSids"
            >
              集约化平台认证登录
            </a>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 页脚 -->
    <div class="login-footer">
      <p>© 2025 政策沟通交流系统 | 技术支持: IT运维部</p>
    </div>

    <!-- 图形验证码组件 -->
    <Verify ref="verify" :captcha-type="'blockPuzzle'" :img-size="{width:'400px',height:'200px'}"
            @success="handleLogin" />

    <!-- 忘记密码对话框 -->
    <el-dialog title="找回密码" :visible.sync="forgetDialogVisible" width="30%">
      <el-form>
        <el-form-item label="账号">
          <el-input placeholder="请输入您的账号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input placeholder="请输入注册时使用的邮箱"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="forgetDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="forgetDialogVisible = false">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {idsLogin, sendSmsCode, smsLogin, socialAuthRedirect} from "@/api/login";
import {getTenantIdByName} from "@/api/system/tenant";
import {getCaptchaEnable, getTenantEnable} from "@/utils/ruoyi";
import {
  getPassword,
  getRememberMe, getTenantName,
  getUsername,
  removePassword, removeRememberMe, removeTenantName,
  removeUsername,
  setPassword, setRememberMe, setTenantId, setTenantName, setToken,
  setUsername
} from "@/utils/auth";
import Verify from '@/components/Verifition/Verify';

export default {
  name: "Login",
  components: {
    Verify
  },
  data() {
    return {
      forgetDialogVisible: false,
      passwordVisible: false,
      codeUrl: "",
      captchaEnable: true,
      tenantEnable: true,
      mobileCodeTimer: 0,
      loginForm: {
        loginType: "uname",
        username: "",
        password: "",
        captchaVerification: "",
        mobile: "",
        mobileCode: "",
        rememberMe: false,
        tenantName: "",
      },
      scene: 21,

      LoginRules: {
        username: [
          {required: true, trigger: "blur", message: "用户名不能为空"}
        ],
        password: [
          {required: true, trigger: "blur", message: "密码不能为空"}
        ],
        tenantName: [
          {required: true, trigger: "blur", message: "租户不能为空"},
          {
            validator: (rule, value, callback) => {
              getTenantIdByName(value).then(res => {
                const tenantId = res.data;
                if (tenantId && tenantId >= 0) {
                  setTenantId(tenantId)
                  callback();
                } else {
                  callback('租户不存在');
                }
              });
            },
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      redirect: undefined
    };
  },
  created() {
    this.tenantEnable = getTenantEnable();
    if (this.tenantEnable) {
      getTenantIdByName(this.loginForm.tenantName).then(res => {
        const tenantId = res.data;
        if (tenantId && tenantId >= 0) {
          setTenantId(tenantId)
        }
      });
    }
    this.captchaEnable = getCaptchaEnable();
    this.redirect = this.$route.query.redirect ? decodeURIComponent(this.$route.query.redirect) : undefined;
    this.getCookie();
  },
  methods: {
    togglePasswordVisibility() {
      this.passwordVisible = !this.passwordVisible;
      const input = this.$refs.loginForm.$el.querySelector('input[type="password"]');
      if (input) {
        input.type = this.passwordVisible ? 'text' : 'password';
      }
    },
    showForgetDialog() {
      this.forgetDialogVisible = true;
    },
    getCode() {
      if (!this.captchaEnable) {
        this.handleLogin({})
        return;
      }
      this.$refs.verify.show()
    },
    getCookie() {
      const username = getUsername();
      const password = getPassword();
      const rememberMe = getRememberMe();
      const tenantName = getTenantName();
      this.loginForm = {
        ...this.loginForm,
        username: username ? username : this.loginForm.username,
        password: password ? password : this.loginForm.password,
        rememberMe: rememberMe ? getRememberMe() : false,
        tenantName: tenantName ? tenantName : this.loginForm.tenantName,
      };
    },
    handleLogin(captchaParams) {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            setUsername(this.loginForm.username)
            setPassword(this.loginForm.password)
            setRememberMe(this.loginForm.rememberMe)
            setTenantName(this.loginForm.tenantName)
          } else {
            removeUsername()
            removePassword()
            removeRememberMe()
            removeTenantName()
          }
          this.loginForm.captchaVerification = captchaParams.captchaVerification
          this.$store.dispatch(this.loginForm.loginType === "sms" ? "SmsLogin" : "Login", this.loginForm).then(() => {
            this.$router.push({path: this.redirect || "/"}).catch(() => {
            });
          }).catch(() => {
            this.loading = false;
          });
        }
      });
    },
    getSmsCode() {
      if (this.mobileCodeTimer > 0) return;
      this.$refs.loginForm.validate(valid => {
        if (!valid) return;
        sendSmsCode(this.loginForm.mobile, this.scene, this.loginForm.uuid, this.loginForm.code).then(res => {
          this.$modal.msgSuccess("获取验证码成功")
          this.mobileCodeTimer = 60;
          let msgTimer = setInterval(() => {
            this.mobileCodeTimer = this.mobileCodeTimer - 1;
            if (this.mobileCodeTimer <= 0) {
              clearInterval(msgTimer);
            }
          }, 1000);
        });
      });
    },
    loginWithTRSids() {
      idsLogin().then(res => {
        let authUrl = res.data;
        window.location.href = authUrl;
      }).catch(error => {
        this.$message.error('操作失败: ' + error.message);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .login-bg-decoration {
    position: absolute;
    width: 100%;
    height: 100%;

    .circle {
      position: absolute;
      border-radius: 50%;
      background: rgba(24, 144, 255, 0.1);
    }

    .circle-1 {
      width: 600px;
      height: 600px;
      top: -300px;
      right: -300px;
    }

    .circle-2 {
      width: 400px;
      height: 400px;
      bottom: -200px;
      left: -200px;
    }

    .circle-3 {
      width: 200px;
      height: 200px;
      bottom: 100px;
      right: 100px;
    }
  }

  .login-card {
    width: 420px;
    padding: 40px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    z-index: 1;

    .login-header {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        width: 80px;
        height: 80px;
        margin: 0 auto 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f0f7ff;
        border-radius: 50%;

        svg {
          width: 40px;
          height: 40px;
        }
      }

      .system-name {
        font-size: 24px;
        color: #1890ff;
        margin-bottom: 8px;
        font-weight: 600;
      }

      .system-description {
        font-size: 14px;
        color: #999;
        margin: 0;
      }
    }

    .login-form {
      .form-content {
        .el-input {
          ::v-deep .el-input__inner {
            height: 44px;
            line-height: 44px;
            padding-left: 40px;
          }

          ::v-deep .el-input__prefix {
            display: flex;
            align-items: center;
            left: 10px;
          }
        }

        .password-eye {
          cursor: pointer;
          color: #c0c4cc;
          margin-right: 10px;

          &:hover {
            color: #1890ff;
          }
        }

        .form-options {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;

          .forget-password {
            font-size: 13px;
          }
        }

        .login-btn {
          width: 100%;
          height: 44px;
          font-size: 16px;
          margin-top: 10px;
          background: #1890ff;
          border: none;

          &:hover {
            background: #40a9ff;
          }
        }

        .form-footer {
          text-align: center;
          margin-top: 20px;
          display: flex;
          flex-direction: column;
          align-items: center;

          .btn-trsids {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 44px;
            padding: 0 15px;
            background-color: #1890ff;
            color: white;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s;
            border: 1px solid #1890ff;
            margin-bottom: 15px;
            text-decoration: none;

            &:hover {
              background-color: #40a9ff;
              border-color: #40a9ff;
              color: white;
            }

            &:active {
              background-color: #096dd9;
              border-color: #096dd9;
            }
          }

          .el-divider {
            background-color: #dcdfe6;
          }

          .el-link {
            font-size: 12px;
          }
        }
      }
    }
  }

  .login-footer {
    margin-top: 30px;
    text-align: center;
    font-size: 12px;
    color: #999;
    z-index: 1;
  }
}

@media (max-width: 768px) {
  .login-container {
    padding: 20px;

    .login-card {
      width: 100%;
      padding: 30px 20px;
    }
  }
}
</style>
