<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>{{ curation_title }}</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <v-row>
        <v-col
          cols="4"
          align="right"
        >
          19금 :
        </v-col>
        <v-col
          align="left"
        >
          <div v-if="is_adult">
            O
          </div>
          <div v-else>
            X
          </div>
        </v-col>
        <v-spacer />
        <v-col>
          <v-btn
            v-if="is_series"
            block
            color="#3bb9f1"
            dark
            depressed
            @click="showAddSeries"
          >
            시리즈 등록
          </v-btn>
          <v-btn
            v-else
            block
            color="#3bb9f1"
            dark
            depressed
            @click="showAddContent"
          >
            콘텐츠 등록
          </v-btn>
        </v-col>
      </v-row>
      <v-row>
        <v-col
          cols="4"
          align="right"
        >
          내용 :
        </v-col>
        <v-col
          cols="8"
          align="left"
        >
          <vue-show-more-text
            :style="{ padding: '0' }"
            :text="curation_description"
            :lines="2"
          />
        </v-col>
      </v-row>
      <v-row>
        <v-col>
          <v-simple-table class="elevation-10">
            <template>
              <thead>
                <tr>
                  <th class="text-center">
                    썸네일
                  </th>
                  <th class="text-center">
                    제목
                  </th>
                  <th class="text-center">
                    내용
                  </th>
                  <th class="text-center">
                    크리에이터
                  </th>
                  <th class="text-center">
                    19금
                  </th>
                  <th class="text-center">
                    관리
                  </th>
                </tr>
              </thead>
              <draggable
                v-model="items"
                tag="tbody"
                @end="onDropCallback(items)"
              >
                <tr
                  v-for="item in items"
                  :key="item.id"
                >
                  <td align="center">
                    <v-img
                      max-width="70"
                      max-height="70"
                      :src="item.coverImageUrl"
                      class="rounded-circle"
                    />
                  </td>
                  <td>
                    <vue-show-more-text
                      :text="item.title"
                      :lines="3"
                    />
                  </td>
                  <td style="max-width: 200px !important; word-break:break-all; height: auto;">
                    <vue-show-more-text
                      :text="item.desc"
                      :lines="3"
                    />
                  </td>
                  <td>{{ item.creatorNickname }}</td>
                  <td>
                    <div v-if="item.isAdult">
                      O
                    </div>
                    <div v-else>
                      X
                    </div>
                  </td>
                  <td>
                    <v-btn
                      :disabled="is_loading"
                      @click="deleteConfirm(item)"
                    >
                      삭제
                    </v-btn>
                  </td>
                </tr>
              </draggable>
            </template>
          </v-simple-table>
        </v-col>
      </v-row>
    </v-container>

    <v-dialog
      v-model="show_add_content_dialog"
      max-width="1000px"
      persistent
    >
      <v-card>
        <v-card-title>
          콘텐츠 추가
        </v-card-title>
        <v-card-text>
          <v-text-field
            v-model="search_word"
            label="콘텐츠 제목"
            @keyup.enter="searchContentItem"
          >
            <v-btn
              slot="append"
              color="#3bb9f1"
              dark
              @click="searchContentItem"
            >
              검색
            </v-btn>
          </v-text-field>
        </v-card-text>
        <v-card-text v-if="search_item_list.length > 0 || add_item_list.length > 0">
          <v-row>
            <v-col>
              검색결과
              <v-simple-table>
                <template v-slot:default>
                  <thead>
                    <tr>
                      <th class="text-center">
                        제목
                      </th>
                      <th />
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="item in search_item_list"
                      :key="item.id"
                    >
                      <td>{{ item.title }}</td>
                      <td>
                        <v-btn
                          color="#3bb9f1"
                          @click="addItem(item)"
                        >
                          추가
                        </v-btn>
                      </td>
                    </tr>
                  </tbody>
                </template>
              </v-simple-table>
            </v-col>
            <v-col v-if="add_item_list.length > 0">
              추가할 콘텐츠
              <v-simple-table>
                <template>
                  <thead>
                    <tr>
                      <th class="text-center">
                        제목
                      </th>
                      <th />
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="item in add_item_list"
                      :key="item.id"
                    >
                      <td>{{ item.title }}</td>
                      <td>
                        <v-btn
                          color="#3bb9f1"
                          @click="removeItem(item)"
                        >
                          제거
                        </v-btn>
                      </td>
                    </tr>
                  </tbody>
                </template>
              </v-simple-table>
            </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
            color="blue darken-1"
            text
            @click="addItemInCuration"
          >
            추가
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog
      v-model="show_add_series_dialog"
      max-width="1000px"
      persistent
    >
      <v-card>
        <v-card-title>
          시리즈 추가
        </v-card-title>
        <v-card-text>
          <v-text-field
            v-model="search_word"
            label="시리즈 제목"
            @keyup.enter="searchSeriesItem"
          >
            <v-btn
              slot="append"
              color="#3bb9f1"
              dark
              @click="searchSeriesItem"
            >
              검색
            </v-btn>
          </v-text-field>
        </v-card-text>
        <v-card-text v-if="search_item_list.length > 0 || add_item_list.length > 0">
          <v-row>
            <v-col>
              검색결과
              <v-simple-table>
                <template v-slot:default>
                  <thead>
                    <tr>
                      <th class="text-center">
                        제목
                      </th>
                      <th />
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="item in search_item_list"
                      :key="item.id"
                    >
                      <td>{{ item.title }}</td>
                      <td>
                        <v-btn
                          color="#3bb9f1"
                          @click="addItem(item)"
                        >
                          추가
                        </v-btn>
                      </td>
                    </tr>
                  </tbody>
                </template>
              </v-simple-table>
            </v-col>
            <v-col v-if="add_item_list.length > 0">
              추가할 시리즈
              <v-simple-table>
                <template>
                  <thead>
                    <tr>
                      <th class="text-center">
                        제목
                      </th>
                      <th />
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="item in add_item_list"
                      :key="item.id"
                    >
                      <td>{{ item.title }}</td>
                      <td>
                        <v-btn
                          color="#3bb9f1"
                          @click="removeItem(item)"
                        >
                          제거
                        </v-btn>
                      </td>
                    </tr>
                  </tbody>
                </template>
              </v-simple-table>
            </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
            color="blue darken-1"
            text
            @click="addItemInCuration"
          >
            추가
          </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-if="selected_item !== null">
          {{ selected_item.title }} 삭제하시겠습니까?
        </v-card-text>
        <v-card-text v-else>
          삭제하시겠습니까?
        </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
            color="blue darken-1"
            text
            @click="removeItemInCuration"
          >
            확인
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import Draggable from 'vuedraggable';
import * as api from "@/api/audio_content"
import VueShowMoreText from 'vue-show-more-text'

export default {
  name: 'ContentCurationDetail',

  components: {VueShowMoreText, Draggable},

  data() {
    return {
      is_loading: false,
      curation_id: 0,
      curation_title: '',
      curation_description: '',
      is_series: false,
      is_adult: false,

      items: [],

      show_add_series_dialog: false,
      show_add_content_dialog: false,
      show_delete_confirm_dialog: false,

      search_word: '',
      selected_item: null,
      add_item_list: [],
      search_item_list: [],
    }
  },

  async created() {
    this.curation_id = this.$route.params.curation_id
    this.curation_title = this.$route.params.title
    this.curation_description = this.$route.params.description
    this.is_series = this.$route.params.is_series
    this.is_adult = this.$route.params.is_adult
    await this.getCurationItems()
  },

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

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

    cancel() {
      this.search_word = ''
      this.add_item_list = []
      this.search_item_list = []
      this.selected_item = null
      this.show_add_series_dialog = false
      this.show_add_content_dialog = false
      this.show_delete_confirm_dialog = false
    },

    deleteConfirm(item) {
      this.selected_item = item
      this.show_delete_confirm_dialog = true
    },

    showAddContent() {
      this.show_add_content_dialog = true
    },

    showAddSeries() {
      this.show_add_series_dialog = true
    },

    addItem(item) {
      this.search_item_list = this.search_item_list.filter((t) => {
        return t.id !== item.id
      });
      this.add_item_list.push(item)
    },

    removeItem(item) {
      this.add_item_list = this.add_item_list.filter((t) => {
        return t.id !== item.id
      });
      this.search_item_list.push(item)
    },

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

      try {
        this.is_loading = true
        const res = await api.updateItemInCurationOrders(this.curation_id, 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 searchContentItem() {
      if (this.search_word.length < 2) {
        this.notifyError('검색어를 2글자 이상 입력하세요.')
        return
      }

      this.is_loading = true

      try {
        const res = await api.searchContentItem(this.curation_id, this.search_word)

        if (res.data.success === true) {
          this.search_item_list = res.data.data
          if (res.data.data.length <= 0) {
            this.notifyError('검색결과가 없습니다.')
          }
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    },

    async searchSeriesItem() {
      if (this.search_word.length < 2) {
        this.notifyError('검색어를 2글자 이상 입력하세요.')
        return
      }

      this.is_loading = true

      try {
        const res = await api.searchSeriesItem(this.curation_id, this.search_word)

        if (res.data.success === true) {
          this.search_item_list = res.data.data
          if (res.data.data.length <= 0) {
            this.notifyError('검색결과가 없습니다.')
          }
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      } finally {
        this.is_loading = false
      }
    },

    async addItemInCuration() {
      this.is_loading = true
      const itemIdList = this.add_item_list.map((item) => {
        return item.id
      })

      try {
        const res = await api.addItemToCuration(this.curation_id, itemIdList)

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

    async removeItemInCuration() {
      this.is_loading = true

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

    async getCurationItems() {
      this.is_loading = true

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

<style scoped>

</style>
