<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 in tops" :key="top[0]">
                    <a href="" class="popular__card">
                        <div class="card">
                            <div class="card-content d-flex align-items-center">
                                <span class="d-inline-block">{{ top[3] }}</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">
                <button class="btn__showmore" @click.prevent="showMore">
                    顯示更多
                </button>
            </div>
            <div class="row">
                <div class='col-12'>
                    <b-card shadow>
                        <h4>Sample data</h4>
                        <div>
                            <h4>searches / month</h4>
                            <strong></strong>
                        </div>
                        <ve-line :data="chartDatat" :settings="chartSettings" :colors="color"></ve-line>
                    </b-card>
                </div>
            </div>
            <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-comment mr-1"></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-1">最近搜尋字詞</p>
                <span class="btn 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>
            <h3 class="usernews__table__title">其他賣家這麼賣</h3>
            <div class="mb-5 row align-items-center">
                <div class="col-12 col-lg-9 col-table">
                <b-table striped hover sticky-header='400px'
                    :items="recommends"
                    :fields="fields" 
                    :sort-by.sync="sortBy"
                    :sort-desc.sync="sortDesc"></b-table>
                </div>
                <div class="col-12 col-lg-3">
                    <b-card shadow>
                        <ve-line :data="chartData[1]" :settings="chartSettings" :colors="color"></ve-line>
                    </b-card>
                </div>
            </div>
        <!-- <h3 class="usernews__table__title">找文章靈感</h3>
        <div class="mb-4">
            <b-table striped hover :items="blogIdeas"></b-table>
        </div>
            <h3 class="usernews__table__title">關注商品趨勢</h3>
            <div class="row my-4">
                <div class='col-12 col-lg-4 col-card' v-for="(data, i) in groupChar" :key="i">
                    <b-card shadow>
                        <h4>{{ data.group_chinese_name }}</h4>
                        <div>
                            <h4>searches / month</h4>
                            <strong>{{ check(data) }}</strong>
                        </div>
                        <ve-line :data="chartData[i]" :settings="chartSettings" :colors="color"></ve-line>
                    </b-card>
                </div>
            </div>-->
        </div> 
        <b-modal ref="my-modal" hide-footer hide-header title="Using Component Methods">
            <div class="d-block text-center">
                <img src="../assets/checked.png">
                <h3>明天收到資料</h3>
            </div>
            <b-button class="mt-3" variant="outline-danger" block @click="closeModal">關閉</b-button>
        </b-modal>
        </div>
</template>

<script>
export default {
    name: 'Usernews',
    data() {
        return {
            query: '',
            groupChar: [],
            sortBy: '銷售量',
            sortDesc: true,
            color: ['#dd6565'],
            fields: [
                { key: '商品標題', sortable: true },
                { key: '銷售量', sortable: true },
                { key: '價格', sortable: true },
            ],
            recommends: [
            ],
            chartSettings: {
                area: true,
            },
            chartDatat: {
                columns: ['月份', '次數'],
                rows: [
                    { 月份: '2021-01', 次數: 1000 },
                    { 月份: '2021-02', 次數: 400 },
                    { 月份: '2021-03', 次數: 200 },
                    { 月份: '2021-04', 次數: 600 },
                    { 月份: '2021-05', 次數: 800 },
                ]
            },
            chartData: [],
            warnmsg: '',
            isLoading: false,
            history: [],
            tops: [],
            topAmount: 10,
        }
    },
    methods: {
        search(words) {
            const vm = this;
            vm.warnmsg = '';
            let word = words.trim();
            if(word) {
               // vm.isLoading = true;
                if(!vm.history.includes(word)){
                    vm.history.unshift(word);
                }
                localStorage.setItem('searchedWords', JSON.stringify(vm.history));
                vm.$http.post('http://www.googo.org:8050/api/attention_product',
                { name: word }).then(res => {
                    console.log(res.data);
                    vm.$refs['my-modal'].show();
                })
                vm.$http.get(`http://www.googo.org:8050/api/shopee_data/?search_keyword=${word}`).then(res => {
                    let resData = [...res.data];
                    if(resData.length > 0) {
                        resData = resData.sort((a,b) => {
                            return a.sold > b.sold ? -1 : 1;
                        }).map((el, idx) => {
                            return { 商品標題: el.title, 銷售量: el.sold, 價格: el.price }
                        }).slice(0, 49);
                        console.log(resData);
                        vm.recommends = resData;
                    } else {
                        vm.$http.get(`http://www.googo.org:8050/api/marketing_advice/crawl_shopee/?search=${word}`).then(res => {
                            let resData = [...res.data];
                            resData = resData.map((el, idx) => {
                                return { 商品標題: el.title, 銷售量: el.sold, 價格: el.price }
                            });
                            console.log(resData);
                            vm.recommends = resData;
                            vm.isLoading = false;
                        });
                    }
                });
            } else {
                vm.warnmsg = '請輸入字詞';
                vm.query = '';
            }
        },
        getCharData() {
            const vm = this;
            vm.$http.get('http://www.googo.org:8050/api/groups/data/').then(res => {
                let resData = [...res.data.slice(0, 3)];
                vm.groupChar = resData;
                console.log(resData);
                let tempData = [];
                resData.forEach((item, i) => {
                    let tempTrend = item.data_trends.map((el, idx) => {
                        return { 月份: el.month, 次數: el.popularity }
                    }); 
                    let charData = { columns: ['月份', '次數'], rows: tempTrend};
                    tempData.push(charData);

                });
                vm.chartData = tempData;
                console.log(tempData);
            });
        },
        check(data) {
            let total = 0;
            data.data_trends.forEach(item => {
                total += item.popularity;
            });
            let threshold = Math.floor(total / 12);
            return threshold;
        },
        getDefaultData() {
            const vm  = this;
            vm.isLoading = true;
            vm.$http.get('http://www.googo.org:8050/api/marketing_advice/crawl_shopee/?search=%E8%A1%9B%E7%94%9F%E7%B4%99').then(res => {
                let resData = [...res.data];
                resData = resData.sort((a,b) => {
                    return a.sold > b.sold ? -1 : 1;
                }).map((el, idx) => {
                    return { 商品標題: el.title, 銷售量: el.sold, 價格: el.price }
                }).slice(0, 49);
                console.log(resData);
                vm.recommends = resData;
                vm.isLoading = false;
            })
        },
        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.$http.get(`http://api.ptt.cx:8000/ts_top/${vm.topAmount}`).then(res => {
                console.log(res.data);
                vm.tops = res.data;
            });
        },
        showMore() {
            const vm = this;
            vm.topAmount += 10;
            if(vm.topAmount >20) {
                return 
            } else {
                vm.getTops();
            }
        }
    },
    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.getDefaultData();
        this.history = JSON.parse(localStorage.getItem('searchedWords')) || [];
    }
}
</script>
