<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="curations"
            :loading="is_loading"
            item-key="id"
            class="elevation-1"
            hide-default-footer
            disable-pagination
          >
            <template v-slot:body="props">
              <draggable
                v-model="props.items"
                tag="tbody"
                @end="onDropCallback(props.items)"
              >
                <tr
                  v-for="(item, index) in props.items"
                  :key="index"
                >
                  <td>
                    {{ item.title }}
                  </td>
                  <td>
                    {{ item.description }}
                  </td>
                  <td>
                    <h3 v-if="item.isAdult">
                      O
                    </h3>
                    <h3 v-else>
                      X
                    </h3>
                  </td>
                  <td>
                    <v-row>
                      <v-col />
                      <v-col>
                        <v-btn
                          :disabled="is_loading"
                          @click="showModifyDialog(item)"
                        >
                          수정
                        </v-btn>
                      </v-col>

                      <v-col>
                        <v-btn
                          :disabled="is_loading"
                          @click="deleteConfirm(item)"
                        >
                          삭제
                        </v-btn>
                      </v-col>
                      <v-col />
                    </v-row>
                  </td>
                </tr>
              </draggable>
            </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-if="is_modify === true">
            콘텐츠 큐레이션 수정
          </v-card-title>
          <v-card-title v-else>
            콘텐츠 큐레이션 등록
          </v-card-title>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                제목
              </v-col>
              <v-col cols="8">
                <v-text-field
                  v-model="curation.title"
                  label="제목"
                  required
                />
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                설명
              </v-col>
              <v-col cols="8">
                <v-text-field
                  v-model="curation.description"
                  label="설명"
                  required
                />
              </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="curation.is_adult"
                  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="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-row>

    <v-dialog
      v-model="show_delete_confirm_dialog"
      max-width="400px"
      persistent
    >
      <v-card>
        <v-card-text />
        <v-card-text>
          "{{ selected_curation.title }}"을 삭제하시겠습니까?
        </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="deleteCuration"
          >
            확인
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

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

export default {
    name: "AudioContentCuration",
    components: {Draggable},
    data() {
        return {
            is_loading: false,
            is_modify: false,
            show_delete_confirm_dialog: false,
            show_write_dialog: false,
            selected_curation: {},
            curation: {is_adult: false},
            curations: [],
            headers: [
                {
                    text: '제목',
                    align: 'center',
                    sortable: false,
                    value: 'title',
                },
                {
                    text: '설명',
                    align: 'center',
                    sortable: false,
                    value: 'description',
                },
                {
                    text: '19금',
                    align: 'center',
                    sortable: false,
                    value: 'isAdult',
                },
                {
                    text: '관리',
                    align: 'center',
                    sortable: false,
                    value: 'management'
                },
            ],
        }
    },

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

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

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

        showWriteDialog() {
            this.show_write_dialog = true
        },

        showModifyDialog(item) {
            this.is_modify = true
            this.selected_curation = item

            this.curation.id = item.id
            this.curation.title = item.title
            this.curation.description = item.description
            this.curation.is_adult = item.isAdult

            this.show_write_dialog = true
        },

        cancel() {
            this.curation = {is_adult: false}
            this.selected_curation = {}

            this.is_modify = false
            this.show_write_dialog = false
        },

        validate() {
            if (
                this.curation.title === null ||
                this.curation.title === undefined ||
                this.curation.title.trim().length <= 0
            ) {
                this.notifyError("제목을 입력하세요")
                return false
            }

            if (
                this.curation.description === null ||
                this.curation.description === undefined ||
                this.curation.description.trim().length <= 0
            ) {
                this.notifyError("설명을 입력하세요")
                return false
            }

            return true
        },

        deleteConfirm(curation) {
            this.selected_curation = curation
            this.show_delete_confirm_dialog = true
        },

        deleteCancel() {
            this.selected_curation = {}
            this.show_delete_confirm_dialog = false
        },

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

            this.isLoading = true

            try {
                const request = {
                    title: this.curation.title,
                    description: this.curation.description,
                    isAdult: this.curation.is_adult
                }

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

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

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

            try {
                let request = {id: this.curation.id}
                if (this.selected_curation.title !== this.curation.title && this.curation.title.trim().length > 0) {
                    request.title = this.curation.title
                }

                if (
                    this.selected_curation.description !== this.curation.description &&
                    this.curation.description.trim().length > 0
                ) {
                    request.description = this.curation.description
                }

                if (this.selected_curation.isAdult !== this.curation.is_adult) {
                    request.isAdult = this.curation.is_adult
                }

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

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

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

            try {
                let request = {id: this.selected_curation.id, isActive: false}

                const res = await api.modifyCuration(request)
                if (res.status === 200 && res.data.success === true) {
                    this.show_delete_confirm_dialog = false
                    this.cancel()
                    this.notifySuccess('삭제되었습니다.')

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

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

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

        async getCurations() {
            this.is_loading = true

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

<style scoped>

</style>
