<template>
    <div>
        <div class="w1400">
            <div class="info-bos">
                <section class="info-logo page-logo">
                    <!-- <img src="../../../../resources/jpg/info-logo.png" alt=""> -->

                    <h1>회원정보 수정</h1>
                </section>
                <div class="info-sec-grid">


                    <!-- 기본 회원정보 -->
                    <section class="info-sec">

                        <div>
                            <p class="info-th">아이디</p>
                            <span>{{ user.user_id }}</span>
                        </div>
                        <div class="info-pw">
                            <p class="info-th">비밀번호</p>
                            <span>********</span>
                        </div>
                        <div>
                            <p class="info-th">회원구분</p>
                            <span>{{ user.user_auth === "company" ? "기업회원" : "일반회원" }}</span>
                        </div>

                        <div class="info-th-email">
                            <p class="info-th">이메일</p>
                            <p><input type="text" class="info-input" v-model="user.user_eml" ref="user_eml"></p>
                            <button class="blue-btn" @click="emailDuplicateCheck">중복확인</button>
                        </div>
                        <div>
                            <p class="info-th">담당자명</p>
                            <p><input type="text" class="info-input" v-model="user.user_nm" ref="user_nm"></p>
                        </div>
                        <div class="info-pw-maill">
                            <p class="info-th">메일 구독서비스</p>
                            <!-- <div>
                                <input type="radio" name="gender">
                                <p>구독</p>
                                <input type="radio" name="gender">
                                <p>미구독</p>
                            </div> -->
                            <div>
                                <input type="radio" name="subscription" value="true" v-model="user.subscribe">
                                <p>구독</p>

                                <input type="radio" name="subscription" value="false" v-model="user.subscribe">
                                <p>미구독</p>
                            </div>
                        </div>

                    </section>


                    <!-- 기업 회원정보 -->
                    <section v-if="user.user_auth == 'company'" class="info-sec-1">

                        <section class="company-info">
                            <p>
                                <!-- <img :src="'http://localhost:8080' + logoFile.file_path + '/' + logoFile.file_nm + '.' + logoFile.file_extn_nm"
                                    width="100%" alt=""> -->
                                <img :src="logoPreview || 'http://localhost:8080' + logoFile.file_path + '/' + logoFile.file_nm + '.' + logoFile.file_extn_nm"
                                    width="100%" alt="">
                            </p>
                            <div class="blue-btn" @click="openlogoFileInput" style="cursor: pointer;">
                                로고 수정하기
                            </div>
                            <input type="file" accept="image/*" name="logoImg" id="logoImg" ref="logoImg"
                                        @change="logoUpload" style="display: none;" />
                        </section>
                        <div>
                            <p>사업자등록번호</p>
                            <span>{{ company.company_id }}</span>
                        </div>
                        <div>
                            <p>업체명</p>
                            <span>{{ company.company_nm }}</span>
                        </div>
                        <div class="join-sec2 joinsub">
                            <div class="join-sec-sub">
                                <p>우리회사 키워드</p>
                            </div>
                            <div>
                                <p v-show="checkedKeywords.length < 3" class="item-style err-text" style="color: red;">최소
                                    3개 ~ 최대 6개를 선택해주세요.
                                </p>
                                <p v-show="checkedKeywords.length == 6" class="item-style err-text" style="color: red;">최대
                                    6개까지 입니다.</p>
                                <div class=" keyword-wrap" style="padding: 1rem 0;">
                                    <ul>
                               
                                        <li v-for="(keyword, index) in keywords" :key="index">
                                            <!-- <input type="checkbox" :id="keyword.name" v-model="keyword.checked"
                                             class="keyword-label" :disabled="isCheckboxDisabled(index)"
                                            style="display: none;" /> -->
                                            <input type="checkbox" :id="keyword.name" v-model="keyword.checked"
                                             class="keyword-label" style="display: none;"/>
                                            <label :for="keyword.name" class="keyword">{{ keyword.name }}</label>
                                        </li>
                                        
                                    </ul>
                                </div>

                            </div>
                        </div>

                        <div>
                            <p>한줄소개</p>
                            <span><input type="text" name="" id="" v-model="company.company_simple_info" ref="company_simple_info"></span>

                        </div>
                        <div class="join-sec1 joinsub0-1">
                            <div class="join-sec-sub ">
                                <p>주소</p>
                            </div>
                            <div class="address-sec">
                                <div class="flex-start add-search">
                                    <input type="text" placeholder="우편번호" v-model="company['company_zip']" readonly />
                                    <button id="postcode" class="blue-btn" @click="openPostcode">검색</button>
                                </div>
                                <div>
                                    <input type="text" v-model="company['company_addr']" placeholder="주소" readonly />
                                </div>
                                <div>
                                    <input type="text" v-model="company['company_daddr']" placeholder="상세주소" ref="company_daddr" />
                                </div>
                            </div>
                        </div>
                        <div>
                            <p>홈페이지</p>
                            <span><input type="text" name="" id="" v-model="company.company_hp_url" ref="company_hp_url"></span>
                        </div>
                        <div>
                            <p>대표전화</p>
                            <span><input type="text" name="" id="" v-model="company.company_telno" ref="company_telno"></span>

                        </div>
                        <div class="info-sec-summary">
                            <details open>
                                <summary @click="initEditor(1)">기업소개</summary>
                                <div>
                                    <textarea name="smart1" id="smart1"></textarea>
                                </div>
                            </details>
                            <details open>
                                <summary @click="initEditor(2)">대표 기술 소개</summary>
                                <div>
                                    <textarea name="smart2" id="smart2"></textarea>
                                </div>
                            </details>
                            <details open>
                                <summary @click="initEditor(3)">서비스 소개</summary>
                                <div>
                                    <textarea name="smart3" id="smart3"></textarea>
                                </div>
                            </details>
                        </div>
                        <div class="info-th-file">
                            <p class="info-th">회사소개서</p>
                            <a style="font-size: 15px;" class="down-btn-1"
                                :href="'http://localhost:8080' + proFile.file_path + '/' + proFile.file_nm + '.' + proFile.file_extn_nm"
                                target='_blank' download>
                                {{ proFile.real_file_nm }}
                            </a>
                            <span>
                                <button class="blue-btn" @click="openProFileInput">변경</button>
                                <input type="file" name="companyProfile" id="companyProfile" ref="companyProfile"
                                    @change="companyProfileUpload" style="display:none" />
                            </span>
                        </div>
                        <div>
                            <p class="info-th">명함</p>
                            <span class="matchingbox-img">
                                <label for="file-input" class="file-input" @click="openCardFileInput">
                                    <img :src="cardPreview || 'http://localhost:8080' + cardFile.file_path + '/' + cardFile.file_nm + '.' + cardFile.file_extn_nm"
                                    width="100%" alt="">
                                </label>
                                <input type="file" accept="image/*" name="imgFile" id="businessCardImg" ref="businessCardImg"
                                @change="businessCardUpload" style="display: none;" /></span>
                        </div>
                    </section>



                    <section class="info-sec-bt">
                        <!-- <router-link to="/info.page"> -->
                            <button class="gray-btn" @click="goToInfoPage">이전</button>
                            <!-- <button class="blue-btn" @click="updateUser">저장하기</button> -->
                            <button class="blue-btn" v-if="user.user_auth == 'company'" @click="companyUpdate">저장하기</button>
                            <button class="blue-btn" v-if="user.user_auth === 'common'" @click="updateUser">저장하기</button>
                        <!-- </router-link> -->
                    </section>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { useStore } from "vuex";
import axios from "axios";
import crypto from "crypto-js";
import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer';
import '@toast-ui/editor/dist/toastui-editor.css';
import '@toast-ui/editor/dist/i18n/ko-kr';
import { faListSquares } from "@fortawesome/free-solid-svg-icons";

export default {
    data() {
        return {
            store: useStore(),
            fileList: [],
            logoFile: {},
            cardFile: {},
            proFile: {},
            company: {
                company_id: null,
                company_nm: null,
                company_info: null,
                company_point: null,
                company_technology: null,
                company_service: null,
                company_simple_info: null,
                company_zip: null,
                company_addr: null,
                company_daddr: null,
                company_hp_url: null,
                company_telno: null,
                file_id: null,
                user_id: null,
                keyword: '',
                company_matching_cnt: null,
                company_pick_cnt: null,
            },
            user: {
                user_id: null,
                user_pw: null,
                user_eml: null,
                user_auth: null,
                user_nm: null,
                subscribe: null,
            },
            oEditors: [],
            // 키워드 배열
            // keywords: ['#수학', '#영어', '#정보', '#초등', '#중등', '#고등', '#AI튜터', '#블록코딩', '#패턴인식', '#대시보드', '#학습분석', '#보편적학습설계', '#클라우드', '#AI보조교사', '#음성인식', '#학습맵', '#맞춤형콘텐츠'],
            keywords:[],
            selectedKeywords: [],
            checkedKeywords: [],
            originalSubscribe: null,
            originalEmail: null,
            emlDuplicateChecked: true,
            initializedEditors: [],
            cardPreview: null,
            logoPreview: null,
            file: null,
            deleteFileList: [],
            islogoFileChanged: false,
            isProFileChanged: false,
            isCardFileChanged: false,
            insertFileList: [],
        }
    },
    methods: {
        openPostcode() {
            new window.daum.Postcode({
                oncomplete: (data) => {
                    this.company.company_zip = data.zonecode;
                    this.company.company_addr = data.roadAddress;
                },
            }).open();
        },

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

        uploadFile() {
            this.$refs.fileInput.click();
        },

        userSelectOne: function () {
            const vm = this;
            axios({
                url: '/user/myPageUserSelectOne.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'user_id': vm.store.state.loginUser.user_id }
            }).then(function (response) {
                // vm.user = response.data
                vm.user.user_id = response.data.user_id;
                vm.user.user_eml = response.data.user_eml;
                vm.user.user_nm = response.data.user_nm;
                vm.user.user_auth = response.data.user_auth;
                vm.user.subscribe = response.data.subscribe;
                vm.originalSubscribe = response.data.subscribe;
                vm.originalEmail = response.data.user_eml;
                if (vm.user.user_auth == "company") {
                    vm.companySelectOne();
                }
            }).catch(function (error) {
                console.log("userSelectOne - error : ", error);
            });
        },

        companySelectOne: function () {
            const vm = this;
            axios({
                url: '/company/selectOneForMypage.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: { 'user_id': vm.user.user_id }
            }).then(function (response) {
                vm.company = response.data.result
                
                const selectedKeywordList = response.data.result.keyword;
                const selectedKeywords = selectedKeywordList.split('#').filter(keyword => keyword !== '').map(keyword => '#' + keyword);
                vm.selectedKeywords = selectedKeywords;
                vm.showKeywordList(selectedKeywords);
                if (response.data.selectFileList.length != 0) {
                    vm.fileList = response.data.selectFileList;
                    for (let i = 0; i < vm.fileList.length; i++) {
                        if (vm.fileList[i].file_ty == "logo") {
                            vm.logoFile = vm.fileList[i];
                        } else if (vm.fileList[i].file_ty == "card") {
                            vm.cardFile = vm.fileList[i]
                        } else if (vm.fileList[i].file_ty == "profile") {
                            vm.proFile = vm.fileList[i]
                        }

                    }
                }
                vm.initEditor(1)
                vm.initEditor(2)
                vm.initEditor(3)
            }).catch(function (error) {
                console.log("companySelectOne - error : ", error);
            });
        },

        downloadFile: function (item) {
            const vm = this;
            let path = item.file_path + '/' + item.file_nm + '.' + item.file_extn_nm;
            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);
                }

                this.$router.go(0);

            }).catch(function (error) {
                console.log('error - ', error)
                alert('에러발생');
            });
        },

        initEditor: function (idx) {
            const vm = this;
            if (this.initializedEditors[idx]) {
                return;
            }
            
            // 스마트 에디터 적용
            const oEditors = vm.oEditors;
            nhn.husky.EZCreator.createInIFrame({
                oAppRef: oEditors,
                elPlaceHolder: 'smart' + idx,
                sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
                htParams: {
                    bSkipXssFilter: true,
                    bUseVerticalResizer: true,
                    bUseModeChanger: true
                },
                fOnAppLoad: function () {
                    let initData = '';
                    switch (idx) {
                        case 1:
                            initData = vm.company.company_info;
                            break;
                        case 2:
                            initData = vm.company.company_technology;
                            break;
                        case 3:
                            initData = vm.company.company_service;
                            break;
                    }
                    oEditors.getById["smart" + idx].exec("PASTE_HTML", [initData]);
                },
                fCreator: "createSEditor2"
            });
            vm.initializedEditors[idx] = true;
        },
        
        updateUser : function(){
            if(!this.validationCheckForUser()){
                return 
            }        
            
            const vm = this;
            
            var iv = vm.store.state.key.iv;
            var salt = vm.store.state.key.salt;
            var passPhrase = vm.store.state.key.ENC_KEY;
            var keySize = 128;
            var iterationCount = 1000;
            var key128Bits100Iterations = crypto.PBKDF2(passPhrase, crypto.enc.Hex.parse(salt), { keySize: keySize / 32, iterations: iterationCount });

            let encryptedUserId = crypto.AES.encrypt(vm.user.user_id, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();
            let encryptedUserNm = crypto.AES.encrypt(vm.user.user_nm, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();
            let encryptedUserEm = crypto.AES.encrypt(vm.user.user_eml, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let data = {
                "user_id": encryptedUserId,
                "user_nm": encryptedUserNm,
                "user_eml": encryptedUserEm,
            }
            console.log('subscribe  - ', vm.originalSubscribe,'    ', vm.user.subscribe)
            axios({
                url: '/user/userUpdate.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: data
            }).then(function(response) {
                if(response.data == 1){
                    if(vm.originalSubscribe != vm.user.subscribe && vm.originalSubscribe == true){
                        vm.subscDelete()
                    } else if(vm.originalSubscribe != vm.user.subscribe && vm.originalSubscribe == false) {
                        vm.subscInsert()
                    } else {
                        alert("회원정보 수정이 완료되었습니다.")
                        vm.$router.push('/info.page');
                    }
                } else {
                    alert('회원정보 수정에 실패하였습니다.')
                }
            }).catch(function (error) {
                console.log('error - ', error)
                alert('유저 업데이트 에러발생');
            });
        },

        subscInsert : function() {
            const vm = this;

            var iv = vm.store.state.key.iv;
            var salt = vm.store.state.key.salt;
            var passPhrase = vm.store.state.key.ENC_KEY;
            var keySize = 128;
            var iterationCount = 1000;
            var key128Bits100Iterations = crypto.PBKDF2(passPhrase, crypto.enc.Hex.parse(salt), { keySize: keySize / 32, iterations: iterationCount });

            let encryptedUserId = crypto.AES.encrypt(vm.user.user_id, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();
            let encryptedUserEm = crypto.AES.encrypt(vm.user.user_eml, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let data = {
                "user_id": encryptedUserId,
                "user_eml": encryptedUserEm,
            }

            axios({
                url: '/subsc/subscInsert.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: data
            }).then(function (response) {
                if(response.data == 1){
                    alert("회원정보 수정이 완료되었습니다.")
                    vm.$router.push('/info.page');
                }             
            }).catch(function (error) {
                console.log('error - ', error)
                alert('구독 등록 에러발생');
            });
        },

        subscDelete : function() {
            const vm = this;

            var iv = vm.store.state.key.iv;
            var salt = vm.store.state.key.salt;
            var passPhrase = vm.store.state.key.ENC_KEY;
            var keySize = 128;
            var iterationCount = 1000;
            var key128Bits100Iterations = crypto.PBKDF2(passPhrase, crypto.enc.Hex.parse(salt), { keySize: keySize / 32, iterations: iterationCount });

            let encryptedUserEm = crypto.AES.encrypt(vm.user.user_eml, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let data = {
                "user_eml": encryptedUserEm,
            }

            axios({
                url: '/subsc/subscDelete.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: data
            }).then(function (response) {
                if(response.data == 1){
                    alert("회원정보 수정이 완료되었습니다.")
                    vm.$router.push('/info.page');
                }             
            }).catch(function (error) {
                console.log('error - ', error)
                alert('구독 취소 에러발생');
            });
        },

        emailDuplicateCheck : function() {
            let emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            if(!emailRegex.test(this.user.user_eml)){
                alert('이메일 형식이 올바르지 않습니다.')
                this.$refs.user_eml.focus();
                return ;
            }
            
            const vm = this;

            var iv = vm.store.state.key.iv;
            var salt = vm.store.state.key.salt;
            var passPhrase = vm.store.state.key.ENC_KEY;
            var keySize = 128;
            var iterationCount = 1000;
            var key128Bits100Iterations = crypto.PBKDF2(passPhrase, crypto.enc.Hex.parse(salt), { keySize: keySize / 32, iterations: iterationCount });

            let encryptedUserEm = crypto.AES.encrypt(vm.user.user_eml, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let data = {
                "user_eml": encryptedUserEm,
            }

            axios({
                url: '/user/userEmlCheck.json',
                method: 'post',
                headers: {
                    'Content-Type' : 'application/json; charset=UTF-8',
                },
                data: data
            }).then(function(response) {
                if(response.data == false){
                    vm.emlDuplicateChecked = false;
                    alert("사용할 수 없는 이메일입니다.")
                } else {
                    vm.emlDuplicateChecked = true;
                    alert("사용가능한 이메일입니다.")
                }
            }).catch(function(error){
                console.log('error - ', error)
                alert('이메일 중복체크 에러발생');
            });
        },

        showKeywordList : function(selectedKeywords) {
            const vm = this;
            axios({
                url: "/keyword/keywordList.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                },
            }).then(function (response) {
                vm.keywords = response.data.map(item => {
                    return {
                        name: item.keyword_nm, 
                        checked: (selectedKeywords && selectedKeywords.includes(item.keyword_nm)) ? true : false
                    };
                });
            }).catch(function (error) {
                console.log("keywordList - error : ", error);
            });
        },

         //로고 이미지 등록
         logoUpload: function (e) {
            const vm = this;

            const MAX_WIDTH = 340;
            const MAX_HEIGHT = 120;

            for (const file of e.target.files) {
                
                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 + "입니다.");
                            vm.$refs.logoImg.value= '';
                        } else {
                            vm.logoPreview = reader.result;
                            vm.file.append('logo_img', file);
                            vm.deleteFileList.push(vm.logoFile);
                            const fileItem = { file, file_ty: 'logo'};
                            vm.insertFileList.push(fileItem);
                        }   
                    };
                };
                reader.readAsDataURL(file);
                vm.islogoFileChanged = true;
            }
        },

        //명함 이미지 등록
        businessCardUpload: function (e) {
            const vm = this;

            const MAX_WIDTH = 1087;
            const MAX_HEIGHT = 614;

            for (const file of e.target.files) {
                
                var reader = new FileReader();
                reader.onload = function () {
                    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 + "픽셀" + "입니다.");
                            vm.$refs.businessCardImg.value = '';
                        } else {
                            vm.cardPreview = reader.result;
                            vm.file.append('business_card_img', file);
                            const fileItem = { file, file_ty: 'card'};
                            vm.insertFileList.push(fileItem);
                            vm.deleteFileList.push(vm.cardFile);
                        }
                    };
                };
                reader.readAsDataURL(file);
                vm.isCardFileChanged = true;
            }
        },

        //회사소개서 등록
        companyProfileUpload: function (e) {
            const vm = this;
            // for (const file of e.target.files) {
            //     vm.file.append('company_profile', file);
            // }
            const file = e.target.files[0];
            if(file){
                vm.proFile.real_file_nm = file.name;
                vm.file.append('company_profile',file)
                vm.isProFileChanged = true;
                const fileItem = { file, file_ty: 'profile'};
                vm.insertFileList.push(fileItem);
                vm.deleteFileList.push(vm.proFile);
            }
        },
        
        openlogoFileInput() {
            this.$refs.logoImg.click();
        },

        openProFileInput(){
            this.$refs.companyProfile.click();
        },
        
        openCardFileInput() {
            this.$refs.businessCardImg.click();
        },

        companyUpdate: function() {
            if (!this.validationCheckForUser() || !this.validationCheckForCompany()) {
                return;
            }

            const vm = this;
            const oEditors = vm.oEditors;
            let fields = ['company_info', 'company_technology', 'company_service'];

            for (let i = 0; i < fields.length; i++) {
                let idx = i + 1;

                oEditors.getById["smart"+idx].exec("UPDATE_CONTENTS_FIELD", []);
                vm.company[fields[i]] = document.getElementById("smart"+idx).value;
            }

            //키워드 바인딩
            vm.company['keyword'] = vm.checkedKeywords.join('');
  
            axios({
                url: '/company/companyUpdate.json',
                method: 'post',
                headers: {
                    'Content-Type' : 'application/json; charset=UTF-8',
                },
                data: vm.company
            }).then(function(response) {
                if(response.data == 1){
                    if(vm.insertFileList.length > 0){
                        vm.commonFileUpdate()
                    } else {
                        vm.updateUser()
                    }
                } else {
                    alert('회원정보 수정에 실패하였습니다.')
                }
            }).catch(function(error){
                console.log('error - ', error)
                alert('기업 업데이트 에러발생');
            });
        },
        
        commonFileUpdate : function() {
            const vm = this;
            let formData = new FormData();

            for (let i = 0; i < vm.insertFileList.length; i++) {
                formData.append('file', vm.insertFileList[i].file);
                formData.append('file_ty', vm.insertFileList[i].file_ty);
            }
            formData.append('deleteFile', JSON.stringify(vm.deleteFileList));
            formData.append("company", JSON.stringify(vm.company));

            axios({
                url: "/file/fileUpdateForUser.file",
                method: "post",
                headers: {
                    "Content-Type": "multipart/form-data; charset=UTF-8",
                },
                data: formData
            }).then(function (response) {
                if(response.data > 0 ){
                    vm.updateUser();
                } else {
                    alert('회원정보 수정에 실패하였습니다.')
                }
            }).catch(function (error) {
                console.log("commonFileUpdate - error : ", error);
            });
        },

        //일반회원 유효성 검사
        validationCheckForUser : function(){
            //이메일
            if(this.user.user_eml === null || this.user.user_eml === ''){
                alert('이메일은 필수값입니다.')
                this.$refs.user_eml.focus();
                return false;
            }
            if(!this.emlDuplicateChecked){
                alert('이메일 중복체크는 필수입니다.')
                this.$refs.user_eml.focus();
                return false;
            } 
            
            //담당자명
            let userNmRegex = /^[가-힣a-zA-Z\s]*$/;
            if(this.user.user_nm === null || this.user.user_nm === ''){
                alert('이름은 필수값입니다.')
                this.$refs.user_nm.focus();
                return false;
            } else if(!userNmRegex.test(this.user.user_nm)){
                alert('특수문자와 숫자는 입력하실 수 없습니다.')
                this.$refs.user_nm.focus()
                return false;
            }

            return true;
        },

        validationCheckForCompany : function(){
            //키워드
            if(this.checkedKeywords.length < 3 || this.checkedKeywords.length > 6){
                alert('키워드는 최소 3개에서 최대 6개를 선택해주세요.')
                return false;
            }
            
            //한줄소개
            if(this.company.company_simple_info === null || this.company.company_simple_info === ''){
                alert('기업 한줄 소개는 필수값입니다.')
                this.$refs.company_simple_info.focus();
                return false;
            }
            
            //기업주소
            if(this.company.company_zip === null || this.company.company_zip === '' ||
                this.company.company_addr === null || this.company.company_addr === '' ||
                this.company.company_daddr === null || this.company.company_daddr === ''){
                    alert('기업 주소를 입력해주세요.')
                    this.$refs.company_daddr.focus();
                    return false;
            }

            //기업홈페이지
            // if(this.company.company_hp_url === null || this.company.company_hp_url === ''){
            //     alert('기업 홈페이지는 필수값입니다.')
            //     this.$refs.company_hp_url.focus();
            //     return false;
            // }
            if (this.company.company_hp_url !== null && this.company.company_hp_url !== '') {
                if (!this.company.company_hp_url.startsWith('http://') && !this.company.company_hp_url.startsWith('https://')) {
                    alert("홈페이지 주소는 http:// 또는 https://로 시작해야합니다.");
                    this.$refs.company_hp_url.focus();
                    return false;
               }
            }

            //대표전화
            let telRegex = /^[0-9]*$/;
            if(this.company.company_telno === null || this.company.company_telno === ''){
                alert('대표전화번호 입력은 필수입니다.')
                this.$refs.company_telno.focus();
                return false;
            } else if(!telRegex.test(this.company.company_telno)){
                alert('대표전화번호는 숫자만 입력할 수 있습니다.')
                this.$refs.company_telno.focus();
                return false;
            }

            return true;
        },

        goToInfoPage: function() {
            this.$router.push('/info.page');
        }
    },
    watch: {
        'user.user_eml': {
            handler: function(newVal, oldVal) {
                if(this.originalEmail !== newVal) {
                    this.emlDuplicateChecked = false;
                }
            },
            immediate: false
        },

        keywords: {
            handler() {
                this.checkedKeywords = this.keywords.filter(keyword => keyword.checked).map(keyword => keyword.name); 
                
                if (this.checkedKeywords.length > 6) {
                    alert('최대 6개까지만 선택 가능합니다.');
                    let removedKeywords = this.checkedKeywords.splice(6);
                    removedKeywords.forEach(removedKeyword => {
                        let keyword = this.keywords.find(keyword => keyword.name === removedKeyword);
                        keyword.checked = false;
                    });
                }
            },
            deep: true
        }
    },
    computed: {

    },
    mounted() {
        console.log('Infosub mounted');
        this.file = new FormData()
        this.userSelectOne()
    }
}
</script>




