<template>
  <div>
    <Loading :active.sync="isLoading" :opacity="0.8">
      <template slot="default">
        <img src="../assets/ajax-loader.gif">
      </template>
    </Loading>
    <template v-if="table_show">
       <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 in customData" :key="`gr-${item.id}`">
              <th>{{ item.groups.group_chinese_name }}</th>
              <td v-for="(t,idx) in item.groups.trends[i]" :key="`tr-${idx}`">
                <button type="button" class="btn__kw" data-toggle="modal"
                data-target="#exampleModalCenter"
                @click.prevent="showModal(item.groups.data_suggests)" v-b-tooltip.hover.righttop="'點選查看常用關鍵字組'">關鍵字</button>
                <div class="highTrend dark-1 p-2 mt-2" v-b-tooltip.hover.righttop="'該客群的搜尋次數高於歷史平均值'" variant="primary" v-if="check(t.popularity, item.groups)">Popular</div>
              </td>
            </tr>
          </tbody>
      </table>
    
    
      <h3 class="">2019-20行銷事項參考</h3>
      <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 ,it) in json" :key="`cal-${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>
    </template>
    
    <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 words__block">
                    <div class="d-flex justify-content-between align-items-center">
                      <span class="d-flex mb-2"><i class="fas fa-clock d-inline-block mr-1"></i>日期：{{ word.start }} - {{ word.end}}</span>
                      <span class="openWords" @click="openWords"><i class="fas fa-chevron-down"></i></span>
                    </div>
                    <template v-for="(each, idx) in word.suggests">
                      <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';
import axios from 'axios';

export default {
  name: 'Home',
  components: {
  },
  props: [
    'userId',
    'logselected'
  ],
  data() {
    return {
      group_datas: [],
      user_groups: [],
      isLoading: false,
      ex: [],
      month: [['Jan', 'Feb', 'Mar'], ['Apr', 'May', 'Jun'], ['Jul', 'Aug', 'Sep'], ['Oct', 'Nov', 'Dec']],
      tempkeywords: [],
      selected: 0,
      json: [],
      customData: [],
      servicelist: [],
      serviceSelected: '',
      table_show: true,
    };
  },
  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.reverse();
        },
        check(num, grpdata) {
            let total = 0;
            grpdata.trends.forEach(item => {
                item.forEach(single => {
                    total += single.popularity;
                })
            });
            let threshold = total / 12;
            if(num > threshold) {
                return true;
            } else {
                return false;
            }
        },
        getcalData() {
          this.$http.get('http://www.googo.org:8050/api/get_2020_marketing_cal').then(res => {
                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);
                })
            });
        },
        getCustomData(id) {
          const vm = this;
          vm.isLoading = true;
          this.$http.get(`http://www.googo.org:8050/api/user_groups_data/${id}`).then(res => {
                vm.customData = res.data;
                vm.customData.forEach((item, idx) => {
                  if(item.groups.data_trends) {
                    let newD = [];
                    item.groups.data_trends.forEach((k, i) => {
                      if(i%3===0){
                        newD.push([]);
                      }
                      const page = parseInt(i/3);
                      newD[page].push(k);
                    });
                  item.groups.trends = newD;
                  }else {
                     item.groups.trends = [
                      [{popularity: 0}, {popularity: 0}, {popularity: 0}],
                      [{popularity: 0}, {popularity: 0}, {popularity: 0}],
                      [{popularity: 0}, {popularity: 0}, {popularity: 0}],
                      [{popularity: 0}, {popularity: 0}, {popularity: 0}]
                    ]
                  }
            });
            vm.isLoading = false;
          });
        },
        GetObjVal(val) {
            return Object.values(val);
        },
        GetObjKey(val) {
            return Object.keys(val)[0];
        },
        openWords(e) {
          const { currentTarget } = e;
          $(currentTarget).parent().parent().toggleClass('autoHeight');
          if($(currentTarget).children().hasClass('fa-chevron-down')){
            $(currentTarget).children().removeClass();
            $(currentTarget).children().addClass('fas fa-chevron-up');
          } else{
            $(currentTarget).children().removeClass();
            $(currentTarget).children().addClass('fas fa-chevron-down');
          }
        },
        getServTypeLi() {
          this.$http.get('http://www.googo.org:8050/api/service_type/').then(res => {
            this.servicelist = res.data;
          });
        },
        submit_type() {
          // console.log(this.serviceSelected);
          const vm = this;
          vm.table_show = true;
          this.getCustomData();
          this.getcalData();
        },
        examineLog() {
          if(this.logselected) {
            this.getCustomData();
          }else {
            this.table_show = false;
          }
        },
  },
 /*  beforeRouteEnter (to, from, next) {
    axios.get('http://www.googo.org:8050/api/auth/user_status', { 
      headers: {
        'Authorization' : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyMCwiZXhwIjoxNjIwNzg5Mzc4LCJzdWIiOjIwfQ.C-S2gPHkZ0RnejcfCFVoYKiwsNuMVH5QZdNqSKvZPZs"
      }
    }).then(res => {
        let userid = res.data.data.user_id;
        axios.get('http://www.googo.org:8050/api/user_groups_data/20').then(res => {
          if(res.data.length === 0){
            next({ path: '/serviceselection'});
          }else {
            next();
          }
        });
      });
  }, */
  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.getCustomData(this.userId);
    this.getcalData();
    this.getServTypeLi();
  }
};

</script>
