<template>
    <div class="join-page page">
        <div class="w1400">
            <div class="join-b">
                <div class="page-logo flex-start">
                    <img src="../../../../resources/jpg/data-img-text.png" alt="">
                    <h1>회원가입</h1>
                </div>
                <div class="join-b-button">
                    <input type="radio" id="company" v-model="selectedMembership" value="company">
                    <!-- <label for="company" class="radio-t t1" @click="initEditor()" -->
                    <label for="company" class="radio-t t1"
                        :style="{ backgroundColor: selectedMembership === 'company' ? '#e2ecfc' : '#86868644' }">
                        기업회원
                        <img src="../../../../resources/jpg/join-bt2.png" alt="">
                    </label>
                    <input type="radio" id="common" v-model="selectedMembership" value="common">
                    <label for="common" class="radio-t t2"
                        :style="{ backgroundColor: selectedMembership === 'common' ? '#e6fff1' : '#86868644' }">
                        일반회원
                        <img src="../../../../resources/jpg/join-bt.png" alt="">
                    </label>
                </div>
                <div class="join-text">
                    <p class="item-style err-text">※회원가입 유형을 선택해주세요.</p>
                </div>
            </div>
            <div v-if="selectedMembership === 'company'" class="join-b">
                <div class="login-info">
                    <div>
                        <h3>회원정보</h3>
                        <p>※ 기업회원의 경우 담당자 1인만 가입할 수 있습니다. 이미 가입한 기업은 중복 계정 생성이 불가합니다.
                        </p>
                        <hr>
                    </div>
                    <div class="join-sec1 joinsub0">
                        <div class="join-sec-sub ">
                            <span>아이디</span>
                        </div>
                        <div>
                            <input type="text" v-model="combinedUserId" @blur="validateID" class="id-input"
                                placeholder="아이디를 입력하세요." ref="user_id" />
                            <p v-show="validateId != null" class="item-style err-text">{{ validateId }}</p>
                        </div>
                        <div>
                            <button class="blue-btn join-blue-btn" @click="userIdCheck">중복확인</button>
                        </div>
                    </div>
                    <div class="join-sec3 joinsub">
                        <div class="join-sec-sub">
                            <span>비밀번호</span>
                        </div>
                        <div class="join-sub-input">
                            <input type="password" v-model="user['user_pw']" @change="passwordSyncCheck()"
                                placeholder="비밀번호 6~20자 영문, 숫자 조합" ref="user_pw">
                        </div>
                    </div>
                    <div class="join-sec4 joinsub">
                        <div class="join-sec-sub">
                            <span>비밀번호 확인</span>
                        </div>
                        <div class="join-sub-input">
                            <input type="password" v-model="pwCheck" @keyup="passwordSyncCheck()" placeholder="비밀번호 확인">
                            <div v-if="this.passwordCheckFlag === true" class="item-style suc-text">비밀번호 일치</div>
                            <div v-else-if="this.passwordCheckFlag === false" class="item-style err-text">비밀번호 불일치</div>
                        </div>

                    </div>
                    <div class="join-sec5 joinsub">
                        <div class="join-sec-sub">
                            <span>담당자명</span>
                        </div>
                        <div class="join-uplodebox">
                            <input type="text" v-model="user['user_nm']" ref="user_nm">
                        </div>
                    </div>
                    <div class="join-sec5-1 ">
                        <div class="join-sec-sub join-sec-1">
                            <span>담당자 명함</span>
                        </div>
                        <div class="join-sub-input join-imgbox" @click="openCardFileInput">
                            <p>1087 X 614</p>
                            <img v-if="cardPreview" :src="cardPreview" />
                            <input type="file" accept="image/*" name="imgFile" id="businessCardImg" ref="businessCardImg"
                            @change="businessCardUpload" style="display: none;" />
                        </div>
                        <p></p>
                        <p class="text-info">※ 명함크기는 최소크기 1087 x 614 픽셀 이상 등록 가능합니다.</p>
                    </div>
                    <div class="join-sec6">
                        <div class="join-sec-sub">
                            <span>이메일</span>
                        </div>
                        <div class="email-sec">
                            <div>
                                <input type="text" name="email_id" id="email_id" v-model="email_id" ref="email_id">
                            </div>
                            <div>@</div>
                            <div>
                                <input v-if="select_email_dns == null" type="text" name="email_dns" id="email_dns"
                                    v-model="email_dns" ref="email_dns">
                                <input v-else type="text" name="email_dns" id="email_dns" v-model="select_email_dns"
                                    ref="email_dns">
                            </div>
                            <div>
                                <select name="email_sel" id="email_sel" v-model="select_email_dns">
                                    <option :value=null>직접 입력</option>
                                    <option value="naver.com">naver.com</option>
                                    <option value="hanmail.net">hanmail.net</option>
                                    <option value="gmail.com">google.com</option>
                                    <option value="daum.net">daum.net</option>
                                    <option value="kakao.com">kakao.com</option>
                                    <option value="icloud.com">icloud.com</option>
                                </select>
                            </div>
                            <div>
                                <button class="blue-btn join-blue-btn" @click="emailDuplicateCheck">중복확인</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="login-info2">
                    <div>
                        <h3>회사소개</h3>
                        <hr>
                    </div>
                    <div class="login-info-grid">
                        <div class="login-info-grid-1">
                            <div class="join-sec0">
                                <div class="uploaded-box">

                                    <div class="uploaded-box-radius">
                                        <p>LOGO</p>
                                        <img v-if="logoPreview" :src="logoPreview" />
                                    </div>
                                    
                                    <div class="btn-upload-join" @click="openFileInput">
                                        우리회사 로고 업로드하기
                                    </div>
                                    
                                    <input type="file" accept="image/*" name="logoImg" id="logoImg" ref="logoImg"
                                    @change="logoUpload" style="display: none;" />
                                </div>
                                <p class="text-info">※ 명함크기는 최대크기 340 x 120 픽셀 까지 등록 가능합니다.</p>
                            </div>
                        </div>
                        <div class="login-info-grid-2">
                            <div class="join-sec1 joinsub0">
                                <div class="join-sec-sub ">
                                    <span>사업자등록번호</span>
                                </div>
                                <div>
                                    <input type="text" v-model="company.company_id" @blur="validateBusinessNumber"
                                        class="id-input" placeholder="사업자등록번호를 숫자만 입력하세요." ref="company_id" />
                                    <p v-show="businessNumber != null">{{ businessNumber }}</p>
                                </div>
                                <div>
                                    <!-- <button @click="companyIdCheck" class="blue-btn join-blue-btn">중복확인</button> -->
                                    <button @click="checkBusinessId" class="blue-btn join-blue-btn">중복확인</button>
                                </div>
                            </div>
                            <div class="join-sec1 joinsub0-1">
                                <div class="join-sec-sub ">
                                    <span>회사명</span>
                                </div>
                                <div>
                                    <input type="text" v-model="company['company_nm']" placeholder="회사명을 입력해주세요."
                                        ref="company_nm">
                                </div>
                            </div>
                            <div class="join-sec1 joinsub0-1">
                                <div class="join-sec-sub ">
                                    <span>한 줄 소개</span>
                                </div>
                                <div>
                                    <input type="text" v-model="company['company_simple_info']"
                                        placeholder="20자 이내로 회사를 소개해주세요." maxlength='20' ref="company_simple_info">
                                </div>
                            </div>
                            <div class="join-sec1 joinsub0-1">
                                <div class="join-sec-sub ">
                                    <span>주소</span>
                                </div>
                                <div class="address-sec">
                                    <div class="flex-start add-search">
                                        <input type="text" placeholder="우편번호" v-model="company['company_zip']" readonly
                                            ref="company_zip" />
                                        <button id="postcode" class="blue-btn join-blue-btn"
                                            @click="openPostcode">검색</button>
                                    </div>
                                    <div>
                                        <input type="text" v-model="company['company_addr']" placeholder="주소" readonly
                                            ref="company_addr" />
                                    </div>
                                    <div>
                                        <input type="text" v-model="company['company_daddr']" placeholder="상세주소"
                                            ref="company_daddr" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="join-sec1 joinsub0-1">
                            <div class="join-sec-sub ">
                                <span>홈페이지</span>
                            </div>
                            <div>
                                <input type="text" v-model="company['company_hp_url']" placeholder="회사 홈페이지 주소를 입력해주세요."
                                    ref="company_hp_url">
                            </div>
                        </div>
                        <div class="join-sec1 joinsub0-1">
                            <div class="join-sec-sub ">
                                <span>대표전화</span>
                            </div>
                            <div class="tell-sec">
                                <select v-model="tel1" style="margin-left: 0px;">
                                    <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>
                                </select>
                                <span>-</span>
                                <input type="text" v-model="tel2" ref="tel2">
                                <span>-</span>
                                <input type="text" v-model="tel3" ref="tel3">
                            </div>
                        </div>
                        <div class="join-sec2 joinsub">
                            <div class="join-sec-sub">
                                <span>우리회사 키워드</span>
                            </div>
                            <div>
                                <p v-show="selectedKeywords.length < 3" class="item-style err-text">최소 3개 ~ 최대 6개를 선택해주세요.
                                </p>
                                <p v-show="selectedKeywords.length == 6" class="item-style err-text">최대 6개까지 입니다.</p>
                                <div class="keyword-wrap">
                                    <ul>
                                        <li v-for="(keyword, index) in keywords" :key="index">
                                            <input type="checkbox" :id="keyword" v-model="selectedKeywords" :value="keyword"
                                                class="keyword-label" :disabled="isCheckboxDisabled(index)"
                                                style="display: none;" />
                                            <label :for="keyword" class="keyword">{{ keyword }}</label>
                                        </li>
                                    </ul>
                                </div>

                            </div>
                        </div>
                    </div>
                    <div class="login-info-grid-3">
                        <div class="join-sec3  j-s-3">
                            <div class="join-sec-sub">
                                <span>회사소개글</span>
                            </div>
                            <div class="join-sub-input">
                                <details>
                                    <summary @click="initEditor(1)">기업소개</summary>
                                    <div>
                                        <textarea name="smart1" id="smart1" v-model="company['company_info']"></textarea>
                                    </div>
                                </details>
                                <details>
                                    <summary @click="initEditor(2)">대표 기술 소개</summary>
                                    <div>
                                        <textarea name="smart2" id="smart2"
                                            v-model="company['company_technology']"></textarea>
                                    </div>
                                </details>
                                <details>
                                    <summary @click="initEditor(3)">서비스 소개</summary>
                                    <div>
                                        <textarea name="smart3" id="smart3" v-model="company['company_service']"></textarea>
                                    </div>
                                </details>
                            </div>
                        </div>
                        <div class="join-sec4 ">
                            <div class="join-sec-sub join-sec-1">
                                <span>회사소개서 첨부파일</span>
                            </div>
                            <div class="join-sub-input">
                                <input type="file" name="companyProfile" id="companyProfile" ref="companyProfile"
                                    @change="companyProfileUpload" />
                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="join-email-bt flex-start">
                        <input type="checkbox" v-model="subscribe">
                        <span>E-mail 구독서비스를 신청하시겠습니까?</span>
                    </div>
                    <div class="join-end-bt">
                        <button @click="goBack">이전</button>
                        <button @click="commonFileInsert">회원가입</button>
                    </div>
                </div>
            </div>
            <!-- 일반회원↓ -->
            <div v-if="selectedMembership === 'common'" class="join-b">
                <div class="login-info">
                    <div>
                        <h3>회원정보</h3>
                        <hr>
                    </div>
                    <div class="join-sec1 joinsub0">
                        <div class="join-sec-sub ">
                            <span>아이디</span>
                        </div>
                        <div>
                            <input type="text" v-model="combinedUserId" @blur="validateID" class="id-input"
                                placeholder="아이디를 입력하세요." ref="user_id" />
                            <p v-show="validateId != null" class="item-style err-text">{{ validateId }}</p>
                        </div>
                        <div>
                            <button class="blue-btn join-blue-btn " @click="userIdCheck">중복확인</button>
                        </div>
                    </div>
                    <div class="join-sec3 joinsub">
                        <div class="join-sec-sub">
                            <span>비밀번호</span>
                        </div>
                        <div class="join-sub-input">
                            <input type="password" v-model="user['user_pw']" @change="passwordSyncCheck()"
                                placeholder="비밀번호 6~20자 영문, 숫자 조합" ref="user_pw">
                        </div>
                    </div>
                    <div class="join-sec4 joinsub">
                        <div class="join-sec-sub">
                            <span>비밀번호 확인</span>
                        </div>
                        <div class="join-sub-input">
                            <input type="password" v-model="pwCheck" @keyup="passwordSyncCheck()" placeholder="비밀번호 확인">
                            <div v-if="this.passwordCheckFlag" class="item-style suc-text">비밀번호 일치</div>
                            <div v-else-if="this.passwordCheckFlag === false" class="item-style err-text">비밀번호 불일치</div>
                        </div>

                    </div>
                    <div class="join-sec5 joinsub">
                        <div class="join-sec-sub">
                            <span>담당자명</span>
                        </div>
                        <div class="join-uplodebox">
                            <input type="text" v-model="user['user_nm']" ref="user_nm">
                        </div>
                    </div>
                    <div class="join-sec6">
                        <div class="join-sec-sub">
                            <span>이메일</span>
                        </div>
                        <div class="email-sec">
                            <div>
                                <input type="text" name="email_id" id="email_id" v-model="email_id" ref="email_id">
                            </div>
                            <div>@</div>
                            <div>
                                <input v-if="select_email_dns == null" type="text" name="email_dns" id="email_dns"
                                    v-model="email_dns" ref="email_dns">
                                <input v-else type="text" name="email_dns" id="email_dns" v-model="select_email_dns"
                                    ref="email_dns">
                            </div>
                            <div>
                                <select name="email_sel" id="email_sel" v-model="select_email_dns">
                                    <option :value=null>직접 입력</option>
                                    <option value="naver.com">naver.com</option>
                                    <option value="hanmail.net">hanmail.net</option>
                                    <option value="gmail.com">google.com</option>
                                    <option value="daum.net">daum.net</option>
                                    <option value="kakao.com">kakao.com</option>
                                    <option value="icloud.com">icloud.com</option>
                                </select>
                            </div>
                            <div>
                                <button class="blue-btn join-blue-btn" @click="emailDuplicateCheck">중복확인</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="join-email-bt flex-start">
                        <input type="checkbox" v-model="subscribe">
                        <span>E-mail 구독서비스를 신청하시겠습니까?</span>
                    </div>
                    <div class="join-end-bt">
                        <button @click="goBack">이전</button>
                        <button @click="userInsert">회원가입</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!---------------------------------------------------------------------------------------------------------------->


    <!-- 회원가입 완료 모달 -->
    <div class="modal-wrapper" v-if="isVisible">
        <div class="modal-container">
            <div class="login-modal">


                <h1>회원가입 안내</h1>

                <p>회원가입이 완료되었습니다.

                    회원가입 승인 전까지 특정 서비스는 이용하실 수 없으며,
                    승인 이후 모든 서비스를 이용하실 수 있습니다.
                    또한, 해당 기업은 같은 기업명으로 중복 계정 생성이 불가합니다.
                </p>

            </div>
            <div>
                <button class="blue-btn" @click="hideDiv">확인</button>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import COMMON_UTIL from '../../../../resources/js/commonUtil.js';
import { useStore } from "vuex";
import crypto from "crypto-js";
import { faLastfmSquare } from '@fortawesome/free-brands-svg-icons';

export default {
    data() {
        return {
            fileList: [],
            company: {
                company_id: null,
                company_nm: null,
                company_info: 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: '',
            },
            user: {
                user_id: null,
                user_pw: null,
                user_eml: null,
                user_auth: null,
                user_nm: null,
            },
            file: null,
            // 키워드 배열
            // keywords: ['#수학', '#영어', '#정보', '#초등', '#중등', '#고등', '#AI튜터', '#블록코딩', '#패턴인식', '#대시보드', '#학습분석', '#보편적학습설계', '#클라우드', '#AI보조교사', '#음성인식', '#학습맵', '#맞춤형콘텐츠'],
            keywords: [],
            selectedKeywords: [],
            // 이미지
            logo_img: null,
            business_card_img: null,
            company_profile: null,
            //기업 ID 중복 확인
            companyIdCheck_boolean: null,
            //사용자 ID 중복 확인
            userIdCheck_boolean: null,
            //PW 확인
            pwCheck: null,
            passwordCheckFlag: null,
            // 이메일
            email_id: null,
            email_dns: null,
            select_email_dns: null,
            // 회원구분
            selectedMembership: '',
            isVisible: false,
            selectedImage: null,
            oEditors: [],
            logoPreview: null,
            cardPreview: null,
            combinedUserId: '',
            showModal: false,
            showModal2: false,
            tagInput: '#',
            tags: [],
            businessNumber: null,
            validateId: null,
            store: useStore(),
            // 회사대표연락처
            tel1: null,
            tel2: null,
            tel3: null,
            initializedEditors: {},
            subscribe: false,
            emlDuplicateChecked: false,
            logoFile: {},
            cardFile: {},
            proFile: {},
            store: useStore(),
        }
    },
    methods: {
        // validateID
        validateID() {
            if (COMMON_UTIL.idCheck(this.user.user_id) === false) {
                this.validateId = '5~20자의 영문 소문자, 숫자와 특수기호(_),(-)만 사용 가능합니다.';
            } else {
                this.validateId = '';
            }
        },
        validateBusinessNumber() {
            if (COMMON_UTIL.businessNumber(this.company.company_id) === false) {
                this.businessNumber = '사업자등록번호를 다시 한번 확인해주세요.';
            } else {
                this.businessNumber = '';
            }
        },
        isCheckboxDisabled(index) {
            // 선택 가능한 체크박스 개수를 6개로 제한
            return this.selectedKeywords.length === 6 && !this.selectedKeywords.includes(this.keywords[index]);
        },
        removeTag(index) {
            this.selectedKeywords.splice(index, 1);
        },
        //비밀번호 매칭 확인
        passwordSyncCheck: function () {
            if (this.user.user_pw != this.pwCheck) this.passwordCheckFlag = false;
            else this.passwordCheckFlag = true;
        },
        // 로고 이미지 업로드
        openFileInput() {
            this.$refs.logoImg.click();
        },
        openCardFileInput() {
            this.$refs.businessCardImg.click();
        },
        fileUpload(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.selectedImage = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        },
        fileRemove(idx) {

            this.fileList.splice(idx, 1);

            if (this.selectedImage === this.fileList[idx]) {
                this.selectedImage = null;
            }
        },

        //company ID 중복 검사
        companyIdCheck: function () {
            const vm = this;
            axios({
                url: '/company/companySelectOne.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.company
            }).then(function (response) {
                // console.log("idCheck - response : ", response.data);
                if (response.data != null) {
                    alert("중복된 사업자등록번호 입니다.");
                    vm.companyIdCheck_boolean = false;
                    return false;
                } else {
                    alert("사용가능한 사업자등록번호 입니다.");
                    vm.companyIdCheck_boolean = true;
                    return true;
                }
            }).catch(function (error) {
                console.log("companyIdCheck - error : ", error);
                alert("중복검사 오류, 다시 시도해주세요.");
            });
        },
        //user ID 중복 검사
        userIdCheck: function () {
            const vm = this;
            let userIdRegex = /^[a-z0-9_-]{5,20}$/;
            if (!userIdRegex.test(vm.user.user_id)) {
                alert('아이디는 5~20자의 영문 소문자, 숫자와 특수기호(_),(-)만 사용 가능합니다.')
                vm.$refs.user_id.focus();
                return false;
            }


            axios({
                url: '/user/userIdCheck.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.user
            }).then(function (response) {
                // console.log("idCheck - response : ", response.data);
                if (response.data != false) {
                    alert("중복된 ID 입니다.");
                    vm.userIdCheck_boolean = false;
                    return false;
                } else {
                    alert("사용가능한 ID 입니다.");
                    vm.userIdCheck_boolean = true;
                    return true;
                }
            }).catch(function (error) {
                console.log("userIdCheck - error : ", error);
                alert("중복검사 오류, 다시 시도해주세요.");
            });
        },

        userInsert: function () {
            this.user.user_auth = this.selectedMembership;

            const vm = this;

            // 유효성 검사
            if (!this.validationCheckForUser()) {
                return;
            }

            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 encryptedUserPw = crypto.AES.encrypt(vm.user.user_pw, 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_pw": encryptedUserPw,
                "user_nm": encryptedUserNm,
                "user_eml": encryptedUserEm,
                "user_auth": vm.user.user_auth
            }

            axios({
                url: "/user/userInsert.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                // data: vm.user,
                data: data
            }).then(function (response) {
                if (response.data == 1) {
                    if (vm.subscribe) {
                        vm.subscInsert()
                    } else if (vm.user.user_auth === 'company') {
                        vm.companyInsert()
                    } else {
                        vm.isVisible = true;
                    }
                }
            }).catch(function (error) {
                console.log("userInsert - error : ", error);
                vm.user.user_pw = null;
                vm.pwCheck = null;
            });
        },

        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 && vm.user.user_auth == "company") {
                    vm.companyInsert();
                } else {
                    vm.isVisible = true;
                }
            }).catch(function (error) {
                console.log("userInsert - error : ", error);
                vm.user.user_pw = null;
                vm.pwCheck = null;
            });
        },

        //회원가입 등록
        companyInsert: function () {
            const vm = this;

            //에디터 내의 내용을 바인딩(기업소개, 대표기술소개, 서비스소개)
            const oEditors = this.oEditors;
            let fields = ['company_info', 'company_technology', 'company_service'];

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

                oEditors.getById[editorId].exec("UPDATE_CONTENTS_FIELD", []);
                this.company[fields[i]] = document.getElementById(editorId).value;
            }
            //키워드 바인딩
            this.company['keyword'] = this.selectedKeywords.join('');
            //기업 대표 연락처 바인딩
            this.company['company_telno'] = this.tel1 + this.tel2 + this.tel3;
            // for (let i = 0; i < vm.tags.length; i++) {
            //     vm.company.keyword += vm.tags[i];
            // }

            axios({
                url: "/company/companyInsert.json",
                method: "post",
                headers: {
                    "Content-Type": "application/json; charset=UTF-8",
                },
                data: vm.company,
            }).then(function (response) {
                // vm.userInsert();
                vm.isVisible = true;
            }).catch(function (error) {
                console.log("companyInsert - error : ", error);
                vm.user.user_pw = null;
                vm.pwCheck = null;
            });
        },

        // file 유효성 검사
        validateFile: function () {
            if (COMMON_UTIL.isEmpty(this.file)) {
                alert('파일을 첨부해주세요.');
                return false;
            }
        },
        //file 등록
        commonFileInsert: function () {

            //기업회원 유효성 검사
            if (!this.validationCheckForUser() || !this.validationCheckForCompany()) {
                return;
            }
            const vm = this;

            vm.file.append('params', JSON.stringify(this.company));
            axios({
                url: "/commonFile/commonFileInsert.file",
                method: "post",
                headers: {
                    "Content-Type": "multipart/form-data; charset=UTF-8",
                },
                data: vm.file,
            }).then(function (response) {
                vm.company["file_id"] = response.data;
                vm.userInsert();
            }).catch(function (error) {
                console.log("commonFileInsert - 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.logoFile = file;
                        }
                    };
                };
                reader.readAsDataURL(file);

            }
        },
        //명함 이미지 등록
        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.file.append('business_card_img', file);
                            vm.cardPreview = reader.result;
                            vm.cardFile = file;
                        }
                    };
                };
                reader.readAsDataURL(file);
            }
        },
        companyProfileUpload: function (e) {
            const vm = this;
            for (const file of e.target.files) {
                vm.file.append('company_profile', file);
                vm.proFile = file;
            }
        },
        //유효성 검사
        joinInsertCheck: function () {
            const commonValidation = () => {
                if (COMMON_UTIL.isEmpty(this.user.user_id)) {
                    alert('ID를 입력해주세요.');
                    return false;
                }

                if (this.idChcek_boolean === false) {
                    alert("ID 중복검사를 완료해주세요.")
                    return false;
                }

                if (COMMON_UTIL.isEmpty(this.user.user_pw)) {
                    alert('비밀번호를 입력해주세요.');
                    return false;
                }

                if (COMMON_UTIL.pwCheck(this.user.user_pw) === false) {
                    alert('8~16자의 영문 대/소문자, 숫자, 특수문자를 사용해 주세요.');
                    return false;
                }

                if (COMMON_UTIL.isEmpty(this.user.user_nm)) {
                    alert('이름을 입력해주세요.');
                    return false;
                }

                if (COMMON_UTIL.isEmpty(this.email_id)) {
                    alert('이메일 ID를 입력해주세요.');
                    return false;
                }

                if (COMMON_UTIL.isEmpty(this.email_dns)) {
                    alert('이메일을 선택 혹은 입력해주세요.');
                    return false;
                }
                return true;
            };

            if (selectedMembership === 'company') {
                if (!commonValidation()) {
                    return false;
                }

                if (COMMON_UTIL.isEmpty(this.combinedUserId)) {
                    alert('기업회원 별칭을 입력해주세요.');
                    return false;
                }
            } else {
                return commonValidation();
            }

            return true;
        },
        showDiv: function () {
            this.isVisible = true;
        },
        hideDiv: function () {
            this.$router.push({ path: '/Login.page', query: {} });
            this.isVisible = false;
        },

        // OPEN API로 입력받은 사업자번호가 유효한지 확인
        checkBusinessId: function () {
            let companyIdRegex = /^\d{10}$/;
            if (!companyIdRegex.test(this.company.company_id)) {
                alert('사업자등록번호는 10자리의 숫자만 입력할 수 있습니다.')
                this.$refs.company_id.focus();
                return;
            }

            let data = {
                "b_no": [this.company.company_id],
            };
            let serviceKey = "tv%2BMQ3E5HDTJC%2FIesanH6vabhvAikzVV3P5%2F5UhoEuCTMWjNnWhPy36jCpn13qPP5tmN%2Fx2eEg0WAK73VZv5tA%3D%3D"
            axios({
                url: "https://api.odcloud.kr/api/nts-businessman/v1/status?serviceKey=" + serviceKey,
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json"
                },
                data: data,
            }).then(response => {
                if (response.data.match_cnt > 0) {
                    this.companyIdCheck();
                } else {
                    alert('유효하지 않은 사업자 번호입니다.')
                }
            }).catch(error => {
                console.log("checkBusinessId - error : ", error);
                alert('API 요청에 실패하였습니다.')
            });

        },

        // 주소 입력 메서드
        openPostcode() {
            new window.daum.Postcode({
                oncomplete: (data) => {
                    // 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분
                    this.company.company_zip = data.zonecode;
                    this.company.company_addr = data.roadAddress;
                },
            }).open();
        },

        initEditor: function (idx) {
            if (this.initializedEditors[idx]) {
                return;
            }

            // 스마트 에디터 적용
            const oEditors = this.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 = '<div align="" style=""><div align="" style=""><div align="" style=""><div align="" style=""><div align="" style=""><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><p><span style="font-size: 14pt; font-family: Tahoma;"><b>■ 기업명</b></span></p></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><p><b><span style="color: rgb(136, 136, 136); font-size: 14pt; font-family: Tahoma;">■</span><span style="font-size: 14pt; font-family: Tahoma;">&nbsp;소개</span></b></p></blockquote><p><br></p><p><br></p><p></p></div></div></div></div><p><br></p></div><p><br></p>';
                            break;
                        case 2:
                            initData = '<div align="" style=""><div align="" style=""><div align="" style=""><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b><span style="font-size: 14pt; font-family: Tahoma;">기술명</span></b></blockquote><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">적용기술</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">원리</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">활용</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">적용사례</b></blockquote><p><br></p><p><br></p><p></p></div></div></div><p><br></p>';
                            break;
                        case 3:
                            initData = '<div align="" style=""><div align="" style=""><div align="" style=""><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">서비스명</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">대상</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">과목</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">적용기술</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">세부기능</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">적용효과</b></blockquote><p><b><br></b></p><p><b><br></b></p><blockquote class="se2_quote3" style="margin: 0px 0px 30px; padding: 10px; border: 1px dashed rgb(204, 204, 204); color: rgb(136, 136, 136);"><b><span style="font-size: 14pt; font-family: Tahoma;">■&nbsp;</span></b><b style="font-family: Tahoma; font-size: 14pt;">적용사례</b></blockquote><p><br></p><p><br></p><p></p></div></div></div><p><br></p>';
                            break;
                    }
                    oEditors.getById["smart" + idx].exec("PASTE_HTML", [initData]);
                },
                fCreator: "createSEditor2"
            });
            this.initializedEditors[idx] = true;
        },

        emailDuplicateCheck: 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: '/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('이메일 중복체크 에러발생');
            });
        },

        //일반회원 유효성검사
        validationCheckForUser: function () {
            //유저 아이디
            let userIdRegex = /^[a-z0-9_-]{5,20}$/;
            if (!this.userIdCheck_boolean) {
                alert('아이디 중복체크는 필수입니다.');
                this.$refs.user_id.focus();
                return false;
            } else if (!userIdRegex.test(this.user.user_id)) {
                alert('아이디는 5~20자의 영문 소문자, 숫자와 특수기호(_),(-)만 사용 가능합니다.')
                this.$refs.user_id.focus();
                return false;
            }
            //유저 패스워드
            let passwordRegex = /^[A-Za-z0-9]{6,20}$/;
            if (!this.passwordCheckFlag) {
                alert('비밀번호가 불일치합니다.')
                this.$refs.user_pw.focus();
                return false;
            } else if (!passwordRegex.test(this.user.user_pw)) {
                alert('비밀번호는 6~20자의 영문, 숫자만 사용 가능합니다.')
                this.$refs.user_pw.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;
            }

            //유저 이메일

            if (this.email_id === null || this.email_id === '') {
                alert('이메일은 필수값입니다.')
                this.$refs.email_id.focus();
                return false;
            }

            if (this.select_email_dns == null) {
                if (this.email_dns === null || this.email_dns === '') {
                    alert('이메일은 필수값입니다.')
                    this.$refs.email_dns.focus();
                    return false;
                } else {
                    let emailDnsRegex = /^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
                    if (!emailDnsRegex.test(this.email_dns)) {
                        alert('이메일 형식이 올바르지 않습니다.')
                        this.$refs.email_dns.focus();
                        return false;
                    }
                }
            }
            if (!this.emlDuplicateChecked) {
                alert('이메일 중복체크는 필수입니다.');
                this.$refs.email_id.focus();
                return false;
            }

            //유저 권한
            return true;
        },

        //기업회원 유효성검사
        validationCheckForCompany: function () {
            //기업아이디
            var companyIdRegex = /^\d{10}$/;
            if (!this.companyIdCheck_boolean) {
                alert('사업자등록번호 중복체크는 필수입니다.')
                this.$refs.company_id.focus();
                return false;
            } else if (!companyIdRegex.test(this.company.company_id)) {
                alert('사업자등록번호는 10자리의 숫자만 입력할 수 있습니다.')
                this.$refs.company_id.focus();
                return false;
            }
            //기업명
            if (this.company.company_nm === null || this.company.company_nm === '') {
                alert('회사명은 필수값입니다.')
                this.$refs.company_nm.focus();
                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;
            // } else 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;
            // }
            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;
               }
            }
            
            //기업대표번호
            var telRegex = /^\d{3,4}$/;
            if (this.tel1 === null || this.tel1 === '' ||
                this.tel2 === null || this.tel2 === '' ||
                this.tel3 === null || this.tel3 === '') {
                alert('대표전화 입력은 필수입니다.')
                this.$refs.tel2.focus();
                return false;
            }
            if (!telRegex.test(this.tel2)) {
                alert('3~4자리의 숫자만 입력 가능합니다.')
                this.$refs.tel2.focus();
                return false;
            }
            if (!telRegex.test(this.tel3)) {
                alert('3~4자리의 숫자만 입력 가능합니다.')
                this.$refs.tel3.focus();
                return false;
            }

            //키워드
            if (this.selectedKeywords.length < 3 || this.selectedKeywords.length > 6) {
                alert('키워드는 최소 3개에서 최대 6개를 선택해주세요.')
                return false;
            }
            //첨부파일
            if (this.cardFile.size === undefined) {
                alert('명함파일 등록은 필수입니다.')
                return false;
            }
            if (this.logoFile.size === undefined) {
                alert('회사로고 파일 등록은 필수입니다.')
                return false;
            }
            if (this.proFile.size === undefined) {
                alert('회사소개서 등록은 필수입니다.')
                return false;
            }
            const oEditors = this.oEditors;
            let fields = ['company_info', 'company_technology', 'company_service'];

            for (let i = 0; i < fields.length; i++) {
            
                let idx = i + 1;
                let editorId = "smart" + idx;
                if (!this.initializedEditors[idx]) {
                    alert('회사소개글 등록은 필수입니다.')
                    return false;
                } 

                oEditors.getById[editorId].exec("UPDATE_CONTENTS_FIELD", []);
                this.company[fields[i]] = document.getElementById(editorId).value;
            }
            
            return true;
        },
        goBack() {
            this.$router.go(-1)
        }

    },




    watch: {
        "email_id": function () {
            this.user["user_eml"] = this.email_id + "@" + this.email_dns;
        },
        // "email_dns": function () {
        //     this.user["user_eml"] = this.email_id + "@" + this.email_dns;
        // },
        email_dns: {
            handler() {
                this.user["user_eml"] = this.email_id + "@" + this.email_dns;
            },
            immediate: true
        },
        "select_email_dns": function () {
            this.user["user_eml"] = this.email_id + "@" + this.select_email_dns;
        },
        "user.user_eml": function () {
            this.emlDuplicateChecked = false;
        },
        "company.company_id": function () {
            this.companyIdCheck_boolean = false;
        },
        "combinedUserId": function () {
            this.userIdCheck_boolean = false;
        }

    },
    computed: {
        combinedUserId: {
            get() {
                return this.user.user_id;

            },
            set(value) {
                //console.log("Setting combinedUserId:", value);
                this.user.user_id = value;
                this.company.user_id = value;
            },
        },
    },
    created() {
        const vm = this;
        axios({
            url: "/keyword/keywordList.json",
            method: "post",
            headers: {
                "Content-Type": "application/json",
            },
        }).then(function (response) {
            vm.keywords = response.data.map(item => item.keyword_nm);
        }).catch(function (error) {
            console.log("keywordList - error : ", error);
        });
    },
    mounted() {
        this.file = new FormData()
        // 스마트 에디터 적용
        // this.initEditor();
    }
}
</script>

