<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>{{ $t('comp.sideMenu.calc.live') }}</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="$t('view.agent.calculate.common.startDate')"
                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="$t('view.agent.calculate.common.endDate')"
                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"
          >
            {{ $t('view.agent.calculate.common.search') }}
          </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>{{ $t('view.agent.calculate.common.total') }}</td>
                <td>{{ $n(total.count || 0, 'decimal') }}</td>
                <td>{{ $n(total.totalCan || 0, 'decimal') }} {{ $t('common.unit.can') }}</td>
                <td>{{ $n(total.krw || 0, 'currency') }}</td>
                <td>{{ $n(total.fee || 0, 'currency') }}</td>
                <td>{{ $n(total.settlementAmount || 0, 'currency') }}</td>
                <td>{{ $n(total.tax || 0, 'currency') }}</td>
                <td>{{ $n(total.depositAmount || 0, 'currency') }}</td>
                <td>{{ $n(total.agentSettlementAmount || 0, 'currency') }}</td>
              </tr>
            </template>

            <template v-slot:item.totalCan="{ item }">
              {{ $n(item.totalCan || 0, 'decimal') }} {{ $t('common.unit.can') }}
            </template>
            <template v-slot:item.krw="{ item }">
              {{ $n(item.krw || 0, 'currency') }}
            </template>
            <template v-slot:item.fee="{ item }">
              {{ $n(item.fee || 0, 'currency') }}
            </template>
            <template v-slot:item.settlementAmount="{ item }">
              {{ $n(item.settlementAmount || 0, 'currency') }}
            </template>
            <template v-slot:item.tax="{ item }">
              {{ $n(item.tax || 0, 'currency') }}
            </template>
            <template v-slot:item.depositAmount="{ item }">
              {{ $n(item.depositAmount || 0, 'currency') }}
            </template>
            <template v-slot:item.agentSettlementAmount="{ item }">
              {{ $n(item.agentSettlementAmount || 0, 'currency') }}
            </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: 'AgentCalculateLive',
  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는 locale 변경 시 computed에서 생성
    }
  },
  computed: {
    headers() {
      return [
        { text: this.$t('view.agent.calculate.columns.nickname'), value: 'creatorNickname', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.count'), value: 'count', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.totalCan'), value: 'totalCan', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.krw'), value: 'krw', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.fee'), value: 'fee', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.settlementAmount'), value: 'settlementAmount', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.tax'), value: 'tax', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.depositAmount'), value: 'depositAmount', align: 'center', sortable: false },
        { text: this.$t('view.agent.calculate.columns.agentSettlementAmount'), 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.getLiveByCreator(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) { // 일부 API는 success 없이 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 || this.$t('common.error.unknown'))
        }
      } catch (e) {
        this.notifyError(this.$t('common.error.unknown'))
      } finally {
        this.is_loading = false
      }
    }
  }
}
</script>

<style scoped>
</style>
