<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="pwinfro">
                            <p class="info-th ">비밀번호</p>
                            <span> <button @click="openModal1">비밀번호 변경하기</button></span>
                        </div>
                        <div>
                            <p class="info-th">회원구분</p>
                            <span>{{ user.user_auth == "company" ? "기업회원" : "일반회원 " }}</span>
                        </div>
                        <div>
                            <p class="info-th">이메일</p>
                            <span>{{ user.user_eml }}</span>
                        </div>
                        <div>
                            <p class="info-th">담당자명</p>
                            <span>{{ user.user_nm }}</span>
                        </div>
                        <div>
                            <p class="info-th">메일 구독서비스</p>
                            <span>{{ user.subscribe == false ? '미구독' : '구독'}}</span>
                        </div>

                    </section>


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

                        <section>
                            <p>
                                <!-- <img src="../../../../resources/jpg/zigaksa.jpg" alt=""> -->
                                <img :src="'http://211.253.8.180:8082' + logoFile.file_path + '/' + logoFile.file_nm + '.' + logoFile.file_extn_nm"
                                    width="100%" alt="">
                            </p>
                        </section>
                        <div>
                            <p>사업자등록번호</p>
                            <span>{{ company.company_id }}</span>
                        </div>
                        <div>
                            <p>업체명</p>
                            <span>{{ company.company_nm }}</span>
                        </div>

                        <div>
                            <p>한줄소개</p>
                            <span>{{ company.company_simple_info }}</span>
                        </div>
                        <div>
                            <p>주소</p>
                            <span>[{{ company.company_zip }}] {{ company.company_addr }} {{ company.company_daddr }}</span>
                        </div>
                        <div>
                            <p>홈페이지</p>
                            <span class="info-td">{{ company.company_hp_url }}</span>
                        </div>
                        <div>
                            <p>대표전화</p>
                            <span>{{ company.company_telno }}</span>
                        </div>
                        <div class="info-keword">
                            <p class="info-keword-far">업체 키워드</p>
                            <span class="keyword" v-for="(keyword, index) in company.keyword.slice(1).split('#')"
                                :key="index">
                                #{{ keyword }}
                            </span>
                        </div>
                        <div class="info-sec-summary">
                            <sapn class="info-th">업체 소개글</sapn>
                            <details>
                                <!-- <summary @click="getViewer(0)">기업소개</summary>
                                <div>
                                    <span id="viewer1" ref="viewer1" class="viewer"></span>
                                </div> -->
                                <!-- </details> -->
                                <summary @click="getViewer(0)">기업소개</summary>
                                <div>
                                    <span v-html="company.company_info"></span>
                                </div>
                            </details>
                            <details>
                                <summary @click="getViewer(1)">대표 기술 소개</summary>
                                <div>
                                    <span id="viewer2" ref="viewer2" class="viewer"></span>
                                </div>
                            </details>
                            <details>
                                <summary @click="getViewer(2)">서비스 소개</summary>
                                <div>
                                    <span id="viewer3" ref="viewer3" class="viewer"></span>
                                </div>
                            </details>
                        </div>
                        <div>
                            <p class="info-th">첨부파일</p>
                            <a @click="downloadFile(proFile)">{{ proFile.real_file_nm }}</a>
                            <!-- <a style="font-size: 15px;" class="down-btn-1"
                                :href="'http://211.253.8.180:8082' + proFile.file_path + '/' + proFile.file_nm + '.' + proFile.file_extn_nm" target='_blank' download>
                                {{ proFile.real_file_nm }}
                            </a> -->
                        </div>
                        <div class="">
                            <p class="info-th info-keword-far">명함</p>
                            <a @click="downloadFile(cardFile)">{{ cardFile.real_file_nm }}</a>
                            <!-- <a style="font-size: 15px;" class="down-btn-1 downbtn-none"
                                :href="'http://211.253.8.180:8082' + cardFile.file_path + '/' + cardFile.file_nm + '.' + cardFile.file_extn_nm" target='_blank' download>
                                {{ cardFile.real_file_nm }}
                            </a> -->
                            <div class="matchingbox-img">
                                <img :src="'http://211.253.8.180:8082' + cardFile.file_path + '/' + cardFile.file_nm + '.' + cardFile.file_extn_nm"
                                    width="100%" alt="">
                            </div>

                        </div>
                    </section>
                    <section class="info-sec-bt">
                        <!-- <router-link to="/infosub.page"> -->
                            <button class="blue-btn"  @click="infoUpdate">수정하기</button>
                        <!-- </router-link> -->
                    </section>

                </div>
            </div>
        </div>
        <div v-show="showpwchange2" class="pwchange2">
            <div class="pwchange-div">
                <p>비밀번호 변경하기</p>
                <div>
                    <ul>
                        <li>
                            <span>현재 비밀번호</span>
                            <input type="password" v-model="presentPwd">
                        </li>
                        <li>
                            <span>변경할 비밀번호</span>
                            <input type="password" v-model="changePwd">
                        </li>
                        <li>
                            <span>비밀번호 확인</span>
                            <input type="password" v-model="changePwdCheck">
                        </li>
                    </ul>
                </div>
                <!-- <div>
                    <p>비밀번호 변경이 완료되었습니다.</p>
                </div> -->
                <div>
                    <button @click="closeModal2" class="dark-gray-btn">이전</button>
                    <button @click="checkPwd" class="blue-btn">변경하기</button>
                    <!-- <button @click="closeModal2">닫기</button> -->
                </div>
            </div>
        </div>
        <div v-if="isModalOpen" class="modal-wrapper">
      <div class="modal-container admin-alert">
         <p class="modal-text">
            승인 대기 중입니다. 이후 내정보 수정이 가능합니다.
         </p>
         <div class="modal-end">
            <button class="dark-gray-btn" @click="closeModal()" style="width:100%">닫기</button>
         </div>
      </div>
   </div>
    </div>
</template>

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

export default {
    data() {
        return {
            showpwchange2: false,
            showpwchange3: false,
            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,
            },
            presentPwd: null,
            changePwd : null,
            changePwdCheck : null,
            isModalOpen:false
        }
    },
    methods: {
        openModal: function () {
         this.isModalOpen = true;
      },

      closeModal: function () {
         this.isModalOpen = false;
         this.modalType = null;
      },

        openModal1() {
            this.showpwchange2 = true;
        },

        closeModal2() {
            this.showpwchange2 = false;
        },

        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

                if (vm.user.user_auth == "company") {
                    vm.companySelectOne();
                }
            }).catch(function (error) {
                console.log("userSelectOne - error : ", error);
            });
        },

        infoUpdate: function () {
            const isUserLogin = this.store.state.loginUser;
            if (isUserLogin.create_account_approval === 'N') {
                this.isModalOpen = true;
            } else{
                this.$router.push('/Infosub.page');
            }
        },

        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
                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]
                        }

                    }
                }
            }).catch(function (error) {
                console.log("companySelectOne - error : ", error);
            });
        },

        getViewer(idx) {
            const vm = this;
            let data = [vm.company.company_info, vm.company.company_technology, vm.company.company_service][idx];
            this.viewer = new Viewer({
                el: this.$refs[`viewer${idx + 1}`],
                initialEditType: 'wysiwyg',
                previewStyle: 'vertical',
                initialValue: data,
                customHTMLRenderer: {
                    htmlBlock: {
                        iframe(node) {
                            return [
                                { type: 'openTag', tagName: 'iframe', outerNewLine: true, attributes: node.attrs },
                                { type: 'html', content: node.childrenHTML },
                                { type: 'closeTag', tagName: 'iframe', outerNewLine: true },
                            ];
                        },
                    }
                },
            });
        },

        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('에러발생');
            });
        },


        checkPwd: function() {
            const vm = this;
            let passwordRegex = /^[A-Za-z0-9]{6,20}$/;
            if (vm.changePwd == null){
                alert("변경할 비밀번호를 입력해주세요.")
                return;
            } else if(vm.changePwdCheck == null) {
                alert("비밀번호 확인을 입력해주세요.")
                return;
            } else if (vm.changePwd !== vm.changePwdCheck) {
                alert("비밀번호가 불일치합니다.");
                return;  
            } else if(!passwordRegex.test(vm.changePwd)){
                alert('비밀번호는 6~20자의 영문, 숫자만 사용 가능합니다.')
                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.presentPwd, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let user = {
                user_id: encryptedUserId,
                user_pw: encryptedUserPw
            };

            axios({
                url: '/user/checkPresentPwd.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: user
            }).then(function (response) {
                if(response.data == 1){
                    vm.changePassword()
                } else {
                    alert("현재 비밀번호가 일치하지 않습니다.");
                }
            }).catch(function (error) {
                console.log("companySelectOne - error : ", error);
            });
        },

        changePassword: 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 encryptedUserPw = crypto.AES.encrypt(vm.changePwd, key128Bits100Iterations, { iv: crypto.enc.Hex.parse(iv) }).toString();

            let user = {
                user_id: encryptedUserId,
                user_pw: encryptedUserPw
            };

            axios({
                url: '/user/userPwUpdate.json',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                },
                data: user
            }).then(function (response) {
                if(response.data == 1){
                    alert('비밀번호 변경에 성공하였습니다.')
                    vm.changePwd = null;
                    vm.presentPwd = null;
                    vm.changePwdCheck = null;
                    vm.closeModal2()
                } else {
                   alert('비밀번호 변경에 실패하였습니다.') 
                }
            }).catch(function (error) {
                console.log("companySelectOne - error : ", error);
            });
        },

    },


    watch: {

    },
    computed: {

    },
    mounted() {
        this.userSelectOne();
    }
}
</script>



