<template>
    <div class="chart-page">
        <div class="title-wrap">
            <div class="flex-start">
                <h2 class="main-title">매칭현황 통계</h2>
            </div>
        </div>
        <div class="content-wrap">
            <ul class="tab-menu">
                <li v-for="(tab, index) in tabMenu" :key="index">
                    <a @click="currentTabChange(index)" :class="{ active: currentTab === index }">{{ tab }}</a>
                </li>
            </ul>
            <div class="tab-content">
                <div v-if="currentTab == 0">
                    <div class="chart">
                        <div class="chart-top">
                            <div class="flex">
                                <div class="date-zone flex-start">
                                    <!-- <input type="date" name="" id="" min="2023-11-24" :max="listSearch.endDate" v-model="listSearch.startDate"> -->
                                    <input type="date" name="" id="" :max="listSearch.endDate" v-model="listSearch.startDate">
                                    <span>~</span>
                                    <!-- <input type="date" name="" id="" :min="listSearch.startDate" :max="oneMonthLater" v-model="listSearch.endDate"> -->
                                    <input type="date" name="" id="" :min="listSearch.startDate" :max="yesterDay" v-model="listSearch.endDate">
                                    <button class="blue-btn" @click="listTypeCheck()">조회</button>
                                </div>
                                <div class="date-check flex-end">
                                    <div>
                                        <input type="radio" name="pickMatching1" id="pick1" style="display:none"
                                            @click="handleRadioClick('pick', $event)" :checked="selectedOption1 === 'pick'">
                                        <label for="pick1">Pick</label>
                                    </div>
                                    <div>
                                        <input type="radio" name="pickMatching1" id="matching1" style="display:none"
                                            @click="handleRadioClick('matching', $event)"
                                            :checked="selectedOption1 === 'matching'">
                                        <label for="matching1">Matching</label>
                                    </div>
                                </div>
                            </div>
                            <BarChart :chartData="companyStatisticsList" :mapping="keyMapping" columnX="company_nm"/>
                        </div>
                        <div class="table-zone">
                            <div class="btn-wrap">
                                <button class="blue-border-bnt" @click="statisticsLogExcel()">Excel 다운로드</button>
                            </div>
                            <table class="statistics-table">
                                <colgroup>
                                    <col style="width: 16%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th rowspan="2">기업별</th>
                                        <th colspan="6" v-if="selectedOption1 === 'pick'">Pick</th>
                                        <th colspan="6" v-else-if="selectedOption1 === 'matching'">Matching</th>
                                    </tr>
                                    <tr>
                                        <th>성공건수</th>
                                        <th>실패건수</th>
                                        <th>진행중인건수</th>
                                        <th>요청받은건수</th>
                                        <th>요청한 건수</th>
                                        <th>전체 요청수</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(item, index) in companyStatisticsList" :key="index">
                                        <td>{{ item.company_nm }}</td>
                                        <td>{{ item.succesee_cnt }}</td>
                                        <td>{{ item.failed_cnt }}</td>
                                        <td>{{ item.progress_cnt }}</td>
                                        <td>{{ item.to_cnt }}</td>
                                        <td>{{ item.from_cnt }}</td>
                                        <td>{{ item.total_cnt }}</td>
                                    </tr>
                                </tbody>
                            </table>
                            <table class="sum-table">
                                <colgroup>
                                    <col style="width: 16%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                    <col style="width: 14%;" />
                                </colgroup>
                                <tbody>
                                    <tr>
                                        <th>합계</th>
                                        <td>{{ totalCount.succesee_cnt }}</td>
                                        <td>{{ totalCount.failed_cnt }}</td>
                                        <td>{{ totalCount.progress_cnt }}</td>
                                        <td>{{ totalCount.to_cnt }}</td>
                                        <td>{{ totalCount.from_cnt }}</td>
                                        <td>{{ totalCount.total_cnt}}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="bottom-wrap">
                            <PaginationButton v-model:currentPage="listSearch.currentPage" :perPage="listSearch.perPage"
                                :total-count="companySelectListCount" :max-range="5" :click="listTypeCheck" />
                        </div>
                    </div>
                </div>
                <div v-if="currentTab == 1">
                    <div class="chart">
                        <div class="chart-top">
                            <div class="flex">
                                <select name="" id="" v-model="company_id" @change="changeCompany($event)">
                                    <option v-for="(item, idx) in companyList" :key="idx" :value=item.company_id>{{
                                        item.company_nm }}</option>
                                </select>
                                <div class="date-check flex-end">
                                    <div>
                                        <input type="radio" name="pickMatching2" id="pick2" style="display:none"
                                            @click="handleRadioClick('pick', $event)" :checked="selectedOption2 === 'pick'">
                                        <label for="pick2">Pick</label>
                                    </div>
                                    <div>
                                        <input type="radio" name="pickMatching2" id="matching2" style="display:none"
                                            @click="handleRadioClick('matching', $event)"
                                            :checked="selectedOption2 === 'matching'">
                                        <label for="matching2">Matching</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="table-zone">
                            <div class="btn-wrap">

                                <button class="blue-border-bnt" @click="statisticsDetailLogExcel()">Excel 다운로드</button>
                            </div>
                            <table class="statistics-table">
                                <colgroup>
                                    <col style="width: 20%;" />
                                    <col style="width: 16%;" />
                                    <col style="width: 16%;" />
                                    <col style="width: 16%;" />
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th rowspan="2">기업명</th>
                                        <th colspan="3" v-if="selectedOption2 === 'pick'">Pick</th>
                                        <th colspan="3" v-else-if="selectedOption2 === 'matching'">Matching</th>
                                    </tr>
                                    <tr>
                                        <th>상대기업명</th>
                                        <th colspan="2">현황</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(item, idx) in companyDetailStatistics" :key="idx">
                                        <td v-if="idx === 0" :rowspan="companyDetailStatistics.length">{{ company_nm }}</td>
                                        <td>{{ item.company_nm }}</td>
                                        <td>{{ item.division }}</td>
                                        <td>{{ item.state }}</td>
                                        <!-- <td v-if="item.division == 'reception'">요청받음</td>
                                        <td v-else>요청함</td>
                                        <td v-if="item.complete_yn && item.refuse_yn == 'N'">성공</td>
                                        <td v-else-if="item.division == 'reception' && item.refuse_yn == 'Y'">거절함</td>
                                        <td v-else-if="item.division == 'dispatch' && item.refuse_yn == 'Y'">거절됨</td>
                                        <td v-else>진행중</td> -->
                                    </tr>
                                </tbody>
<!-- 
                                <tbody v-else>
                                    <tr v-for="(item, idx) in companyDetailStatistics" :key="idx">
                                        <td v-if="idx === 0" :rowspan="companyDetailStatistics.length">{{ company_nm }}</td>
                                        <td>{{ item.company_nm }}</td>
                                        <td v-if="item.division == 'reception'">요청받음</td>
                                        <td v-else>요청함</td>
                                        <td v-if="item.complete_yn && item.refuse_yn == 'N' && !item.cancel_yn">성공</td>
                                        <td v-else-if="item.cancel_yn">성공 후 취소</td>
                                        <td v-else-if="item.division == 'reception' && item.refuse_yn == 'Y'">거절함</td>
                                        <td v-else-if="item.division == 'dispatch' && item.refuse_yn == 'Y'">거절됨</td>
                                        <td v-else>진행중</td>
                                    </tr>
                                </tbody> -->

                            </table>
                            <table class="sum-table">
                                <colgroup>
                                    <col style="width: 20%;" />
                                    <col style="width: 16%;" />
                                    <col style="width: 16%;" />
                                    <col style="width: 16%;" />
                                </colgroup>
                                <tbody>
                                    <tr>
                                        <th>합계</th>
                                        <td colspan="3">{{ detailTotalCount }}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import axios from "axios";
import COMMON_UTIL from '../../../../resources/js/commonUtil.js';
import BarChart from '../../../component/chart/BarChart.vue';
import PaginationButton from '../../../component/pagination/PaginationButton.vue';

export default {

    data() {
        return {
            currentTab: 0,
            tabMenu: ['매칭관리', '매칭관리 세부통계'],
            selectedOption1: "pick",
            selectedOption2: "pick",

            listSearch: {
                currentPage: 1,
                perPage: 10,
                startDate: null,
                endDate: null,
            },

            keyMapping: {
                company_nm: "기업명",
                succesee_cnt: "성공건수",
                failed_cnt: "실패건수", 
                progress_cnt: "진행중인건수",
                to_cnt: "요청받은건수",
                from_cnt: "요청한건수",
                total_cnt: "전체요청수",
            },
            
            // oneMonthLater: COMMON_UTIL.today(),
            yesterDay: COMMON_UTIL.yesterday(),
            
            companyStatisticsList: [],
            companySelectListCount: 0,
            totalCount: {},

            company_id: null,
            company_nm: null,
            companyList: [],
            companyDetailStatistics: [],
            detailTotalCount: 0,
        };
    },
    methods: {
        currentTabChange: function (index) {
            this.currentTab = index;
            if (index == 0) {
                this.listTypeCheck();
            }
        },

        handleRadioClick(option, e) {
            const clickedRadioName = e.target.name;
            if (clickedRadioName == "pickMatching1") {
                this.selectedOption1 = option;
                this.listTypeCheck();
            } else if (clickedRadioName == "pickMatching2") {
                this.selectedOption2 = option;
                this.detailTypeCheck();
            }
        },

        /** 기업 별 픽 통계 */
        companyPickStatistics: function () {
            const vm = this;
            axios({
                url: '/statistics/companyPickStatistics.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.listSearch
            }).then(function (response) {
                vm.companyStatisticsList = response.data.data.companyPickStatistics;
                vm.companySelectListCount = response.data.companySelectListCount;
                vm.totalCount = response.data.data.totalCount;
            }).catch(function (error) {
                console.log("error - ", error)
                alert("PICK 통계 조회 오류, 관리자에게 문의하세요.");
            })
        },

        /** 기업 별 매칭 통계 */
        companyMatchingStatistics: function () {
            const vm = this;
            axios({
                url: '/statistics/companyMatchingStatistics.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.listSearch
            }).then(function (response) {
                vm.companyStatisticsList = response.data.data.companyMatchingStatistics;
                vm.companySelectListCount = response.data.companySelectListCount;
                vm.totalCount = response.data.data.totalCount;
            }).catch(function (error) {
                console.log("error - ", error)
                alert("MATCHING 통계 조회 오류, 관리자에게 문의하세요.");
            })
        },

        /** 선택기업 픽 세부통계 */
        companyDetailPickStatistics: function () {
            const vm = this;

            vm.listSearch.company_id = vm.company_id;
            axios({
                url: '/statistics/companyDetailPickStatistics.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.listSearch
            }).then(function (response) {
                vm.companyDetailStatistics = response.data.companyDetailPickStatistics;
                vm.detailTotalCount = response.data.totalCount;
            }).catch(function (error) {
                console.log("error - ", error)
                alert("PICK 통계 조회 오류, 관리자에게 문의하세요.");
            })
        },

        /** 선택기업 매칭 세부통계 */
        companyDetailMatchingStatistics: function () {
            const vm = this;

            vm.listSearch.company_id = vm.company_id;
            axios({
                url: '/statistics/companyDetailMatchingStatistics.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.listSearch
            }).then(function (response) {
                vm.companyDetailStatistics = response.data.companyDetailMatchingStatistics;
                vm.detailTotalCount = response.data.totalCount;
            }).catch(function (error) {
                console.log("error - ", error)
                alert("MATCHING 통계 조회 오류, 관리자에게 문의하세요.");
            })
        },

        /**매칭관리 타입 검사 */
        listTypeCheck: function () {
            if (this.selectedOption1 == 'pick') {
                this.companyPickStatistics();
            } else {
                this.companyMatchingStatistics();
            }
        },

        // /**매칭관리 날짜선택 유효성 검사 */
        // listDateCheck: function () {
        //     if (COMMON_UTIL.isEmpty(this.listSearch.endDate) === false) {
        //         alert("날짜를 선택해주세요.");
        //     } else {
        //         if (this.selectedOption1 == 'pick') {
        //             this.companyPickStatistics();
        //         } else {
        //             this.companyMatchingStatistics();
        //         }
        //     }
        // },

        /**매칭관리 세부통계 타입 검사 */
        detailTypeCheck: function () {
            if (this.selectedOption2 == 'pick') {
                this.companyDetailPickStatistics();
            } else {
                this.companyDetailMatchingStatistics();
            }
        },

        changeCompany: function(event) {
            let company_id = event.target.value;

            for(let i = 0; i < this.companyList.length; i++) {
                if(company_id == this.companyList[i].company_id) {
                    this.company_nm = this.companyList[i].company_nm;
                }
            }
            this.detailTypeCheck();
        },
        // /**매칭관리 세부통계 날짜선택 유효성 검사 */
        // detailDateCheck: function () {
        //     if (COMMON_UTIL.isEmpty(this.listSearch.endDate) === false) {
        //         alert("날짜를 선택해주세요.");
        //     } else {

        //         if (this.selectedOption1 == 'pick') {
        //             this.companyPickStatistics();
        //         } else {
        //             this.companyMatchingStatistics();
        //         }
        //     }
        // },

        /** 기업 리스트 */
        companySelectList: function () {
            const vm = this;
            axios({
                url: '/statistics/companyNameSelectList.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.listSearch
            }).then(function (response) {
                vm.companyList = response.data
                vm.company_id = vm.companyList[0].company_id;
                vm.company_nm = vm.companyList[0].company_nm;
                vm.companyDetailPickStatistics();
            }).catch(function (error) {
                console.log("error - ", error)
                alert("기업 리스트 조회 오류, 관리자에게 문의하세요.");
            })
        },

        /** 기업 별 통계 엑셀 다운로드 */
        statisticsLogExcel: function() {
            const vm = this;

            if(vm.companySelectListCount === 0) {
                alert("데이터가 없어 EXCEL 다운로드를 실행할 수 없습니다.")
                return
            }

            vm.listSearch.selectedOption1 = vm.selectedOption1;

            axios({
                url: "/statistics/pickStatisticsLogExcel.json",
                method: "post",
                herders: {
                "Content-Type": "application/json; charset=UTF-8",
                },
                responseType: 'arraybuffer',
                data: vm.listSearch,
            })
            .then(function (response) {
                const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers["content-type"] }));
                const link = document.createElement("a");
                link.href = url;
                let today = COMMON_UTIL.today();
                if(vm.selectedOption1 == 'pick') {
                    link.download = '[' + today + ']' + '기업별 pick 통계';
                } else {
                    link.download = '[' + today + ']' + '기업별 matching 통계';
                }
                
                link.click();
                window.URL.revokeObjectURL(url);
            })
                .catch(function (error) {
                console.log("userAccessLogExcel - error : ", error);
                alert("통계 Excel 다운로드 오류, 관리자에게 문의해주세요.");
            });
        },

         /** 세부통계 엑셀 다운로드 */
         statisticsDetailLogExcel: function() {
            const vm = this;

            vm.listSearch.company_nm = vm.company_nm

            if(vm.companySelectListCount === 0) {
                alert("데이터가 없어 EXCEL 다운로드를 실행할 수 없습니다.")
                return
            }

            vm.listSearch.selectedOption2 = vm.selectedOption2;

            axios({
                url: "/statistics/detailStatisticsLogExcel.json",
                method: "post",
                herders: {
                "Content-Type": "application/json; charset=UTF-8",
                },
                responseType: 'arraybuffer',
                data: vm.listSearch,
            })
            .then(function (response) {
                const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers["content-type"] }));
                const link = document.createElement("a");
                link.href = url;
                let today = COMMON_UTIL.today();
                if(vm.selectedOption1 == 'pick') {
                    link.download = '[' + today + ']' + vm.company_nm + ' pick 세부통계';
                } else {
                    link.download = '[' + today + ']' + vm.company_nm + ' matching 세부통계';
                }
                
                link.click();
                window.URL.revokeObjectURL(url);
            })
                .catch(function (error) {
                console.log("userAccessLogExcel - error : ", error);
                alert("통계 Excel 다운로드 오류, 관리자에게 문의해주세요.");
            });
        },
    },
    watch: {
        // 'listSearch.startDate': function (newValue) {
        //     let date = COMMON_UTIL.oneMonthLater(newValue);
        //     this.listSearch.endDate = null;
        //     if (date > COMMON_UTIL.today()) {
        //         this.oneMonthLater = COMMON_UTIL.today();
        //     } else {
        //         this.oneMonthLater = date;
        //     }
        // },
    },
    computed: {},
    components: {
        BarChart: BarChart,
        PaginationButton: PaginationButton,
    },
    mounted() {
        this.companyPickStatistics();
        this.companySelectList();
       
    },
};
</script>
