<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="charge_event_list"
            :loading="is_loading"
            :items-per-page="-1"
            item-key="id"
            class="elevation-1"
            hide-default-footer
          >
            <template v-slot:item.title="{ item }">
              {{ item.title }}
            </template>

            <template v-slot:item.period="{ item }">
              {{ item.startDate }}  ~ {{ item.endDate }}
            </template>

            <template v-slot:item.availableCount="{ item }">
              {{ item.availableCount }} 번 참여가능
            </template>

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

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

            <template v-slot:item.management="{ item }">
              <v-btn
                :disabled="is_loading"
                @click="showModifyDialog(item)"
              >
                수정
              </v-btn>
            </template>
          </v-data-table>
        </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="title"
              label="제목"
              required
            />
          </v-card-text>
          <v-card-text>
            <v-text-field
              v-model="available_count"
              label="참여가능 횟수"
              required
            />
          </v-card-text>
          <v-card-text>
            <v-text-field
              v-model="add_percent"
              label="추가 충전 %"
              required
            />
          </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="start_date"
                  class="datepicker"
                  format="YYYY-MM-DD"
                />
                <div> ~ </div>
                <datetime
                  v-model="end_date"
                  class="datepicker"
                  format="YYYY-MM-DD"
                />
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text v-show="selected_charge_event !== 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
              v-if="selected_charge_event !== null"
              color="blue darken-1"
              text
              @click="modify"
            >
              수정
            </v-btn>
            <v-btn
              v-else
              color="blue darken-1"
              text
              @click="validate"
            >
              등록
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

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

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

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

      selected_charge_event: null,
      title: null,
      start_date: null,
      end_date: null,
      available_count: null,
      add_percent: null,
      is_active: null,

      charge_event_list: [],
      headers: [
        {
          text: '제목',
          align: 'center',
          sortable: false,
          value: 'title',
        },
        {
          text: '기간',
          align: 'center',
          sortable: false,
          value: 'period',
        },
        {
          text: '참여가능 횟수',
          align: 'center',
          sortable: false,
          value: 'availableCount',
        },
        {
          text: '추가 충전 %',
          align: 'center',
          sortable: false,
          value: 'addPercent',
        },
        {
          text: '활성화',
          align: 'center',
          sortable: false,
          value: 'isActive',
        },
        {
          text: '관리',
          align: 'center',
          sortable: false,
          value: 'management'
        },
      ],
    }
  },

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

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

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

    showWriteDialog() {
      this.show_write_dialog = true
    },

    showModifyDialog(item) {
      this.selected_charge_event = item;
      this.title = item.title;
      this.add_percent = item.addPercent;
      this.available_count = item.availableCount;
      this.start_date = item.startDate;
      this.end_date = item.endDate;
      this.is_active = item.isActive;
      this.show_write_dialog = true
    },

    validate() {
      if (this.title === null) {
        this.notifyError('제목을 입력하세요.')
        return
      }

      if (this.available_count === null) {
        this.notifyError('참여가능 횟수를 입력하세요.')
        return
      }

      if (isNaN(this.available_count)) {
        this.notifyError('참여가능 횟수는 숫자만 입력 가능합니다.')
        return
      }

      if (this.add_percent === null) {
        this.notifyError('추가 충전 비율(%)을 입력하세요')
        return
      }

      if (isNaN(this.add_percent)) {
        this.notifyError('추가 충전 비율(%)은 숫자만 입력 가능합니다.')
        return
      }

      if (this.start_date === null || this.end_date === null) {
        this.notifyError('이벤트 기간을 입력하세요.')
        return
      }

      this.submit()
     },

    cancel() {
      this.selected_charge_event = null;
      this.title = null;
      this.add_percent = null;
      this.available_count = null;
      this.start_date = null;
      this.end_date = null;
      this.show_write_dialog = false
    },

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

      this.is_loading = true

      try {
        const res = await api.save(
          this.title,
          this.start_date,
          this.end_date,
          this.available_count,
          this.add_percent
        )

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

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

      this.is_loading = false
    },

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

      this.isLoading = true

      try {
        const res = await api.modify(
          this.selected_charge_event.id,
          this.title !== this.selected_charge_event.title ? this.title : null,
          this.start_date !== this.selected_charge_event.startDate ? this.start_date : null,
          this.end_date !== this.selected_charge_event.endDate ? this.end_date : null,
          this.available_count !== this.selected_charge_event.availableCount ? this.available_count : null,
          this.add_percent !== this.selected_charge_event.addPercent ? this.add_percent : null,
          this.is_active !== this.selected_charge_event.isActive ? this.is_active : null
        )

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

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

    async getChargeEventList() {
      this.is_loading = true

      try {
        const res = await api.getChargeEventList();

        if (res.status === 200 && res.data.success === true) {
          this.charge_event_list = res.data.data
        } else {
          this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }

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

<style scoped>
.datepicker {
  text-align: center;
}

.datepicker-wrapper {
  display: flex;
  flex-direction: row;
}

.datepicker-wrapper > div {
  margin: 20px;
}

.v-card__text {
  margin-top: 20px;
}

.v-card__actions {
  margin-top: 100px;
}

.v-card__actions > .v-btn {
  font-size: 20px;

}
</style>
