<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>크리에이터별 커뮤니티 정산</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <!-- 필터 영역 -->
      <v-row
        class="mt-2 mb-2"
        align="center"
        justify="end"
      >
        <v-col
          cols="12"
          md="3"
        >
          <v-menu
            v-model="menuStart"
            :close-on-content-click="false"
            transition="scale-transition"
            offset-y
            min-width="auto"
          >
            <template v-slot:activator="{ on, attrs }">
              <v-text-field
                v-bind="attrs"
                label="시작일"
                readonly
                dense
                :value="start_date"
                v-on="on"
              />
            </template>
            <v-date-picker
              v-model="start_date"
              scrollable
              @input="menuStart = false"
            />
          </v-menu>
        </v-col>

        <v-col
          cols="12"
          md="3"
        >
          <v-menu
            v-model="menuEnd"
            :close-on-content-click="false"
            transition="scale-transition"
            offset-y
            min-width="auto"
          >
            <template v-slot:activator="{ on, attrs }">
              <v-text-field
                v-bind="attrs"
                label="종료일"
                readonly
                dense
                :value="end_date"
                v-on="on"
              />
            </template>
            <v-date-picker
              v-model="end_date"
              scrollable
              @input="menuEnd = false"
            />
          </v-menu>
        </v-col>

        <v-col
          cols="12"
          md="2"
        >
          <v-btn
            color="#3bb9f1"
            :loading="is_loading"
            @click="fetchItems"
          >
            조회
          </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>
                <td>합계</td>
                <td>{{ (total.count || 0).toLocaleString() }}</td>
                <td>{{ (total.totalCan || 0).toLocaleString() }} 캔</td>
                <td>{{ (total.krw || 0).toLocaleString() }} 원</td>
                <td>{{ (total.fee || 0).toLocaleString() }} 원</td>
                <td>{{ (total.settlementAmount || 0).toLocaleString() }} 원</td>
                <td>{{ (total.tax || 0).toLocaleString() }} 원</td>
                <td>{{ (total.depositAmount || 0).toLocaleString() }} 원</td>
                <td>{{ (total.agentSettlementAmount || 0).toLocaleString() }} 원</td>
              </tr>
            </template>

            <template v-slot:item.totalCan="{ item }">
              {{ (item.totalCan || 0).toLocaleString() }} 캔
            </template>
            <template v-slot:item.krw="{ item }">
              {{ (item.krw || 0).toLocaleString() }} 원
            </template>
            <template v-slot:item.fee="{ item }">
              {{ (item.fee || 0).toLocaleString() }} 원
            </template>
            <template v-slot:item.settlementAmount="{ item }">
              {{ (item.settlementAmount || 0).toLocaleString() }} 원
            </template>
            <template v-slot:item.tax="{ item }">
              {{ (item.tax || 0).toLocaleString() }} 원
            </template>
            <template v-slot:item.depositAmount="{ item }">
              {{ (item.depositAmount || 0).toLocaleString() }} 원
            </template>
            <template v-slot:item.agentSettlementAmount="{ item }">
              {{ (item.agentSettlementAmount || 0).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="onPage"
          />
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script>
import * as api from '@/api/agent_calculate';

export default {
  name: 'AgentCalculateCommunityPost',
  components: { },
  data() {
    return {
      is_loading: false,
      menuStart: false,
      menuEnd: false,
      start_date: null,
      end_date: null,
      page: 1,
      page_size: 20,
      total_page: 0,
      items: [],
      total: {
        count: 0,
        totalCan: 0,
        krw: 0,
        fee: 0,
        settlementAmount: 0,
        tax: 0,
        depositAmount: 0,
        agentSettlementAmount: 0
      },
      headers: [
        { text: '닉네임', value: 'creatorNickname', align: 'center', sortable: false },
        { text: '건수', value: 'count', align: 'center', sortable: false },
        { text: '총 CAN', value: 'totalCan', align: 'center', sortable: false },
        { text: '원화', value: 'krw', align: 'center', sortable: false },
        { text: '수수료', value: 'fee', align: 'center', sortable: false },
        { text: '정산금액', value: 'settlementAmount', align: 'center', sortable: false },
        { text: '세금', value: 'tax', align: 'center', sortable: false },
        { text: '입금액', value: 'depositAmount', align: 'center', sortable: false },
        { text: '에이전트 정산금액', value: 'agentSettlementAmount', align: 'center', sortable: false },
      ]
    }
  },
  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);

    const fdM = (firstDate.getMonth() + 1).toString().padStart(2, '0')
    const ldM = (lastDate.getMonth() + 1).toString().padStart(2, '0')

    this.start_date = `${firstDate.getFullYear()}-${fdM}-0${firstDate.getDate()}`
    this.end_date = `${lastDate.getFullYear()}-${ldM}-${lastDate.getDate()}`

    await this.fetchItems();
  },
  methods: {
    notifyError(message) {
      this.$dialog.notify.error(message)
    },
    async onPage() {
      await this.fetchItems();
    },
    async fetchItems() {
      this.is_loading = true
      try {
        const res = await api.getCommunityByCreator(this.start_date, this.end_date, this.page, this.page_size)
        if (res.status === 200 && res.data && res.data.success === true) {
          const data = res.data.data
          this.items = data.items || []
          this.total = data.total || this.total
          const totalPage = Math.ceil((data.totalCount || 0) / this.page_size)
          this.total_page = totalPage > 0 ? totalPage : 1
        } else if (res.data && res.data.data) {
          const data = res.data.data
          this.items = data.items || []
          this.total = data.total || this.total
          const totalPage = Math.ceil((data.totalCount || 0) / this.page_size)
          this.total_page = totalPage > 0 ? totalPage : 1
        } else {
          this.notifyError(res.data?.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    }
  }
}
</script>

<style scoped>
</style>
