<template>
    <div class="user-wrap">
        <div class="content-box">
            <div class="title-wrap">
                <div class="flex-start">
                    <img src="../../../../resources/jpg/user-icon.png" alt="회원관리 아이콘" class="title-icon">
                    <h2 class="main-title">회원관리</h2>
                </div>
            </div>
            <div class="content-wrap">
                <div class="user grid" v-show="user.user_id != null">
                    <div>
                        <p class="label-title"><i class="fa-solid fa-user-group"></i> 아이디</p>
                        <input type="text" v-model="user.user_id" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-user-group"></i> 비밀번호</p>
                        <button class="gray-btn" @click="resetPassword">비밀번호 초기화</button>
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-check-double"></i> 회원구분</p>
                        <input type="text" v-model="user.user_auth" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-heart"></i> 이름</p>
                        <input type="text" v-model="user.user_nm" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-envelope"></i> 이메일</p>
                        <input type="text" v-model="user.user_eml" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-envelope"></i> 가입 날짜</p>
                        <input type="text" v-model="user.user_reg_dt" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-envelope"></i> 승인 날짜</p>
                        <input type="text" v-model="user.approval_dt" disabled />
                    </div>
                </div>
                <div class="admin grid" v-show="admin.mngr_id != null">
                    <div>
                        <p class="label-title"><i class="fa-solid fa-user-group"></i> 아이디</p>
                        <input type="text" v-model="admin.mngr_id" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-user-group"></i> 비밀번호</p>
                        <button class="gray-btn" @click="openModal">비밀번호 변경</button>
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-heart"></i> 이름</p>
                        <input type="text" v-model="admin.mngr_nm" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-envelope"></i> 이메일</p>
                        <input type="text" v-model="admin.mngr_eml" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-envelope"></i> 등록자</p>
                        <input type="text" v-model="admin.rgtr_id" disabled />
                    </div>
                    <div>
                        <p class="label-title"><i class="fa-solid fa-envelope"></i> 가입 날짜</p>
                        <input type="text" v-model="admin.reg_dt" disabled />
                    </div>
                </div>
                <div class="btn-wrap">
                    <button class="dark-gray-btn" @click="adminSelectListPage()">목록</button>
                    <button class="red-btn" v-if="user.create_account_approval === 'N'"
                        @click="confirmCheck(user.user_id)">승인</button>
                </div>
            </div>
        </div>

    </div>
    <div v-show="showpwchange" class="pwchange2">
        <div class="pwchange-div">
            <p>비밀번호 변경하기</p>
            <div>
                <ul>
                    <li>
                        <span>현재 비밀번호</span>
                        <input type="password" v-model="presentPwd">
                    </li>
                    <li>
                        <span>변경할 비밀번호</span>
                        <input type="password" v-model="changePwd">
                    </li>
                    <li>
                        <span>비밀번호 확인</span>
                        <input type="password" v-model="changePwdCheck">
                    </li>
                </ul>
            </div>
            <div class="btn-wrap">
                <button @click="closeModal" class="dark-gray-btn">이전</button>
                <button @click="checkPwd" class="blue-btn">변경하기</button>
            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import { useRoute } from 'vue-router';
import { useStore } from "vuex";
import crypto from "crypto-js";

export default {
    data() {
        return {
            user: {
                approval_dt: null,
                approval_mngr_id: null,
                company_id: null,
                create_account_approval: null,
                use_yn: null,
                user_auth: null,
                user_eml: null,
                user_id: null,
                user_nm: null,
                user_reg_dt: null,
            },
            admin: {
                mdfcn_dt: null,
                mdfr_id: null,
                mngr_eml: null,
                mngr_id: null,
                mngr_nm: null,
                reg_dt: null,
                rgtr_id: null,
            },
            route: useRoute(),
            showpwchange: false,
            presentPwd: null,
            changePwd : null,
            changePwdCheck : null,
            store: useStore(),
        };
    },
    methods: {
        openModal() {
            this.showpwchange = true;
        },

        closeModal() {
            this.showpwchange = false;
        },
        userSelectOne: function () {
            const vm = this;
            axios({
                url: '/user/userSelectOne.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'user_id': vm.route.query.user_id }
            }).then(function (response) {
                vm.user = response.data
            }).catch(function (error) {
                console.log("error - ", error)
                alert("사용자 상세보기 오류, 관리자에게 문의하세요.");
            })
        },
        adminSelectOne: function () {
            const vm = this;
            axios({
                url: '/managerSelectOne.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'mngr_id': vm.route.query.mngr_id }
            }).then(function (response) {
                vm.admin = response.data
            }).catch(function (error) {
                console.log("error - ", error)
                alert("관리자 상세보기 오류, 관리자에게 문의하세요.");
            })
        },

        //사용자 승인
        approval: function (userId) {
            const vm = this;
            axios({
                url: '/user/userApproval.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { user_id: userId }
            }).then(function (response) {
                if (response.data > 0) {
                    alert(userId + " 님에 대한 승인이 완료되었습니다.");
                }
            }).catch(function (error) {
                console.log("approval - error : ", error);
                alert('승인오류, 관리자에게 문의해주세요.');
            });
        },
        //사용자 승인을 위한 confirm창
        confirmCheck: function (userId) {
            var confirmation = confirm(userId + " 사용자를 승인 하시겠습니까?");
            if (confirmation) {
                this.approval(userId);
            } else {
                alert(userId + " 님에 대한 승인을 취소하였습니다. 확인 후 재승인 해주시기 바랍니다.")
            }
        },

        checkPwd: function() {
            const vm = this;
            if (vm.changePwd == null){
                alert("변경할 비밀번호를 입력해주세요.")
                return;
            } else if(vm.changePwdCheck == null) {
                alert("비밀번호 확인을 입력해주세요.")
                return;
            } else if (vm.changePwd !== vm.changePwdCheck) {
                alert("비밀번호가 불일치합니다.");
                return;  
            }
            
            var iv = vm.store.state.key.iv;
            var salt = vm.store.state.key.salt;
            var passPhrase = vm.store.state.key.ENC_KEY;
            var keySize = 128;
            var iterationCount = 1000;
            var key128Bits100Iterations = crypto.PBKDF2(passPhrase, crypto.enc.Hex.parse(salt), { keySize: keySize / 32, iterations: iterationCount });

            let encryptedMngrId = crypto.AES.encrypt(vm.admin.mngr_id, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();
            let encryptedMngrPw = crypto.AES.encrypt(vm.presentPwd, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let mngr = {
                mngr_id: encryptedMngrId,
                mngr_pw: encryptedMngrPw
            };

            axios({
                url: '/mngrCheckPresentPwd.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: mngr
            }).then(function (response) {
                if(response.data == 1){
                    vm.changePassword()
                } else {
                    alert("현재 비밀번호가 일치하지 않습니다.");
                    vm.changePwd = null;
                    vm.changePwdCheck = null;
                }
            }).catch(function (error) {
                console.log("checkPwd - error : ", error);
            });
        },

        changePassword: function() {
            const vm = this;

            var iv = vm.store.state.key.iv;
            var salt = vm.store.state.key.salt;
            var passPhrase = vm.store.state.key.ENC_KEY;
            var keySize = 128;
            var iterationCount = 1000;
            var key128Bits100Iterations = crypto.PBKDF2(passPhrase, crypto.enc.Hex.parse(salt), { keySize: keySize / 32, iterations: iterationCount });

            let encryptedMngrId = crypto.AES.encrypt(vm.admin.mngr_id, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();
            let encryptedMngrPw = crypto.AES.encrypt(vm.changePwd, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let mngr = {
                mngr_id: encryptedMngrId,
                mngr_pw: encryptedMngrPw
            };

            axios({
                url: '/mngrPwUpdate.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: mngr
            }).then(function (response) {
                if(response.data == 1){
                    alert('비밀번호 변경에 성공하였습니다.')
                    vm.changePwd = null;
                    vm.presentPwd = null;
                    vm.changePwdCheck = null;
                    vm.closeModal()
                } else {
                   alert('비밀번호 변경에 실패하였습니다.') 
                }
            }).catch(function (error) {
                console.log("changePassword - error : ", error);
            });
        },

        resetPassword: function() {
            const vm = this;
            
            var confirmation = confirm(vm.user.user_id + " 사용자의 비밀번호를 아이디와 동일하게 초기화 하시겠습니까?");
            if (!confirmation) {
                alert('초기화를 취소하였습니다.')
                return;
            }

            var iv = vm.store.state.key.iv;
            var salt = vm.store.state.key.salt;
            var passPhrase = vm.store.state.key.ENC_KEY;
            var keySize = 128;
            var iterationCount = 1000;
            var key128Bits100Iterations = crypto.PBKDF2(passPhrase, crypto.enc.Hex.parse(salt), { keySize: keySize / 32, iterations: iterationCount });

            let encryptedUserId = crypto.AES.encrypt(vm.user.user_id, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();
            let encryptedUserPw = crypto.AES.encrypt(vm.user.user_id, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let user = {
                user_id: encryptedUserId,
                user_pw: encryptedUserPw
            };
            
            axios({
                url: '/user/resetUserPwd.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: user
            }).then(function (response) {
                if(response.data == 1){
                    alert('비밀번호 초기화에 성공하였습니다.')
                } else {
                   alert('비밀번호 초기화에 실패하였습니다.') 
                }
            }).catch(function (error) {
                console.log("changePassword - error : ", error);
            });
        },

        //리스트 페이지로 이동
        adminSelectListPage: function () {
            this.$router.push({ path: '/adm/userSelectList.page', query: {} });
        },
    },
    watch: {},
    computed: {},
    components: {},
    mounted() {
        if (this.route.query.user_id) {
            this.userSelectOne();
        } else if (this.route.query.mngr_id) {
            this.adminSelectOne();
        }
    },
};
</script>
<style scoped></style>
