<template>
  <div class="side" style="width: 100%">
    <span v-show="loadComplete">{{showType === 'gallery' || showType === 'collect' ? '本子' : '视频'}}历史</span>
    <div  v-show="loadComplete" class="load_complete">
      <el-table :data="currentTasks" v-show="showType === 'gallery'" :empty-text="emptyText" :row-key="gallery=>gallery.gid">

        <el-table-column type="expand">
          <template #default="props">
            名字:{{ props.row.name}} <br>
            链接:<el-link :href="props.row.link">链接</el-link> <br>
            语言:{{props.row.language}} <br>
            页数:{{props.row.pages}} <br>
            文件大小:{{props.row.fileSize}}<br>
            分辨率:{{props.row.resolution}}<br>
            任务创建时间:{{props.row.createTimeDisplay}}<br>
            标签:{{props.row.tag === '' ? '无': props.row.tag}} <br>
            <span v-show="isLion">
              downloader:{{props.row.downloader}}
            </span>

            <el-button @click="deleteGallery(props.row.gid)" :disabled="props.row.download === undefined">删除</el-button>
            <el-button @click="editGalleryTag(props.row.gid, props.row.tag)">编辑标签</el-button>
            <el-button @click="updateGallery(props.row.link)" :disabled="props.row.download === undefined">更新</el-button>
            <el-button @click="shareGallery({gid:props.row.gid, shortName:props.row.shortName + '.zip'})" v-show="isLion">分享</el-button>
          </template>
        </el-table-column>

        <el-table-column label="名字" width="300vw">
          <template #default="scoped">
            <span @mouseover="showThumbnail(scoped.row)">
                {{galleryNameType === 'shortName' ? scoped.row.shortName: scoped.row.name}}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300vw">
          <template #default="scoped">
            <span>
              <el-button @click="downloadTask(scoped.row.download)" :disabled="scoped.row.download === undefined">下载</el-button>
              <el-button @click="changeGalleryCollect(scoped.row.gid, scoped.row.isCollect)">{{scoped.row.isCollect ? '取消收藏' : '收藏'}}</el-button>
              <el-button @click="onlineGalleryReader(scoped.row.gid)" :disabled="scoped.row.download === undefined">在线看</el-button>
            </span>
          </template>
        </el-table-column>

        <el-table-column label="进度" width="80">
          <template #default="scoped">
            {{ scoped.row.progress }}
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="currentTasks" v-show="showType === 'video'" :empty-text="emptyText" :row-key="video=>video.id">
        <el-table-column type="expand">
          <template #default="props">
            名字:{{props.row.name}}     <br>
            网站:{{props.row.website}}  <br>
            链接:<el-link :href="props.row.link">链接</el-link> <br>
            文件大小:{{props.row.fileSize}} <br>
            视频长度:{{props.row.duration}} <br>
            分辨率:{{props.row.resolution}} <br>
            任务创建时间:{{props.row.createTimeDisplay}}<br>
            标签:{{props.row.tag === '' ? '无': props.row.tag}} <br>
            <span v-show="isLion">
              downloader:{{props.row.downloader}}
            </span>

            <el-button @click="deleteVideo(props.row.id)" :disabled="props.row.download === undefined">删除</el-button>
            <el-button @click="editVideoTag(props.row.id, props.row.tag)">编辑标签</el-button>
          </template>
        </el-table-column>

        <el-table-column label="名字" width="300vw">
          <template #default="scoped">
            {{scoped.row.name}}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300vw">
          <template #default="scoped">
            <span>
              <el-button @click="downloadTask(scoped.row.download)" :disabled="scoped.row.download === undefined">下载</el-button>
              <el-button @click="changeVideoCollect(scoped.row.id, scoped.row.isCollect)">{{scoped.row.isCollect ? '取消收藏' : '收藏'}}</el-button>
              <el-button @click="openVideoPanel(scoped.row.download)" :disabled="scoped.row.download === undefined">在线播放</el-button>
            </span>
          </template>
        </el-table-column>

        <el-table-column label="进度" width="80">
          <template #default="scoped">
            {{ scoped.row.progress }}
          </template>
        </el-table-column>
      </el-table>

      <el-row class="pageChanger">
        <el-col>
          <el-select v-model="showType" @change="changeShowType" class="el-select" style="width: 75px">
            <el-option value="gallery" label="本子"/>
            <el-option value="video" label="视频"/>
          </el-select>
          <el-select v-model="category" @change="changeCategory">
            <template #prefix>
              分类
            </template>
                <el-option value="myCollect" label="我的收藏"/>
                <el-option value="myDownload" label="我的下载"/>
                <el-option value="total" label="全部"/>
              </el-select>
          <el-select v-model="sortType" @change="changeSortType" style="width: 170px">
              <template #prefix>
                排序
              </template>
                <el-option value="name" label="名字"/>
                <el-option value="shortName" label="简洁名字" v-show="showType === 'gallery'"/>
                <el-option value="createTime" label="任务创建时间"/>
              </el-select>
          <el-select v-model="galleryNameType" @change="changeGalleryNameType" v-show="showType === 'gallery'">
              <template #prefix>
                显示
              </template>
                  <el-option value="name" label="名字"/>
                  <el-option value="shortName" label="简洁名字"/>
              </el-select>
        </el-col>
        <el-col>
          <el-button @click="toMin">{{min}}</el-button>
          <el-button @click="previous">-</el-button>
          <el-input v-model="targetPage"
                    @change="changePage"
                    v-show="isEditingPage"
                    @blur="reverseEditMode"
                    class="page"
                    ref="inputNode"></el-input>
          <span @click="reverseEditMode" v-show="!isEditingPage" class="page">{{page}}</span>
          <el-button @click="next">+</el-button>
          <el-button @click="toMax">{{max}}</el-button>
        </el-col>
      </el-row>
    </div>

    <el-dialog v-model="isEditingTag" title="编辑标签">
      <el-form>
        <el-form-item>
          <template #label>
            标签:
          </template>
          <template #default>
            <el-input v-model="tempTag"></el-input>
          </template>
        </el-form-item>
      </el-form>
      <el-footer>
        <el-button @click="tempGid === '' ? submitVideoTag(): submitGalleryTag()">提交修改</el-button>
      </el-footer>
    </el-dialog>

    <el-dialog v-model="isOnlineReading" title="在线预览" @close="closeOnlineReading" width="90%" style="margin-top: 0; margin-bottom: 0; padding: 0">
      <el-scrollbar height="84vh" ref="onlineReadingScrollbar">
        <el-image v-for="(link, index) in currentLinks" :src="link" :style="{'width': imageWidth, 'padding-right': imagePadding, 'background-color': 'ghostwhite'}"
                  :preview-src-list="currentLinks" :initial-index="index" loading="lazy"/>
      </el-scrollbar>
    </el-dialog>

    <span v-show="!loadComplete" class="side">请输入授权码后再查看</span>
  </div>
  <el-dialog v-model="isPlaying" @opened="initPlayer()" @closed="destroyPlayer()" width="635px" title="在线预览">
    <div id="player"></div>
  </el-dialog>
</template>

<script setup>
import store from "../store";
import {computed, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import Player from "xgplayer";

//输入
let inputNode = ref(null)
//是否正在编辑页数
let isEditingPage = ref(false)
//是否正在编辑标签
let isEditingTag = ref(false)
//是否打开播放面板
let isPlaying = ref(false)

//在线播放链接以及播放器实例
let current_video_link = ref("")
let player = ref()

//临时变量
let tempTag = ref("")
let tempGid = ref("")
let tempId = ref("")

let category = ref("myDownload")            //myDownload myCollect total
let galleryNameType = ref("shortName")      // shortName name
let showType = ref("gallery")               // gallery video collect
let sortType = ref("shortName")             // shortName name createTime
let targetPage = ref(1)                     // 当前页数

let onlineReadingScrollbar = ref(null)

//防抖计时器
let debounceTimer = 0
//是否加载完成
let loadComplete = computed(() => {
  return store.state.loadComplete
})

let currentTasks = computed(() => {
  return store.getters.currentTasks ? store.getters.currentTasks: null
})
let isOnlineReading = computed(() => {
  return store.state.isOnlineReading
})

let min = computed(() => {
  return store.getters.min
})
let max = computed(() => {
  if(targetPage.value > store.getters.max)
    store.commit("_changePage", store.getters.max)
  return store.getters.max
})
let page = computed(() => {
  targetPage.value = store.state.page
  return store.state.page
})
let isLion = computed(() => {
  return store.state.userId === 3
})

let emptyText = computed(() => {
  let type = showType.value === 'gallery' ? '本子': '视频'
  let action = category.value === 'myDownload' ? '下载': '收藏'
  return '您未' + action + type
})

//在线预览相关
let currentLinks = computed(() => {
  return store.state.currentLinks
})
let imageWidth = computed(() => {
  return store.state.imageWidth
})
let imagePadding = computed(() => {
  return store.state.imagePadding
})

//翻页
function next() {
  if(targetPage.value < max.value) {
    targetPage.value++
    store.commit("_changePage", targetPage.value)
  }
}
function previous() {
  if(targetPage.value > min.value) {
    targetPage.value--
    store.commit("_changePage", targetPage.value)
  }
}
function toMax() {
  store.commit("_changePage", max.value)
  targetPage.value = max.value
}
function toMin(){
  store.commit("_changePage", min.value)
  targetPage.value = min.value
}
function changePage(){
  if(targetPage.value >= min.value && targetPage.value <= max.value)
    store.commit("_changePage", targetPage.value)
}
function reverseEditMode(){
  isEditingPage.value = !isEditingPage.value
  if(isEditingPage.value){
    inputNode.value.focus()
  }
  targetPage.value = page.value
}

//改变展示类型
function changeCategory(){
  store.commit("_setCategory", category.value)
}
function changeShowType(){
  if(showType.value === 'video')
    sortType.value = 'name'
  store.commit("_setShowType", showType.value)
}
function changeGalleryNameType(){
  store.commit("_setShowNameType", galleryNameType.value)
}
function changeSortType(){
  store.commit("_setSortType", sortType.value)
}

//收藏,编辑标签,提交编辑
function changeGalleryCollect(gid, isCollect){
  if(isCollect)
    store.dispatch("disCollectGallery", gid)
  else
    store.dispatch("collectGallery", gid)
}
function changeVideoCollect(id, isCollect){
  if(isCollect)
    store.dispatch("disCollectVideo", id)
  else
    store.dispatch("collectVideo", id)
}
function editGalleryTag(gid, tag){
  tempTag.value = tag
  tempGid.value = gid
  isEditingTag.value = true
}
function editVideoTag(id, tag){
  tempTag.value = tag
  tempId.value = id
  isEditingTag.value = true
}
function submitGalleryTag(){
  store.dispatch("updateGalleryTag", {gid:tempGid.value, tag:tempTag.value})
  tempTag.value = ''
  tempGid.value = ''
  isEditingTag.value = false
}
function submitVideoTag(){
  store.dispatch("updateVideoTag", {id:tempId.value, tag:tempTag.value})
  tempTag.value = ''
  tempId.value = ''
  isEditingTag.value = false
}

//下载，删除，在线看
function downloadTask(link){
  window.open(link)
}
function updateGallery(link){
  store.dispatch("updateGallery", link)
}
function deleteGallery(gid){
  store.dispatch("deleteGallery", gid)
}
function deleteVideo(id){
  store.dispatch("deleteVideo", id)
}
function onlineGalleryReader(gid){
  store.dispatch("queryOnlineLinks", gid)
}
function closeOnlineReading(){
  store.state.isOnlineReading = false
  onlineReadingScrollbar.value.setScrollTop(0)
}
function shareGallery(data){
  const {gid, shortName} = data
  let link
  axios.post("http://downloader.lionwebsite.xyz/GalleryManage/share?userId=3&expireHour=3&gid=" + gid).then((res) => {
    if(res.data.result === "success"){
      let data = JSON.parse(res.data.data)
      link = 'http://lionwebsite.xyz/GetFile/{0}?ShareCode={1}'.replace('{0}', encodeURIComponent(shortName)).replace('{1}', data.shareCode)
      ElMessage({dangerouslyUseHTMLString: true,
        message: "<span>分享成功， 过期时间:" + data.expireTime + "</span><br><a href=" + link + ">链接</a>",
        duration: 0,
        'show-close': true
      })
      navigator.clipboard.writeText(link)
    }
    else
      ElMessage(res.data.data)
  })
}
function openVideoPanel(link){
  current_video_link.value = link
  isPlaying.value = true
}
function initPlayer(){
  player.value = new Player({
    id: "player",
    url: current_video_link.value,
    videoInit: true,
    lang: 'zh-cn'
  })
}
function destroyPlayer(){
  player.value.destroy()
}

//显示缩略图
function showThumbnail(gallery){
  if(gallery.download !== undefined && gallery.status === "下载完成")
    clearTimeout(debounceTimer)
    debounceTimer = setTimeout(() => {
      store.commit("_changeThumbnailGallery", gallery)
    }, 500)
}
</script>

<style scoped>
  .side{
    text-align: center;
    height: 300px;
  }
  span{
    display: block;
  }
  .pageChanger{
    margin-top: 5vh;
  }
  .el-select{
    width: 135px;
  }
  .page{
    display: inline-block;
    width: 50px;
  }
</style>