<template>
  <div>
     <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center
      pb-2 mb-3">
      <h1 class="h2">近一季行銷建議</h1>
        <div class="d-flex">
          <span>季數</span>
          <select class="custom-select" v-model='selected'>
            <option value="0">Q1</option>
            <option value="1">Q2</option>
            <option value="2">Q3</option>
            <option value="3">Q4</option>
          </select>
        </div>
    </div>
    <div class="table-responsive mb-3" v-for="(month, i) in month" :key="i" v-if='selected == i'> <!-- eslint-disable-line-->
      <table class="table">
        <thead>
          <tr>
            <td>客群</td>
            <th scope="col" width='320'>{{ month[0] }}</th>
            <th scope="col" width='320'>{{ month[1] }}</th>
            <th scope="col" width='320'>{{ month[2] }}</th>
          </tr>
        </thead>
          <tbody>
            <tr v-for="(item ,k) in user_groups" :key="`hhh-${k}`">
              <th>{{ item.group_chinese_name }}</th>
              <td v-for="(t,idx) in item.trends[i]" :key="idx">
                <button type="button" class="btn__kw" data-toggle="modal"
                data-target="#exampleModalCenter"
                @click.prevent="showModal(item.suggests)">關鍵字</button>
                <div class="highTrend dark-1 p-2 mt-2" v-if="check(t.times, item)">Popular</div>
              </td>
            </tr>
            <tr v-for="(item ,it) in json" :key="it">
              <th>{{ item.group }}</th>
              <td v-for="(t, idx) in item.orgData[i]" :key="idx">
                <div class="p-2 mt-2">{{ t.data }}</div>
              </td>
            </tr>
          </tbody>
      </table>
    </div>
    <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenter" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
              <div class="modal-content">
                <div class="modal-header border-0">
                  <h5 class="modal-title" id="exampleModalLongTitle">關鍵字群</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  <div v-for="(word, i) in tempkeywords" :key="i" class="mb-3">
                    <span class="d-flex mb-2"><i class="fas fa-clock d-inline-block mr-1"></i>日期：{{ word.start }} - {{ word.end}}</span>
                    <template v-for="(each, idx) in word.words">
                      <span class="badge badge-warning" :key="idx">{{ each }}</span>
                    </template>
                  </div>
                </div>
                <div class="modal-footer border-0">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">關閉</button>
                </div>
              </div>
            </div>
          </div>
  </div>
</template>

<script>
// @ is an alias to /src
import $ from 'jquery';

export default {
  name: 'Home',
  components: {
  },
  data() {
    return {
      group_datas: [],
      user_groups: [],
      isLoading: false,
      ex: [],
      month: [['Jan', 'Feb', 'Mar'], ['Apr', 'May', 'Jun'], ['Jul', 'Aug', 'Sep'], ['Oct', 'Nov', 'Dec']],
      trends: [
            {
                group: '婚禮', 
                data:[
                    [{month: 'Jan', times: 782}, {month: "Feb", times: 752} , {month: 'Mar', times: 909}],
                    [{month: 'Apr', times: 880}, {month: 'May', times: 929}, {month: "Jun", times: 883} ],
                    [{month: 'Jul', times: 855}, {month: 'Aug', times: 776}, {month: 'Sep', times: 1020}],
                    [{month: "Oct", times: 1206} , {month: 'Nov', times: 1042}, {month: 'Dec', times: 1051}]
                ]
            },
        ],
      keywords: [
            { group: "婚禮", words: ['婚禮穿搭', '婚禮穿搭男', '婚禮穿搭dcard', '婚禮穿搭禁忌', ' 婚禮穿搭褲裝', '婚禮穿搭牛仔褲', '婚禮穿搭女', '婚禮穿搭ptt', '婚禮穿搭夏天', '婚禮穿搭 冬天'] },
            { group: "蔬食", words: ['健康蔬食', '蔬食食譜','素食蔬食']},
            { group: "室內設計", words: ['室內設計風格', '室內設計圖','室內設計網站']}
      ],
      tempkeywords: [],
      selected: 0,
      json: [],
    };
  },
  methods: {
     checkback(num) {
            if(num > 700) {
                return 'dark-2'
            } else if (num > 500) {
                return 'dark-1'
            } else if (num > 300) {
                return 'lighten-1'
            } else {
                return 'lighten-2'
            }
        },
        showModal(keywords) {
            $('#exampleModalCenter').modal('show');
            this.tempkeywords = keywords;
        },
        check(num, grpdata) {
            let total = 0;
            grpdata.trends.forEach(item => {
                item.forEach(single => {
                    total += single.times;
                })
            });
            let threshold = total / 12;
            if(num > threshold) {
                return true;
            } else {
                return false;
            }
        },
        getData() {
            const vm = this;
            this.isLoading = true;
            this.$http.get('http://www.googo.org:8050/api/get_2020_marketing_cal').then(res => {
                console.log(res.data);
                this.json = res.data;
                this.json.splice(34);
                this.json.forEach((item, idx) => {
                    let groupkey = this.GetObjKey(item);
                    item.group = groupkey;
                    let newD = [];
                    item[groupkey].forEach((each, i) => {
                        if(i%3===0){
                            newD.push([]);
                        }
                        const page = parseInt(i/3);
                        newD[page].push(each);
                        item.orgData = newD;
                    });
                    item['orgData'].splice(0, 1);
                })
                console.log(this.json[2]);
            });
            this.$http.get('http://www.googo.org:8050/api/group_datas/').then(res => {
                this.group_datas = res.data;
                //console.log(this.group_datas);
               // this.trends = this.json.filter(item => item['data_type'] === 'trends');
                //this.keywords = this.json.filter(item => item['data_type'] === 'suggests');
                
            });
            this.$http.get('http://www.googo.org:8050/api/user_groups/').then(res => {
                //console.log(res.data);
                this.user_groups = res.data;
                this.user_groups.forEach(item => {
                    this.group_datas.forEach(d => {
                        if(d.group_id === item.id) {
                            d.group_chinese_name = item.group_chinese_name;
                        }
                    })
                });
                /* this.trends = this.group_datas.filter(item => item['data_type'] === 'trends');
                 this.keywords = this.group_datas.filter(item => item['data_type'] === 'suggests');
                this.trends.forEach(item => { 
                    item.times = this.GetObjVal(item.data.data);
                    let newD = [];
                    item.times.forEach((k, i) => {
                        if(i%3===0){
                            newD.push([]);
                        }
                        const page = parseInt(i/3);
                        newD[page].push({times:k});
                        console.log(newD);
                        item.final = newD;
                    });
                }); */
                this.user_groups.forEach(item => {
                    let arr = [];
                    this.group_datas.forEach(d => {
                        if(d.group_id == item.id) {
                            if(d['data_type'] == 'suggests') {
                                arr.push({start: d.start, end: d.end, words: d.data.data});
                                item.suggests = arr;
                                console.log(item.suggests);
                            };
                            if(d['data_type'] == 'trends') {
                                item.trends = d.data.data;
                            }
                        }
                    })
                });
                this.user_groups.forEach(item => {
                    if(item.trends) {
                        const temp = this.GetObjVal(item.trends);
                        let newD = [];
                        temp.forEach((k, i) => {
                            if(i%3===0){
                                newD.push([]);
                            }
                        const page = parseInt(i/3);
                        newD[page].push({times:k});
                        item.trends = newD;
                    });
                    } else {
                        item.trends = [
                            [{times: 0}, {times: 0}, {times: 0}],
                            [{times: 0}, {times: 0}, {times: 0}],
                            [{times: 0}, {times: 0}, {times: 0}],
                            [{times: 0}, {times: 0}, {times: 0}]
                        ]
                    }
                });
                console.log(this.user_groups);
                this.isLoading = false;
            })
        },
        mergeData() {
            this.user_groups.forEach(item => {
                this.group_datas.forEach(d => {
                    if(d['data_type'] == 'suggests') {
                        item.suggests = d.data.data;
                    };
                    if(d['data_type'] == 'trends') {
                        item.trends = d.data.data;
                    }
                })
            });
        },
        getPack() {
            for(let i = 1;i < 5;i++) {
                axios.get(`http://www.googo.org:8050/api/group_datas/group/${i}/`).then(res => {
                console.log(res.data);
                const add = [...res.data];
                this.ex.push(add);
                //this.trends = this.json.filter(item => item['data_type'] === 'trends');
                //this.keywords = this.json.filter(item => item['data_type'] === 'suggests');
                console.log(this.ex);
            });
            }
        },
        filter() {
            this.user_groups .forEach(item => {
                this.group_datas.forEach(d => {
                    if(d.group_id === item.id) {
                        d.group_chinese_name = item.group_chinese_name;
                    }
                })
            });
        },
        GetObjVal(val) {
            return Object.values(val);
        },
        GetObjKey(val) {
            return Object.keys(val)[0];
        }
  },
  created() {
    const d = new Date();
    const m = d.getMonth();
    if (m >= 0 && m < 3) {
      this.selected = 0;
    } else if (m >= 3 && m < 6) {
      this.selected = 1;
    } else if (m >= 6 && m < 9) {
      this.selected = 2;
    } else {
      this.selected = 3;
    };
    this.getData();
    //this.getPack();
  },
};
</script>
