<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>광고 통계</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <v-row>
        <v-spacer />
        <v-col>
          <v-btn
            block
            color="#3bb9f1"
            dark
            depressed
            @click="getTodayStatistics"
          >
            오늘
          </v-btn>
        </v-col>
        <v-col>
          <v-btn
            block
            color="#3bb9f1"
            dark
            depressed
            @click="getYesterdayStatistics"
          >
            어제
          </v-btn>
        </v-col>
        <v-col>
          <v-btn
            block
            color="#3bb9f1"
            dark
            depressed
            @click="getWeekStatistics"
          >
            7일 전
          </v-btn>
        </v-col>
        <v-spacer />
        <v-col>
          <datetime
            v-model="start_date"
            class="datepicker"
            format="YYYY-MM-DD"
          />
        </v-col>
        <v-col cols="1">
          ~
        </v-col>
        <v-col>
          <datetime
            v-model="end_date"
            class="datepicker"
            format="YYYY-MM-DD"
          />
        </v-col>

        <v-col cols="2">
          <v-btn
            block
            color="#3bb9f1"
            dark
            depressed
            @click="getStatistics"
          >
            조회
          </v-btn>
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-data-table
            :headers="headers"
            :items="items"
            :loading="is_loading"
            :items-per-page="-1"
            class="elevation-1"
            hide-default-footer
          >
            <template slot="body.prepend">
              <tr class="summary">
                <td colspan="4">
                  총합계
                </td>
                <td>{{ sumField('launchCount').toLocaleString() }}</td>
                <td>{{ sumField('signUpCount').toLocaleString() }}</td>
                <td>{{ sumField('firstPaymentCount').toLocaleString() }}</td>
                <td>{{ sumField('firstPaymentTotalAmount').toLocaleString() }}</td>
                <td>{{ sumField('repeatPaymentCount').toLocaleString() }}</td>
                <td>{{ sumField('repeatPaymentTotalAmount').toLocaleString() }}</td>
                <td>{{ sumField('allPaymentCount').toLocaleString() }}</td>
                <td>{{ sumField('allPaymentTotalAmount').toLocaleString() }}</td>
                <td>{{ sumField('loginCount').toLocaleString() }}</td>
              </tr>
            </template>

            <template v-slot:item.date="{ item }">
              {{ item.date }}
            </template>

            <template v-slot:item.mediaGroup="{ item }">
              {{ item.mediaGroup }}
            </template>

            <template v-slot:item.pid="{ item }">
              {{ item.pid }}
            </template>

            <template v-slot:item.pidName="{ item }">
              {{ item.pidName }}
            </template>

            <template v-slot:item.launchCount="{ item }">
              {{ item.launchCount.toLocaleString() }}
            </template>

            <template v-slot:item.signUpCount="{ item }">
              {{ item.signUpCount.toLocaleString() }}
            </template>

            <template v-slot:item.firstPaymentCount="{ item }">
              {{ item.firstPaymentCount.toLocaleString() }}
            </template>

            <template v-slot:item.firstPaymentTotalAmount="{ item }">
              {{ item.firstPaymentTotalAmount.toLocaleString() }}
            </template>

            <template v-slot:item.repeatPaymentCount="{ item }">
              {{ item.repeatPaymentCount.toLocaleString() }}
            </template>

            <template v-slot:item.repeatPaymentTotalAmount="{ item }">
              {{ item.repeatPaymentTotalAmount.toLocaleString() }}
            </template>

            <template v-slot:item.allPaymentCount="{ item }">
              {{ item.allPaymentCount.toLocaleString() }}
            </template>

            <template v-slot:item.allPaymentTotalAmount="{ item }">
              {{ item.allPaymentTotalAmount.toLocaleString() }}
            </template>

            <template v-slot:item.loginCount="{ item }">
              {{ item.loginCount.toLocaleString() }}
            </template>
          </v-data-table>
        </v-col>
      </v-row>
      <v-row class="text-center">
        <v-col>
          <v-pagination
            v-model="page"
            :length="total_page"
            circle
            @input="next"
          />
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script>
import * as api from "@/api/marketing";
import datetime from "vuejs-datetimepicker";

export default {
  name: 'MarketingAdStatisticsView',
  components: {datetime},

  data() {
    return {
      is_loading: false,
      start_date: null,
      end_date: null,
      page: 1,
      total_page: 0,

      headers: [
        {
          text: '일자',
          align: 'center',
          sortable: false,
          value: 'date',
        },
        {
          text: '매체',
          align: 'center',
          sortable: false,
          value: 'mediaGroup',
        },
        {
          text: 'pid',
          align: 'center',
          sortable: false,
          value: 'pid',
        },
        {
          text: 'pid명',
          align: 'center',
          sortable: false,
          value: 'pidName',
        },
        {
          text: '앱 실행',
          align: 'center',
          sortable: false,
          value: 'launchCount',
        },
        {
          text: '가입수',
          align: 'center',
          sortable: false,
          value: 'signUpCount',
        },
        {
          text: '첫결제건수',
          align: 'center',
          sortable: false,
          value: 'firstPaymentCount',
        },
        {
          text: '첫결제금액',
          align: 'center',
          sortable: false,
          value: 'firstPaymentTotalAmount',
        },
        {
          text: '재결제건수',
          align: 'center',
          sortable: false,
          value: 'repeatPaymentCount',
        },
        {
          text: '재결제금액',
          align: 'center',
          sortable: false,
          value: 'repeatPaymentTotalAmount',
        },
        {
          text: '총 결제건수',
          align: 'center',
          sortable: false,
          value: 'allPaymentCount',
        },
        {
          text: '총 결제금액',
          align: 'center',
          sortable: false,
          value: 'allPaymentTotalAmount',
        },
        {
          text: '로그인 수',
          align: 'center',
          sortable: false,
          value: 'loginCount',
        }
      ],
      items: [],
    }
  },

  async created() {
    await this.getTodayStatistics();
  },

  methods: {
    notifyError(message) {
      this.$dialog.notify.error(message)
    },

    notifySuccess(message) {
      this.$dialog.notify.success(message)
    },

    sumField(key) {
      return this.items.reduce((a, b) => a + (b[key] || 0), 0)
    },

    formatDate(date) {
      return date.toISOString().split('T')[0];
    },

    async next() {
      await this.getStatistics()
    },

    async getStatistics() {
      this.is_loading = true

      try {
        const res = await api.getStatistics(this.start_date, this.end_date, this.page);

        if (res.status === 200 && res.data.success === true) {
          let data = res.data.data
          this.items = data.items

          const totalPage = Math.ceil(data.totalCount / 20)
          if (totalPage <= 0)
            this.total_page = 1
          else
            this.total_page = totalPage
        } else {
          this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }

        this.is_loading = false
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        this.is_loading = false
      }
    },

    async getTodayStatistics() {
      const today = new Date();

      this.start_date = this.formatDate(today);
      this.end_date = this.formatDate(today);

      await this.getStatistics()
    },

    async getYesterdayStatistics() {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);

      this.start_date = this.formatDate(yesterday);
      this.end_date = this.formatDate(yesterday);
      await this.getStatistics()
    },

    async getWeekStatistics() {
      const week = new Date();
      week.setDate(week.getDate() - 8);

      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);

      this.start_date = this.formatDate(week);
      this.end_date = this.formatDate(yesterday);
      await this.getStatistics()
    }
  },
}
</script>

<style scoped>
.summary {
  background-color: #c4dbf1;
}
</style>
