<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">關鍵字觀測</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="mb-3 d-flex align-items-center justify-content-between">
                <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.once.prevent="search(query, daterng)">套用</button>
                </div>
                <!-- <div class="btn-group group__btn mb-4" role="group" aria-label="date-buttons">
                    <button type="button" class="btn__date">單週</button>
                    <button type="button" class="btn__date">雙週</button>
                    <button type="button" class="btn__date">月</button>
                </div> -->
            </div>
            <div class="row">
                <div class="col-12 col-md-6 text-left hotWord">
                    <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">
                            <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>
                    </div>
                    <!-- <tr v-for="(topic, i) in reltopics" :key="`rew-${i}`">
                        <td><h4 class="reltopic__title mb-0">{{ topic[4] }}</h4></td>
                        <td><span class="badge rounded-pill bg-danger">{{ topic[1]}}</span></td>
                        <td v-if="topic[1]!=='飆升'"><span >{{ topic[1]}}</span></td>
                        <td v-if="topic[1]=='飆升'"><span>+{{ topic[0]}}%</span></td>
                    </tr> -->
                </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 reltopics" :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>
            </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 },
            ],
            recommends: [
            ],
            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: []
        }
    },
    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);
                }
                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.recommends = 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;
                })
            } 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?tc=${vm.topAmount}`).then(res => {
                console.log(res.data);
                vm.tops = res.data;
                vm.isLoading = false;
            });
        },
        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);
            var dd = monthbefore.getDate().toString();
            var mm = (monthbefore.getMonth() + 1).toString();
            var y = monthbefore.getFullYear().toString();
            var someFormattedDate = y + '-'+ mm + '-'+ dd;
            this.initialdate = [someFormattedDate, today];
            // this.daterng = [someFormattedDate, today];
        },
    },
    computed: {
        searchedWords() {
            if(this.history.length > 3){
                this.history.pop();
                localStorage.setItem('searchedWords', JSON.stringify(this.history));
                return this.history;
            } else {
                return this.history;
            }
        }
    },
    created() {
        // this.getCharData();
        this.getTops();
        this.initialDate();
        console.log(this.topAmount);
        this.history = JSON.parse(localStorage.getItem('searchedWords')) || [];
    }
}
</script>
