<template>
  <div class="login" id="loginBox">
    <div class="login-con">
      <div class="img-box">
        <img src="../assets/images/login_left.png" alt="">
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">互联网医院医生端</h3>
        <el-form-item>
          <el-radio-group v-model="loginForm.type">
            <el-radio-button label="1">医生</el-radio-button>
            <el-radio-button label="2">药剂师</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="account">
          <el-input v-model="loginForm.account" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </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="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>{{companyName}}</span>
      <a :href="icpUrl" target="_blank">{{icpRecord}}</a>
    </div>
  </div>
</template>

<script>
import { imConfig } from '@/utils/im'
import { getCodeImg } from "@/api/common";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      companyName: process.env.VUE_APP_COMPANY_NAME,
      icpRecord: process.env.VUE_APP_ICP_RECORD,
      icpUrl: process.env.VUE_APP_ICP_URL,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        account: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        type: '1',
      },
      loginRules: {
        account: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      loading: false,
    };
  },
  watch: {
    $route: {
      handler: function(route) {
      },
      immediate: true
    }
  },
  mounted() {
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      }).catch(err => {
        this.$message.error("验证码获取失败，请刷新重试");
        console.error("验证码接口异常：", err);
      });
    },
    // 读取Cookie中的账号密码
    getCookie() {
      const account = Cookies.get("account");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe');

      // 保留原有loginForm属性（如type），仅覆盖Cookie中存在的值
      this.loginForm = {
        ...this.loginForm,
        account: account || this.loginForm.account,
        password: password ? decrypt(password) : this.loginForm.password,
        rememberMe: rememberMe !== undefined ? Boolean(rememberMe) : this.loginForm.rememberMe
      };
    },
    // 登录核心逻辑
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (!valid) return; // 表单校验失败直接返回

        this.loading = true;
        // 处理记住密码逻辑
        if (this.loginForm.rememberMe) {
          Cookies.set("account", this.loginForm.account, { expires: 30 });
          Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
          Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
        } else {
          Cookies.remove("account");
          Cookies.remove("password");
          Cookies.remove('rememberMe');
        }

        this.$store.dispatch("Login", this.loginForm)
          .then((res) => {
            const loginType = res.doctor.doctorType;
            const userRole = loginType === 1 ? 'doctor' : 'nurse';
            localStorage.setItem('loginType', loginType);
            localStorage.setItem('userRole', userRole);

            // 登录成功跳转首页
            this.$router.push({ path: "/index" });
            this.$message.success("登录成功！");
          })
          .catch((err) => {
            // 登录失败处理
            this.loading = false;
            this.getCode(); // 刷新验证码
            this.$message.error(err.message || "登录失败，请检查账号密码或验证码");
            console.error("登录异常：", err);
          });
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-image: linear-gradient(#0e68c3, #1e99f5);
  background-size: cover;

  .login-con {
    width: 750px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 10px;
    overflow: hidden;
    background: #ffffff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .img-box {
      width: 460px;
      height: 460px;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
  font-size: 18px;
  font-weight: 500;
}

.login-form {
  box-sizing: border-box;
  background: #ffffff;
  width: 330px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }

  .el-radio-group {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
  }

  .el-radio-button {
    margin: 0 15px;
  }
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
    height: 100%;
    width: 100%;
    object-fit: cover;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
  border-radius: 4px;
}

.el-radio-button__inner {
  border-radius: 20px !important;
  padding: 0 20px;
}
</style>
