<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>콘텐츠 배너</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-dialog
      v-model="show_write_dialog"
      max-width="1000px"
      persistent
    >
      <template v-slot:activator="{ on, attrs }">
        <v-container>
          <v-row>
            <v-col cols="10" />
            <v-col>
              <v-btn
                block
                color="#9970ff"
                dark
                depressed
                v-bind="attrs"
                v-on="on"
              >
                배너 등록
              </v-btn>
            </v-col>
          </v-row>
          <draggable
            v-model="banners"
            class="row"
            @end="onDropCallback(banners)"
          >
            <v-col
              v-for="(item, i) in banners"
              :key="i"
              cols="3"
            >
              <v-card>
                <v-card-title>
                  <v-spacer />
                  <v-img :src="item.thumbnailImageUrl" />
                  <v-spacer />
                </v-card-title>
                <v-card-actions>
                  <v-spacer />
                  <v-btn
                    text
                    @click="showModifyBannerDialog(item)"
                  >
                    수정
                  </v-btn>
                  <v-btn
                    text
                    @click="deleteConfirm(item)"
                  >
                    삭제
                  </v-btn>
                  <v-spacer />
                </v-card-actions>
              </v-card>
            </v-col>
          </draggable>
        </v-container>
      </template>

      <v-card>
        <v-card-title>배너 등록</v-card-title>
        <v-card-text>
          <v-row align="center">
            <v-col cols="4">
              배너 타입
            </v-col>
            <v-col cols="8">
              <v-radio-group
                v-model="banner.type"
                row
              >
                <v-radio
                  value="CREATOR"
                  label="크리에이터 채널"
                />
                <v-radio
                  value="LINK"
                  label="외부링크"
                />
                <v-radio
                  value="EVENT"
                  label="이벤트"
                />
              </v-radio-group>
            </v-col>
          </v-row>
        </v-card-text>
        <v-card-text v-if="banner.type === 'CREATOR'">
          <v-row align="center">
            <v-col cols="4">
              크리에이터
            </v-col>
            <v-col cols="8">
              <v-select
                v-model="banner.creator_id"
                :items="creators"
                item-text="name"
                item-value="value"
                label="크리에이터 선택"
              />
            </v-col>
          </v-row>
        </v-card-text>
        <v-card-text v-else-if="banner.type === 'LINK'">
          <v-row align="center">
            <v-col cols="4">
              링크
            </v-col>
            <v-col cols="8">
              <v-text-field
                v-model="banner.link"
                label="링크"
                required
              />
            </v-col>
          </v-row>
        </v-card-text>
        <v-card-text v-else>
          <v-row align="center">
            <v-col cols="4">
              이벤트
            </v-col>
            <v-col cols="8">
              <v-select
                v-model="banner.event_id"
                :items="events"
                item-text="title"
                item-value="value"
                label="이벤트 선택"
              />
            </v-col>
          </v-row>
        </v-card-text>
        <v-card-text>
          <v-row>
            <v-col cols="4">
              19금
            </v-col>
            <v-col cols="8">
              <input
                v-model="banner.is_adult"
                type="checkbox"
              >
            </v-col>
          </v-row>
        </v-card-text>
        <div class="image-select">
          <label for="image">
            배너 이미지 등록
          </label>
          <v-file-input
            id="image"
            v-model="banner.thumbnail_image"
            @change="imageAdd"
          />
        </div>
        <img
          v-if="banner.thumbnail_image_url"
          :src="banner.thumbnail_image_url"
          alt=""
          class="image-preview"
        >
        <v-card-actions v-show="!is_loading">
          <v-spacer />
          <v-btn
            color="blue darken-1"
            text
            @click="cancel"
          >
            취소
          </v-btn>
          <v-btn
            v-if="is_modify === true"
            color="blue darken-1"
            text
            @click="modify"
          >
            수정
          </v-btn>
          <v-btn
            v-else
            color="blue darken-1"
            text
            @click="submit"
          >
            등록
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <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="deleteBanner"
          >
            확인
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import Draggable from "vuedraggable";

import * as memberApi from "@/api/member";
import * as eventApi from "@/api/event";
import * as api from "@/api/audio_content"

export default {
    name: "AudioContentMainTopBanner",

    components: {Draggable},

    data() {
        return {
            is_loading: false,
            is_modify: false,
            show_write_dialog: false,
            show_delete_confirm_dialog: false,
            selected_banner: {},
            banner: {type: 'CREATOR'},
            banners: [],
            events: [],
            creators: [],
        }
    },

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

    methods: {
        imageAdd(payload) {
            const file = payload;
            if (file) {
                this.banner.thumbnail_image_url = URL.createObjectURL(file)
                URL.revokeObjectURL(file)
            } else {
                this.banner.thumbnail_image_url = null
            }
        },

        cancel() {
            this.is_modify = false
            this.show_write_dialog = false
            this.banner = {type: 'CREATOR'}
            this.selected_banner = {}
        },

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

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

        showModifyBannerDialog(banner) {
            this.is_modify = true
            this.selected_banner = banner

            this.banner.id = banner.id
            this.banner.type = banner.type
            this.banner.thumbnail_image_url = banner.thumbnailImageUrl
            this.banner.event_id = banner.eventId
            this.banner.event_thumbnail_image = banner.eventThumbnailImage
            this.banner.creator_id = banner.creatorId
            this.banner.creator_nickname = banner.creatorNickname
            this.banner.link = banner.link
            this.banner.is_adult = banner.isAdult

            this.show_write_dialog = true
        },

        validate() {
            if (this.banner.type === 'EVENT' && (this.banner.event_id === null || this.banner.event_id === undefined)) {
                this.notifyError("이벤트를 선택하세요")
                return false;
            }

            if (
                this.banner.type === 'CREATOR' &&
                (this.banner.creator_id === null || this.banner.creator_id === undefined)) {
                this.notifyError("크리에이터를 선택하세요")
                return false;
            }

            if (
                this.banner.type === 'LINK' &&
                (this.banner.link === null || this.banner.link === undefined || this.banner.link.trim().length <= 0)
            ) {
                this.notifyError("링크를 입력하세요")
                return false;
            }

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

            return true
        },

        deleteConfirm(banner) {
            this.selected_banner = banner
            this.show_delete_confirm_dialog = true
        },

        deleteCancel() {
            this.show_delete_confirm_dialog = false
        },

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

            this.is_loading = true

            try {
                const formData = new FormData()
                formData.append("image", this.banner.thumbnail_image)

                let request = {
                    type: this.banner.type,
                    isAdult: this.banner.is_adult
                }

                if (this.banner.type === 'CREATOR') {
                    request.creatorId = this.banner.creator_id
                } else if (this.banner.type === 'EVENT') {
                    request.eventId = this.banner.event_id
                } else if (this.banner.type === 'LINK') {
                    request.link = this.banner.link
                }

                formData.append("request", JSON.stringify(request))

                const res = await api.saveBanner(formData)
                if (res.status === 200 && res.data.success === true) {
                    this.cancel()
                    this.notifySuccess('등록되었습니다.')

                    this.banners = []
                    await this.getBanners()
                } else {
                    this.notifyError(res.data.message);
                }
            } 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()
                let request = {id: this.banner.id}

                if (this.banner.thumbnail_image !== null) {
                    formData.append("image", this.banner.thumbnail_image)
                }

                if (
                    this.selected_banner.eventId !== this.banner.event_id &&
                    this.banner.event_id !== null &&
                    this.banner.event_id !== undefined
                ) {
                    request.type = this.banner.type
                    request.eventId = this.banner.event_id
                }

                if (
                    this.selected_banner.creator_id !== this.banner.creator_id &&
                    this.banner.creator_id !== null &&
                    this.banner.creator_id !== undefined
                ) {
                    request.type = this.banner.type
                    request.creatorId = this.banner.creator_id
                }

                if (
                    this.selected_banner.link !== this.banner.link &&
                    this.banner.link !== null &&
                    this.banner.link !== undefined
                ) {
                    request.type = this.banner.type
                    request.link = this.banner.link
                }

                if (this.selected_banner.isAdult !== this.banner.is_adult) {
                    request.isAdult = this.banner.is_adult
                }

                formData.append("request", JSON.stringify(request))

                const res = await api.modifyBanner(formData)
                if (res.status === 200 && res.data.success === true) {
                    this.cancel()
                    this.notifySuccess('수정되었습니다.')

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

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

            try {
                const formData = new FormData()
                formData.append("request", JSON.stringify({id: this.selected_banner.id, isActive: false}))
                const res = await api.modifyBanner(formData)
                if (res.status === 200 && res.data.success === true) {
                    this.show_delete_confirm_dialog = false
                    this.cancel()
                    this.notifySuccess('삭제되었습니다.')

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

        async onDropCallback(items) {
            const ids = items.map((item) => {
                return item.id
            })

            const res = await api.updateBannerOrders(ids)
            if (res.status === 200 && res.data.success === true) {
                this.notifySuccess(res.data.message)
            }
        },

        async getCreatorAllList() {
            this.is_loading = true

            try {
                const res = await memberApi.getCreatorAllList()

                if (res.status === 200 && res.data.success === true) {
                    this.creators = res.data.data.map((item) => {
                        return {name: item.nickname, value: item.id}
                    })
                } else {
                    this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
                    this.is_loading = false
                }
            } catch (e) {
                this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
                this.is_loading = false
            } finally {
                this.is_loading = false
            }
        },

        async getEvents() {
            this.is_loading = true
            try {
                const res = await eventApi.getEvents(1)
                if (res.status === 200 && res.data.success === true) {
                    this.events = res.data.data.eventList.map((item) => {
                        return {title: item.title, value: item.id}
                    })
                } else {
                    this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
                }
            } catch (e) {
                this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
                this.is_loading = false
            } finally {
                this.is_loading = false
            }
        },

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

<style scoped>
.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>
