<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>채널 후원 정산</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <v-row>
        <v-col cols="2">
          <datetime
            v-model="start_date"
            class="datepicker"
            format="YYYY-MM-DD"
          />
        </v-col>

        <v-col cols="1">
          ~
        </v-col>

        <v-col cols="2">
          <datetime
            v-model="end_date"
            class="datepicker"
            format="YYYY-MM-DD"
          />
        </v-col>

        <v-col cols="1" />

        <v-col cols="2">
          <v-btn
            block
            color="#3bb9f1"
            dark
            depressed
            @click="getCalculateChannelDonation"
          >
            조회
          </v-btn>
        </v-col>

        <v-spacer />
      </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 v-if="total">
                <td colspan="2">
                  합계
                </td>
                <td class="text-center">
                  {{ total.count.toLocaleString() }} 건
                </td>
                <td class="text-center">
                  {{ total.totalCan.toLocaleString() }} 캔
                </td>
                <td class="text-center">
                  {{ total.krw.toLocaleString() }} 원
                </td>
                <td class="text-center">
                  {{ total.fee.toLocaleString() }} 원
                </td>
                <td class="text-center">
                  {{ total.settlementAmount.toLocaleString() }} 원
                </td>
                <td class="text-center">
                  {{ total.withholdingTax.toLocaleString() }} 원
                </td>
                <td class="text-center">
                  {{ total.depositAmount.toLocaleString() }} 원
                </td>
              </tr>
            </template>

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

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

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

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

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

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

            <template v-slot:item.depositAmount="{ item }">
              {{ item.depositAmount.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/calculate";
import datetime from "vuejs-datetimepicker";

export default {
  name: "CalculateChannelDonation",
  components: {datetime},

  data() {
    return {
      is_loading: false,
      start_date: null,
      end_date: null,
      page: 1,
      page_size: 20,
      total_page: 0,
      items: [],
      total: null,
      headers: [
        {
          text: '날짜',
          align: 'center',
          sortable: false,
          value: 'date',
        },
        {
          text: '크리에이터',
          align: 'center',
          sortable: false,
          value: 'creator',
        },
        {
          text: '건수',
          align: 'center',
          sortable: false,
          value: 'count',
        },
        {
          text: '캔',
          align: 'center',
          sortable: false,
          value: 'totalCan',
        },
        {
          text: '원화',
          align: 'center',
          sortable: false,
          value: 'krw',
        },
        {
          text: '수수료\n(6.6%)',
          align: 'center',
          sortable: false,
          value: 'fee',
        },
        {
          text: '정산금액',
          align: 'center',
          sortable: false,
          value: 'settlementAmount',
        },
        {
          text: '원천세\n(3.3%)',
          align: 'center',
          sortable: false,
          value: 'withholdingTax',
        },
        {
          text: '입금액',
          align: 'center',
          sortable: false,
          value: 'depositAmount',
        },
      ],
    }
  },

  async created() {
    const date = new Date();
    const firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
    const lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    let firstDateMonth = (firstDate.getMonth() + 1).toString()
    if (firstDateMonth.length < 2) {
      firstDateMonth = '0' + firstDateMonth
    }

    let lastDateMonth = (lastDate.getMonth() + 1).toString()
    if (lastDateMonth.length < 2) {
      lastDateMonth = '0' + lastDateMonth
    }

    let firstDateDay = firstDate.getDate().toString()
    if (firstDateDay.length < 2) {
      firstDateDay = '0' + firstDateDay
    }

    let lastDateDay = lastDate.getDate().toString()
    if (lastDateDay.length < 2) {
      lastDateDay = '0' + lastDateDay
    }

    this.start_date = firstDate.getFullYear() + '-' + firstDateMonth + '-' + firstDateDay
    this.end_date = lastDate.getFullYear() + '-' + lastDateMonth + '-' + lastDateDay

    await this.getCalculateChannelDonation()
  },

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

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

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

    async getCalculateChannelDonation() {
      this.is_loading = true

      try {
        const res = await api.getCalculateChannelDonation(this.start_date, this.end_date, this.page, this.page_size)
        if (res.status === 200 && res.data.success === true) {
          this.items = res.data.data.items
          this.total = res.data.data.total
          this.total_page = Math.ceil(res.data.data.totalCount / this.page_size)
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    }
  }
}
</script>

<style scoped>
.datepicker {
  width: 100%;
}
</style>
