<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-for="(item, i) in events"
          :key="i"
          cols="3"
        >
          <v-card>
            <v-card-title>
              <v-spacer />
              <v-img
                :src="item.thumbnailImageUrl"
                @click="clickEvent(item)"
              />
              <v-spacer />
            </v-card-title>
          </v-card>
        </v-col>
      </v-row>
    </v-container>
    <v-row>
      <v-dialog
        v-model="show_write_dialog"
        max-width="1000px"
        persistent
      >
        <v-card>
          <v-card-text />
          <v-card-title v-show="!is_modify">
            이벤트 등록
          </v-card-title>
          <v-card-title v-show="is_modify">
            이벤트 수정
          </v-card-title>
          <v-card-text>
            <v-text-field
              v-model="event.title"
              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="event.startDate"
                  class="datepicker"
                  format="YYYY-MM-DD"
                />
                <div> ~ </div>
                <datetime
                  v-model="event.endDate"
                  class="datepicker"
                  format="YYYY-MM-DD"
                />
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text>
            <div class="image-select">
              <label for="thumbnailImage">
                썸네일 등록
              </label>
              <v-file-input
                id="thumbnailImage"
                v-model="event.thumbnailImage"
                @change="thumbnailImageAdd"
              />
            </div>
            <img
              v-if="event.thumbnailImageUrl"
              :src="event.thumbnailImageUrl"
              alt=""
              class="image-preview"
            >
          </v-card-text>
          <v-card-text>
            <div class="image-select">
              <label for="detailImage">
                상세 이미지 등록
              </label>
              <v-file-input
                id="detailImage"
                v-model="event.detailImage"
                @change="detailImageAdd"
              />
            </div>
            <img
              v-if="event.detailImageUrl"
              :src="event.detailImageUrl"
              alt=""
              class="image-preview"
            >
          </v-card-text>
          <v-card-text>
            <div class="image-select">
              <label for="popupImage">
                팝업 이미지 등록
              </label>
              <v-file-input
                id="popupImage"
                v-model="event.popupImage"
                @change="popupImageAdd"
              />
            </div>
            <img
              v-if="event.popupImageUrl"
              :src="event.popupImageUrl"
              alt=""
              class="image-preview"
            >
          </v-card-text>
          <v-card-text>
            <v-text-field
              v-model="event.link"
              label="link"
              required
            />
          </v-card-text>
          <v-card-text>
            <v-row>
              <v-col cols="4">
                팝업
              </v-col>
              <v-col cols="8">
                <input
                  v-model="event.isPopup"
                  type="checkbox"
                >
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text>
            <v-row>
              <v-col cols="4">
                연령제한
              </v-col>
              <v-col cols="8">
                <v-row>
                  <v-col>
                    <input
                      id="no-auth"
                      v-model="event.isAdult"
                      type="radio"
                      value="false"
                    >
                    <label for="no-auth">
                      본인인증을 하지 않은 유저만
                    </label>
                  </v-col>
                  <v-col>
                    <input
                      id="auth"
                      v-model="event.isAdult"
                      type="radio"
                      value="true"
                    >
                    <label for="auth">
                      본인인증을 한 유저만
                    </label>
                  </v-col>
                  <v-col>
                    <input
                      id="both"
                      v-model="event.isAdult"
                      type="radio"
                      value=""
                    >
                    <label for="both">
                      상관없음
                    </label>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-actions v-show="!is_loading">
            <v-btn
              v-show="is_modify"
              color="blue darken-1"
              text
              @click="deleteConfirm"
            >
              삭제
            </v-btn>
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="cancel"
            >
              취소
            </v-btn>
            <v-btn
              v-show="!is_modify"
              color="blue darken-1"
              text
              @click="submit"
            >
              등록
            </v-btn>
            <v-btn
              v-show="is_modify"
              color="blue darken-1"
              text
              @click="modify"
            >
              수정
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
    <v-row>
      <v-dialog
        v-model="show_delete_confirm_dialog"
        max-width="400px"
        persistent
      >
        <v-card>
          <v-card-text />
          <v-card-text>
            삭제하시겠습니까?
          </v-card-text>
          <v-card-actions v-show="!is_loading">
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="deleteCancel"
            >
              취소
            </v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="deleteEvent"
            >
              확인
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

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

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

  data() {
    return {
      is_loading: false,
      is_modify: false,
      events: [],
      event: { isAdult: '' },
      show_write_dialog: false,
      show_delete_confirm_dialog: false,
    }
  },

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

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

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

    thumbnailImageAdd(payload) {
      const file = payload;
      if (file) {
        this.event.thumbnailImageUrl = URL.createObjectURL(file)
        URL.revokeObjectURL(file)
      } else {
        this.event.thumbnailImageUrl = null
      }
    },

    detailImageAdd(payload) {
      const file = payload;
      if (file) {
        this.event.detailImageUrl = URL.createObjectURL(file)
        URL.revokeObjectURL(file)
      } else {
        this.event.detailImageUrl = null
      }
    },

    popupImageAdd(payload) {
      const file = payload;
      if (file) {
        this.event.popupImageUrl = URL.createObjectURL(file)
        URL.revokeObjectURL(file)
      } else {
        this.event.popupImageUrl = null
      }
    },

    async getEvents() {
      this.is_loading = true

      try {
        const res = await api.getEvents(this.page)
        if (res.status === 200 && res.data.success === true) {
          this.events = res.data.data
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    },

    showWriteDialog() {
      this.event.isAdult = ''
      this.show_write_dialog = true
    },

    clickEvent(item) {
      this.is_modify = true
      this.event.id = item.id
      this.event.thumbnailImageUrl = item.thumbnailImageUrl
      this.event.detailImageUrl = item.detailImageUrl
      this.event.link = item.link
      this.event.title = item.title
      this.event.isPopup = item.isPopup
      this.event.isAdult = item.isAdult === null ? '' : item.isAdult
      this.event.popupImageUrl = item.popupImageUrl
      this.event.startDate = item.startDate
      this.event.endDate = item.endDate
      this.show_write_dialog = true
    },

    cancel() {
      this.is_modify = false
      this.event = { isAdult: '' }
      this.show_write_dialog = false
    },

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

      if (this.event.thumbnailImage == null) {
        this.notifyError("썸네일 이미지를 등록하세요")
        return false;
      }

      if ((this.event.link == null || this.event.link.trim().length <= 0) && this.event.detailImage == null) {
        this.notifyError("상세이미지 혹은 link 둘 중 하나는 반드시 입력해야 합니다.")
        return false;
      }

      if (this.event.startDate == null || this.event.endDate == null) {
        this.notifyError("이벤트 기간을 선택하세요")
        return false;
      }

      return true
    },

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

      this.is_loading = true

      try {
        const formData = new FormData()
        formData.append("title", this.event.title)
        formData.append("thumbnail", this.event.thumbnailImage)
        formData.append("isPopup", this.event.isPopup ? this.event.isPopup : false)
        formData.append("startDate", this.event.startDate)
        formData.append("endDate", this.event.endDate)

        if (this.event.detailImage != null) {
          formData.append("detail", this.event.detailImage)
        }

        if (this.event.popupImage != null) {
          formData.append("popup", this.event.popupImage)
        }

        if (this.event.link != null && this.event.link.trim().length > 0) {
          formData.append("link", this.event.link)
        }

        if (this.event.isAdult !== undefined && this.event.isAdult !== null && this.event.isAdult !== '') {
          formData.append("isAdult", JSON.parse(this.event.isAdult))
        }

        const res = await api.save(formData)
        if (res.status === 200 && res.data.success === true) {
          this.show_write_dialog = false
          this.notifySuccess('등록되었습니다.')
          this.page = 1
          await this.getEvents()
          this.event = { isAdult: '' }
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    },

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

      this.is_loading = true
      try {
        const formData = new FormData()
        formData.append("id", this.event.id)

        if (this.event.title != null && this.event.title.trim().length > 0) {
          formData.append("title", this.event.title)
        }

        if (this.event.thumbnailImage != null) {
          formData.append("thumbnail", this.event.thumbnailImage)
        }

        if (this.event.detailImage != null) {
          formData.append("detail", this.event.detailImage)
        }

        if (this.event.popupImage != null) {
          formData.append("popup", this.event.popupImage)
        }

        if (this.event.isPopup != null) {
          formData.append("isPopup", this.event.isPopup)
        }

        if (this.event.link != null && this.event.link.trim().length > 0) {
          formData.append("link", this.event.link)
        }

        if (this.event.isAdult !== undefined && this.event.isAdult !== null && this.event.isAdult !== '') {
          formData.append("isAdult", JSON.parse(this.event.isAdult))
        }

        if (this.event.startDate != null) {
          formData.append("startDate", this.event.startDate)
        }

        if (this.event.endDate != null) {
          formData.append("endDate", this.event.endDate)
        }

        const res = await api.modify(formData)
        if (res.status === 200 && res.data.success === true) {
          this.show_write_dialog = false
          this.notifySuccess('수정되었습니다.')
          this.page = 1
          await this.getEvents()
          this.event = { isAdult: '' }
          this.is_modify = false
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    },

    deleteConfirm() {
      this.show_delete_confirm_dialog = true
    },

    deleteCancel() {
      this.show_delete_confirm_dialog = false
    },

    async deleteEvent() {
      if (this.is_loading) return;
      this.is_loading = true

      try {
        const res = await api.deleteEvent(this.event.id)
        if (res.status === 200 && res.data.success === true) {
          this.show_write_dialog = false
          this.show_delete_confirm_dialog = false
          this.notifySuccess('삭제되었습니다.')
          this.page = 1
          await this.getEvents()
          this.event = {}
          this.is_modify = false
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    }
  }
}
</script>

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

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

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

.image-select label {
  display: inline-block;
  padding: 10px 20px;
  background-color: #232d4a;
  color: #fff;
  vertical-align: middle;
  font-size: 15px;
  cursor: pointer;
  border-radius: 5px;
}

.v-file-input {
  position: absolute;
  width: 0;
  height: 0;
  padding: 0;
  overflow: hidden;
  border: 0;
}

.image-preview {
  max-width: 100%;
  width: 250px;
  object-fit: cover;
  margin-top: 10px;
}
</style>
