<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>콘텐츠 테마 관리</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-row>
      <v-dialog
        v-model="show_dialog"
        max-width="400px"
        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="themes"
              class="row"
              @end="onDropCallback(themes)"
            >
              <v-col
                v-for="(theme, i) in themes"
                :key="i"
                cols="2"
              >
                <v-card>
                  <v-card-title>
                    <v-spacer />
                    <v-img
                      :src="theme.image"
                      class="rounded-circle"
                    />
                    <v-spacer />
                  </v-card-title>
                  <v-card-title>
                    <v-spacer />
                    {{ theme.theme }}
                    <v-spacer />
                  </v-card-title>
                  <v-card-actions>
                    <v-spacer />
                    <v-btn
                      text
                      @click="deleteTheme(theme)"
                    >
                      삭제
                    </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-text-field
              v-model="theme_text"
              label="테마"
              required
            />
          </v-card-text>
          <div class="image-select">
            <label for="image">
              이미지 등록
            </label>
            <v-file-input
              id="image"
              v-model="image"
              @change="imageAdd"
            />
          </div>
          <img
            v-if="image_url"
            :src="image_url"
            alt=""
            class="image-preview"
          >
          <v-card-actions v-show="!isLoading">
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="cancel"
            >
              취소
            </v-btn>
            <v-btn
              color="blue darken-1"
              text
              @click="submit"
            >
              등록
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

<script>
import * as api from '@/api/audio_content_theme'
import Draggable from "vuedraggable";

export default {
  name: "AudioContentTheme",

  components: {Draggable},

  data() {
    return {
      isLoading: false,
      themes: [],
      show_dialog: false,
      theme_text: null,
      image: null,
      image_url: null
    }
  },

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

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

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

    imageAdd(payload) {
      const file = payload;
      if (file) {
        this.image_url = URL.createObjectURL(file)
        URL.revokeObjectURL(file)
      } else {
        this.image_url = null
      }
    },

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

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

    cancel() {
      this.show_dialog = false
      this.image = null
      this.image_url = null
      this.theme = null
    },

    async getThemes() {
      this.isLoading = true

      try {
        let res = await api.getThemes();
        this.themes = res.data.data
      } catch (e) {
        this.notifyError("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
      } finally {
        this.isLoading = false
      }
    },

    async deleteTheme(theme) {
      this.isLoading = true
      try {
        let res = await api.deleteTheme(theme.id)
        if (res.status === 200 && res.data.success === true) {
          this.notifySuccess(res.data.message)
          await this.getThemes()
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
      } finally {
        this.isLoading = false
      }
    },

    async submit() {
      this.isLoading = true

      const formData = new FormData()
      formData.append("image", this.image)
      formData.append("request", JSON.stringify({theme: this.theme_text}))

      const res = await api.enrollment(formData)

      if (res.status === 200 && res.data.success === true) {
        this.show_dialog = false
        this.image = null
        this.image_url = null
        this.theme_text = null
        this.themes = []
        this.notifySuccess(res.data.message)

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

      this.isLoading = 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>
