<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="flex justify-between align-start">
                    <div class="consulting-zone  gd-12">
                        <div class="form-table-style">
                            <div class="pb15 border-b">
                                <p class="text-rg"><span class="red-text">*</span>필수사항입니다.</p>
                            </div>
                            <table class="form-table mb10">
                                <colgroup>
                                    <col width="50%" />
                                    <col width="50%" />
                                </colgroup>
                                <tr>
                                    <td class="text-lf" colspan="2">
                                        <div class="gd-12">
                                            <label for="" class="form-title mb16">제목</label>
                                            <input type="text" class="full-input" v-model="discussion.dscsnTtl"
                                                autocomplete="off" id="dscsnTtl" placeholder="제목을 입력하세요." />
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12">
                                            <label for="" class="form-title mb16">카테고리</label>
                                            <div class="border radius relative" id="dscsnCtgryId" tabindex="0"
                                                @click="categoryOpen">
                                                <label for="" class="category-select pd10 pr30">{{ 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>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="2" 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="2" class="text-lf">
                                        <p class="form-title mb16">첨부파일</p>
                                        <Attachment @emitFileList="emitFileList" :text="'파일을 첨부해주세요'" />
                                    </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="discussionSelectListPage()">취소</button>
                            </div>
                            <div class="gd-1 pr0">
                                <button class="large-btn blue-btn" title="문의" @click="discussionInsert()"
                                    v-if="pageAuth.wrAuthrtYn === 'Y'">문의</button>
                            </div>
                        </div>
                    </div>
                    <!-- <div class="gd-4">
                        <div class="pd30" style="box-shadow: 0 0 5px #ddd;">
                            <div class="boder-b pb10">
                                <p>문의자 정보</p>
                            </div>
                            <table>
                                <colgroup>
                                    <col width="100%"/>
                                </colgroup>
                                <tr>
                                    <td colspan="2" class="text-lf">
                                        <div class="gd-12 pl0 pr0">
                                            <label for="" class="form-title mb16">소속(기업명)</label>
                                            <input type="text" class="full-input" v-model="memberInfo.entNm" disabled
                                                readonly />
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 pl0 pr0">
                                            <label for="" class="form-title mb16">성명</label>
                                            <input type="text" class="full-input" v-model="memberInfo.mbrEncptFlnm"
                                                disabled readonly />
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 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.mbrEncptTelno" readonly />
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 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" readonly />
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div> -->
                </div>
            </div>
        </div>
    </div>
</template>



<script>
import Attachment from '../../../../component/file/Attachment.vue';
import PageNavigationBar from '../../../../component/pagenavigationbar/PageNavigationBar.vue';
import { defaultSearchParams } from "../../../../../resources/js/defaultSearchParams";
import { findByMbr, findAllCtgry, dscsnSave } from "../../../../../resources/api/inquiry";
import axios from 'axios';

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

            inerTermsModal: false,
            agreey: false,

            // 검색 정보 담는 객체
            search: { ...defaultSearchParams },

            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, // 회원이메일
            },

            categoryList: [],

            oEditors: [],
            // 파일리스트
            files: [],
            // 카테고리 
            categorySelected: false,
            topCategryList: [],
            subCategryList: [],
            topCategoryName: null,
            categoryName: '카테고리 선택',
            mainSelectCategory: null,
            subSelectCategory: null,
            bannerId: 'guide-banner'
        }
    },
    created() {
        this.findByMbr();
        this.findAllCategory();
    },
    methods: {

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

        //글 등록 유효성 검사
        insertValidation: function () {
            const vm = this;

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


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

            // await vm.iframeToTestarea()
            // console.log('vm.discussion.dscsnCn', vm.discussion.dscsnCn)

            const oEditors = vm.oEditors;
            oEditors.getById["smart"].exec("UPDATE_CONTENTS_FIELD", []);
            // 스마트에디터의 iframe에 있는 내용을 textarea로. 
            vm.discussion.dscsnCn = document.getElementById("smart").value;
            //4.내용 null검사
            if (this.$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 discussionInsert() {
            const vm = this;
            if (!vm.insertValidation()) return;

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

            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("discussion", JSON.stringify(vm.discussion));

                vm.$store.commit('setLoading', true);
                axios({
                    url: '/aidt/inquiry/dscsnSave.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.$getCmmnMessage('msg001'));
                        vm.$router.push({ name: 'EntInquirySelectList' });
                    } 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 dscsnSave(vm.discussion);

                    alert(vm.$getCmmnMessage('msg001'));

                    if (response.status == 200) {
                        vm.$router.push({ name: 'EntInquirySelectList' });
                    }
                } 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);
                }
            }
        },

        //상담 리스트로 이동
        discussionSelectListPage: function () {
            if (!confirm(this.$getCmmnMessage("cnf008","작성을 "))) return;
            this.$router.push({ name: 'EntInquirySelectList' });
        },

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

        //회원 정보 불러오기
        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);
                    history.back();
                } else {
                    // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                    alert(this.$getCmmnMessage('err005'));
                }
            }
        },

        // 카테고리 정보 불러오기
        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관리자에게 문의해주세요.");
                    alert(this.$getCmmnMessage('err005'));
                }
            }
        },

        //하위 카테고리 정보 불러오기
        subCategorySelectList: function (topCategry) {
            this.mainSelectCategory = topCategry.dscsnCtgryNm;
            const vm = this;
            axios({
                url: '/discussion/subCategory.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: topCategry
            }).then(function (response) {
                vm.subCategryList = response.data;

                if (response.data.length === 0) {
                    //하위 카테고리가 존재하지 않으면 선택 카테고리에 상위 카테고리 넣기
                    vm.selectedCategory = topCategry;
                } else {
                    //하위 카테고리가 존재하면 상위카테고리 이름 넣기
                    vm.topCategoryName = topCategry.dscsnCtgryNm
                }
            }).catch(function (error) {
                alert('하위 카테고리 목록 조회 오류, 관리자에게 문의하세요.');
            })
        },

        //하위 카테고리 클릭 시 선택한 카테고리에 하위 카테고리 넣기
        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.dscsnCtgryId = this.selectedCategory.dscsnCtgryCd;
            this.categorySelected = true;
            // this.topCategoryName = null;
        },

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

    },
    watch: {

    },
    computed: {

    },
    components: {
        'PageNavigationBar': PageNavigationBar,
        'Attachment': Attachment
    },
    mounted() {
        const oEditors = this.oEditors;
        nhn.husky.EZCreator.createInIFrame({
            oAppRef: oEditors,
            elPlaceHolder: "smart",
            sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
            htParams: {
                bUseToolbar: true,				// 툴바 사용 여부 (true:사용/ false:사용하지 않음)
                bSkipXssFilter: true,
                bUseVerticalResizer: true,
                bUseModeChanger: true
            },
            fCreator: "createSEditor2"
        });
    },

}
</script>
