<template>
    <div class="news-wrap">
        <div class="content-box">
            <div class="title-wrap">
                <div class="flex-start">
                    <img src="../../../../resources/jpg/mail-icon.png" alt="메일 아이콘" class="title-icon">
                    <h2 class="main-title">메일발송 관리</h2>
                </div>
            </div>
            <div class="content-wrap">
                <table class="insert-table">
                    <tbody>
                        <tr>
                            <th>받는사람</th>
                            <td>
                                <div class="flex mail-write">
                                    <input type="text" name="" id="user" v-model="to">
                                    <button class="blue-btn" @click="modalType = 'userList'">주소록</button>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th>제목</th>
                            <td><input type="text" name="" id="newsTitle" v-model="subject"></td>
                        </tr>
                        <tr>
                            <th>내용</th>
                            <td><textarea name="smart" id="smart" style="width:100%"></textarea></td>
                        </tr>
                    </tbody>
                </table>
                <div class="btn-wrap">
                    <button class="dark-gray-btn">임시저장</button>
                    <button class="gray-btn" @click="selectList">이전</button>
                    <button class="blue-btn" @click="openSendModal">전송</button>
                </div>
            </div>
        </div>
        <div v-show="isModalOpen" class="modal-wrapper">
            <div class="modal-container mail-modal">
                <div class="modal-title">
                    <h2>주소 추가</h2>
                </div>
                <div v-show="modalType == 'userList'" class="modal-content-monthly">
                    <div class="search-zone flex">
                        <input type="text" class="user-search" v-model="searchKeyword" />
                        <button class="blue-btn" @click="searchUsers">검색</button>
                    </div>
                    <div class="list-zone">
                        <div class="user-list">
                            <p>사용자 선택</p>
                            <ul>
                                <li><input type="checkbox" v-model="toggleOptions.selectCompany" id="companyAll"
                                        class="user-li" @change="toggleChnage('selectCompany')">
                                    <label for="companyAll" v-bind:style="{ color: 'red' }">기업회원(전체)</label>
                                </li>
                                <li><input type="checkbox" v-model="toggleOptions.selectNormal" id="commonAll"
                                        class="user-li" @change="toggleChnage('selectNormal')">
                                    <label for="commonAll" v-bind:style="{ color: 'red' }">일반회원(전체)</label>
                                </li>
                                <li><input type="checkbox" v-model="toggleOptions.selectAll" id="all" class="user-li"
                                        @change="toggleChnage('selectAll')">
                                    <label for="all" v-bind:style="{ color: 'red' }">전체선택</label>
                                </li>
                                <hr>
                                <li v-for="(user, index) in searchedUsers" :key="index">
                                    <input type="checkbox" v-model="selectedUsers" :id="'customer' + index" :value="user"
                                        @change="toggleChnage('selectUser')">
                                    <label :for="'customer' + index" v-if="user.is_company === 'Yes'"> {{ user.company_nm }}
                                        (기업)</label>
                                    <label :for="'customer' + index" v-else> {{ user.user_nm }} (일반)</label>
                                </li>
                            </ul>
                        </div>
                        <div class="select-list">
                            <p>선택된 사용자</p>
                            <ul>
                                <li v-for="(user, index) in selectedUsers" :key="index" class="flex">
                                    <p v-if="user.is_company === 'Yes'"> {{ user.company_nm }} (기업)</p>
                                    <p v-else> {{ user.user_nm }} (일반)</p>
                                    <button class="red-border-btn small-btn" @click="removeUser(index)">삭제</button>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="modal-end">
                    <button class="dark-gray-btn small-btn" @click="closeModal">취소</button>
                    <button class="blue-btn small-btn" @click="managerInsert">저장</button>
                </div>
            </div>
        </div>
        <div v-show="isSendModalOpen" class="modal-wrapper">
            <div class="modal-container">
                <div class="modal-content-monthly alert-modal">
                    <p>해당 메일을 발송하시겠습니까?</p>
                </div>
                <div class="modal-end">
                    <button class="dark-gray-btn  small-btn" @click="closeSendModal()">취소</button>
                    <button class="blue-btn  small-btn" @click="sendMail">확인</button>
                </div>
            </div>
        </div>

    </div>
</template>
<script>
import '@toast-ui/editor/dist/toastui-editor.css';
import axios from 'axios';

export default {
    data() {
        return {
            oEditors: [], // oEditors는 스마트에디터용
            // 모달창 오픈 상태
            isModalOpen: false,
            isSendModalOpen: false,
            // 모달창 타입
            modalType: null,

            // user 배열
            users: [],
            selectedUsers: [], // 선택된 유저 
            searchedUsers: [], // 검색된 유저
            searchKeyword: '', // 검색 키워드

            emailList: "",

            // 주소록 토글 옵션
            toggleOptions: {
                selectCompany: false,
                selectNormal: false,
                selectAll: false,
            },

            // api 접근 토큰
            accessToken: null,
            to: '',  // 받는 사람
            subject: '',  // 제목
            content: '',  // 내용
            userName: ''	// 보내는 사람 이름
        };
    },
    methods: {
        // 모달 메서드
        openModal: function () {
            this.userMailList();
            this.isModalOpen = true;
        },

        closeModal: function () {
            this.isModalOpen = false;
            console.log("1");
            this.modalType = null;
            console.log("2");
            this.selectedUsers = []; // 모달 닫히며 검색, 선택 초기화
            this.searchKeyword = [];
            this.searchKeyword = '';
            this.toggleOptions.selectAll = false;
            this.toggleOptions.selectCompany = false;
            this.toggleOptions.selectNormal = false;
        },

        // 전송창 모달 메서드
        openSendModal: function () {
            this.isSendModalOpen = true;
        },

        closeSendModal: function () {
            this.isSendModalOpen = false;
        },

        // 주소록에서 유저 삭제 
        removeUser: function (index) {
            this.selectedUsers.splice(index, 1);
            this.toggleOptions.selectAll = false;
            this.toggleOptions.selectCompany = false;
            this.toggleOptions.selectNormal = false;
        },

        // 선택된 사용자 메일 주소 추가 메서드
        managerInsert: function () {
            this.emailList = "";

            for (const user of this.selectedUsers) {
                this.emailList += user.user_eml + ";";
            }
            this.to = this.emailList;
            this.closeModal();
        },

        // 전체회원, 기업회원, 일반회원 체크따라 바꾸기
        toggleChnage: function (activeOption) {
            Object.keys(this.toggleOptions).forEach((option) => {
                if (option !== activeOption) {
                    this.toggleOptions[option] = false;
                }
            });
            if (this.toggleOptions[activeOption]) {
                this.selectedUsers = [];
                Object.keys(this.toggleOptions).forEach((option) => {
                    if (this.toggleOptions[option]) {
                        if (option === 'selectAll') {
                            this.selectedUsers = [...this.searchedUsers];
                        } else if (option === 'selectCompany') {
                            this.selectedUsers.push(
                                ...this.searchedUsers.filter((user) => user.is_company === 'Yes')
                            );
                        } else if (option === 'selectNormal') {
                            this.selectedUsers.push(
                                ...this.searchedUsers.filter((user) => user.is_company === 'No')
                            );
                        }
                        else {
                            this.toggleOptions.selectAll = false;
                            this.toggleOptions.selectCompany = false;
                            this.toggleOptions.selectNormal = false;
                        }
                    }
                });
            } else if (activeOption !== 'selectUser') {
                this.selectedUsers = [];
            }
        },

        // 검색 메서드
        searchUsers: function () {
            if (this.searchKeyword === '') {
                this.searchedUsers = this.users;
            } else {
                this.searchedUsers = this.users.filter(user => {
                    if (user.is_company === 'Yes') {
                        return user.company_nm && user.company_nm.toLowerCase().includes(this.searchKeyword.toLowerCase());
                    } else {
                        return user.user_nm && user.user_nm.toLowerCase().includes(this.searchKeyword.toLowerCase());
                    }
                });
            }
        },

        // 페이지 이동 메서드
        selectList: function () {
            this.$router.push({ path: '/adm/mailSelectList.page' });
        },

        // 유저 데이터 받아오는 메서드
        userMailList: function () {
            axios.get('/mail/user.json')
                .then(response => {
                    this.users = response.data;
                    this.searchedUsers = response.data;
                })
                .catch(error => {
                    console.error(error);
                });
        },

        // 토큰 받아오는 메서드
        fetchToken: function () {
            axios.get('/token/get.json')
                .then(response => {
                    const token = response.data;
                    // 토큰을 저장
                    this.accessToken = token;
                })
                .catch(error => {
                    console.error(error);
                });
        },

        // 메일 보내는 메서드
        sendMail: function () {
            const vm = this;
            const oEditors = this.oEditors;
            oEditors.getById["smart"].exec("UPDATE_CONTENTS_FIELD", []);

            const mailData = {
                to: this.to,
                subject: this.subject,
                body: document.getElementById("smart").value,
                userName: 'keris'
            };

            const headers = {
                'Authorization': `Bearer ${this.accessToken}`,
                'Content-Type': 'application/json'
            };

            // Axios를 사용하여 서버로 메일 데이터 전송
            axios.post('/mail/send.json', mailData, { headers })
                .then(response => {
                    console.log(response.data);
                    vm.selectList();
                })
                .catch(error => {
                    console.error(error);
                    vm.selectList();
                });
        }

    },
    watch: {
        "modalType": function (newValue, oldValue) {
            if (this.modalType != null) {
                console.log("modalType watch: ", newValue, oldValue);
                this.openModal();
            }
        },
    },
    computed: {},
    components: {},
    mounted() {
        // 스마트 에디터 적용
        const oEditors = this.oEditors;
        nhn.husky.EZCreator.createInIFrame({
            oAppRef: oEditors,
            elPlaceHolder: "smart",
            sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2noTool.html", // 영상, 이미지 기능 추가 안된 쪽의 html 적용
            htParams: {
                bUseToolbar: true,				// 툴바 사용 여부 (true:사용/ false:사용하지 않음)
                bSkipXssFilter: true,
                bUseVerticalResizer: true,
                bUseModeChanger: true
            },
            fCreator: "createSEditor2"
        });

        this.fetchToken();
    }
};
</script>
