<template>
    <div>
        <Loading :active.sync="isLoading" :opacity="0.8">
            <template slot="default">
                <img src="../assets/ajax-loader.gif">
            </template>
        </Loading>
        <div class="container">
            <h3 class="usernews__table__title mt-3">本日熱門關鍵字排行</h3>
            <div class="row mb-3">
                <div class="col-6 mb-3" v-for="(top, i) in tops" :key="top[0]">
                    <a href="" class="popular__card" @click.prevent="search(top[1])">
                        <div class="card">
                            <div class="card-content d-flex align-items-center">
                                <span class="d-inline-block">{{ i + 1 }}</span>
                                <p class="d-inline-block pb-0 mb-0 popular__word">{{ top[1] }}</p>
                                <i class="fas fa-chart-line"></i>
                            </div>
                        </div>
                    </a>
                </div>
            </div>
            <div class="my-3 mb-5">
                <button class="btn__showmore" v-if="topAmount>=20" @click.prevent="topAmount=5; getTops()" >
                    收起
                </button>
                <button class="btn__showmore" @click.prevent="showMore" v-else>
                    顯示更多
                </button>
            </div>
            <h3 class="usernews__table__title mt-3">歷史熱門關鍵字排行</h3>
            <div class="date__input mb-3">
                    <date-picker v-model="singledate"
                        type="date"
                        placeholder="選擇日期"
                        format='YYYY-MM-DD'
                        value-type="YYYY-MM-DD"
                        :editable="false"
                        :default-value="yesterday"
                        :disabled-date="disabledAfterToday"></date-picker>
                    <button class='sub__date' @click.prevent="getHisTops(singledate)">套用</button>
                </div>
            <div class="row mb-3">
                <div class="col-6 col-md-3 mb-3" v-for="(htop, i) in HisTops" :key="htop[0]">
                    <a href="" class="popular__card" @click.prevent="search(htop[1])">
                        <div class="card">
                            <div class="card-content d-flex align-items-center justify-content-around">
                                <span class="d-inline-block">{{ i + 1 }}</span>
                                <p class="d-inline-block pb-0 mb-0 popular__word-history">{{ htop[1] }}</p>
                                <i class="fas fa-chart-line"></i>
                            </div>
                        </div>
                    </a>
                </div>
            </div>
            <h3 class="usernews__table__title">關鍵字觀測</h3>
            <form id="searchform" class="d-flex search__form mx-auto">
                <input type="search" class="search__bar" placeholder="輸入您感興趣的字詞或主題" v-model='query'>
                <button class="search__btn" type="button" id="search__btn" @click.prevent="search(query)">
                    <i class="fas fa-search"></i>搜尋
                </button>
                <span class="warnmsg" v-if="warnmsg">{{ warnmsg }}</span>
            </form>
            <div class="mt-1 history__block" v-if="history.length > 0">
                <p class="mb-2">最近搜尋字詞</p>
                <span class="btn__searchedWord" v-for="(item, i) in searchedWords" :key="i" @click.prevent="search(item)">{{ item }}
                    <span class="btn__delete" @click.prevent.stop="deleteWord(item)">X</span>
                </span>
            </div>
            <div class="relBlock mb-3 d-flex align-items-center justify-content-between" v-if="reltopics.length > 0">
                <div>
                    <h2 class="text-muted kw__title">關鍵字</h2>
                    <span class="kw__query">{{ query.trim() }}</span>
                    <!-- <i class="fas fa-long-arrow-alt-up kw__icon kw__icon__up"></i> -->
                    <!-- <i class="fas fa-long-arrow-alt-down kw__icon kw__icon__down"></i> -->
                    <!-- <div class="">
                        <span>正在熱搜關鍵字：</span>
                        <b-badge href="#" variant="info" v-for="(rec, i) in recommends" :key="i">{{ rec[0] }}</b-badge>
                    </div> -->
                </div>
                <div class="date__input mb-3">
                    <date-picker v-model="daterng"
                        type="date" range
                        :placeholder="`${initialdate[0]}~${initialdate[1]}`"
                        format='YYYY-MM-DD'
                        value-type="YYYY-MM-DD"></date-picker>
                    <button class='sub__date' @click.prevent="search(query, daterng)">套用</button>
                </div>
            </div>
            <div class="row result" v-if="reltopics.length > 0">
                <div class="col-12 col-md-6 text-left hotWord mb-5">
                    <h3 class="usernews__table__title">正在熱搜關鍵字</h3>
                    <div class="row justify-content-center">
                        <b-card class="col-5 hotWord__card mr-2">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="">
                                    <h3 class="mb-0 hotWord__card__title">館長 健身房</h3>
                                </div>
                                <div>
                                    <span class="d-block text-muted hotWord__card__muted">熱度</span>
                                    <span class="d-block hotWord__card__num">8060</span>
                                </div>
                            </div>
                        </b-card>
                        <b-card class="col-5 hotWord__card mr-2">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="">
                                    <h3 class="mb-0 hotWord__card__title">館長 健身房</h3>
                                </div>
                                <div>
                                    <span class="d-block text-muted hotWord__card__muted">熱度</span>
                                    <span class="d-block hotWord__card__num">8060</span>
                                </div>
                            </div>
                        </b-card>
                         <b-card class="col-5 hotWord__card" v-for="(relquery, i) in relqueries" :key="`req-${i}`">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="">
                                    <h3 class="mb-0 hotWord__card__title">{{ relquery[0] }}</h3>
                                </div>
                                <div>
                                    <span class="d-block text-muted hotWord__card__muted">熱度</span>
                                    <span class="d-block hotWord__card__num">{{ relquery[1] }}</span>
                                </div>
                            </div>
                        </b-card>
                    </div>
                </div>
                <div class="col-12 col-md-6 text-left">
                    <h3 class="usernews__table__title">相關主題</h3>
                    <table class="table">
                        <tr>
                            <th>相關詞</th>
                            <th></th>
                            <th>成長率</th>
                            <th>主題</th>
                        </tr>
                        <tr v-for="(topic, i) in filterTopics[page]" :key="`rew-${i}`">
                            <td><h4 class="reltopic__title mb-0">{{ topic[4] }}</h4></td>
                            <template v-if="topic[1]=='飆升'">
                                <td><span class="badge rounded-pill bg-danger text-light">{{ topic[1]}}</span></td>
                                <td><span>+{{ topic[0]}}%</span></td>
                                <td><span class="badge rounded-pill reltopic__tag">{{ topic[5]}}</span></td>
                            </template>
                            <template v-if="topic[1]!=='飆升'">
                                <td></td>
                                <td><span>+{{ topic[0]}}%</span></td>
                                <td><span class="badge rounded-pill reltopic__tag">{{ topic[5]}}</span></td>
                            </template>
                        </tr>
                    </table>
                    <div class="text-center">
                        <button class="prenxt-btn" @click.prevent="prevnext('prev')" :class="{'disabled': page === 0}"><i class="fas fa-chevron-left"></i></button>
                        <button class="prenxt-btn" @click.prevent="prevnext('next')" :class="{'disabled': page >= totalPages-1 }"><i class="fas fa-chevron-right"></i></button>
                    </div>
                </div>
            </div>
            <div v-if="reltopics.length == 0 && query">
                <p>查無資料</p>
            </div>
            <div class="row my-5 ">
                <div class='col-12'>
                    <b-card shadow>
                        <div>
                            <h4>searches / month</h4>
                            <strong></strong>
                        </div>
                        <ve-line :data="chartDatat" :settings="chartSettings" :colors="color"></ve-line>
                    </b-card>
                </div>
            </div>
        </div> 
    </div>
</template>

<script>
import DatePicker from 'vue2-datepicker';


export default {
    name: 'Usernews',
    components: { DatePicker },
    data() {
        return {
            query: '',
            groupChar: [],
            sortDesc: true,
            color: ['#dd6565'],
            fields: [
                { key: '商品標題', sortable: true },
                { key: '銷售量', sortable: true },
                { key: '價格', sortable: true },
            ],
            relqueries: [
            ],
            reltopics: [

            ],
            chartSettings: {
                area: true,
            },
            chartDatat: {
                columns: ['月份', '次數'],
                rows: [
                    { 月份: '2021-01', 次數: 1000 },
                    { 月份: '2021-02', 次數: 400 },
                    { 月份: '2021-03', 次數: 200 },
                    { 月份: '2021-04', 次數: 600 },
                    { 月份: '2021-05', 次數: 800 },
                ]
            },
            warnmsg: '',
            isLoading: false,
            history: [],
            tops: [],
            topAmount: 5,
            daterng: [],
            initialdate: [],
            singledate: '',
            HisTops: [],
            yseterday: '',
            page: 0,
            totalPages: 0,
            params: ''
        }
    },
    methods: {
        search(words, date = this.initialdate) {
            const vm = this;
            vm.warnmsg = '';
            let word = words.trim();
            vm.query = words.trim();
            console.log(vm.daterng);
            if(word) {
                vm.isLoading = true;
                if(!vm.history.includes(word)){
                    vm.history.unshift(word);
                }
                vm.daterng = date;
                localStorage.setItem('searchedWords', JSON.stringify(vm.history));
                vm.$http.get(`http://api.ptt.cx:8000/related_queries1/${word}?fd=2021-01-01&td=2021-02-30`, {headers: {'Access-Control-Allow-Origin': '*'}}).then(res => {
                    vm.relqueries = res.data;
                    console.log(res.data);
                    vm.isLoading = false;
                });
                vm.$http.get(`http://api.ptt.cx:8000/related_topics1/${word}?fd=${date[0]}&td=${date[1]}`,  {headers: {'Access-Control-Allow-Origin': '*'}}).then(res => {
                    console.log(`http://api.ptt.cx:8000/related_topics1/${word}?fd=${date[0]}&td=${date[1]}`);
                    vm.reltopics = res.data;
                    vm.isLoading = false;
                })
                /* this.$nextTick(() => {
                    const el = this.$el.querySelector('.result');
                    el.scrollTop = el.offsetTop;
                    console.log('test');
                }) */
            } else {
                vm.warnmsg = '請輸入字詞';
                vm.query = '';
            }
        },
        deleteWord(word) {
            let index = this.history.indexOf(word);
            this.history.splice(index, 1);
            localStorage.setItem('searchedWords', JSON.stringify(this.history));
        },
        closeModal() {
            this.$refs['my-modal'].hide();
        },
        getTops() {
            const vm = this;
            //vm.isLoading = true;
            vm.$http.get(`http://api.ptt.cx:8000/ts_top?td=${vm.initialdate[1]}&tc=${vm.topAmount}`, {headers: {'Access-Control-Allow-Origin': '*'}}).then(res => {
                console.log(res.data);
                vm.tops = res.data;
                vm.isLoading = false;
            });
        },
        getHisTops(date = this.singledate) {
            const vm = this;

            vm.$http.get(`http://api.ptt.cx:8000/ts_top?td=${date}&tc=20`, {headers: {'Access-Control-Allow-Origin': '*'}}).then(res => {
                console.log(res.data);
                vm.HisTops = res.data;
            });
        },
        showMore() {
            const vm = this;
            console.log(vm.topAmount);
            vm.topAmount += 5;
            if(vm.topAmount >20) {
                return 
            } else {
                vm.getTops();
            }
        },
        initialDate() {
            let today = new Date().toISOString().slice(0, 10);
            let newdate = new Date();
            let monthbefore = new Date(newdate.getTime() - 30*60*60*24*1000);
            let dd = monthbefore.getDate().toString();
            let mm = (monthbefore.getMonth() + 1).toString();
            dd = dd.length < 2 ? '0'+ dd : dd;
            mm = mm.length < 2 ? '0'+ mm : mm;
            let y = monthbefore.getFullYear().toString();
            let someFormattedDate = y + '-'+ mm + '-'+ dd;
            this.initialdate = [someFormattedDate, today];
            let yesterday = new Date(newdate.getTime() - 60*60*24*1000);
            yesterday = yesterday.toISOString().slice(0, 10);
            this.singledate = yesterday;
            this.yesterday = yesterday;
            // this.daterng = [someFormattedDate, today];
        },
        disabledAfterToday(date) {
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            return date > today;
        },
        prevnext(method) {
            const vm = this;
            if(method === 'prev') {
                if(vm.page === 0) {
                    vm.page = 0;
                }else {
                    vm.page -= 1;
                }
            }else if(method === 'next') {
                if(vm.page >= vm.totalPages-1) {
                    vm.page = vm.totalPages-1;
                }else {
                    vm.page += 1;
                }
            }
        },
        randomString(length){
            var result = '';
            var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var charactersLength = characters.length;
            for ( var i = 0; i < length; i++ ) {
                result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            return result;
        },
    },
    computed: {
        searchedWords() {
            if(this.history.length > 3){
                this.history.pop();
                localStorage.setItem('searchedWords', JSON.stringify(this.history));
                return this.history;
            } else {
                return this.history;
            }
        },
        filterTopics() {
            const vm = this;
            const newData = [];
            let items = [];
            items = [...vm.reltopics];
            items.forEach((item, i) => {
                if(i % 8 === 0) {
                    newData.push([]);
                }
                const page = parseInt(i/8);
                
                newData[page].push(item);
            })
            vm.totalPages = newData.length;
            return newData;
        }
    },
    mounted() {
        /* this.params = this.$route.query;
        const params = new URLSearchParams();
        params.append('grant_type', 'authorization_code');
        params.append('code', this.query);
        params.append('redirect_uri', 'http://localhost:8081/#/');
        params.append('client_id', '1656094964');
        params.append('client_secret', '9250a4db57e157ae4e93f987d92457f3');
        this.$http.post('https://api.line.me/oauth2/v2.1/token', {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}, params).then((res) => {
            console.log(res);
        }) */
    },
    created() {
        // this.getCharData();
        this.initialDate();
        this.getHisTops();
        this.getTops();
        
        console.log(this.topAmount);
        this.history = JSON.parse(localStorage.getItem('searchedWords')) || [];
    }
}
</script>
