<template>
    <div :class="{ 'content': true, 'login-page': innerStep === 0 }">     
        <div >       
            <div class="w1280">
                <div>
                    <div class="border pd30  mt40 ">
                        <div class="flex justify-between align-center  border-b mb30">
                            <div class="content-border-title">
                                <h2 class="middle-title">기업정보</h2>
                            </div>
                            <p><span class="red-text">*</span>필수사항 입니다.</p>
                        </div>
                        <div class="form-table-style">
                            <table class="form-table mb10">
                                <tr>
                                        <td class="text-lf">
                                            <div class="gd-12 pl0 pr0">
                                                <div class="mb16">
                                                    <label for="" class="form-title ">기업로고</label>
                                                </div>
                                                <div class="gd-6 pl0 mb10">
                                                    <div class="logo-zone border flex justify-center radius">
                                                        <img v-if="logoPreview || logoFile" :src="logoPreview || $replaceImagePath(logoFile.ablstPathNm)" width="100%" alt="기업로고" class="inline"> 
                                                        <p v-else class="text-ct detail-bold">Logo</p>
                                                    </div>
                                                </div>
                                                <ul class="mb10">
                                                    <li class="small-text">&#8251; 이미지는 340*120 사이즈를 권장합니다.</li>
                                                </ul>
                                                <div class="gd-6 pl0">
                                                    <label for="logoImg" class="cursor upload-btn pd5">찾아보기</label>
                                                    <input type="file" accept="image/*" name="logoImg" id="logoImg"
                                                        @change="logoUpload" style="display: none;"  ref="logoImg"/>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 pl0 pr0">
                                            <div class="mb16">
                                                <label for="" class="form-title ">기업명</label>
                                            </div>
                                            <div class="gd-6 pl0">
                                                <input type="text" class="full-input" placeholder="기업명을 입력하세요."
                                                    v-model="ent_info.entNm" id="ent_nm" autocomplete="off"/>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 pl0 pr0">
                                            <div class="mb16">
                                                <label for="" class="form-title ">사업자등록번호</label>
                                            </div>
                                            <div class="flex justify-start align-center">
                                                <div class="gd-6 pl0">
                                                    <input type="text" class="full-input" placeholder="사업자등록번호를 숫자만 입력해주세요."
                                                        v-model="ent_info.brno" id="brno" disabled />
                                                </div>
                                                <div class="gd-2 pl0 pr0">
                                                    <!-- <button class="large-btn blue-border-btn"
                                                        @click="checkBusinessId()">중복확인</button> -->
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 pl0">
                                            <div class="mb16">
                                                <p class="form-title ">한 줄 소개</p>
                                                <p>20자 이내로 회사를 소개 해주세요.</p>
                                            </div>
                                            <input type="text" class="full-input" maxlength="20"
                                                placeholder="한 줄 소개를 입력하세요." v-model="ent_info.entIntrdSmryCn"
                                                id="ent_intrcn_smry" autocomplete="off"/>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 pl0 pr0">
                                            <div class="mb16">
                                                <label for="" class="form-title ">주소</label>

                                            </div>
                                            <div class="flex justify-start align-center mb5">
                                                <div class="gd-2 pl0">
                                                    <input type="text" class="full-input" placeholder="우편번호" disabled
                                                        v-model="ent_info.zip" />
                                                </div>
                                                <div class="gd-2 pl0 pr0">
                                                    <button class="large-btn blue-border-btn" title="찾기" @click="openPostcode()">
                                                        찾기</button>
                                                </div>
                                            </div>
                                            <div class="gd-4 mb5 pl0 pr0">
                                                <input type="text" class="full-input" placeholder="주소" disabled
                                                    v-model="ent_info.entAddr" id="ent_addr" />
                                            </div>
                                            <div class="gd-4 pl0 pr0">
                                                <input type="text" class="full-input" placeholder="상세주소"
                                                    v-model="ent_info.entDaddr" id="ent_daddr" autocomplete="off"/>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-8 pl0">
                                            <div class="mb16">
                                                <label for="" class="form-title ">홈페이지</label>
                                            </div>
                                            <input type="text" class="full-input" placeholder="홈페이지를 입력해주세요."
                                                v-model="ent_info.hmpUrl" id="hmpg_url" autocomplete="off"/>
                                        </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-2 pl0 pr0">
                                                    <select name="" id="ent_tel1" v-model="ent_tel1"
                                                        class="full-select ml0">
                                                        <option value="null">선택하세요.</option>
                                                        <option value="02">02</option>
                                                        <option value="031">031</option>
                                                        <option value="032">032</option>
                                                        <option value="033">033</option>
                                                        <option value="041">041</option>
                                                        <option value="042">042</option>
                                                        <option value="043">043</option>
                                                        <option value="044">044</option>
                                                        <option value="051">051</option>
                                                        <option value="052">052</option>
                                                        <option value="053">053</option>
                                                        <option value="054">054</option>
                                                        <option value="055">055</option>
                                                        <option value="061">061</option>
                                                        <option value="062">062</option>
                                                        <option value="063">063</option>
                                                        <option value="064">064</option>
                                                        <option value="070">070</option>
                                                    </select>
                                                </div>
                                                <div class="pd10">-</div>
                                                <div class="gd-2 pl0 pr0">
                                                    <input type="text" class="" v-model="ent_tel2" id="ent_tel2" autocomplete="off"/>
                                                </div>
                                                <div class="pd10">-</div>
                                                <div class="gd-2 pl0 pr0">
                                                    <input type="text" class="" v-model="ent_tel3" id="ent_tel3" autocomplete="off"/>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                        <td>
                                            <div class="gd-12 pl0 pr0">
                                                <div class="mb16">
                                                    <label  class="form-title ">기업 출원 정보</label>
                                                </div>
                                                <div class="flex align-center mb15">
                                                    <div v-for="(item, index) in ctgryCdList" :key="index" class="gd-2 pl0">
                                                        <input type="radio" :name="`first_info_${index}`" :id="item.cdId" :value="item.cdId" v-model="ent_info.entSeNm" />
                                                        <label :for="item.cdId">{{ item.cdNm }}</label>
                                                    </div>
                                                </div>
                                                <div class="flex align-center mb15">
                                                    <select name="" id=""  :disabled="ent_info.entSeNm !== 'applPrnmnt'" class="gd-2" v-model="ent_info.mainApplEntYn">
                                                        <option value="">선택</option>
                                                        <option value="Y">주 출원사</option>
                                                        <option value="N">보조 출원사</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="gd-12 pl0 pr0">
                                            <div class="mb16">
                                                <p for="" class="form-title ">우리회사 키워드</p>
                                                <p>최소 3개에서 최대 6개를 선택해주세요.</p>
                                            </div>
                                            <div class="keyword-wrap flex justify-start align-center">
                                                <div v-for="(keyword, index) in keywords" :key="keyword.cdId" class="gd-2 mb5">
                                                    <input type="checkbox" :id="`keyword-${keyword.cdId}`"
                                                        :value="keyword.cdId" v-model="ent_info.selectedKeywords"
                                                        class="keyword-label" :disabled="isCheckboxDisabled(index)"
                                                        style="display: none;" />
                                                    <label :for="`keyword-${keyword.cdId}`" class="keyword text-ct">#{{ keyword.cdNm }}</label>
                                                </div>
                                            </div>  
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="flex justify-start align-center">
                                            <div class="gd-12 pl0 pr0">
                                                <label for="" class="form-title mb16">기업인증</label>
                                                <Attachment @emitFiles="emitFiles" :type="'registration'" :updateFile="registraitonFile"
                                                @file-deleted="handleFileDeleted" :options="{ allowedExtensions: ['pdf'] }"/>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-lf">
                                        <div class="flex justify-start align-center">
                                            <div class="gd-12 pl0 pr0">
                                                <div class=" mb16">
                                                            <label for="" class="form-title mb10">기업등록신청서</label>
                                                            <div class="gd-2 pl0 pr0">
                                                                <button class="large-btn blue-border-btn" title="기업등록신청서 다운로드" @click="$downloadFileByIdNoAuthCheck('FILE_0000000002', 'CMMN_FILE_0000000002', 'AI 디지털교과서 통합지원센터 신규 기업등록신청서(양식).hwp', 'BBS_0000000032')">기업등록신청서</button>
                                                            </div>
                                                        </div>
                                                <Attachment @emitFiles="emitFiles" :type="'applyForm'" :updateFile="applyFormFile"
                                                 @file-deleted="handleFileDeleted" :options="{ allowedExtensions: ['pdf'] }"/>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="flex justify-between align-center" style="margin-top: 10px;">
                        <div class="gd-1 pd0">
                            <button class="large-btn darkg-border-btn ml0" title="취소"  @click="isCancel">취소</button>
                        </div>
                        <div class="gd-1 pd0">
                            <button class="large-btn blue-btn ml0" title="수정" v-if="ent_info.aprvAplySttsCd!= 'reject' " @click="updateEntRequest()">수정</button>
                            <button class="large-btn blue-btn ml0" title="재신청" v-else @click="updateEntRequest()">재신청</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div v-show="isCancelModal" class="modal-wrapper" role="dialog" 
        aria-modal="true">
            <div class="modal-container small-modal">
                <div class="modal-title">
                    <div class="flex justify-between align-center">
                        <h2 class="page-sub-title">알림</h2>
                        <button class="icon-btn black" aria-label="modalCloseButton" @click="closeCancelModal()" title="닫기">
                            <svg-icon type="mdi" :path="closePath" role="img"  aria-labelledby="modalCloseButton"></svg-icon>
                        </button>
                    </div>
                </div>
                <div class="modal-content-monthly alert-modal">
                    <p class="detail-text text-ct">기업 정보 수정을 취소하시겠습니까?</p>
                </div>
                <div class="modal-end  flex justify-between align-center">
                    <div class="gd-6"><button class="gray-btn  large-btn" title="취소" @click="closeCancelModal()">취소</button>
                    </div>
                    <div class="gd-6"><button class="blue-btn  large-btn" title="확인" @click="manageEntInfo()">확인</button></div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Attachment from '../../../component/file/Attachment.vue'
import axios from "axios";
import { useStore } from "vuex";
import PageNavigationBar from '../../../component/pagenavigationbar/PageNavigationBar.vue'
import COMMON_UTIL from '../../../../resources/js/commonUtil';
import { mdiWindowClose } from '@mdi/js';
//API
import { pwdCheck } from '../../../../resources/api/userPage';
import { keywordFindAll } from '../../../../resources/api/companyApply';
import { myEntInfo } from "../../../../resources/api/entInfo";

export default {
    data() {
        return {
            closePath:mdiWindowClose,
            newPwZone: false,
            isCancelModal: false,
            innerStep: 0,
            
            user_pw : null,
            keywords : [],

            //기업상세
            ent_info: {
                entId: null,
                brno: null,
                entNm: null,
                entChcCnt: null,
                entMtchCnt: null,
                inqCnt: null,
                entIntrdSmryCn: null,
                zip: null,
                entAddr: null,
                entDaddr: null,
                hmpUrl: null,
                entTelno: null,
                stdgCd: null,
                fileMngId: null,
                aprvAplySttsCd: null,
                autzrId: null,
                aprvDt: null,
                rjctCn: null,
                rtrnrId: null,
                rjctDt: null,
                frstRegDt: null,
                selectedKeywords: [],
                isEntRegist: false,
                entSeNm: null,
                mainApplEntYn: ''
            },
            // 기업 파일 리스트 
            entFileList: [],
            ent_tel1 : null,
            ent_tel2 : null,
            ent_tel3 : null,
            file: null,

            registraitonFile : null,
            applyFormFile : null,
            logoFile : null,

            //추가파일리스트
            insertFileList:[],
            //삭제파일리스트
            deleteFileList:[],
            //최초로고파일
            prevLogoFile:{},
            //로고파일
            logoFile: {},
            logoPreview: null,
            store: useStore(),
            randumNum : null,

            requestCode : [],
            ctgryCdList: []
        }
    },
    methods: {
        newPwShow: function () {
            this.newPwZone = true
        },
        isCancel: function () {
            this.isCancelModal = true
        },
        closeCancelModal: function () {
            this.isCancelModal = false
        },
        stepGo: function (num) {
            this.innerStep = num
        },

        //DAUM 주소 API 주소검색
        openPostcode: function () {

            // this.ent_info.zip = '38541'; //우편코드
            // this.ent_info.ent_addr ='경북 경산시 대학로 280'; //주소코드
            // this.ent_info.ent_daddr = '영남대학교 창업보육센터 신관 217호'
            // this.ent_info.stdg_cd = '4729011500' //법정동코드4

            let width = 500; //팝업의 너비
            let height = 600; //팝업의 높이
            new daum.Postcode({
                oncomplete: (data) => {
                    width: width;
                    height: height;
                    this.ent_info.zip = data.zonecode; //우편코드
                    this.ent_info.entAddr = data.roadAddress; //주소코드
                    this.ent_info.stdgCd = data.bcode //법정동코드
                },
            }).open({
                left: (window.screen.width / 2) - (width / 2),
                top: (window.screen.height / 2) - (height / 2)
            });
        },

        // 이미지 업로드
        logoUpload: function (event) {
            const vm = this;

            const allowedExtensions = ['jpg', 'jpeg', 'png'];
            const files = event.target.files;
            const MAX_WIDTH = 340;
            const MAX_HEIGHT = 120;

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const fileExtension = this.getExtension(file.name).toLowerCase();

                if (allowedExtensions.includes(fileExtension)) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var img = new Image();
                        img.src = reader.result;
                        img.onload = function () {
                            // 이미지의 실제 크기 확인
                            var width = img.width;
                            var height = img.height;
                            // 정해진 크기보다 큰 경우 경고창 표시
                            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                                alert("로고 이미지 크기는 최대 " + MAX_WIDTH + "x" + MAX_HEIGHT + "입니다.");
                            } else {
                                vm.logoPreview = reader.result;
                                //최초 변경시에만 deleteFileList에 넣을것
                                if (vm.prevLogoFile === vm.logoFile){
                                    vm.deleteFileList.push(vm.logoFile);
                                }
                                vm.logoFile = file;
                                const fileItem = { file, file_ty: 'logo' };
                                //추가 할때마다 insertFileList에서 logo 타입 삭제
                                const index = vm.insertFileList.findIndex(item => item.file_ty === 'logo');
                                if (index !== -1) {
                                    vm.insertFileList.splice(index, 1);
                                }
                                vm.insertFileList.push(fileItem);
                            }
                        };
                    };
                    reader.readAsDataURL(file);
                } else {
                    // 허용되지 않는 확장자인 경우 경고 메시지 표시 등의 처리
                    alert(`${file.name}은 허용되지 않는 파일 형식입니다.`);
                }
            }
        },

        getExtension(filename) {
            const lastIndex = filename.lastIndexOf('.');
            return filename.substring(lastIndex + 1);
        },

        
        //파일목록 받아오기
       emitFiles: function (files) {
            let data = {
                file_ty : files.type,
                file : files.filelist[0]
            }

            this.insertFileList.push(data);
            if(files.type === 'registration'){
                this.deleteFileList.push(this.registraitonFile)
            } else if(files.type === 'applyForm') {
                this.deleteFileList.push(this.applyFormFile)
            } else if(files.type === 'logo') {
                this.deleteFileList.push(this.logoFile)
            }
        },

         // 초기정보 호출 
        init : async function(){
            const vm = this;          
            // 실행
            try {
                this.$setLoading(true);
                this.requestCode = await this.$getCommonCode('aprvAplySttsCd');
                const response = await myEntInfo();
                vm.ent_info = response.data.data.entInfo;
                if(!response.data.data.entInfo.mainApplEntYn){
                    vm.ent_info.mainApplEntYn = '';
                } 
                // 기업 파일 리스트 
                vm.entFileList = response.data.data.entFileList;
                // 기업 키워드 리스트
                vm.entKeywordList = response.data.data.entKeywordList;
                // 내정보 
                vm.myInfo = response.data.data.myInfo;

                //파일 셋팅
                vm.fileInit()
                //전화번호 셋팅
                vm.settingTelNum(vm.ent_info.entTelno)
                //키워드 셋팅
                vm.keywordInit(vm.entKeywordList)

            
            } catch (error) {
                console.log(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.$setLoading(false);
            }
        },  

        //파일 셋팅
        fileInit: function() {
            const vm = this;

            for (let i = 0; i < vm.entFileList.length; i++) {
                if (vm.entFileList[i].fileTypeNm == "registration") {
                    vm.registraitonFile = vm.entFileList[i];
                    vm.registraitonFile.name = vm.entFileList[i].fileNm;
                    vm.registraitonFile.size = vm.entFileList[i].fileSz;
                } else if (vm.entFileList[i].fileTypeNm == "applyForm") {
                    vm.applyFormFile = vm.entFileList[i]
                    vm.applyFormFile.name = vm.entFileList[i].fileNm;
                    vm.applyFormFile.size = vm.entFileList[i].fileSz;
                } else if (vm.entFileList[i].fileTypeNm == "logo") {
                    vm.prevLogoFile = vm.entFileList[i]
                    vm.logoFile = vm.entFileList[i]
                    vm.logoFile.name = vm.entFileList[i].fileNm;
                    vm.logoFile.size = vm.entFileList[i].fileSz;
                }
            }
        },

        //키워드 셋팅
        keywordInit: function(seletedKeywords) {
            this.ent_info.selectedKeywords = this.keywords.filter(keyword => seletedKeywords.includes(keyword.cdNm)).map(keyword => keyword.cdId);
        },

        //기업 유효성 검사
        companyValidation: function () {
            //기업명 
            this.ent_info.entNm = this.ent_info.entNm ? this.ent_info.entNm.trim() : null
            if (!this.ent_info.entNm) {
                alert("기업명을 입력해주세요.");
                document.getElementById("ent_nm").focus();
                return false;
            }
            let entNameRegex = /^[가-힣A-Za-z0-9\s()]{2,50}$/;
            if (!entNameRegex.test(this.ent_info.entNm)) {
                alert("유효하지 않은 기업명입니다.");
                document.getElementById("ent_nm").focus();
                return false;
            }
            //주소
            if (!this.ent_info.entAddr) {
                alert("주소입력은 필수입니다.");
                document.getElementById("ent_addr").focus();
                return false;
            }
            //상세주소 유효성검사
            this.ent_info.entDaddr = this.ent_info.entDaddr ? this.ent_info.entDaddr.trim() : null
            var entAddrRegex = /^[가-힣A-Za-z0-9\s\-\/]{1,100}$/;
            if (!entAddrRegex.test(this.ent_info.entDaddr)) {
                alert("유효하지 않은 상세주소입니다.");
                document.getElementById("ent_daddr").focus();
                return false;
            }
            //홈페이지
            this.ent_info.hmpUrl = this.ent_info.hmpUrl ? this.ent_info.hmpUrl.trim() : null
            if (!this.ent_info.hmpUrl) {
                alert("홈페이지 주소를 입력해주세요.");
                document.getElementById("hmpg_url").focus();
                return false;
            }
            if (this.ent_info.hmpUrl.length > 200) {
                alert("홈페이지 주소는 200자까지 입력가능합니다.");
                document.getElementById("hmpg_url").focus();
                return false;
            }
            //홈페이지의 기본적인 유효성 검사
            // let urlRegex = /^(www\.)?([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$/;
            let urlRegex = /^(https?:\/\/)?([\w\d-]+\.)+[\w\d-]{2,}(\/[\w\d-./?%&=]*)?$/i
            if (!urlRegex.test(this.ent_info.hmpUrl)) {
                alert("유효하지 않은 홈페이지 주소입니다.");
                document.getElementById("hmpg_url").focus();
                return false;
            }
            //대표전화
            let tel1Regex = /^\d{2,3}$/;
            let tel2Regex = /^\d{3,4}$/;
            let tel3Regex = /^\d{4}$/;
            this.ent_tel1 = this.ent_tel1 ? this.ent_tel1.trim() : null
            this.ent_tel2 = this.ent_tel2 ? this.ent_tel2.trim() : null
            this.ent_tel3 = this.ent_tel3 ? this.ent_tel3.trim() : null
             //대표전화 null검사
             if ((this.ent_tel1 == null) || (this.ent_tel2 == null) || (this.ent_tel3 == null)) {
                alert("대표전화 번호를 입력해주세요.");

                // 각각의 경우에 맞는 포커스 지정
                if (this.ent_tel1 == null) {
                    document.getElementById("ent_tel1").focus();
                } else if (this.ent_tel2 == null) {
                    document.getElementById("ent_tel2").focus();
                } else if (this.ent_tel3 == null) {
                    document.getElementById("ent_tel3").focus();
                }
                return false;
            }

            if (!tel1Regex.test(this.ent_tel1)) {
                alert("첫 번째 번호는 2~3자리 숫자여야 합니다.");
                document.getElementById("ent_tel1").focus();
                return false;
            }

            if (!tel2Regex.test(this.ent_tel2)) {
                alert("두 번째 번호는 3~4자리 숫자여야 합니다.");
                document.getElementById("ent_tel2").focus();
                return false;
            }

            if (!tel3Regex.test(this.ent_tel3)) {
                alert("세 번째 번호는 4자리 숫자여야 합니다.");
                document.getElementById("ent_tel3").focus();
                return false;
            }

            //대표전화검증완료시 저장
            this.ent_info.entTelno = this.ent_tel1 + this.ent_tel2 + this.ent_tel3;

            //기업 출원 정보 확인
            if(!this.ent_info.entSeNm){
                alert("기업 출원 정보를 입력해주세요.")
                return false;
            }
            
            //출원 예정을 선택 시 주출원사여부 검사
            if(this.ent_info.entSeNm === 'applPrnmnt'){
                if(!this.ent_info.mainApplEntYn){
                    alert("출원사 유형을 선택해주세요.")
                    return false;
                }
            } else {
                this.ent_info.mainApplEntYn = null
            }

            //키워드 검사
            if(this.ent_info.selectedKeywords.length !== 0){
                if (this.ent_info.selectedKeywords.length < 3) {
                    alert("키워드를 선택 시 최소 3개를 선택하셔야 합니다.");
                    return false;
                }
            }

            return true;
        },

        //기업 수정
        updateEntRequest : function() {
            const vm = this;

            if(!vm.companyValidation()) return;

            let formData = new FormData();
            vm.insertFileList.forEach((item) => {
                formData.append('files', item.file); 
                formData.append('file_ty', item.file_ty); 
            });

            formData.append('deleteFile', JSON.stringify(vm.deleteFileList));
            formData.append("ent_info", JSON.stringify(vm.ent_info));
            vm.store.commit('setLoading', true);
            this.$setLoading(true);
            axios({
                url: '/ent/entInfoUpdate.file',
                method: 'post',
                headers: {
                    'Content-Type': 'multipart/form-data',
                    Authorization: vm.store.state.authorization,
                },
                data: formData
            }).then(function (res) {
                if(res.status === 200){
                    alert("기업정보 수정에 성공하였습니다.")
                    vm.manageEntInfo()
                }
            }).catch(function (error) {
                alert(error.response.data.message);
            }).finally(function () {
                vm.$setLoading(false);
            });;
        },

        entRegistDownload: function () {
            const vm = this;
            // let path = 'C:\\AIDT\\FILES\\KERIS/20240509_f8d82053-50b2-43bf-8132-45727h34asd.hwp'
            let path = '/AIDT/FILES/KERIS/20240509_f8d82053-50b2-43bf-8132-45727h34asd.hwp'
            this.$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, 'AI 디지털교과서 통합지원센터 신규 기업등록신청서(양식).hwp');
                } else {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = 'AI 디지털교과서 통합지원센터 신규 기업등록신청서(양식).hwp';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            }).catch(function (error) {
                // alert('파일 다운로드 실패, 다시 시도해주세요.');
                alert(vm.$getCmmnMessage("err024"))
            }).finally(function () {
                vm.$setLoading(true);
            });
        },

        //전화번호 셋팅
        settingTelNum : function(phoneNumber) {
            let barPhoneNumber = COMMON_UTIL.HyphenMinus(phoneNumber)
            const parts = barPhoneNumber.split('-');
            this.ent_tel1 =parts[0]
            this.ent_tel2 =parts[1]
            this.ent_tel3 =parts[2]
        },

        isCheckboxDisabled(index) {
            //선택 가능한 체크박스 개수를 6개로 제한 
            let isSelected = this.ent_info.selectedKeywords.includes(this.keywords[index].cdId);
            return this.ent_info.selectedKeywords.length >= 6 && !isSelected;
        },

        /******************** V2 *******************/

        //키워드 목록 조회
        async keywordSelectList() {
            try {
                const res = await keywordFindAll();
                this.keywords = res.data.data;
            } catch(error) {
                alert("키워드 목록 조회에 실패하였습니다.")
            }
        },

        fnKeywordViewList() {
            this.keywordSelectList()
        },

        handleFileDeleted(deletedFileKey) {
            let newFormData = new FormData;
            for (let [key, value] of this.file.entries()) {
                if (key !== deletedFileKey) {
                    newFormData.append(key, value);
                }
            }

            // 새로운 FormData 객체로 업데이트
            this.file = newFormData;
        }, 

        // 조회페이지 이동 
        manageEntInfo : function(){
            this.$emit("setPage", 2);
        },

        //기업출원 카테고리코드
        async findAllCtgry() {
            this.ctgryCdList = await this.$getCommonCode('entApplCtgryCd');
        },
    },
    watch: {
        "ent_info.selectedKeywords": function (newValue, oldValue) {},
    },
    computed: {},
    components: {
        'Attachment': Attachment,
        'PageNavigationBar':PageNavigationBar
    }, 
    created() {
        this.findAllCtgry()
    },
    mounted() {
        this.fnKeywordViewList()
        this.init()
    }
}
</script>
