<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="admin-company">
                    <div class="company-zone">
                        <div class="company-grid">
                            <div class="logo-img">
                                <img :src="'http://211.253.8.180:8082' + logoFile.file_path + '/' + logoFile.file_nm + '.' + logoFile.file_extn_nm"
                                    alt="">
                            </div>
                            <table>
                                <tbody>
                                    <tr>
                                        <td>
                                            <P class="company-label">업체명</P>
                                            <P>{{ company.company_nm }}</P>
                                        </td>
                                        <td>
                                            <p class="company-label">사업자등록번호</p>
                                            <p>{{ company.company_id }}</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <p class="company-label">주소</p>
                                            <p>[{{ company.company_zip }}] {{ company.company_addr }} {{
                                                company.company_daddr }}</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <p class="company-label">홈페이지</p>
                                            <p>{{ company.company_hp_url }}</p>
                                        </td>
                                        <td>
                                            <p class="company-label">대표전화</p>
                                            <p>{{ company.company_telno }}</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <p class="company-label">업체 키워드</p>
                                            <p class="keyword-grid">
                                                <span class="keyword"
                                                    v-for="(keyword, index) in company.keyword.slice(1).split('#')"
                                                    :key="index">
                                                    #{{ keyword }}
                                                </span>
                                            </p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <p class="company-label">회사소개서 첨부파일</p>
                                            <p>
                                                <a style="font-size: 15px;" class="down-btn-1"
                                                    :href="'http://211.253.8.180:8082' + proFile.file_path + '/' + proFile.file_nm + '.' + proFile.file_extn_nm"
                                                    target='_blank' download>
                                                    {{ proFile.real_file_nm }}
                                                </a>
                                            </p>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="company-introduce">
                            <details open>
                                <summary @click="getViewer(0)">기업소개</summary>
                                <div class="introduce-content">
                                    <span v-html="company.company_info"></span>
                                </div>
                            </details>
                            <details open>
                                <summary @click="getViewer(1)">대표 기술 소개</summary>
                                <div class="introduce-content">
                                    <span v-html="company.company_technology"></span>
                                </div>
                            </details>
                            <details open>
                                <summary @click="getViewer(2)">서비스 소개</summary>
                                <div class="introduce-content">
                                    <span v-html="company.company_service"></span>
                                </div>
                            </details>
                        </div>
                    </div>
                    <div class="user-zone">
                        <div class="user-grid">
                            <div class="business-card">
                                <img :src="'http://211.253.8.180:8082' + cardFile.file_path + '/' + cardFile.file_nm + '.' + cardFile.file_extn_nm"
                                    alt="">
                            </div>
                            <div class="user grid">
                                <div>
                                    <p class="label-title"><i class="fa-solid fa-user-group"></i> 아이디</p>
                                    <input type="text" disabled v-model="user.user_id" />
                                </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" disabled :value="user.user_auth == 'common' ? '일반회원' : '기업회원'" />
                                </div>
                                <div>
                                    <p class="label-title"><i class="fa-solid fa-heart"></i> 이름</p>
                                    <input type="text" disabled v-model="user.user_nm" />
                                </div>
                                <div>
                                    <p class="label-title"><i class="fa-solid fa-envelope"></i> 이메일</p>
                                    <input type="text" disabled v-model="user.user_eml" />
                                </div>
                                <div>
                                    <p class="label-title"><i class="fa-solid fa-envelope"></i> 가입 날짜</p>
                                    <input type="text" disabled :value="yyyymmdd(user.user_reg_dt)" />
                                </div>
                                <div>
                                    <p class="label-title"><i class="fa-solid fa-envelope"></i> 승인 날짜</p>
                                    <input type="text" disabled :value="yyyymmdd(user.approval_dt)" />
                                </div>
                            </div>
                        </div>
                    </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";
import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer';
import '@toast-ui/editor/dist/toastui-editor.css';
import '@toast-ui/editor/dist/i18n/ko-kr';
import COMMON_UTIL from '../../../../resources/js/commonUtil.js';

export default {
    data() {
        return {
            fileList: [],
            logoFile: {},
            cardFile: {},
            proFile: {},
            company: {
                company_id: null,
                company_nm: null,
                company_info: null,
                company_point: null,
                company_technology: null,
                company_service: null,
                company_simple_info: null,
                company_zip: null,
                company_addr: null,
                company_daddr: null,
                company_hp_url: null,
                company_telno: null,
                file_id: null,
                user_id: null,
                keyword: '',
                company_matching_cnt: null,
                company_pick_cnt: null,
            },
            user: {
                user_id: null,
                user_pw: null,
                user_eml: null,
                user_auth: null,
                user_nm: null,
                subscribe: null,
                approval_mngr_id: null,
                create_account_approval: null,
                approval_dt: null,
                user_reg_dt: null,
            },
            route: useRoute(),
            showpwchange: false,
            store: useStore(),
        };
    },
    methods: {
        openModal() {
            this.showpwchange = true;
        },

        closeModal() {
            this.showpwchange = false;
        },

        //날짜 시,분,초 자르기
        yyyymmdd: function (date) {
            return COMMON_UTIL.yyyymmdd(date);
        },

        userSelectOne: function () {
            const vm = this;
            axios({
                url: '/user/myPageUserSelectOne.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'user_id': vm.route.query.user_id }
            }).then(function (response) {
                vm.user.user_id = response.data.user_id;
                vm.user.user_eml = response.data.user_eml;
                vm.user.user_nm = response.data.user_nm;
                vm.user.user_auth = response.data.user_auth;
                vm.user.user_reg_dt = response.data.user_reg_dt;
                vm.user.approval_dt = response.data.approval_dt;
                vm.user.subscribe = response.data.subscribe;
                vm.user.create_account_approval = response.data.create_account_approval
                vm.companySelectOne();
            }).catch(function (error) {
                console.log("userSelectOne - error : ", error);
            });
        },

        companySelectOne: function () {
            const vm = this;
            axios({
                url: '/company/selectOneForMypage.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: { 'user_id': vm.user.user_id }
            }).then(function (response) {
                vm.company = response.data.result
                if (response.data.selectFileList.length != 0) {
                    vm.fileList = response.data.selectFileList;
                    for (let i = 0; i < vm.fileList.length; i++) {
                        if (vm.fileList[i].file_ty == "logo") {
                            vm.logoFile = vm.fileList[i];
                        } else if (vm.fileList[i].file_ty == "card") {
                            vm.cardFile = vm.fileList[i]
                        } else if (vm.fileList[i].file_ty == "profile") {
                            vm.proFile = vm.fileList[i]
                        }

                    }
                }
            }).catch(function (error) {
                console.log("companySelectOne - error : ", error);
            });
        },

        getViewer(idx) {
            const vm = this;
            let data = [vm.company.company_info, vm.company.company_technology, vm.company.company_service][idx];
            this.viewer = new Viewer({
                el: this.$refs[`viewer${idx + 1}`],
                initialEditType: 'wysiwyg',
                previewStyle: 'vertical',
                initialValue: data,
                customHTMLRenderer: {
                    htmlBlock: {
                        iframe(node) {
                            return [
                                { type: 'openTag', tagName: 'iframe', outerNewLine: true, attributes: node.attrs },
                                { type: 'html', content: node.childrenHTML },
                                { type: 'closeTag', tagName: 'iframe', outerNewLine: true },
                            ];
                        },
                    }
                },
            });
        },


         //사용자 승인
         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 + " 님에 대한 승인을 취소하였습니다. 확인 후 재승인 해주시기 바랍니다.")
            }
        },
        //리스트 페이지로 이동
        adminSelectListPage: function () {
            this.$router.push({ path: '/adm/userSelectList.page', query: {} });
        },

        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);
            });
        },

    },
    watch: {},
    computed: {},
    components: {},
    mounted() {
        this.userSelectOne()
    },
};
</script>
<style scoped></style>
