<template>
  <div>
    <v-toolbar dark>
      <v-btn
        icon
        @click="$router.back()"
      >
        <v-icon>mdi-arrow-left</v-icon>
      </v-btn>
      <v-toolbar-title>{{ displayNickname }} 정산 상세 - 콘텐츠</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <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="startDateStr"
                v-on="on"
              />
            </template>
            <v-date-picker
              v-model="startDateStr"
              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="endDateStr"
                v-on="on"
              />
            </template>
            <v-date-picker
              v-model="endDateStr"
              scrollable
              @input="menuEnd = false"
            />
          </v-menu>
        </v-col>
        <v-col
          cols="12"
          md="2"
        >
          <v-btn
            color="primary"
            :loading="isLoading"
            @click="onSearch"
          >
            조회
          </v-btn>
        </v-col>
      </v-row>


      <!-- 테이블 영역 -->
      <v-data-table
        :headers="headers"
        :items="items"
        :loading="isLoading"
        :items-per-page="pageSize"
        class="elevation-1"
        disable-pagination
        hide-default-footer
      >
        <!-- 표 최상단 합계 행 -->
        <template v-slot:body.prepend>
          <tr>
            <td class="text-center">
              합계
            </td>
            <td class="text-center">
              {{ numberFormat(total.count) }}
            </td>
            <td class="text-center">
              {{ numberFormat(total.totalCan) }}
            </td>
            <td class="text-center">
              {{ currencyKRW(total.krw) }}
            </td>
            <td class="text-center">
              {{ currencyKRW(total.fee) }}
            </td>
            <td class="text-center">
              {{ currencyKRW(total.settlementAmount) }}
            </td>
            <td class="text-center">
              {{ currencyKRW(total.tax) }}
            </td>
            <td class="text-center">
              {{ currencyKRW(total.depositAmount) }}
            </td>
            <td class="text-center">
              {{ currencyKRW(total.agentSettlementAmount) }}
            </td>
          </tr>
        </template>
        <template v-slot:item.count="{ item }">
          {{ numberFormat(item.count) }}
        </template>
        <template v-slot:item.totalCan="{ item }">
          {{ numberFormat(item.totalCan) }}
        </template>
        <template v-slot:item.krw="{ item }">
          {{ currencyKRW(item.krw) }}
        </template>
        <template v-slot:item.fee="{ item }">
          {{ currencyKRW(item.fee) }}
        </template>
        <template v-slot:item.settlementAmount="{ item }">
          {{ currencyKRW(item.settlementAmount) }}
        </template>
        <template v-slot:item.tax="{ item }">
          {{ currencyKRW(item.tax) }}
        </template>
        <template v-slot:item.depositAmount="{ item }">
          {{ currencyKRW(item.depositAmount) }}
        </template>
        <template v-slot:item.agentSettlementAmount="{ item }">
          {{ currencyKRW(item.agentSettlementAmount) }}
        </template>
      </v-data-table>

      <!-- 페이지네이션 -->
      <div class="d-flex justify-center mt-2">
        <v-pagination
          v-model="page"
          :length="totalPages"
          :total-visible="7"
          @input="onPageChange"
        />
      </div>
    </v-container>
  </div>
</template>

<script>
import { getAgentContentSettlementByCreator } from '@/api/agent'

export default {
  name: 'AgentContentSettlement',
  props: { agentId: { type: [String, Number], required: true } },
  data() {
    const today = new Date()
    const yyyy = today.getFullYear()
    const mm = String(today.getMonth() + 1).padStart(2, '0')
    const dd = String(today.getDate()).padStart(2, '0')
    const firstDay = `${yyyy}-${mm}-01`
    const endDay = `${yyyy}-${mm}-${dd}`
    return {
      startDateStr: firstDay,
      endDateStr: endDay,
      menuStart: false,
      menuEnd: false,
      page: 1,
      pageSize: 20,
      isLoading: false,
      totalCount: 0,
      totalPages: 1,
      total: { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 },
      items: [],
      headers: [
        { text: '닉네임', value: 'creatorNickname', align: 'center' },
        { text: '건수', value: 'count', align: 'center', width: 100 },
        { text: '총 CAN', value: 'totalCan', align: 'center', width: 120 },
        { text: '원화', value: 'krw', align: 'center', width: 140 },
        { text: '수수료', value: 'fee', align: 'center', width: 120 },
        { text: '정산금액', value: 'settlementAmount', align: 'center', width: 140 },
        { text: '세금', value: 'tax', align: 'center', width: 120 },
        { text: '입금액', value: 'depositAmount', align: 'center', width: 140 },
        { text: '에이전트 정산', value: 'agentSettlementAmount', align: 'center', width: 160 },
      ]
    }
  },
  computed: {
    displayNickname() {
      const q = (this.$route && this.$route.query) || {}
      return q.nickname || '에이전트'
    }
  },
  mounted() { this.fetchList() },
  methods: {
    numberFormat(n) { return new Intl.NumberFormat('ko-KR').format(Number(n || 0)) },
    currencyKRW(n) { return new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW', maximumFractionDigits: 0 }).format(Number(n || 0)) },
    onSearch() { this.page = 1; this.fetchList() },
    onPageChange() { this.fetchList() },
    async fetchList() {
      this.isLoading = true
      try {
        const res = await getAgentContentSettlementByCreator(this.agentId, {
          startDateStr: this.startDateStr,
          endDateStr: this.endDateStr,
          page: this.page,
          size: this.pageSize,
        })
        let payload = res && res.data ? res.data : null
        if (payload && payload.data && (!payload.items && !payload.totalCount)) payload = payload.data
        const data = payload || { totalCount: 0, total: {}, items: [] }
        this.totalCount = Number(data.totalCount || 0)
        this.totalPages = Math.max(1, Math.ceil(this.totalCount / this.pageSize))
        const defTotal = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
        this.total = Object.assign({}, defTotal, data.total || {})
        this.items = Array.isArray(data.items) ? data.items : []
      } catch (e) {
        this.totalCount = 0
        this.totalPages = 1
        this.total = { count: 0, totalCan: 0, krw: 0, fee: 0, settlementAmount: 0, tax: 0, depositAmount: 0, agentSettlementAmount: 0 }
        this.items = []
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped>
</style>
