<template>
  <div class="login" :style="'background-image:url(' + Background + ');'">
    <el-form
      ref="loginForm"
      :model="state.loginForm"
      :rules="state.loginRules"
      label-position="left"
      label-width="0px"
      class="login-form"
    >
      <h3 class="title">银收客后台管理</h3>
      <el-form-item>
        <el-radio-group v-model="state.loginForm.loginType">
          <el-radio-button :value="0">商户</el-radio-button>
          <el-radio-button :value="1">员工</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
          v-model="state.loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="商户号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="staffUserName" v-if="state.loginForm.loginType == 1">
        <el-input
          v-model="state.loginForm.staffUserName"
          type="text"
          auto-complete="off"
          placeholder="账号"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="state.loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin"
        ></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <div class="code_wrap">
          <el-input
            v-model="state.loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter="handleLogin"
          ></el-input>
          <div class="login-code">
            <img :src="state.codeUrl" @click="getCode" />
          </div>
        </div>
      </el-form-item>

      <el-form-item style="width: 100%">
        <el-button
          :loading="state.loading"
          size="default"
          type="primary"
          style="width: 100%"
          @click.prevent="handleLogin"
        >
          <span v-if="!state.loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div id="el-login-footer">
      <span>⋅</span>
      <a href="https://beian.miit.gov.cn/#/Integrated/index" target="_blank"></a>
    </div>
  </div>
</template>

<script setup>
import { encrypt } from "@/utils/rsaEncrypt";
import $API_login from "@/api/account/login";
import { $douyin_checkIn } from "@/api/coup/index";
import Cookies from "js-cookie";
import Background from "@/assets/images/background_img.jpg";
import { useUserStore } from "@/store";
import { useRoute } from "vue-router";
import router from "@/router";
const route = useRoute();

const state = reactive({
  Background: Background,
  codeUrl: "",
  cookiePass: "",
  loginForm: {
    username: "ymf",
    password: "123456",
    // rememberMe: false,
    code: "",
    uuid: "",
    staffUserName: "",
    loginType: 0,
  },
  loginRules: {
    username: [{ required: true, trigger: "blur", message: "商户号不能为空" }],
    password: [{ required: true, trigger: "blur", message: "密码不能为空" }],
    code: [{ required: true, trigger: "change", message: "验证码不能为空" }],
    staffUserName: [{ required: true, trigger: "change", message: "用户名不能为空" }],
  },
  loading: false,
  redirect: undefined,
});

watch(
  () => state.loginForm.loginType,
  (newval) => {
    if (1) {
      delete state.loginForm.staffUserName;
    } else {
      state.loginForm.staffUserName = "";
    }
  }
);

onMounted(() => {
  // 获取验证码
  getCode();
  // // 获取用户名密码等Cookie
  // this.getCookie()
  // // token 过期提示
  // this.point()

  let getinfo = localStorage.getItem("MerchantId");
  let info = JSON.parse(getinfo);
  if (info && info.staffUserName) {
    state.loginForm.staffUserName = info.staffUserName;
    state.loginForm.username = info.username;
  }
});
function getCode() {
  $API_login.getCaptcha().then((res) => {
    console.log(res);
    state.codeUrl = res.code;
    state.loginForm.uuid = res.uuid;
  });
}
function getCookie() {
  const username = Cookies.get("username");
  let password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  // 保存cookie里面的加密后的密码
  state.cookiePass = password === undefined ? "" : password;
  password = password === undefined ? state.loginForm.password : password;
  state.loginForm = {
    username: username === undefined ? state.loginForm.username : username,
    password: password,
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
    code: "",
    loginType: 0,
  };
}

const loginForm = ref(null);
const userStore = useUserStore();

/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect() {
  const query = route.query;
  const redirect = query.redirect ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}
function handleLogin() {
  loginForm.value.validate((valid) => {
    if (valid) {
      state.loading = true;
      const user = { ...state.loginForm };
      //      user.password = encrypt(user.password);
      console.log(user);
      userStore
        .login(user)
        .then(async (res) => {
          await userStore.getUserInfo();
          await $douyin_checkIn();

          const { path, queryParams } = parseRedirect();
          console.log(res, "Denglv返回");
          router.push({ path: path, query: queryParams });
        })
        .catch(() => {
          state.loading = false;
        });
    } else {
      console.log("error submit!!");
      return false;
    }
  });
}
</script>

<style scoped lang="scss">
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-size: cover;
  padding-right: 15%;
}

.title {
  margin: 0 auto 50px auto;
  text-align: center;
  color: #707070;
  font-size: 36px;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 500px;
  padding: 50px 50px 50px 50px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

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

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.code_wrap {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.login-code {
  width: 33%;
  display: inline-block;
  height: 38px;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>
