<template>
    <section class="main-sec sec1">
        <!-- <div class="main-content"> -->
        <div class="flex">
            <!-- 매칭비주얼 -->
            <div class="matching-box-wrap">
                <div class="w1400">
                    <div class="matching-wrap">
                        <div class="matching-img">
                            <img src="../../../../resources/jpg/mat-img.png" alt="">
                        </div>
                        <!-- 매칭 텍스트 -->
                        <div class="matching-text">
                            <i class="fa-regular fa-handshake fa-lg" style="color: #ffffff;"></i>
                            <p>기업 홍보관</p>
                        </div>
                        <div class="matching-img">
                            <img src="../../../../resources/jpg/mat-img1.png" alt="">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <div class="page">
        <div class="w1400">
            <div class="page-logo flex-start">
                <img src="../../../../resources/jpg/mat-img-d.png" alt="">
                <h1>회사소개</h1>

            </div>
            <div class="matDtail-sec">
                <section class="mat-sec1">
                    <h2> {{ company.company_nm }} <span v-if="best === 'best'">(BEST 기업)</span></h2>
                    <div @click="downloadProfile()">
                        <label for="dtaildown">회사소개서 다운로드</label>
                        <i class="fa-solid fa-download" style="color: #ffffff;"></i>
                    </div>
                </section>

                <!-- /상세내용 -->
                <section class="mat-sec2">
                    <div class="info-sec-summary">
                        <sapn class="info-th"></sapn>
                        <div>
                            <p class="introduce-title">기업소개</p>
                            <div id="viewer1" ref="viewer1" class="viewer"></div>
                        </div>
                        <div>
                            <p class="introduce-title">대표 기술 소개</p>
                            <div id="viewer2" ref="viewer2" class="viewer"></div>
                        </div>
                        <div>
                            <p class="introduce-title">서비스 소개</p>
                        <div id="viewer3" ref="viewer3" class="viewer"></div>
                        </div>
                    </div>
                    <div class="mat-sec2-end">
                        <div>
                            <i v-if="!company.pick_yn" class="fa-regular fa-heart fa-lg" style="color: #3f87f7;"
                                @click="pickConfirm()"></i>
                            <i v-else class="fa fa-heart fa-lg" style="color: #d41515;" @click="pickCancelModal()"></i>
                            <p  @click="openPickListMadal">
                                <span id="pickBtn">{{ company.company_pick_cnt }}개</span>의 기업이
                            pick했습니다!
                            </p>
                            
                        </div>
                        <p><span>조회수</span>{{ company.view_cnt }}</p>

                    </div>
                </section>

                <section class="mat-sec2-bt">
                    <button @click="goToPage2">목록</button>
                </section>
            </div>
        </div>
    </div>


    <div v-show="pickModal" class="matching-modal2">
        <div class="flex-end">
            <button class="join-text-bt3" @click="closePickListMadal">X</button>
        </div>
        <div class="mat-modal">
            <h2>우리기업을 PICK한 기업</h2>
        </div>
        <div class="mat-scroll">
            <table class="mat-modal-img">
                <colgroup>
                    <col style="width: 30%;" />
                    <col style="width: 40%;" />
                    <col style="width: 30%;" />
                </colgroup>
                <tbody>
                    <tr v-for="(item, idx) in pickSelectList" :key="idx">
                        <td>
                            <p>
                                <img :src="'http://localhost:8080' + item.file_path + '/' + item.file_nm + '.' + item.file_extn_nm">
                            </p>
                        </td>
                        
                        <td style=" text-align : center;">
                            {{ item.company_nm }}
                        </td>
                        <td>
                            <button v-if="item.pick_yn && item.refuse_yn == 'N'" disabled :style="{ backgroundColor: '#ccc' }">완료</button>
                            <button v-else-if="item.refuse_yn == 'Y'" disabled :style="{ backgroundColor: 'rgb(221, 97, 97)' }">거절함</button>
                            <button v-else :style="{ backgroundColor: '#3f87f7' }" @click="modalPick(item)"> 수락</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
      
    </div>

    <div v-show="isModalOpen" class="modal-wrapper">
        <div class="modal-container admin-alert">
            <div v-show="modalType == 'duplication'" class="modal-content-monthly alert-modal">
                <p>비회원은 해당 기능을 이용하실 수 없습니다.</p>
            </div>
            <div v-show="modalType == 'alert'" class="modal-content-monthly alert-modal">
                <p>가입 승인 중 입니다.<br />해당 기능을 이용하실 수 없습니다.</p>
            </div>
            <div v-show="modalType == 'save'" class="modal-content-monthly alert-modal">
                <p>일반 회원은 해당 기능을 이용하실 수 없습니다.</p>
            </div>
            <div v-show="modalType == 'me'" class="modal-content-monthly alert-modal">
                <p>자신의 기업에는 PICK을 할 수 없습니다.</p>
            </div>
            <div class="modal-end">
                <button class="blue-btn small-btn" @click="closeModal">확인</button>
            </div>
        </div>
    </div>
</template>

<script>
import { useStore } from "vuex";
import axios from 'axios';
import COMMON_UTIL from '../../../../resources/js/commonUtil.js';
import { useRoute } from 'vue-router';
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 * as FileSaver from 'file-saver';

export default {
    data() {
        return {
            company: {
                company_id: null,
                company_nm: null,
                company_info: null,
                company_point: null,
                file_id: null,
                user_id: null,
                keyword: null,
                company_pick_cnt: null,
                company_technology: null,
                company_service: null,
                view_cnt: null,
                file_path: null,
                file_nm: null,
                file_extn_nm: null,
                pick_yn: null,

            },
            best: null,
            userCompanyId: null,
            pickSelectList: [],
            pickModal: false,
            isAccepted: false,
            buttonText: '수락',
            buttonColor: '#3f87f7',
            items: [

                { id: 2, text: "oo출판사" },

            ],
            route: useRoute(),
            store: useStore(),
            isModalOpen:false,
            modalType: null
        }
    },
    methods: {
        openModal: function () {
            this.isModalOpen = true;
        },
        closeModal: function () {
            this.modalType = null;
            this.isModalOpen = false;
        },

        companySelectOne: function () {
            const vm = this;

            vm.best = vm.route.query.best;

            axios({
                url: '/matching/companySelectOne.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'company_id': vm.route.query.company_id }
            }).then(function (response) {
                vm.company = response.data;
                vm.userCompanyId = response.data.userCompanyId;
            }).catch(function (error) {
                console.log("error - ", error)
                alert("기업 상세보기 조회 오류, 관리자에게 문의하세요.");
            })
        },

        getViewer(data, viewerId) {
            this.viewer = new Viewer({
                el: this.$refs[viewerId],
                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 },
                            ];
                        },
                    }
                },
            });
        },


        downloadProfile: function () {
            const vm = this;
            let path = vm.company.file_path + '/' + vm.company.file_nm + '.' + vm.company.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, vm.company.real_file_nm);
                } else {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = vm.company.real_file_nm;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                }

                let company_id = vm.company.company_id;

                axios({
                    url: '/statistics/profileLogInsert.json',
                    method: 'post',
                    hearder: {
                        'Content-Type': "application/json; charset=UTF-8",
                    },
                    data: { 'company_id': company_id }
                }).then(function (response) {
                    vm.$router.go(0);
                })

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

        openPickListMadal() {
            const vm = this;
            if (this.company.company_id === this.userCompanyId) {
                this.pickModal = true;

                axios({
                    url: '/matching/pickSelectList.json',
                    method: 'post',
                    hearder: {
                        'Content-Type': "application/json; charset=UTF-8",
                    },
                    data: vm.company
                }).then(function (response) {
                    vm.pickSelectList = response.data;
                }).catch(function (error) {
                    console.log("error - ", error)
                    alert("PICK 목록 조회 오류, 관리자에게 문의하세요.");
                })
            }
        },

        pickConfirm: function () {
            const isUserLogin = this.store.state.loginUser;
            console.log(isUserLogin);
            if (isUserLogin === null) {
                this.modalType = 'duplication';
            } else if (isUserLogin.create_account_approval === 'N' && isUserLogin.user_auth === 'company') {
                this.modalType = 'alert';
            } else if (isUserLogin.user_auth === 'common') {
                this.modalType = 'save';
            } else if (isUserLogin.create_account_approval === 'Y' && isUserLogin.user_auth === 'company') {
                if (this.userCompanyId != this.company.company_id) {
                    if (confirm(this.company.company_nm + "에 PICK 신청을 하시겠습니까?")) {
                        this.pick()
                    }
                } else {
                    this.modalType = 'me';
                }
            }

        },

        pickCancelModal: function () {
            if (confirm(this.company.company_nm + "에게 신청한 PICK을 취소 하시겠습니까?")) {
                this.pickCancel()
            }
        },

        pick: function () {
            const vm = this;

            axios({
                url: '/matching/pick.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.company
            }).then(function (response) {
                alert(response.data);
                vm.companySelectOne();
            }).catch(function (error) {
                console.log('error - ', error)
                alert('기업 목록 조회 오류, 관리자에게 문의하세요.');
            })
        },

        pickCancel: function () {
            const vm = this;

            axios({
                url: '/matching/pickCancel.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.company
            }).then(function (response) {
                alert(response.data);
                vm.companySelectOne();
            }).catch(function (error) {
                console.log('error - ', error)
                alert('기업 목록 조회 오류, 관리자에게 문의하세요.');
            })
        },

        modalPick: function (item) {
            const vm = this;

            axios({
                url: '/matching/pick.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: item
            }).then(function (response) {
                alert(response.data);
                vm.openPickListMadal();
            }).catch(function (error) {
                console.log('error - ', error)
                alert('기업 목록 조회 오류, 관리자에게 문의하세요.');
            })
        },

        closePickListMadal() {
            this.pickModal = false;
        },

        accept() {
            this.isAccepted = !this.isAccepted;
            this.buttonText = this.isAccepted ? '수락완료' : '수락';
            this.buttonColor = this.isAccepted ? '#ccc' : '#3f87f7';
        },

        goToPage2() {
            this.$router.push('/Matching.page')
        },
    },
    watch: {
        'company': function (nuwValue) {
            console.log(nuwValue);
            this.getViewer(nuwValue.company_info, 'viewer1');
            this.getViewer(nuwValue.company_service, 'viewer2');
            this.getViewer(nuwValue.company_technology, 'viewer3');
        },
        "modalType": function (newValue, oldValue) {
            if (this.modalType != null) {
                console.log("modalType watch: ", newValue, oldValue);
                this.openModal();
            }
        },
    },
    computed: {

    },
    mounted() {
        console.log('Matching mounted');
        this.companySelectOne();
    }
}
</script>

