<template>
    <div class="content">
        <div class="sub-title-area mb-110">
            <h2>로그인</h2>
            <div class="breadcrumb-list">
                <ul>
                    <!-- Bind the image source dynamically for homeicon -->
                    <li><img :src="homeicon" alt="Home Icon"></li>
                    <li><img :src="righticon" alt="Home Icon"></li>
                    <li>로그인</li>
                </ul>
            </div>
        </div>
        <form action="login" class="login-form">
            <dl>
                <dd class="mb-25">
                    <label for="id">아이디</label>
                    <input type="text" id="id"  placeholder="아이디를 입력하세요." v-model="member['loginId']">
                </dd>

                <dd class="mb-10">
                    <label for="pw">비밀번호</label>
                    <input type="password" id="pw"  placeholder="비밀번호를 입력하세요." v-model="member['password']"
                        @keyup.enter="fnLogin">
                </dd>
                <dd class="check-area flex-end mb-25">
                    <input type="checkbox" class="margin-top">
                    <label for="save">아이디 저장</label>
                </dd>
            </dl>
            <!-- Bind the image source dynamically for loginicon -->
            <button type="button" @click="fnLogin"><img :src="loginicon" alt="Login Icon"><span>로그인</span></button>
        </form>
    </div>
</template>

<script>
import { useStore } from "vuex";
import axios from "axios";

export default {
    data() {
        return {
            // Define the image sources
            homeicon: 'client/resources/images/icon/home.png',
            loginicon: 'client/resources/images/icon/lock.png',
            righticon: 'client/resources/images/icon/right.png',

            member: {
                loginId: null,
                password: null,
            },
            store: useStore(),
        };
    },
    methods: {
        async fnLogin() {
            try {
                const response = await axios.post("/user/login.json", this.member, {
                    headers: {
                        "Content-Type": "application/json; charset=UTF-8",
                    },
                });

                console.log(response); // 응답 확인

                if (response.status === 200) {
                    const newToken = response.headers.authorization;
                    this.store.commit("setAuthorization", newToken);

                    // JWT 디코딩
                    const mbr = this.decodeJwt(newToken);
                    if (mbr) {
                        this.store.commit("setUserId", mbr.userId);
                        this.store.commit("setLoginId", mbr.loginId);
                        this.store.commit("setUserNm", mbr.userNm);
                        this.store.commit("setRoles", mbr.roles);
                    }

                    // 리다이렉트 처리
                    this.$router.push("/");
                }
            } catch (error) {
                console.error("Login error:", error);
                const message = error.response?.data?.message || "로그인에 실패했습니다.";
                alert(message);
            }
        },
        decodeJwt(token) {
            const base64String = token.split(".")[1];
            const base64 = base64String.replace(/-/g, "+").replace(/_/g, "/");
            const jsonPayload = decodeURIComponent(
                atob(base64)
                    .split("")
                    .map(c => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
                    .join("")
            );
            return JSON.parse(jsonPayload);
        }
    },
    watch: {},
    computed: {},
    components: {},
    created() { },
    mounted() { },
};
</script>
