<template>
    <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">{{ $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">
                    <!-- <p class="content-title2 mb20">상담신청내용</p> -->
                    <Inquiry :propsType="'Q'" :propsData="discussion" :propsFiles="fileList" />
                    <h2 class="content-title2 mb20" v-if="answerList.length != 0">상담답변내역</h2>
                    <div v-for="(answer, idx) in answerList" :key="idx">
                        <Inquiry :propsType="'A'" :propsData="answer" :propsFiles="answer.fileList" :idx="idx"
                            :answerCount="answerList.length" @reload="reload()" />
                    </div>
                    <div
                        v-show="demand.dmndCn != null && demand.dmndTypeNm === 'dmndRequest' && (demand.rcvrId === $store.state.mbrId || $store.state.authrtTypeLvl === '1' || demand.rqstrId === $store.state.mbrId)">
                        <p class="content-title2 mb20">카테고리 재지정/추가답변요청 사유</p>
                        <div class="background-box pd30 radius mb30">
                            <p class="detail-bold">{{ demand.dscsnCtgryNm }} (으)로 카테고리를 재지정/추가답변요청 하였습니다.</p>
                            <div style="min-height:'10rem'; max-height:20rem" class="overflow-y">
                                <div id="reRequestViewer" ref="reRequestViewer" class="reRequestViewer"></div>
                            </div>
                        </div>
                    </div>

                    <!-- <div v-if="demand.dmndCn =! null && demand.dmndTypeNm === 'request' && (demand.rcvrId != $store.state.mbrId && $store.state.authrtTypeLvl != '1')">
                    <p>추가요청된 답변을 기다리고 있습니다.</p>
                </div> -->
                    <div v-show="isEditorOpen" class="mb20">
                        <p class="content-title2 mb20">상담답변작성</p>
                        <div class="border radius pd30">
                            <div class="form-table-style">
                                <table class="form-table ">
                                    <tr>
                                        <td class="text-lf">
                                            <div class="gd-12 pl0 pr0">
                                                <div class="mb16">
                                                    <label for="" class="form-title mb10">답변제목</label>
                                                </div>
                                                <div>
                                                    <input type="text" class="full-input" v-model="answer.ansTtl"
                                                        autocomplete="false" id="ans_ttl" placeholder="제목을 입력하세요.">
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="text-lf">
                                            <div class="gd-12 pl0 pr0">
                                                <div class="mb16">
                                                    <label for="" class="form-title mb10">답변내용</label>
                                                </div>
                                                <div>
                                                    <textarea name="answerEdit" id="answerEdit"></textarea>
                                                </div>
                                            </div>
                                            <div>
                                                <p class="form-title mb16">첨부파일</p>
                                                <Attachment @emitFileList="emitFileList" :text="'파일을 첨부해주세요'" />
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                                <div class="pt15 border-t">
                                    <div class="flex justify-end align-center">
                                        <!-- <div class="gd-1 pl0">
                                        <button class="large-btn red-border-btn"
                                            @click="isEditorOpen = false">취소</button>
                                    </div> -->
                                        <div class="gd-1 pr0 pl0"> <button class="large-btn blue-btn"
                                                @click="ansInsertProc()">등록</button></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-if="demand.dmndTypeNm === 'dmndRequest'"
                        class="btn-zone flex justift-between align-center no-gutters">
                        <div class="gd-1 pl0">
                            <button class="large-btn darkg-border-btn ml0" @click="discussionListPage()">목록</button>
                        </div>
                        <div class="gd-11 flex justify-end align-center">
                            <div class="gd-1 pl0">
                                <button class="large-btn green-border-btn ml0"
                                    v-if="demand.rcvrId === $store.state.mbrId || $store.state.authrtTypeLvl === '1'"
                                    @click="findAllCategory('re')">재지정</button>

                            </div>
                            <div class="gd-1 pl0 pr0"><button class="large-btn blue-btn ml0"
                                    v-if="demand.rcvrId === $store.state.mbrId || $store.state.authrtTypeLvl == '1'"
                                    @click="acceptProc()">접수</button></div>
                        </div>
                    </div>
                    <div v-if="demand.dmndTypeNm === 'dmndComplete'"
                        class="btn-zone flex justift-between align-center no-gutters">
                        <div class="gd-1 pl0">
                            <button class="large-btn darkg-border-btn ml0" @click="discussionListPage()">목록</button>
                        </div>
                        <div class="gd-11 flex justify-end align-center"
                            v-if="allComplete && $store.state.authrtTypeLvl === '1'">
                            <div class="gd-1 pr0 pl0">
                                <button class="large-btn blue-border-btn ml0"
                                    @click="discusstionComplete()">답변공개</button>
                            </div>
                        </div>
                        <div class="gd-11 flex justify-end align-center">
                            <div class="gd-1 pl0 "
                                v-if="(demand.clrId === $store.state.mbrId || $store.state.authrtTypeLvl === '1') && discussion.dscsnSttsNm === 'inquireReceipt'">
                                <button class="large-btn green-border-btn ml0"
                                    @click="findAllCategory('add')">추가답변요청</button>
                            </div>
                            <div class="gd-1 pl0 pr0"
                                v-if="(demand.clrId === $store.state.mbrId || $store.state.authrtTypeLvl === '1') && discussion.dscsnSttsNm === 'inquireReceipt'">
                                <button class="large-btn blue-border-btn ml0" @click="approvalRequest()">답변승인요청</button>
                            </div>
                        </div>
                    </div>
                    <div v-if="demand.dmndTypeNm != 'dmndComplete' && demand.dmndTypeNm != 'dmndRequest'"
                        class="btn-zone flex justift-between align-center no-gutters">
                        <div class="gd-1 pl0">
                            <button class="large-btn darkg-border-btn ml0" @click="discussionListPage()">목록</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div v-show="categryModal" class="modal-wrapper" role="dialog" 
    aria-modal="true">
        <div class="modal-container" style="height: 80%;">
            <div class="modal-title">
                <div class="flex justify-between align-center">
                    <h2 class="page-sub-title">카테고리 지정</h2>
                    <button class="icon-btn black" @click="categryModalClose()" aria-label="closeButton" id="closeButton">
                        <svg-icon type="mdi" :path="closePath" aria-labelledby="closeButton"></svg-icon>
                    </button>
                </div>
            </div>
            <div class="modal-content-monthly">
                <div class="flex justify-start align-start pb10 category-top-zone">
                    <div class="depth1 gd-6 content pl0">
                        <p class="modal-sub-title mb10 relative pl10">카테고리 선택</p>
                        <div class=" border radius content pd10" style="height: calc(100% - 35.5px);min-height: calc(100% - 35.5px);">
                            <ul class="content overflow-y">
                                <li v-for="(category, idx) in categoryList" :key="idx" @click="selectCategory(category)"
                                    :class="{ 'cursor pd10 detail-text': true, 'selected-item': category.dscsnCtgryId === mainSelectCategory }">
                                    <span class="mr5"><svg-icon type="mdi" :width="20" :height="20" :path="categoryPath"> </svg-icon></span>{{ category.dscsnCtgryNm }}</li>
                            </ul>
                        </div>

                    </div>
                    <div class="depth2 gd-6 content pr0">
                        <p class="modal-sub-title mb10 relative pl10">담당자 선택</p>
                        <div class=" border radius content pd10" style="height: calc(100% - 35.5px);min-height: calc(100% - 35.5px);">
                            <ul v-if="categoryPicList.length != 0" class="content overflow-y">
                                <li v-for="(category, idx) in categoryPicList" :key="idx"
                                    @click="selectCategoryPic(category.member)"
                                    :class="{ 'cursor pd10 detail-text': true, 'selected-item': category.member.mbr_encpt_flnm === mainSelectCategoryPic }">
                                    <span class="mr5"><svg-icon type="mdi" :width="20" :height="20" :path="crownPath" v-if="category.rprsPicYn === 'Y'"> </svg-icon><svg-icon type="mdi" :width="20" :height="20" :path="userPath" v-else> </svg-icon></span>{{ category.member.mbr_encpt_flnm }} </li>
                            </ul>
                            <ul v-else-if="mainSelectCategory === null"  class="flex-column justify-center align-center content">
                                <li class="text-ct">카테고리를 선택해주세요.</li>
                            </ul>
                            <ul v-else-if="categoryPicList.length === 0 && mainSelectCategory != null" class="flex-column justify-center align-center content">
                                <li class="text-ct">상담사가 없습니다.<br /> 상담사 등록 후 선택해주세요.</li>
                            </ul>
                        </div>

                    </div>
                    <!-- <div class="depth2 gd-6 content overflow-y">
                        <ul ㅊ>
                            <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="editor-wrap">
                    <p class="modal-sub-title mb10 relative pl10">재지정 사유</p>
                    <textarea name="reRequest" id="reRequest" style="width: 100%; min-height: 35rem;"></textarea>
                </div>
            </div>
            <div class="modal-end flex justify-end align-center pd0">
                <div class="gd-2 pl0">
                    <button @click="categryModalClose()" class="large-btn gray-btn ml0">취소</button>
                </div>
                <div class="gd-2 pl0 pr0">
                    <button class="large-btn blue-btn ml0" @click="reRequest()">확인</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Attachment from '../../../../component/file/Attachment.vue';
import PageNavigationBar from '../../../../component/pagenavigationbar/PageNavigationBar.vue'
import Inquiry from '../../../../component/inquiry/Inquiry.vue';
import ProgressBar from '../../../../component/progressbar/ProgressBar.vue';
import axios from 'axios';
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 { mdiWindowClose,mdiCrownCircle,mdiAccountCircle,mdiViewList } from '@mdi/js';
import {
    findByDscsn,
    findAllCtgry,
    acceptProc,
    ansInsertProc,
    reRequestProc,
    approvalProc,
    dscsnCompleteProc,
    findAllDscsnCtgryPic
} from "../../../../../resources/api/inquiry";
export default {
    data() {
        return {
            // 페이지 권한 객체
            pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,
            // id
            pageId: this.$route.query.pageId,

            closePath: mdiWindowClose,
            discussion: {},
            demand: {
                clrId: null,
                dmndCn: null,
                dmndDt: null,
                dmndSeq: null,
                dmndTypeNm: null,
                dscsnCtgryId: null,
                dscsnCtgryNm: null,
                dscsnId: null,
                rcptDt: null,
                rcvrId: null,
                reRequestType: null,
                rqstrId: null,
            },
            userPath:mdiAccountCircle,
            crownPath:mdiCrownCircle,
            categoryPath:mdiViewList,
            // 파일리스트
            fileList: [],

            // 카테고리 
            categoryList: [],
            categoryPicList: [],

            //답변리스트
            answerList: [],
            answer: {},

            isEditorOpen: false,
            oEditors: [],// oEditors는 스마트에디터용
            initializedEditors: false,
            initializedreRequestEditors: false,

            categryModal: false,
            reRequestModal: false,
            topCategoryName: null,
            categoryName: null,

            selectedCategory: {
                dscsnCtgryNm: null,
                dscsnCtgryId: null
            },

            selectedCategoryPic: {},

            reRequestObject: {
                dscsnId: null,
                dmndSeq: null,
                dscsnCtgryId: null,
                dmndCn: null
            },

            reRequestType: null,
            allComplete: false,
            mainSelectCategory: null,
            mainSelectCategoryPic: null,
            subSelectCategory: null,

            files: [],
            bannerId : 'guide-banner'
        }
    },
    created() {
        this.findByDscsn();
    },
    methods: {
        categryModalOpen(type) {

            this.categryModal = true;
            this.reRequestType = type;

            if (this.initializedreRequestEditors) {
                return
            }
            
            // 스마트 에디터 적용
            const oEditors = this.oEditors;
            nhn.husky.EZCreator.createInIFrame({
                oAppRef: oEditors,
                elPlaceHolder: "reRequest",
                sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
                htParams: {
                    bUseToolbar: true,				// 툴바 사용 여부 (true:사용/ false:사용하지 않음)
                    bSkipXssFilter: true,
                    bUseVerticalResizer: true,
                    bUseModeChanger: true,
                    nHeight: 1 
                },
                fCreator: "createSEditor2"
            });

            this.initializedreRequestEditors = true;

        },
        categryModalClose() {
            this.categryModal = false;
            this.selectedCategory.dscsnCtgryId = null;
            this.mainSelectCategory = null;
            this.selectedCategoryPic = {};
            this.reRequestObject.dmndCn = null;
            this.categoryPicList = [];
            this.resetEditor();
        },

        resetEditor: function () {
            const oEditors = this.oEditors;
            oEditors.getById['reRequest'].exec("SET_IR", [""]); //내용초기화
        },

        editorOpen() {
            this.isEditorOpen = true;

            if (this.initializedEditors) {
                return;
            }

            // 스마트 에디터 적용
            const oEditors = this.oEditors;
            nhn.husky.EZCreator.createInIFrame({
                oAppRef: oEditors,
                elPlaceHolder: "answerEdit",
                sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
                htParams: {
                    bUseToolbar: true,				// 툴바 사용 여부 (true:사용/ false:사용하지 않음)
                    bSkipXssFilter: true,
                    bUseVerticalResizer: true,
                    bUseModeChanger: true
                },
                fCreator: "createSEditor2"
            });
            this.initializedEditors = true;
        },

        editorClose() {
            this.isEditorOpen = false;
        },

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

                const response = await findByDscsn(data);

                if (response.status == 200) {

                    if(response.data.data.discussion.useYn === 'N') {
                        alert("이미 삭제된 상담입니다.")
                        this.discussionListPage();
                        return
                    }

                    this.discussion = response.data.data.discussion;
                    this.demand = response.data.data.demand;
                    this.answerList = response.data.data.ansList;
                    
                    if (response.data.data.fileList.length != 0) {
                        this.fileList = response.data.data.fileList;
                    }

                    if ((this.demand.dmndTypeNm === 'dmndAccept' && this.demand.clrId === this.$store.state.mbrId) || (this.demand.dmndTypeNm === 'dmndAccept' && this.$store.state.authrtTypeLvl === '1')) {
                        this.editorOpen()
                    }

                    if (this.demand.dmndTypeNm === 'dmndRequest' && this.demand.dmndCn != null && (this.demand.rcvrId === this.$store.state.mbrId || this.$store.state.authrtTypeLvl === '1' || this.demand.rqstrId === this.$store.state.mbrId)) {
                        this.getViewer(this.demand.dmndCn);
                    }

                    if (this.discussion.dscsnSttsNm != 'inquireComplete') {
                        this.ansStatusCheck();
                    } else {
                        this.allComplete = false;
                    }
                }
            } 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 acceptProc() {
            if (!confirm(this.$getCmmnMessage("cnf017","해당 문의를 "))) return
            delete this.demand.dmndDt;

            this.$store.commit('setLoading', true);
            try {
                const data = this.demand
                const response = await acceptProc(data);
                const result = response.data.data;

                if (result == -1) {
                    alert("문의자가 카테고리를 수정하여 접수할 수 없습니다.")
                    this.discussionListPage();
                } else {
                    this.findByDscsn();
                    alert("해당 문의를 접수하였습니다.");
                }
            } 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'));
                }
            } finally {
                this.$store.commit('setLoading', false);
            }
        },

        //답변등록 유효성 검사
        answerInsertValidation: function () {
            const vm = this;

            //9.제목 null검사
            vm.answer.ansTtl = vm.answer.ansTtl != null ? vm.answer.ansTtl.trim() : null
            if (this.$isEmpty(vm.answer.ansTtl)) {
                alert("제목을 입력하세요.")
                document.getElementById("ans_ttl").focus();
                return false;
            }
            //10.제목 길이검사
            if (vm.answer.ansTtl.length > 100) {
                alert("제목은 100자를 넘길 수 없습니다.")
                document.getElementById("ans_ttl").focus();
                return false;
            }

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

            return true;
        },

        //답변 등록
        async ansInsertProc() {
            const vm = this;
            if (!vm.answerInsertValidation()) return;
            if (!confirm(this.$getCmmnMessage("cnf003","답변을 "))) return;

            vm.answer.dscsnId = vm.demand.dscsnId;
            vm.answer.dmndSeq = vm.demand.dmndSeq;

            let formData = new FormData();
            if (vm.files.length > 0) {
                for (let i = 0; i < vm.files.length; i++) {
                    formData.append('file', vm.files[i]);
                }
                formData.append("answer", JSON.stringify(vm.answer));

                vm.$store.commit('setLoading', true);
                axios({
                    url: '/aidt/inquiry/answer/insert.file',
                    method: 'post',
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        Authorization: vm.$store.state.authorization,
                    },
                    data: formData
                }).then(function (response) {
                    if (response.status === 200) {
                        alert("답변등록을 완료하였습니다.");
                        vm.findByDscsn();
                        vm.editorClose();
                    } else {
                        alert("문의 등록 중 오류가 발생하였습니다.\n담당자에게 문의하세요.");
                    }
                }).catch(function (error) {
                    alert("문의 등록 중 오류가 발생하였습니다.\n담당자에게 문의하세요.");
                }).finally(function () {
                    vm.$store.commit('setLoading', false);
                });
            } else {
                vm.$store.commit('setLoading', true);
                try {
                    const response = await ansInsertProc(vm.answer);

                    if (response.status == 200) {
                        alert("답변등록을 완료하였습니다.");
                        vm.findByDscsn();
                        vm.editorClose();
                    }
                } catch (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);
                }
            }

        },

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

        // 최상위 카테고리 정보 불러오기
        async findAllCategory(type) {

            try {
                const response = await findAllCtgry();

                this.categoryList = response.data.data.categoryList;

                if(type === 'add') {
                    this.categoryList = this.categoryList.filter(category => {
                        // answerList 배열에 category.dscsnCtgryCd와 일치하는 dscsnCtgryId가 있는지 확인
                        const isMatch = this.answerList.some(answer => answer.dscsnCtgryId === category.dscsnCtgryId);

                        // demand 객체에 category.dscsnCtgryCd와 일치하는 dscsnCtgryId가 있는지 확인
                        const isDemandMatch = this.demand.dscsnCtgryId === category.dscsnCtgryId;
                        // 일치하는 요소가 없으면 true를 반환하여 filter 결과에 포함시킴
                        return !isMatch && !isDemandMatch;
                        // return !isDemandMatch;
                    });
                }
                
                this.categryModalOpen(type)
                // 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관리자에게 문의해주세요.");
                    alert(this.$getCmmnMessage('err005'));
                }
            }
        },

        //카테고리 멤버 목록 조회
        async findAllDscsnCtgrPic(category) {
            try {
                const response = await findAllDscsnCtgryPic(category);

                if (response.status == 200) {
                    this.categoryPicList = response.data.data
                    this.mainSelectCategoryPic = response.data.data[0].member.mbr_encpt_flnm;
                    this.selectedCategoryPic = response.data.data[0].member;
                }
            } 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'));
                }
            }
        },

        //화면에 보여줄 최종 카테고리명 만들기
        selectCategory: function (category) {
            this.selectedCategoryPic = {};
            this.categoryName = category.dscsnCtgryNm;
            this.selectedCategory.dscsnCtgryId = category.dscsnCtgryId
            this.mainSelectCategory = category.dscsnCtgryId;
            this.findAllDscsnCtgrPic(category);
        },

        selectCategoryPic: function (categoryPic) {
            this.mainSelectCategoryPic = categoryPic.mbr_encpt_flnm
            this.selectedCategoryPic = categoryPic
        },

        reRequest: async function () {
            const vm = this;

            // await vm.selectCategory();
            
            vm.reRequestObject.dscsnId = vm.demand.dscsnId;
            vm.reRequestObject.dmndSeq = vm.demand.dmndSeq + 1;
            vm.reRequestObject.dscsnCtgryId = vm.selectedCategory.dscsnCtgryId;
            vm.reRequestObject.rcvrId = vm.selectedCategoryPic.mbr_id;
            vm.reRequestObject.rqstrId = vm.demand.rqstrId;
            vm.reRequestObject.reRequestType = vm.reRequestType;

            //1.카테고리 선택 검사
            if (this.$isEmpty(vm.reRequestObject.dscsnCtgryId)) {
                alert("카테고리를 선택 하세요.")
                return;
            }

            // 카테고리 상담사 지정 검사
            if (this.$isEmpty(vm.reRequestObject.rcvrId)) {
                alert("상담사를 지정해주세요.")
                return;
            }

            const oEditors = vm.oEditors;
            oEditors.getById["reRequest"].exec("UPDATE_CONTENTS_FIELD", []);
            // 스마트에디터의 iframe에 있는 내용을 textarea로. 
            vm.reRequestObject.dmndCn = document.getElementById("reRequest").value;

            //2.내용 null검사
            if (this.$isEmpty(vm.reRequestObject.dmndCn) || this.removeHtmlAndSpace(vm.reRequestObject.dmndCn) === '') {
                alert("내용을 입력하세요.")
                oEditors.getById["reRequest"].exec("FOCUS");
                return false;
            }

            //3.내용 검사
            if (vm.reRequestObject.dmndCn.length > 5000) {
                alert("내용은 5000자를 넘길 수 없습니다.")
                oEditors.getById["reRequest"].exec("FOCUS");
                return;
            }

            if (vm.reRequestType === 'add') {
                if (!confirm(this.categoryName + ' 카테고리로 추가답변요청을 하시겠습니까?')) return;
            } else {
                if (!confirm(this.categoryName + ' 카테고리로 재지정 하시겠습니까?')) return;
            }

            try {
                const response = await reRequestProc(vm.reRequestObject);

                if (response.status == 200) {
                    if (vm.reRequestType === 'add') {
                        alert("추가답변을 요청하였습니다.")
                    } else {
                        alert("카테고리 재지정이 완료되었습니다.")
                    }
                    vm.discussionListPage();
                    vm.categryModalClose();
                }
            } catch (error) {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                    alert(error.response.data.message);
                } else {
                    // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                    alert(vm.$getCmmnMessage('err005'));
                }
            }
        },

        async approvalRequest() {
            const vm = this;

            if (!confirm(this.$getCmmnMessage("cnf019","답변승인"))) {
                return;
            }

            vm.$store.commit('setLoading', true);
            try {
                const response = await approvalProc(vm.demand);

                if (response.status == 200) {
                    alert("승인신청을 완료 하였습니다.")
                    vm.findByDscsn();
                }
            } catch (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);
            }
        },

        getViewer(data) {
            this.reRequestViewer = new Viewer({
                el: this.$refs.reRequestViewer,
                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 },
                            ];
                        },
                    }
                },
            });
        },

        discussionListPage: function () {
            this.$router.push({ name: 'MngrInquirySelectList' });
        },

        ansStatusCheck: function () {
            let aprv = true;
            this.answerList.forEach((answer) => {
                if (answer.aprvYn != 'Y') aprv = false;
            })

            if (this.answerList.length === 0) aprv = false;
            if (aprv) this.allComplete = true;
        },

        reload() {
            this.findByDscsn();
            // this.answerSelectList();
        },

        async discusstionComplete() {
            const vm = this;

            if (!confirm(this.$getCmmnMessage("cnf018","해당 문의에 대한 답변을 "))) return;

            vm.$store.commit('setLoading', true);
            try {
                const response = await dscsnCompleteProc(vm.discussion);

                if (response.status == 200) {
                    alert("답변공개를 완료 하였습니다.")
                    vm.findByDscsn();
                }
            } catch (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);
            }
        },

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

    },
    computed: {

    },
    components: {
        'PageNavigationBar': PageNavigationBar,
        'Inquiry': Inquiry,
        'ProgressBar': ProgressBar,
        'Attachment': Attachment
    },
    mounted() {


    },

}
</script>
