<template>
    <div class="border radius pd30 mb30">
        <div class="inquiry-category mb20" v-if="propsType === 'Q'">
            <div class="flex justify-between align-center">
                <span class="category-zone" v-if="$store.state.authrtTypeLvl !== '4'">{{ data.dscsnCtgryNm }}</span>
                <span class="category-zone"
                    v-if="$store.state.authrtTypeLvl === '4' && data.dscsnSttsNm === 'inquireComplete'">{{
                        data.dscsnCtgryNm }}</span>
                <span class="category-zone"
                    v-if="$store.state.authrtTypeLvl === '4' && data.dscsnSttsNm !== 'inquireComplete'">{{
                    data.entCtgryNm}}</span>
                <div class="flex align-center" v-if="$store.state.authrtTypeLvl !== '4'">
                    <p class="mr10">검토 필요 여부</p>
                    <div class="onoffswitch">
                        <input id="myonoffswitch" class="onoffswitch-checkbox" name="onoffswitch" type="checkbox"
                            v-model="type" @change="eduYn()" />
                        <label for="myonoffswitch" class="onoffswitch-label">
                            <div class="onoffswitch-inner"></div>
                            <div class="onoffswitch-switch"></div>
                        </label>
                    </div>
                </div>
            </div>
        </div>
        <div class="inquiry-category mb20" v-else>
            <div class="flex align-center">
                <span class="category-zone">{{ answerData.dscsnCtgryNm }}</span>
                <p class="detail-text ml10" v-if="$store.state.authrtTypeLvl !== '4'">
                    <span class="detail-bold">답변자</span><span class="inline-block pd5">&#183;</span><span>{{
                        answerData.mbrEncptFlnm }}</span>
                </p>
            </div>
        </div>
        <div class="title-topzone flex justify-between align-center pb10 mb30">
            <div class="question-zone" :style="propsType === 'A' && !isContentUpdate ? 'width:100%' : ''">
                <div>
                    <h3 v-if="propsType === 'Q'" class="question"><span
                            class="text-icon inline-block text-ct mr10">Q</span> {{ data.dscsnTtl }}</h3>
                    <div v-if="propsType === 'A' && !isContentUpdate" class="flex justify-between align-center">
                        <h3 class="answer mr15"><span class="text-icon inline-block text-ct mr10">A</span>
                            {{ answerData.ansTtl }}</h3>
                        <p v-if="$store.state.authrtTypeLvl !== '4'">
                            <span v-if="answerData.ansSttsNm === 'ansAnswer'"
                                class="answer-success pd5 inline-block small-text">답변완료</span>
                            <span v-else-if="answerData.ansSttsNm === 'ansRequest'"
                                class="application-success pd5 inline-block small-text">승인신청</span>
                            <span v-else-if="answerData.ansSttsNm === 'ansReject'"
                                class="application-fail pd5 inline-block small-text">반려</span>
                            <span v-else class="success pd5 inline-block small-text">승인완료</span>
                        </p>
                    </div>
                </div>
            </div>
            <div v-if="propsType === 'Q' && $store.state.authrtTypeLvl === '4'" class="inquiry-status">
                <p v-if="data.dscsnSttsNm === 'inquireRequest'">접수중</p>
                <p v-else-if="data.dscsnSttsNm === 'inquireComplete'" style="color:#28a745">답변완료</p>
                <p v-else style="color:#007aff">처리중</p>
            </div>
            <div v-if="propsType === 'Q' && $store.state.authrtTypeLvl !== '4'" class="inquiry-status">
                <p v-if="data.dscsnSttsNm === 'inquireRequest'">문의요청</p>
                <p v-else-if="data.dscsnSttsNm === 'inquireReceipt'">접수완료</p>
                <p v-else-if="data.dscsnSttsNm === 'inquireWait'">승인대기</p>
                <p v-else-if="data.dscsnSttsNm === 'inquireReject'">반려</p>
                <p v-else>승인완료</p>
            </div>
        </div>
        <p v-if="propsType === 'A' && isContentUpdate" class="answer mb15">
            <input type="text" class="full-input" v-model="change_Ans_ttl" autocomplete="off" id="ans_ttl">
        </p>
        <!-- role이 사용자 -->
        <div v-if="propsType === 'Q'" class="question-userinfo pd15 radius mb15">
            <p class="detail-text mb5"><span class="detail-bold"> {{ data.mbrEncptFlnm }}</span><span
                    class="inline-block pd5">&#183;</span><span>{{ data.entNm }}</span></p>
            <p class="detail-text"><span class="inline-block mr10" aria-label="phoneInfo" id="phoneInfo"><svg-icon type="mdi" :path="phonePath" role="img"
                        aria-labelledby="phoneInfo"></svg-icon> {{
                            hyphenMinus(data.mbrEncptTelno)
                    }}</span> <span class="inline-block" aria-label="emailInfo" id="emailInfo"><svg-icon type="mdi" :path="emailPath" role="img"
                        aria-labelledby="emailInfo"></svg-icon> {{ data.mbrEncptEmad
                    }}</span>
            </p>
        </div>

        <div v-show="!isContentUpdate" class="inquiry-content border-b mb25">
            <div id="viewer" ref="viewer" class="viewer"></div>
            <!-- 날짜 -->
            <div class="inquiry-date " v-if="propsType === 'Q'">
                <p class="text-rg detail-text">{{ data.frstRegDt }}</p>
            </div>
            <div class="inquiry-date " v-else>
                <p class="text-rg detail-text">{{ answerData.ansDt }}</p>
            </div>
        </div>


        <!-- 첨부파일 -->
        <div v-show="isContentUpdate" class="inquiry-contetn mb25">
            <textarea :name="`update-${idx}`" :id="`update-${idx}`" style="width:100%"></textarea>
            <Attachment v-if="propsType === 'A'" :id="`attachment-${idx}`" @emitFileList="emitFileList"
                :text="'파일을 첨부해주세요'" :discussionFiles="fileList" />
        </div>

        <div class="download-zone mb25" v-if="!isContentUpdate">
            <div v-if="fileList.length != 0" class="company-profile">
                <div class="download-item flex justify-between align-center pd10 mb10 border"
                    v-for="(file, idx) in fileList" :key="idx">
                    <p class="ellipsis gd-10">{{ file.fileNm }}</p>
                    <div class="gd-2 flex align-center justify-end">
                        <button class="icon-btn" title="다운로드" aria-label="download" @click="$downloadFile(file, pageAuth)"><svg-icon type="mdi"
                                :path="downloadPath" role="img" aria-labelledby="download"></svg-icon></button>
                    </div>
                </div>
            </div>
            <div v-else class="company-profile">
                <div class="download flex justify-between align-center pd10">
                    <p class="detail-text">첨부된 파일이 없습니다.</p>
                </div>
            </div>
        </div>
        <div v-if="propsType === 'A' && (answerData.answrId === $store.state.mbrId || $store.state.authrtTypeLvl === '1')"
            :class="{ 'pt15 mt30': answerData.ansSttsNm === 'ansReject' || answerData.ansSttsNm === 'ansAnswer' }"
            :style="{ 'border-top': (answerData.ansSttsNm === 'ansReject' || answerData.ansSttsNm === 'ansAnswer') ? '1px solid #bdbdbd' : 'none' }">
            <div class="btn-zone flex justify-end align-center">
                <div class="gd-1 pl0 pr0" v-if="!isContentUpdate && answerData.ansSttsNm === 'ansAnswer'">
                    <button class="large-btn blue-border-btn ml0" title="수정" @click="editorOpen()">수정</button>
                </div>
                <div class="gd-1 pr0" v-if="!isContentUpdate && answerData.ansSttsNm === 'ansReject'">
                    <button class="large-btn green-border-btn ml0" title="수정(반려)" @click="editorOpen()">수정(반려)</button>
                </div>
                <div class="gd-1 pr0"
                    v-if="isContentUpdate && (answerData.ansSttsNm === 'ansAnswer' || ($store.state.authrtTypeLvl === '1' && answerData.ansSttsNm != 'ansComplete'))">
                    <button class="large-btn green-border-btn ml0" title="수정완료" @click="editorSubmit('update')">수정완료</button>
                </div>
                <div class="gd-1 pr0" v-if="isContentUpdate && answerData.ansSttsNm === 'ansReject'">
                    <button class="large-btn blue-border-btn ml0" title="승인요청" @click="editorSubmit('reRequest')">승인요청</button>

                </div>
                <div class="gd-1 pr0" v-if="isContentUpdate">
                    <button class="large-btn darkg-border-btn ml0" title="취소" @click="editorClose()">취소</button>
                </div>
            </div>
        </div>

        <div v-if="propsType === 'A' && $store.state.authrtTypeLvl === '1'"
            :class="{ 'pt15 mt30 mb30': answerData.ansSttsNm === 'ansRequest' }"
            :style="{ 'border-top': answerData.ansSttsNm === 'ansRequest' ? '1px solid #bdbdbd' : 'none' }">
            <div class="btn-zone4 flex justify-end align-center">
                <div class="gd-1 pl0">
                    <button v-if="!isContentUpdate && answerData.ansSttsNm === 'ansRequest'"
                        class="large-btn blue-btn ml0" title="승인" @click="answerApproval()">승인</button>
                </div>
                <div class="gd-1 pl0">
                    <button v-if="!isContentUpdate && answerData.ansSttsNm === 'ansRequest'"
                        class="large-btn green-border-btn ml0" title="수정" @click="editorOpen()">수정</button>
                </div>
                <div class="gd-1 pl0">
                    <button v-if="!isContentUpdate && answerData.ansSttsNm === 'ansRequest'"
                        class="large-btn darkg-border-btn ml0" title="반려" @click="answerRejectEditor()">반려</button>
                </div>
                <div class="gd-1 pl0 pr0">
                    <button v-if="!isContentUpdate && answerData.ansSttsNm === 'ansRequest'"
                        class="large-btn red-border-btn ml0" title="삭제" @click="answerDelete()">삭제</button>
                </div>
            </div>
        </div>

        <div v-show="answerData.ansSttsNm === 'ansReject' && !isReject && (answerData.answrId === $store.state.mbrId || $store.state.authrtTypeLvl === '1')"
            class="mb25 mt25 pd15 radius" style="background-color: var(--background-white);">
            <p class="detail-text"><span class="detail-bold">반려자</span><span
                    class="inline-block pd5">&#183;</span><span>{{ answerData.rtrnrNm }}</span></p>
            <div id="rejectViewer" ref="rejectViewer"></div>
        </div>


        <!-- 모달: 반려사유 -->
        <Modal :showModal="isReject" :className="'medium-modal auto-height'">
            <template v-slot:header>
                <p class="page-sub-title">반려사유</p>
                <button class="close-btn" aria-label="modal close" title="닫기" @click="rejectEditorClose()">
                    <svg-icon type="mdi" :path="closePath" role="img" aria-labelledby="modal close"></svg-icon>
                </button>
            </template>
            <div class="content">
                <textarea :name="`rejectEditor-${idx}`" :id="`rejectEditor-${idx}`" style="width:100%; "></textarea>
            </div>
            <template v-slot:footer>
                <div class="gd-2 pr0">
                    <button class="large-btn darkg-border-btn ml0" title="취소" @click="rejectEditorClose()">취소</button>
                </div>
                <div class="gd-2 pr0">
                    <button class="large-btn green-border-btn ml0" title="완료" @click="answerReject()">완료</button>
                </div>
            </template>
        </Modal>
    </div>
</template>



<script>
import Attachment from '../../component/file/Attachment.vue';
import Modal from '../../component/modal/Modal.vue';
import axios from 'axios';
import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer';
import { mdiPhone, mdiEmail, mdiWindowClose, mdiFileDownloadOutline } from '@mdi/js';
import '@toast-ui/editor/dist/toastui-editor.css';
import '@toast-ui/editor/dist/i18n/ko-kr';
import * as FileSaver from 'file-saver';
import {
    ansUpdateProc,
    ansRejectProc,
    ansReRequestProc,
    ansDeleteProc,
    ansApprovalProc,
    approvalProc,
    rvwProc
} from "../../../resources/api/inquiry";
export default {
    props: {
        propsType: {
            type: String
        },
        propsData: {
            type: Object,
            default: {}
        },
        propsFiles: {
            type: Object,
            default: ''
        },
        answerCount: {
            type: Number
        },
        idx: {
            type: Number
        }
    },
    data() {
        return {
            pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,
            dataType: null,
            data: {},
            closePath: mdiWindowClose,
            downloadPath: mdiFileDownloadOutline,
            oEditors: [],
            isContentUpdate: false,
            initializedEditors: false,
            initializedRejectEditors: false,
            isReject: false,
            answerData: {},
            rejectData: {
                dscsnId: null,
                ansId: null,
                dmndSeq: null,
                rjctCn: null,
                rjctId: null,
                answrId: null
            },
            change_Ans_ttl: null,
            phonePath: mdiPhone,
            emailPath: mdiEmail,

            fileList: [],

            // 파일리스트
            emitFiles: [],
            insertFileList: [],
            deleteFileList: [],
            type: false
        }
    },
    methods: {
        editorOpen() {
            this.isContentUpdate = true;

            if (this.initializedEditors) {
                return;
            }
            this.initEditor(this.answerData.ansCn)
            this.initializedEditors = true;
        },

        editorClose() {
            if (!confirm(this.$getCmmnMessage("cnf007"))) {
                return
            }

            this.resetEditor(this.answerData.ansCn)
            this.change_Ans_ttl = this.answerData.ansTtl;
            this.isContentUpdate = false;
        },

        editorSubmit(type) {

            if (type === 'reRequest') {
                this.answerReRequest();
            } else {
                this.answerUpdate();
            }


        },

        updateViewerHTML(newHTML) {
            this.viewer.setHTML(newHTML);
        },

        rejectEditorClose() {
            this.isReject = false;
        },

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

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

        resetEditor: function (data) {
            const oEditors = this.oEditors;
            let id = "update-" + this.idx
            oEditors.getById[id].exec("SET_IR", [""]); //내용초기화
            oEditors.getById[id].exec("PASTE_HTML", [data]);
        },

        // 에디터 만들기 
        initEditor: function (initData) {
            // 스마트 에디터 적용
            let id = "update-" + this.idx
            const oEditors = this.oEditors;
            nhn.husky.EZCreator.createInIFrame({
                oAppRef: oEditors,
                elPlaceHolder: id,
                sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
                htParams: {
                    bSkipXssFilter: true,
                    bUseVerticalResizer: true,
                    bUseModeChanger: true
                },
                fOnAppLoad: function () {
                    oEditors.getById[id].exec("SET_IR", [""]); //내용초기화
                    oEditors.getById[id].exec("PASTE_HTML", [initData]);
                },
                fCreator: "createSEditor2"
            });
        },

        downloadFile: function (item) {
            const vm = this;
            let path = item.file_path + '/' + item.file_nm + '.' + item.file_extn_nm;
            vm.$store.commit('setLoading', true);
            axios({
                url: '/file/downloadFile.json',
                method: 'post',
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                responseType: 'blob',
                data: `file_path=${encodeURIComponent(path)}`
            }).then((response) => {

                const blob = new Blob([response.data]);
                const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

                if (isSafari) {
                    FileSaver.saveAs(blob, item.real_file_nm);
                } else {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = item.real_file_nm;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            }).catch(function (error) {
                // alert('파일 다운로드 실패, 다시 시도해주세요.');
                alert(vm.$getCmmnMessage("err024"))
            }).finally(function () {
                vm.$store.commit('setLoading', false);
            });
        },

        async answerApproval() {
            const vm = this;
            if (!confirm(this.$getCmmnMessage("cnf005","답변을 "))) return

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

                if (response.status == 200) {
                    alert("답변을 승인 하였습니다.")
                    vm.answerData = response.data.data.answer
                    vm.$emit("reload");
                }
            } 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);
            }
        },

        answerRejectEditor: function () {
            this.isReject = true;
            this.initializedRejectEditors = false;

            if (this.initializedRejectEditors) {
                return;
            }

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

        },

        async answerDelete() {
            const vm = this;

            if (vm.answerCount === 1) {
                alert("답변이 단건일 경우, 해당 답변을 삭제하실 수 없습니다.")
                return;
            }
            if (!confirm(this.$getCmmnMessage("cnf002","답변을 "))) return;

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

                if (response.status == 200) {
                    alert("답변을 삭제 하였습니다.")
                    vm.$emit("reload")
                }
            } 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);
            }
        },

        async answerReject() {
            const vm = this;

            vm.rejectData.dscsnId = vm.answerData.dscsnId;
            vm.rejectData.ansId = vm.answerData.ansId;
            vm.rejectData.dmndSeq = vm.answerData.dmndSeq;
            vm.rejectData.rjctId = vm.answerData.rjctId;
            vm.rejectData.answrId = vm.answerData.answrId;

            const oEditors = vm.oEditors;
            let editorId = "rejectEditor-" + this.idx

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

            if (!confirm(this.$getCmmnMessage("cnf006","해당 답변을 "))) {
                return;
            }

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

                if (response.status == 200) {
                    alert("해당답변을 반려 하였습니다.")
                    vm.answerData = response.data.data.answer;
                    vm.isReject = false;
                    vm.$emit("reload")
                }
            } 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, ''); // 모든 공백 제거
        },

        updateEditor() {
            const vm = this;

            const oEditors = vm.oEditors;
            let editorId = "update-" + this.idx

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

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

        async answerReRequest() {
            const vm = this;

            if (!vm.updateEditor()) return;
            if (!confirm(this.$getCmmnMessage("cnf013","해당 답변을 "))) return;

            vm.answerData.ansTtl = vm.change_Ans_ttl;

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

                if (response.status == 200) {
                    alert("해당답변을 재요청 하였습니다.")
                    vm.answerData = response.data.data.answer;
                    vm.isContentUpdate = false;
                    vm.getViewer(vm.answerData.ansCn);
                    vm.change_Ans_ttl = vm.answerData.ansTtl
                    vm.$emit("reload")
                }
            } 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);
            }
        },

        async answerUpdate() {
            const vm = this;

            if (!vm.updateEditor()) return;
            if (!confirm(this.$getCmmnMessage("cnf004","답변을 "))) return;

            vm.answerData.ansTtl = vm.change_Ans_ttl;


            vm.emitFiles.forEach(file => {
                const existsInFileListName = vm.fileList.some(fileListItem => fileListItem.fileNm === file.name);
                const existsInFileListSize = vm.fileList.some(fileListItem => fileListItem.fileSz === file.size);
                if (!existsInFileListName && !existsInFileListSize) {
                    vm.insertFileList.push(file);
                }
            });

            if (vm.emitFiles != []) {
                vm.fileList.forEach(fileListItem => {
                    const existsInFileListName = vm.emitFiles.some(file => file.name === fileListItem.fileNm);
                    const existsInFileListSize = vm.emitFiles.some(file => file.size === fileListItem.fileSz);
                    if (!existsInFileListName && !existsInFileListSize) {
                        vm.deleteFileList.push(fileListItem);
                    }
                });
            }
            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("answer", JSON.stringify(vm.answerData));

                vm.$store.commit('setLoading', true);
                axios({
                    url: '/aidt/inquiry/answer/update.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.answerData = response.data.data.answer;
                        // vm.fileList = response.data.data.answer.fileList;
                        vm.isContentUpdate = false;
                        vm.getViewer(vm.answerData.ansCn);
                        vm.change_Ans_ttl = vm.answerData.ansTtl;
                        vm.$emit("reload")
                    } 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 ansUpdateProc(vm.answerData);

                    if (response.status == 200) {
                        alert("해당답변을 수정 하였습니다.")
                        vm.answerData = response.data.data.answer;
                        vm.isContentUpdate = false;
                        vm.getViewer(vm.answerData.ansCn);
                        vm.change_Ans_ttl = vm.answerData.ansTtl;
                    }
                } 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);
                }
            }
        },

        hyphenMinus: function (telno) {
            return this.$HyphenMinus(telno);
        },

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

        async eduYn() {
            const vm = this;
            if (!confirm(this.$getCmmnMessage("cnf009","검토 여부를 "))) {
                this.type = !this.type
                return;
            } else {
                this.data.rvwYn = this.type === true ? 'Y' : 'N';

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

                    if (response.status == 200) {
                        alert("검토여부를 변경 하였습니다.")
                    }
                } 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 {
                    this.$store.commit('setLoading', false);
                }
            }

        }
    },
    watch: {
        'propsData': function (newValue) {
            if (this.propsType === 'A') {
                this.answerData = this.propsData;
                this.change_Ans_ttl = this.answerData.ansTtl;
                this.getViewer(this.answerData.ansCn);
                if (this.answerData.ansSttsNm === 'ansReject') {
                    this.getRejectViewer(this.answerData.rjctCn);
                }
            } else {
                this.data = newValue;
                this.type = newValue.rvwYn === 'Y' ? true : false;
                this.getViewer(newValue.dscsnCn);
            }
        },

        'propsFiles': function (newValue) {
            this.fileList = newValue;
        },

        'answerCount': function (newValue) {
        }
    },
    computed: {

    },
    components: {
        'Attachment': Attachment,
        'Modal': Modal
    },
    mounted() {
        if (this.propsType === 'A') {
            this.answerData = this.propsData;
            this.change_Ans_ttl = this.answerData.ansTtl;
            this.fileList = this.propsFiles;
            this.getViewer(this.answerData.ansCn);
            if (this.answerData.ansSttsNm === 'ansReject') {
                this.getRejectViewer(this.answerData.rjctCn);
            }
        }
    },

}
</script>

<style scoped>
.viewer {
    user-select: text;
}
</style>
