<template>
    <div>
        <div class="content">
            <div :class="{ 'top-banner banner  guide-banner': true, [bannerId]: true }"
                v-if="this.$route.path.startsWith('/aidt')">
                <div class="flex-column align-center justify-center content">
                    <h1 class="banner-title text-ct white" aria-live="assertive">{{ $getMenuInfo().menuNm }}</h1>
                    <p class="box-title text-ct white">{{ $getMenuInfo().menuCn }}</p>
                </div>
            </div>
            <PageNavigationBar />
            <div class="pt100 pb100">
                <div class="w1280">
                    <div class="consulting-zone">
                        <div class="form-table-style">
                            <div class="flex flex-end pt15 pb15 border-b">
                                <p><span class="red-text">*</span>필수사항 입니다.</p>
                            </div>
                            <table class="form-table mb10">
                                <tr>
                                    <td class="text-lf">
                                        <label for="" class="form-title mb16">제목</label>
                                        <input type="text" class="full-input" v-model="discussion.dscsnTtl"
                                            autocomplete="off" id="dscsn_ttl" placeholder="제목을 입력하세요.">
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <label for="" class="form-title mb16">카테고리</label>
                                        <div class="border radius relative" id="dscsn_ctgry_id" tabindex="0"
                                            style="background-color: #f2f2f2;">
                                            <label for="" class="category-select pd10 pr30" id="dscsnCtgryId"> {{
                                                categoryName }}</label>
                                            <!-- <div class="category-option pd10 border radius overflow-y"
                                                :style="categorySelected ? 'display:block' : 'display:none'">
                                                <div class="pb10">
                                                    <div class="depth1 gd-6 content">
                                                        <ul>
                                                            <li v-for="(categry, idx) in categoryList" :key="idx"
                                                                @click="selectCategory(categry)"
                                                                :class="{ 'cursor pd10 detail-text': true, 'selected-item': categry.dscsnCtgryNm === mainSelectCategory }">
                                                                {{ categry.dscsnCtgryNm }}</li>
                                                        </ul>
                                                    </div>

                                                    <div class="depth2 gd-6 content overflow-y">
                                                        <ul v-if="subCategryList.length != 0">
                                                            <li v-for="(subCategry, idx) in subCategryList" :key="idx"
                                                            @click="categoryClick(subCategry)"  :class="{'cursor pd10 detail-text':true, 'selected-item': subCategry.dscsnCtgryNm === subSelectCategory}">{{ subCategry.dscsnCtgryNm }}</li>
                                                        </ul>
                                                        <ul v-else>
                                                            <li>카테고리를 선택해주세요.</li>
                                                        </ul>
                                                    </div>
                                                </div>
                                                <div class="flex justify-end align-center pt10 border-t">
                                                    <div class="gd-1 pl0">
                                                        <button class="large-btn darkg-border-btn" @click="categorySelected = false">취소</button>
                                                    </div>
                                                    <div class="gd-1 pl0 ">
                                                        <button class="large-btn blue-btn" @click="selectCategory()" >선택</button>
                                                    </div>
                                                </div>
                                            </div> -->
                                        </div>

                                    </td>
                                </tr>
                                <!-- <tr>
                                    <td class="text-lf">
                                        <div class="gd-6 pl0 pr0">
                                            <label for="" class="form-title mb16">성명</label>
                                            <input type="text" class="full-input" v-model="memberInfo.mbrEncptFlnm"
                                                id="rgtr_nm" disabled />
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="3" class="text-lf">
                                        <div class="gd-6 pl0 pr0">
                                            <label for="" class="form-title mb16">소속(기업명)</label>
                                            <input type="text" class="full-input" v-model="memberInfo.entNm"
                                                id="rgtr_ogdp" disabled />
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-6 pl0 pr0">
                                            <label for="" class="form-title mb16">연락처</label>
                                            <div class="flex justify-start no-gutters">
                                                <div class="gd-12 pl0 pr0">
                                                    <input type="text" class="full-input" id="tel1" disabled
                                                        v-model="memberInfo.mbrEncptTelno" />
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-6 pl0 pr0">
                                            <label for="" class="form-title mb16">이메일</label>
                                            <div class="flex justify-start no-gutters">
                                                <div class="gd-12 pl0 pr0">
                                                    <input type="text" class="full-input" disabled
                                                        v-model="memberInfo.mbrEncptEmad" />
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr> -->
                                <tr>
                                    <td colspan="3" class="text-lf">
                                        <label for="" class="form-title mb16">내용</label>
                                        <p class="pb10">
                                            다른 문서 작성 도구나 뷰어로부터의 복사 및 붙여넣기 시, 원본의 스타일이 정확하게 반영되지 않을 수 있습니다.
                                        </p>
                                        <textarea name="smart" id="smart" style="width:100%; height: 35rem;"></textarea>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="3" class="text-lf">
                                        <p class="form-title mb16">첨부파일</p>
                                        <Attachment @emitFileList="emitFileList" @fileDelet="fileDelet" :text="'파일을 첨부해주세요'"
                                            :discussionFiles="fileList" />
                                    </td>
                                </tr>
                            </table>

                        </div>
                        <div class="flex justify-end btn-zone">
                            <div class="gd-1 pr0">
                                <button class="large-btn darkg-border-btn" title="취소"
                                    @click="confirmDiscussionOnePage()">취소</button>
                            </div>
                            <div class="gd-1 pr0">
                                <button class="large-btn blue-btn" title="수정" @click="discussionUpdate()"
                                    v-if="pageAuth.mdfcnAuthrtYn === 'Y'">수정</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>



<script>
import Attachment from '../../../../component/file/Attachment.vue';
import PageNavigationBar from '../../../../component/pagenavigationbar/PageNavigationBar.vue';
import { findByDscsn, dscsnUpdate, findByMbr, findAllCtgry } from "../../../../../resources/api/inquiry";
import axios from 'axios';
import { useRoute } from 'vue-router';

export default {
    data() {
        return {
            // 페이지 권한 객체
            pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,

            // id
            pageId: this.$route.query.pageId,

            inerTermsModal: false,
            agreey: false,

            discussion: {
                entId: null, // 사업자등록번호
                dscsnTtl: null,  //타이틀
                dscsnCn: null,  //내용
                dscsnCtgryId: null, //상담 카테고리
            },

            memberInfo: {
                mbrId: null, // 회원ID
                mbrEncptFlnm: null, // 회원이름
                entId: null, // 기업아이디
                brno: null, // 사업자등록번호
                entNm: null, // 기업명
                mbrEncptTelno: null, // 회원전화번호
                mbrEncptEmad: null, // 회원이메일
            },

            route: useRoute(),

            oEditors: [],
            // 파일리스트
            files: [],
            deleteFiles:[],
            
            //처음 받아오는 파일 리스트
            fileList: [],
            insertFileList: [],
            deleteFileList: [],

            // 카테고리 
            categoryList: [],
            categorySelected: false,
            topCategryList: [],
            subCategryList: [],
            topCategoryName: null,
            categoryName: null,
            mainSelectCategory: null,
            subSelectCategory: null,
            bannerId: 'guide-banner'
        }
    },
    methods: {

        categoryOpen: function () {
            this.categorySelected = !this.categorySelected
        },

        //글 수정 유효성 검사
        updateValidation: function () {
            const vm = this;

            vm.discussion.dscsnTtl = vm.discussion.dscsnTtl != null ? vm.discussion.dscsnTtl.trim() : null
            //1.제목 null검사
            if (vm.$isEmpty(vm.discussion.dscsnTtl)) {
                alert("제목을 입력하세요.")
                document.getElementById("dscsn_ttl").focus();
                return false;
            }
            //2.제목 길이검사
            if (vm.discussion.dscsnTtl.length > 50) {
                alert("제목은 50자를 넘길 수 없습니다.")
                document.getElementById("dscsn_ttl").focus();
                return false;
            }

            // 3.카테고리!!
            // if (vm.$isEmpty(vm.discussion.dscsnCtgryId)) {
            //     alert("카테고리를 선택하세요.")
            //     document.getElementById("dscsn_ctgry_id").focus();
            //     return false;
            // }

            const oEditors = vm.oEditors;
            oEditors.getById["smart"].exec("UPDATE_CONTENTS_FIELD", []);
            // 스마트에디터의 iframe에 있는 내용을 textarea로. 
            vm.discussion.dscsnCn = document.getElementById("smart").value;
            //4.내용 null검사
            if (vm.$isEmpty(vm.discussion.dscsnCn) || vm.removeHtmlAndSpace(vm.discussion.dscsnCn) === '') {
                alert("내용을 입력하세요.")
                oEditors.getById["smart"].exec("FOCUS");
                return false;
            }
            //5.내용 길이 검사
            if (vm.discussion.dscsnCn.length > 5000) {
                alert("내용은 5000자 까지 입력할 수 있습니다.")
                oEditors.getById["smart"].exec("FOCUS");
                return false;
            }

            return true;
        },

        //상담 수정
        async discussionUpdate() {
            const vm = this;
            if (!vm.updateValidation()) return;

            vm.discussion.entId = vm.memberInfo.entId;``

            if(vm.files.length > 0 ) {
                vm.files.forEach(file => {
                    vm.insertFileList.push(file);
                })
            }
            // vm.files.forEach(file => {
            //     const existsInFileListName = vm.fileList.some(fileListItem => fileListItem.fileNm === file.name);
            //     const existsInFileListSize = vm.fileList.some(fileListItem => fileListItem.fileSz === file.size);
            //     console.log('existsInFileListName -- ', existsInFileListName, 'existsInFileListSize -- ', existsInFileListSize);
            //     if (!existsInFileListName && !existsInFileListSize) {
            //         console.log('file', file)
            //         vm.insertFileList.push(file);
            //     }
            // });
            // if (vm.files != []) {
            //     vm.fileList.forEach(fileListItem => {
            //         const existsInFileListName = vm.files.some(file => file.name === fileListItem.fileNm);
            //         const existsInFileListSize = vm.files.some(file => file.size === fileListItem.fileSz);
            //         if (!existsInFileListName && !existsInFileListSize) {
            //             console.log('fileListItem', fileListItem)
            //             vm.deleteFileList.push(fileListItem);
            //         }
            //     });
            // }
            if (vm.deleteFiles.length > 0) {
                vm.deleteFiles.forEach(file => {
                    vm.deleteFileList.push(file);
                });
            }
            let formData = new FormData();

            if (vm.insertFileList.length > 0 || vm.deleteFileList.length > 0) {
                if (vm.insertFileList.length > 0) {
                    for (let i = 0; i < vm.insertFileList.length; i++) {
                        formData.append('file', vm.insertFileList[i]);
                    }
                }

                if (vm.deleteFileList.length > 0) {
                    formData.append('deleteFile', JSON.stringify(vm.deleteFileList));
                }

                formData.append("discussion", JSON.stringify(vm.discussion));
                vm.$store.commit('setLoading', true);
                axios({
                    url: '/aidt/inquiry/dscsnUpdate.file',
                    method: 'post',
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        Authorization: vm.$store.state.authorization,
                    },
                    data: formData
                }).then(function (response) {
                    let result = response.data.data;
                    if (response.status == 200) {
                        if (result === -1) alert("이미 접수된 문의입니다. 접수된 문의는 수정이 불가합니다.");
                        else alert(vm.$getCmmnMessage('msg002'));
                        vm.discussionOnePage()
                    } else {
                        const errorData = response.data;
                        if (errorData.message != null && errorData.message != "") {
                            alert(errorData.message);
                        } else {
                            // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                            alert(vm.$getCmmnMessage('err005'));
                        }
                    }
                }).catch(function (error) {
                    alert("문의 수정 중 오류가 발생하였습니다. \n담당자에게 문의하세요.");
                }).finally(function () {
                    vm.$store.commit('setLoading', false);
                });
            } else {
                vm.$store.commit('setLoading', true);
                try {
                    const response = await dscsnUpdate(vm.discussion);
                    const result = response.data.data;
                    if (response.status == 200) {
                        if (result === -1) alert("이미 접수된 문의입니다. 접수된 문의는 수정이 불가합니다.");
                        else alert(vm.$getCmmnMessage('msg002'));
                        vm.discussionOnePage()
                    }
                } catch (error) {
                    console.lof(error)
                    const errorData = error.response.data;
                    if (errorData.message != null && errorData.message != "") {
                        alert(error.response.data.message);
                    } else {
                        // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                        alert(vm.$getCmmnMessage('err005'));
                    }
                } finally {
                    vm.$store.commit('setLoading', false);
                }
            }
        },

        discussionOnePage: function () {
            this.$router.push({ name: 'EntInquirySelectOne', query: { 'pageId': this.discussion.dscsnId } });
        },

        confirmDiscussionOnePage: function () {
            if (!confirm(this.$getCmmnMessage("cnf008","문의 수정을 "))) return
            this.$router.push({ name: 'EntInquirySelectOne', query: { 'pageId': this.discussion.dscsnId } });
        },

        removeHtmlAndSpace: function (str) {
            return str.replace(/<[^>]*>/g, '') // HTML 태그 제거
                .replace(/&nbsp;/gi, ' ') // &nbsp;를 공백으로 변환
                .replace(/\s/g, ''); // 모든 공백 제거
        },

        //상담 상세 조회
        async findByDscsn() {
            try {
                const data = { dscsnId: this.pageId }

                const response = await findByDscsn(data);

                if (response.status == 200) {
                    this.discussion = response.data.data.discussion;
                    if (response.data.data.fileList.length != 0) {
                        this.fileList = response.data.data.fileList;
                    }
                    this.categoryName = response.data.data.discussion.dscsnCtgryNm;
                    this.initEditor(this.discussion.dscsnCn);
                }
            } catch (error) {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                    alert(error.response.data.message);
                } else {
                    // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                    alert(this.$getCmmnMessage('err005'));
                }
            }
        },

        //회원 정보 불러오기
        async findByMbr() {
            try {
                const response = await findByMbr();
                this.memberInfo = response.data.data;
            } catch (error) {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                    alert(error.response.data.message);
                } else {
                    // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                    alert(this.$getCmmnMessage('err005'));
                }
            }
        },

        // 에디터 만들기 
        initEditor: function (initData) {
            // 스마트 에디터 적용
            const oEditors = this.oEditors;
            nhn.husky.EZCreator.createInIFrame({
                oAppRef: oEditors,
                elPlaceHolder: "smart",
                sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
                htParams: {
                    bSkipXssFilter: true,
                    bUseVerticalResizer: true,
                    bUseModeChanger: true
                },
                fOnAppLoad: function () {
                    oEditors.getById["smart"].exec("PASTE_HTML", [initData]);
                    document.getElementById("dscsn_ttl").focus();
                    document.getElementById("dscsn_ttl").blur();
                },
                fCreator: "createSEditor2"
            });

        },

        // 카테고리 정보 불러오기
        // async findAllCategory() {
        //     try {
        //         const response = await findAllCtgry();

        //         this.categoryList = response.data.data.categoryList;
        //         this.categoryList.unshift({ dscsnCtgryId: null, dscsnCtgryNm: '전체' })
        //     } catch (error) {
        //         const errorData = error.response.data;
        //         if (errorData.message != null && errorData.message != "") {
        //             alert(error.response.data.message);
        //         } else {
        //             alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        //         }
        //     }
        // },

        //하위 카테고리 클릭 시 선택한 카테고리에 하위 카테고리 넣기
        categoryClick: function (subCategry) {
            this.selectedCategory = subCategry;
            this.subSelectCategory = subCategry.dscsnCtgryNm
        },

        //화면에 보여줄 최종 카테고리명 만들기
        selectCategory: function (categry) {
            // if(this.topCategoryName != null) {
            //     this.categoryName = this.topCategoryName + ' > ' + this.selectedCategory.dscsnCtgryNm;
            // } else {
            //     this.categoryName = this.selectedCategory.dscsnCtgryNm;
            // }
            this.categoryName = categry.dscsnCtgryNm;
            this.discussion.dscsnCtgryId = categry.dscsnCtgryId
            // this.discussion.dscsn_ctgry_cd = this.selectedCategory.dscsnCtgryCd;
            this.categorySelected = true;
            // this.topCategoryName = null;
        },

        //파일 컴포넌트에서 파일 리스트 받기
        emitFileList: function (files) {
            
            this.files = files;
            this.deleteFileList = [];
            this.insertFileList = [];
        },

        fileDelet: function(file) {
            this.deleteFiles.push(file);
        }

    },
    watch: {

    },
    computed: {

    },
    components: {
        'PageNavigationBar': PageNavigationBar,
        'Attachment': Attachment
    },
    mounted() {
        this.findByMbr();
        this.findByDscsn();
        // this.findAllCategory();
    },

}
</script>

