<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="8" />
        <v-col>
          <v-btn
            block
            color="#3bb9f1"
            dark
            depressed
            @click="showWriteDialog"
          >
            크리에이터 정산비율 추가 등록
          </v-btn>
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-data-table
            :headers="headers"
            :items="items"
            :loading="is_loading"
            :items-per-page="-1"
            item-key="id"
            class="elevation-1"
            hide-default-footer
          >
            <template v-slot:item.nickname="{ item }">
              {{ item.nickname }}
            </template>

            <template v-slot:item.subsidy="{ item }">
              {{ item.subsidy.toLocaleString('en-US') }}원
            </template>

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

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

            <template v-slot:item.communitySettlementRatio="{ item }">
              {{ item.communitySettlementRatio }}%
            </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-row>
        <v-dialog
          v-model="show_write_dialog"
          max-width="1000px"
          persistent
        >
          <v-card>
            <v-card-title>크리에이터 정산비율</v-card-title>
            <v-card-text>
              <v-text-field
                v-model="creator_settlement_ratio.creator_id"
                label="크리에이터 번호"
              />
            </v-card-text>
            <v-card-text>
              <v-text-field
                v-model="creator_settlement_ratio.subsidy"
                label="지원금"
              />
            </v-card-text>
            <v-card-text>
              <v-text-field
                v-model="creator_settlement_ratio.liveSettlementRatio"
                label="라이브 정산비율(%)"
              />
            </v-card-text>
            <v-card-text>
              <v-text-field
                v-model="creator_settlement_ratio.contentSettlementRatio"
                label="콘텐츠 정산비율(%)"
              />
            </v-card-text>
            <v-card-text>
              <v-text-field
                v-model="creator_settlement_ratio.communitySettlementRatio"
                label="커뮤니티 정산비율(%)"
              />
            </v-card-text>
            <v-card-actions v-show="!is_loading">
              <v-spacer />
              <v-btn
                color="blue darken-1"
                text
                @click="cancel"
              >
                취소
              </v-btn>
              <v-btn
                color="blue darken-1"
                text
                @click="validate"
              >
                등록하기
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </v-container>
  </div>
</template>

<script>
import * as api from "@/api/calculate";

export default {
  name: "CreatorSettlementRatio",

  data() {
    return {
      is_loading: false,
      page: 1,
      total_page: 0,
      items: [],
      creator_settlement_ratio: {},
      show_write_dialog: false,
      headers: [
        {
          text: '닉네임',
          align: 'center',
          sortable: false,
          value: 'nickname',
        },
        {
          text: '지원금',
          align: 'center',
          sortable: false,
          value: 'subsidy',
        },
        {
          text: '라이브 정산비율',
          align: 'center',
          sortable: false,
          value: 'liveSettlementRatio',
        },
        {
          text: '콘텐츠 정산비율',
          align: 'center',
          sortable: false,
          value: 'contentSettlementRatio',
        },
        {
          text: '커뮤니티 정산비율',
          align: 'center',
          sortable: false,
          value: 'communitySettlementRatio',
        },
      ],
    }
  },

  async created() {
    await this.getSettlementRatio()
  },

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

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

    showWriteDialog() {
      this.show_write_dialog = true
    },

    cancel() {
      this.creator_settlement_ratio = {}
      this.show_write_dialog = false
    },

    validate() {
      if (this.creator_settlement_ratio.creator_id === null) {
        this.notifyError('크리에이터 번호를 입력하세요')
        return
      }

      if (this.creator_settlement_ratio.subsidy === null || isNaN(this.creator_settlement_ratio.subsidy)) {
        this.notifyError('지원금은 숫자만 입력가능합니다')
        return
      }

      if (this.creator_settlement_ratio.liveSettlementRatio === null || isNaN(this.creator_settlement_ratio.liveSettlementRatio)) {
        this.notifyError('라이브 정산비율은 숫자만 입력가능합니다')
        return
      }

      if (this.creator_settlement_ratio.contentSettlementRatio === null || isNaN(this.creator_settlement_ratio.contentSettlementRatio)) {
        this.notifyError('콘텐츠 정산비율은 숫자만 입력가능합니다')
        return
      }

      if (this.creator_settlement_ratio.communitySettlementRatio === null || isNaN(this.creator_settlement_ratio.communitySettlementRatio)) {
        this.notifyError('커뮤니티 정산비율은 숫자만 입력가능합니다')
        return
      }

      this.createCreatorSettlementRatio();
    },

    async createCreatorSettlementRatio() {
      if (this.is_loading) return;

      this.is_loading = true

      try {
        const res = await api.createCreatorSettlementRatio(this.creator_settlement_ratio)

        if (res.status === 200 && res.data.success === true) {
          this.cancel()
          this.notifySuccess(res.data.message || '등록되었습니다.')

          this.items = [];
          this.creator_settlement_ratio = {};
          await this.getSettlementRatio()
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
      }

      this.is_loading = false
    },

    async getSettlementRatio() {
      this.is_loading = true

      try {
        const res = await api.getSettlementRatio(this.page)
        if (res.status === 200 && res.data.success === true) {
          const data = res.data.data

          const total_page = Math.ceil(data.totalCount / 20)
          this.items = data.items

          if (total_page <= 0)
            this.total_page = 1
          else
            this.total_page = total_page
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    },

    async next() {
      if (this.search_word.length < 2) {
        this.search_word = ''
      }

      await this.getSettlementRatio()
    },
  },
}
</script>

<style scoped>

</style>
