<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="10" />
        <v-col>
          <v-btn
            block
            color="#9970ff"
            dark
            depressed
            @click="showWriteDialog"
          >
            쿠폰 등록
          </v-btn>
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-data-table
            :headers="headers"
            :items="coupon_list"
            :loading="is_loading"
            :items-per-page="-1"
            item-key="id"
            class="elevation-1"
            hide-default-footer
            @click:row="getCouponNumberList"
          >
            <template v-slot:item.id="{ item }">
              {{ item.id }}
            </template>

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

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

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

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

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

            <template v-slot:item.isMultipleUse="{ item }">
              <div v-if="item.isMultipleUse">
                O
              </div>
              <div v-else>
                X
              </div>
            </template>

            <template v-slot:item.isActive="{ item }">
              <div v-if="item.isActive">
                O
              </div>
              <div v-else>
                X
              </div>
            </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>

    <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="coupon_name"
              label="쿠폰명"
            />
          </v-card-text>
          <v-card-text>
            <v-text-field
              v-model="can"
              label="쿠폰금액"
            />
          </v-card-text>
          <v-card-text>
            <v-text-field
              v-model="coupon_number_count"
              label="발행수량"
            />
          </v-card-text>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                유효기간
              </v-col>
              <v-col
                cols="8"
                class="datepicker-wrapper"
              >
                <datetime
                  v-model="validity"
                  class="datepicker"
                  format="YYYY-MM-DD"
                />
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                인증 계정당 중복 사용 가능여부
              </v-col>
              <v-col cols="8">
                <input
                  v-model="is_multiple_use"
                  type="checkbox"
                >
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text v-show="selected_coupon !== null">
            <v-row align="center">
              <v-col cols="4">
                활성화
              </v-col>
              <v-col cols="8">
                <input
                  v-model="is_active"
                  type="checkbox"
                >
              </v-col>
            </v-row>
          </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-row>
      <v-dialog
        v-model="show_coupon_number_list_dialog"
        max-width="1000px"
        persistent
      >
        <v-card>
          <v-card-text>
            <v-data-table
              :headers="detail_headers"
              :items="coupon_number_list"
              :loading="is_loading"
              :items-per-page="-1"
              class="elevation-1"
              hide-default-footer
            >
              <template v-slot:item.couponNumberId="{ item }">
                {{ item.couponNumberId }}
              </template>

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

              <template v-slot:item.isUsed="{ item }">
                <div v-if="item.isUsed">
                  O
                </div>
                <div v-else>
                  X
                </div>
              </template>
            </v-data-table>
          </v-card-text>
          <v-card-text>
            <v-row class="text-center">
              <v-col>
                <v-pagination
                  v-model="coupon_number_page"
                  :length="coupon_number_total_page"
                  circle
                  @input="couponNumberNext"
                />
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-actions v-show="!is_loading">
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="cancel"
            >
              확인
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

<script>
import * as api from '@/api/can'
import datetime from "vuejs-datetimepicker";

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

  data() {
    return {
      is_loading: false,
      is_modify: false,
      show_write_dialog: false,
      show_coupon_number_list_dialog: false,

      coupon_number_list: [],
      selected_coupon: null,
      coupon_name: null,
      can: null,
      validity: null,
      is_active: null,
      is_multiple_use: false,
      coupon_number_count: null,

      page: 1,
      total_page: 0,

      coupon_number_page: 1,
      coupon_number_total_page: 0,

      detail_headers: [
        {
          text: '순번',
          align: 'center',
          sortable: false,
          value: 'couponNumberId',
        },
        {
          text: '쿠폰번호',
          align: 'center',
          sortable: false,
          value: 'couponNumber',
        },
        {
          text: '사용여부',
          align: 'center',
          sortable: false,
          value: 'isUsed',
        },
      ],

      headers: [
        {
          text: '순번',
          align: 'center',
          sortable: false,
          value: 'id',
        },
        {
          text: '쿠폰명',
          align: 'center',
          sortable: false,
          value: 'couponName',
        },
        {
          text: '쿠폰금액',
          align: 'center',
          sortable: false,
          value: 'can',
        },
        {
          text: '발행수량',
          align: 'center',
          sortable: false,
          value: 'couponCount',
        },
        {
          text: '사용수량',
          align: 'center',
          sortable: false,
          value: 'useCouponCount',
        },
        {
          text: '유효기간',
          align: 'center',
          sortable: false,
          value: 'validity',
        },
        {
          text: '중복사용여부',
          align: 'center',
          sortable: false,
          value: 'isMultipleUse',
        },
        {
          text: '활성화',
          align: 'center',
          sortable: false,
          value: 'isActive',
        },
        {
          text: '엑셀 다운로드',
          align: 'center',
          sortable: false,
          value: 'download',
        }
      ],

      coupon_list: [],
    }
  },

  async created() {
    await this.getCouponList();
  },

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

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

    showWriteDialog() {
      this.show_write_dialog = true
    },

    validate() {
      if (this.coupon_name === null) {
        this.notifyError('쿠폰명을 입력하세요.')
        return
      }

      if (this.can === null) {
        this.notifyError('쿠폰금액을 입력하세요.')
        return
      }

      if (isNaN(this.can)) {
        this.notifyError('쿠폰금액은 숫자만 입력 가능합니다.')
        return
      }

      if (this.can < 1) {
        this.notifyError('쿠폰금액은 1 이상 입력 가능합니다.')
        return
      }

      if (this.coupon_number_count === null) {
        this.notifyError('발행수량을 입력하세요.')
        return
      }

      if (isNaN(this.coupon_number_count)) {
        this.notifyError('발행수량은 숫자만 입력 가능합니다.')
        return
      }

      if (this.coupon_number_count < 5) {
        this.notifyError('발행수량은 5 이상 입력 가능합니다.')
        return
      }

      if (this.validity === null) {
        this.notifyError('유효기간을 입력하세요.')
        return
      }

      this.submit()
    },

    cancel() {
      this.is_modify = false
      this.show_write_dialog = false
      this.show_coupon_number_list_dialog = false

      this.selected_coupon = null
      this.coupon_number_list = []
      this.coupon_name = null
      this.can = null
      this.validity = null
      this.is_active = null
      this.is_multiple_use = false
      this.coupon_number_count = null
    },

    async getCouponList() {
      this.isLoading = true
      try {
        let res = await api.getCouponList(this.page);

        if (res.status === 200 && res.data.success === true) {
          const data = res.data.data

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

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

    async getCouponNumberList(value) {
      this.selected_coupon = value
      await this.couponNumberNext()
    },

    async couponNumberNext() {
      this.is_loading = true

      try {
        const res = await api.getCouponNumberList(this.selected_coupon.id, this.coupon_number_page)
        if (res.status === 200 && res.data.success === true) {
          const data = res.data.data

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

          if (total_page <= 0)
            this.coupon_number_total_page = 1
          else
            this.coupon_number_total_page = total_page

          this.show_coupon_number_list_dialog = true
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }

        this.is_loading = false
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        this.is_loading = false
      }
    },

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

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

      this.is_loading = true

      try {
        const res = await api.generateCoupon(
          this.coupon_name,
          this.can,
          this.validity,
          this.is_multiple_use,
          this.coupon_number_count
        );

        if (res.status === 200 && res.data.success === true) {
          this.cancel()
          this.notifySuccess(res.data.message || '쿠폰생성이 시작되었습니다. 잠시만 기다려 주세요')

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

      this.is_loading = false
    },
  }
}
</script>
