<template>
    <div class="mat-main">
        <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>
        <!-- best기업 -->
        <section class="matching-box-main">
            <div class="matching-box-wrap-one">
                <div class="w1400">
                    <div class="keyword-wrap filtering">
                        <ul>
                            <li v-for="(keywordItem, index) in keywords" :key="index">
                                <input type="checkbox" :id="keywordItem" v-model="companyListSearch.selectedKeywords"
                                    :value="keywordItem" class="keyword-label" style="display: none;"
                                    @click.stop="toggleKeyword(keywordItem)" />
                                <label :for="keywordItem" class="keyword">{{ keywordItem }}</label>
                            </li>
                        </ul>
                    </div>
                    <div class="btn-wrap">
                        <div class="data-select">
                            <select v-model="companyListSearch.searchType" name="data-table-sild" id="data-table-sild">
                                <option v-for="(item, idx) in option" :key="idx" :value=item.value>
                                    {{ item.name }}
                                </option>
                            </select>
                            <div class="input-group">
                                <input type="text" class="input" placeholder="검색어를 입력해주세요."
                                    v-model="companyListSearch.searchText" @keyup.enter="companySelectList()">
                                <input class="button--submit" value="검색" type="submit" @click="companySelectList()">
                            </div>
                        </div>
                    </div>
                    <div class="matching-box-grid">
                        <!-- best 기업 -->
                        <div class="matching-page-text">
                            <i class="fa-solid fa-crown fa-2xl" style="color: #ffef3c;"></i>
                            <h3>BEST 기업</h3>
                        </div>

                        <div class="matching-box-txt">
                            <p>※ BEST기업은 pick, 조회수, 매칭수 순으로 선정됩니다</p>
                        </div>
                        <div class="matching-box-bos">
                            <div v-for="(item, idx) in companyTop6List" :key="idx" class="matching-box  matchingbox"
                                @click="companySelectOnePage(item, 'best')">
                                <h3>{{ item.company_nm }}</h3>
                                <div class="matchingbox-img">
                                    <img :src="'http://localhost:8080' + item.file_path + '/' + item.file_nm + '.' + item.file_extn_nm"
                                        width="100%" alt="">
                                </div>
                                <p class="content-detail">{{ item.company_simple_info }}</p>
                                <div class="matchingbox-1">
                                    <p v-if="!item.pick_yn" @click.stop="pickModal(item)" class="matchingbox-text"
                                        style="color: #3f87f7;"><i class="fa-regular fa-heart fa-lg"
                                            style="color: #3f87f7;"></i> {{
                                                item.company_pick_cnt }} </p>
                                    <p v-else @click.stop="pickCancelModal(item)" class="matchingbox-text"><i
                                            class="fa fa-heart fa-lg" style="color: #d41515;"></i> {{ item.company_pick_cnt
                                            }} </p>
                                    <p class="matchingbox-text">조회수 <span>{{ item.view_cnt }}</span></p>
                                </div>
                                <div class="matching-span">
                                    <span v-for="(item, idx1) in keywordList[idx]" :key="idx1">#{{ item }}</span>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </section>
        <!-- 일반기업 -->
        <section class="matching-box-main">
            <div class="matching-box-main-two">
                <div class="w1400">
                    <div class="matching-grid-wrap">
                        <div class="flex-end">
                            <p style="color: #ff8a8a;margin-bottom:10px">
                                &#8251; 기업 배너의 순서는 기업명의 오름차순입니다.
                            </p>
                        </div>
                        <div class="matching-box-grid-two">
                            <div class="matching-box-2" v-for="(item, idx) in companyList" :key="idx"
                                @click="companySelectOnePage(item)">
                                <div>
                                    <h5>{{ item.company_nm }}</h5>
                                    <div class="matching-span">
                                        <span v-for="(item, idx1) in keywordList[idx]" :key="idx1"> #{{ item }}</span>
                                    </div>
                                    <div class="matchingbox-2">
                                        <p v-if="!item.pick_yn" @click.stop="pickModal(item)"><i
                                                class="fa-regular fa-heart fa-lg" style="color: #3f87f7;"></i> {{
                                                    item.company_pick_cnt }} </p>
                                        <p v-else @click.stop="pickCancelModal(item)"><i class="fa fa-heart fa-lg"
                                                style="color: #d41515;"></i> {{ item.company_pick_cnt }} </p>
                                        <p>조회수 <span>{{ item.view_cnt }}</span> </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        <div class="bottom-wrap">
            <PaginationButton v-model:currentPage="companyListSearch.currentPage" :perPage="companyListSearch.perPage"
                :total-count="companyListCount" :max-range="5" :click="companySelectList" />
        </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 PaginationButton from '../../../component/pagination/PaginationButton.vue';

export default {
    data() {
        return {
            companyListSearch: {
                currentPage: 1,
                perPage: 12,
                searchType: 'company_name',
                searchText: null,
                selectedKeywords: [],
            },
            page_nm: '기업홍보관',
            userCompanyId: null,
            bestList: [],
            companyList: [],
            keyword: [],
            keywordList: [],
            companyTop6List: [],
            companyListCount: 0,
            companyIdx: 0,
            pickModalOpen: false,
            store: useStore(),
            // 필터링을 위한 키워드
            keywords: [],
            isModalOpen: false,
            modalType: null,

            option: [
                { name: '기업명', value: 'company_name' },
            ]
        }
    },
    methods: {
        openModal: function () {
            this.isModalOpen = true;
        },
        closeModal: function () {
            this.modalType = null;
            this.isModalOpen = false;
        },
        companySelectList: function () {
            const vm = this;
            console.log("vm.selectedKeywords", vm.companyListSearch.selectedKeywords)

            axios({
                url: '/matching/companySelectList.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.companyListSearch
            }).then(function (response) {
                vm.companyList = response.data.companySelectList;
                vm.companyListCount = response.data.companySelectListCount;
                vm.companyIdx = vm.companyListCount - (vm.companyListSearch.currentPage - 1) * vm.companyListSearch.perPage;
                vm.companyTop6List = response.data.companyTop6;
                vm.userCompanyId = response.data.userCompanyId;

                for (let i = 0; i < vm.companyList.length; i++) {
                    vm.keyword = vm.companyList[i].keyword.split('#', 4);
                    vm.keyword.splice(0, 1)
                    vm.keywordList[i] = vm.keyword
                    console.log("keyword", vm.keywordList);
                }

            }).catch(function (error) {
                console.log('error - ', error)
                alert('기업 목록 조회 오류, 관리자에게 문의하세요.');
            })
        },

        pickModal: function (item) {
            const isUserLogin = this.store.state.loginUser;
            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 != item.company_id) {
                    if (confirm(item.company_nm + "에게 PICK 신청을 하시겠습니까?")) {
                        this.pick(item)
                    }
                } else {
                    this.modalType = 'me';
                }
            }
        },

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

        pick: 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.companySelectList();
            }).catch(function (error) {
                console.log('error - ', error)
                alert(' PICK 오류, 관리자에게 문의하세요.');
            })
        },

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

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

        companySelectOnePage: function (item) {
            const vm = this;
            let best = 'non'
            for (let i = 0; i < vm.companyTop6List.length; i++) {
                if (vm.companyTop6List[i].company_id === item.company_id) {
                    best = 'best';
                }
            }
            axios({
                url: '/matching/companyViewCountAdd.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'company_id': item.company_id }
            }).then(function (response) {
                vm.$router.push({ path: '/MatchingOne.page', query: { 'company_id': item.company_id, 'best': best } })
                .then(() => vm.$nextTick())// DOM 업데이트를 기다립니다.
                .then(() => window.scrollTo(0, 0)); // 그
            }).catch(function (error) {
                    console.log("기업 상세조회 오류, 관리자에게 문의하세요.");
                })
    },

    /**페이지 접속 로그 등록 */
    pageLogInsert: function () {
        const vm = this;

        axios({
            url: '/statistics/pageLogInsert.json',
            method: 'post',
            headers: {
                'Content-Type': "application/json; charset=UTF-8",
            },
            data: { "page_nm": vm.page_nm }
        })
    },

    toggleKeyword(keywordItem) {
        let index = this.companyListSearch.selectedKeywords.indexOf(keywordItem);
        if (index !== -1) {
            this.companyListSearch.selectedKeywords.splice(index, 1);
        } else {
            this.companyListSearch.selectedKeywords.push(keywordItem);
        }
        this.companySelectList();
    },
},
watch: {
    "modalType": function (newValue, oldValue) {
        if (this.modalType != null) {
            console.log("modalType watch: ", newValue, oldValue);
            this.openModal();
        }
    },
},
computed: {

},
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);
    });
},
components: {
    PaginationButton: PaginationButton,
    },
mounted() {
    console.log('Matching mounted');
    this.pageLogInsert();
    this.companySelectList();
}
}
</script>

