<template>
  <div class="login-wrap">
    <!-- header -->
    <div class="login--header">
      <div class="login--header--l">
        <div class="logo">
          <!-- prettier-ignore  -->
          SHOPDELI
        </div>
      </div>
      <div class="login--header--r"></div>
    </div>
    <!-- login -->
    <div class="login-box">
      <div class="login-l">
        <div class="login-l-center">
          <span class="logo">
            <!-- prettier-ignore  -->
            SHOPDELI
          </span>
          <!-- <p>We Make Scalable Mobility Life</p> -->
        </div>
      </div>
      <div class="login-r">
        <div class="tit-login">
          <strong>로그인</strong>
        </div>
        <div class="login-input-wrap">
          <div
            class="txt-field-box"
            :class="!loginForm.validCheck.input.userId ? 'error' : ''"
          >
            <v-text-field
              v-model="loginForm.userId"
              placeholder="아이디를 입력해주세요"
              class="custom-input"
              @keyup.enter="loginAction(loginForm.userId, loginForm.passwd)"
              @input="setInputField('main_userId')"
            ></v-text-field>
            <i class="ico"></i>
          </div>
          <div
            class="txt-field-box"
            :class="!loginForm.validCheck.input.passwd ? 'error' : ''"
          >
            <v-text-field
              v-model="loginForm.passwd"
              :type="visible ? 'text' : 'password'"
              placeholder="비밀번호를 입력해주세요"
              class="custom-input"
              id="password"
              @keyup.enter="loginAction(loginForm.userId, loginForm.passwd)"
              @input="setInputField('main_passwd')"
            ></v-text-field>
            <i
              class="ico-eye"
              @click.stop="toggleVisibility"
              :class="visible ? 'eye-on' : 'eye-off'"
            ></i>
            <i class="ico"></i>
          </div>
          <!-- <p class="error-txt" v-if="!loginForm.validCheck.inputErrorCheck">
            {{ loginForm.validCheck.passwd }}
          </p> -->
        </div>

        <div class="login-btn-wrap">
          <v-btn
            class="custom-btn btn-blue"
            @keyup.enter="loginAction(loginForm.userId, loginForm.passwd)"
            @click="loginAction(loginForm.userId, loginForm.passwd)"
            >로그인</v-btn
          >
        </div>
        <div class="join--btn--wrap">
          <v-btn class="custom-btn text--btn">아이디 찾기</v-btn>
          <v-btn class="custom-btn text--btn">비밀번호 찾기</v-btn>
          <v-btn class="custom-btn text--btn" @click="location('join')">회원가입</v-btn>
        </div>
        <div class="short--login--wrap">
          <v-btn class="btn--google" @click="onGoogleLogin"></v-btn>
          <v-btn class="btn--kakao"></v-btn>
          <v-btn class="btn--naver"></v-btn>
        </div>
      </div>
    </div>

    <!-- footer -->
    <div class="login-footer">
      <div class="login--footer--l">
        <p>COPYRIGHT@2025 SHOPDELI INC. ALL RIGHTS RESERVED.</p>
        <p>마포구 합정동</p>
      </div>
    </div>
  </div>
</template>

<script setup>
  /************************
   *    import
   ************************/
  //import PrivacyPop from "@/components/login/privacyPop.vue";
  //import AgrNPop from "@/components/terms/agreeNListPop.vue";
  import apiUrl from "@/composables/useApi";
  import QRCode from "qrcode";
  import { useI18n } from "vue-i18n";

  /************************
   *    layout setting
   ************************/
  definePageMeta({
    layout: "loginlayout",
  });

  /************************
   *    plugins inject
   ************************/
  const { $dayjs, $log, $eventBus, $toast, $userAgent } = useNuxtApp();

  const useStore = useDetailStore();
  /************************
   *    data & created
   ************************/
  // 현재 입력 중인 필드를 설정하는 함수
  const setInputField = (name) => {
    fnValidCheck(name);
  };
  const pageId = "login";
  const i18n = useI18n();
  // 다국어
  let listObj = ref({
    langTypeList: {},
  });
  // 로그인 정보
  const loginForm = ref({
    userId: "",
    passwd: "",
    otpNum: "",
    username: "",
    authType: "GOOGLE",
    userAgent: "",
    validCheck: {
      input: {
        userId: true,
        passwd: true,
      },
      otp: {
        otpNum: true,
      },
      inputErrorCheck: true,
      inputValidTxt: "",
      otpValidTxt: "",
      loginValidCheck: false,
      btnTxt: "",
      btnTxtType: "",
    },
  });
  // 구글 OTP 1차 팝업
  const authPop1 = ref({
    popYn: false,
    certifyYN: false,
    userId: "",
    passwd: "",
    otpNum: "",
    validOtpKey: true,
    validOtpTxt: "",
    btnTxt: "",
    btnTxtType: "",
    applyBtn: false,
    succOtpYn: false,
    businessName: "",
    agreeChk1: false,
    agreeChk2: false,
    validCheck: {
      userId: true,
      passwd: true,
    },
    validTxt: "",
    errorCheck: false,
  });
  // 구글 OTP 2차 팝업
  const authPop2 = ref({
    popYn: false,
    otpNum: "",
    validOtpKey: true,
    validOtpTxt: "",
    errorCheck: false,
  });
  // 아이디 찾기
  const findId = ref({
    popYn: false,
    //tenantName: '',
    email: "",
    otpNum: "",
    validCheck: {
      input: {
        //tenantName: true,
        email: true,
      },
      otp: {
        otpNum: true,
      },
      inputErrorCheck: true,
      inputValidTxt: "",
      otpValidTxt: "",
      findIdValidCheck: false,
    },
    btnTxt: "",
  });
  // 비밀번호 초기화
  const resetPw = ref({
    popYn: false,
    userId: "",
    email: "",
    otpNum: "",
    validCheck: {
      input: {
        userId: true,
        email: true,
      },
      otp: {
        otpNum: true,
      },
      inputErrorCheck: true,
      inputValidTxt: "",
      otpValidTxt: "",
      resetPwValidCheck: false,
    },
    btnTxt: "",
  });

  // 초기 패스워드 변경
  const initPw = ref({
    popYn: false,
    passwd: "",
    passwd2: "",
    validCheck: {
      passwd: true,
      passwd2: true,
    },
    passwdCheck: false,
    errorTxt: "",
  });

  const selectPlaceholder = ref("");
  const initAuthPop1 = ref({});
  const initAuthPop2 = ref({});
  const initFindId = ref({});
  const initResetPw = ref({});
  const initInitPw = ref({});
  const googleOtpQrCode = ref("");
  const googleOtpSecretKey = ref("");
  const loginInfo = ref({});
  const checkbox = ref(false);
  const langType = ref("");
  const toggleVisibility = () => {
    visible.value = !visible.value;
  };
  const visible = ref(false);
  const isAgrNPop = ref(false);
  const isShowAgrNPop = ref(false);
  let saveId = localStorage.getItem("saveId");
  if (saveId) {
    checkbox.value = true;
    loginForm.value.userId = saveId;
  }

  // 개인정보처리방침 이용약관 팝업
  //const privacyPop = ref(false);
  const privacyDetail = ref({
    kr: {
      title: "",
      contents: "",
    },
    en: {
      title: "",
      contents: "",
    },
  });
  const systemInfo = ref({
    mode: "",
  });

  const loginAction = (__ID, __PASS) => {
    let _req = {
      id: __ID,
      password: __PASS,
    };

    useAxios()
      .post("/roulette/login", _req)
      .then((res) => {
        if (res.data) {
          // console.log(res.data);
          useAuthStore().setAuth(res.data);
          useAuthStore().setAccessToken(res.data.accessToken);
          useAuthStore().setRefreshToken(res.data.refreshToken);
          localStorage.setItem("tempAccess", __ID);
          useUtil.setPageMove("/view/item");
          useStore.menuInfo.menuIndex = "0";
          useStore.menuInfo.menuId = "menu01";
          useStore.menuInfo.pageRtName = "제품 관리";
          useStore.menuInfo.pageStatus = null;
        }
      })
      .catch((error) => {
        if (error.response) {
          console.log("status:", error.response.status, "data:", error.response.data);
          // 안전하게 errCode, message 접근
          const errData = error.response.data || {};
          const errCode = errData.errCode || errData.errorCode || errData.code || "";
          const errMsg = errData.message || "알 수 없는 오류가 발생했습니다.";
          console.log("errCode:", errCode, "message:", errMsg);
        } else {
          console.log("error:", error.message, error.code);
        }
        if (error.response?.status) {
          fnLoginSet(error.response.data.messages.message);
        }
        $log.debug("[login][fnIdPwCheck][error]");
      })
      .finally(() => {
        $log.debug("[login][fnIdPwCheck][finished]");
      });
  };

  const location = (__id) => {
    switch (__id) {
      case "join":
        useUtil.setPageMove("/auth/join");
        break;
      case "findId":
        findId.value.popYn = true;
        break;
      case "resetPw":
        resetPw.value.popYn = true;
        break;
      default:
        break;
    }
  };

  // onMounted
  onMounted(() => {
    function handleMessage(event) {
      // 개발환경이면 아래처럼 확인
      if (
        event.origin === "http://0.0.0.0:3000" || //배포시 도메인 변경
        event.origin === "http://localhost:3000" //배포시 도메인 변경
      ) {
        const { accessToken, refreshToken, user } = event.data;

        if (user?.JOIN === "1") {
          useAuthStore().setTempData(user);
          useUtil.setPageMove("/auth/join");
        } else {
          //useAuthStore().setAuth(res.data);

          const result = {
            refreshToken: refreshToken,
            user: user,
          };

          //console.log(result);

          //return;

          useAuthStore().setTempData(result);
          useAuthStore().setAccessToken(accessToken);
          useAuthStore().setRefreshToken(refreshToken);
          localStorage.setItem("tempAccess", result.user.NICK_NAME);
          useUtil.setPageMove("/view/item");
          useStore.menuInfo.menuIndex = "0";
          useStore.menuInfo.menuId = "menu02";
          useStore.menuInfo.pageRtName = "이벤트 관리";
          useStore.menuInfo.pageStatus = null;
        }
      }
    }
    window.addEventListener("message", handleMessage);
    onBeforeUnmount(() => window.removeEventListener("message", handleMessage));
  });

  watchEffect(() => {
    // 감시하고자 하는 데이터를 해당 블럭내에서 사용하면 호출된다.
    // getLang.value를 감시하는 상태
    //QfnGetEnumCode(useLangStore().getLang);
  });

  // $eventBus.off("SET_SUCCESS_POPUP");
  // $eventBus.on("SET_SUCCESS_POPUP", () => {
  //   // 안내 팝업 확인 클릭 팝업 초기화처리
  //   fnOtpPopClose("findId");
  //   fnOtpPopClose("resetPw");
  // });

  // $eventBus.off("PASSWD_CHANGE");
  // $eventBus.on("PASSWD_CHANGE", () => {
  //   fnPasswdChange();
  // });

  // $eventBus.off("INIT_PASSWORD");
  // $eventBus.on("INIT_PASSWORD", () => {
  //   initPw.value.popYn = true;
  // });

  // $eventBus.off("SET_LOGIN");
  // $eventBus.on("SET_LOGIN", () => {
  //   fnLogin();
  // });
  /************************
   *    Methods
   ************************/

  const fnLoginSet = (__MSG) => {
    let param = {
      id: pageId,
      title: "로그인",
      content: __MSG,
      yes: {
        text: "확인",
        isProc: true,
        event: "FN_LOGIN",
        param: "",
      },
      no: {
        text: "취소",
        isProc: false,
      },
    };
    $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  };

  // 구글 로그인 버튼 클릭 시 호출
  function onGoogleLogin() {
    const clientId =
      "373780605211-diojebh7mug45urv9rnqdil6n0b1ogge.apps.googleusercontent.com"; // 실제 클라이언트 ID로 교체
    const redirectUri = "https://shopdeli.mycafe24.com/auth/callback"; // 실제 리디렉션 URI로 교체
    const scope = "openid email profile";
    const responseType = "code"; // 또는 'code' (백엔드 연동 시)
    const state = Math.random().toString(36).substring(2);

    const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&client_id=${clientId}&redirect_uri=${encodeURIComponent(
      redirectUri
    )}&response_type=${responseType}&scope=${encodeURIComponent(scope)}&state=${state}`;

    const width = 500;
    const height = 600;
    const dualScreenLeft =
      window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    const dualScreenTop =
      window.screenTop !== undefined ? window.screenTop : window.screenY;

    const currentWidth = window.innerWidth
      ? window.innerWidth
      : document.documentElement.clientWidth
      ? document.documentElement.clientWidth
      : screen.width;

    const currentHeight = window.innerHeight
      ? window.innerHeight
      : document.documentElement.clientHeight
      ? document.documentElement.clientHeight
      : screen.height;

    const left = dualScreenLeft + (currentWidth - width) / 2;
    const top = dualScreenTop + (currentHeight - height) / 2;

    window.open(
      googleAuthUrl,
      "googleLogin",
      `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
    );
  }

  /**
   * @API
   * 최종 로그인 버튼 클릭 시 API
   */
  function fnLogin(__USERID, __USERPASS) {
    // 파라미터 전달 값 [아이디, 비밀번호, otpNum, 브라우저정보]
    //userId: loginForm.value.userId,
    // let _req = {
    //   username: loginForm.value.userId,
    //   password: btoa(loginForm.value.passwd),
    // };

    localStorage.setItem("tempAccess", __USERID);

    if (__USERID == "admin" && __USERPASS == "1234") {
      useUtil.setPageMove("/view/media/newsList");
    } else {
      fnLoginSet("비밀번호가 맞지 않습니다. 확인해주세요.");
    }
    // useAxios()
    //   .post(apiUrl.otpCheck, _req)
    //   .then((res) => {
    //     loginInfo.value = res.data.data;
    //     useAuthStore().setAccessToken(loginInfo.value.accessToken);
    //     useAuthStore().setRefreshToken(loginInfo.value.refreshToken);

    //     // OTP key체크 성공 후 개인정보에 대한 API를 호출 한다.
    //     fnServiceModeCheck();
    //     $log.debug("[login][fnLogin][success]");
    //   })
    //   .catch((error) => {
    //     $log.debug("[login][fnLogin][error]");
    //     let errorData = error.response.data;
    //     errorData.type = "fnLogin";
    //     fnLoginFail(errorData);
    //   })
    //   .finally(() => {
    //     $log.debug("[login][fnLogin][finished]");
    //   });
  }
</script>
