<template>
  <el-drawer v-model="isOpenHistoryPanel" direction="ltr" size="100%" @close="closeHistoryPanel" >
    <div class="side">
      <div v-show="loadComplete" class="load_complete">
        <el-table :data="currentTasks" :empty-text="emptyText" :row-key="gallery=>gallery.gid">

          <el-table-column type="expand" width="25px">
            <template #default="props">
              名字:{{ props.row.name}} <br>
              链接:<el-link :href="props.row.link">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="downloadTask(props.row.download)" :disabled="props.row.download === undefined">下载</el-button>
              <el-button @click="deleteGallery(props.row.gid)" :disabled="props.row.download === undefined">删除</el-button>
              <el-button @click="shareGallery({gid:props.row.gid, shortName:props.row.shortName + '.zip'})" v-if="isLion">分享</el-button>
              <el-button @click="changeGalleryCollect(props.row.gid, props.row.isCollect)" :disabled="props.row.download === undefined">{{props.row.isCollect ? '取消收藏' : '收藏'}}</el-button>
              <el-button @click="onlineGalleryReader(props.row.gid)" :disabled="props.row.download === undefined">在线看</el-button>
              <el-button @click="showThumbnail(props.row)" :disabled="props.row.download === undefined">预览封面</el-button><br>
              <el-button @click="editGalleryTag(props.row.gid, props.row.tag)" :disabled="props.row.download === undefined">编辑标签</el-button>
              <el-button @click="updateGallery(props.row.link)" :disabled="props.row.download === undefined">更新本子</el-button>
            </template>
          </el-table-column>

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

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

        <el-row class="pageChanger">
          <el-col>
          <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: 165px">
            <template #prefix>
              排序
            </template>
            <el-option value="name" label="名字"/>
            <el-option value="shortName" label="简洁名字"/>
            <el-option value="createTime" label="任务创建时间"/>
          </el-select>
          <el-select v-model="galleryNameType" @change="changeGalleryNameType">
            <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>
    </div>
  </el-drawer>

  <el-dialog v-model="isEditingTag" title="编辑标签" width="100%">
    <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="submitGalleryTag()">提交修改</el-button>
    </el-footer>
  </el-dialog>

  <el-dialog v-model="isOnlineReading" title="在线预览" @close="closeOnlineReading" width="90%" top="0">
    <el-scrollbar height="80vh" ref="onlineReadingScrollbar">
      <el-image v-for="(link, index) in currentLinks" :src="link" :style="{'width': 'auto', 'text-align': 'center', 'background-color': 'ghostwhite'}"
                :preview-src-list="currentLinks" :initial-index="index" loading="lazy"/>
    </el-scrollbar>
  </el-dialog>
</template>

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

//输入
let inputNode = ref(null)
//是否正在编辑页数
let isEditingPage = ref(false)
//是否正在编辑标签
let isEditingTag = ref(false)

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

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

let onlineReadingScrollbar = ref(null)

let loadComplete = computed(() => {
  return store.state.loadComplete
})

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

let isOpenHistoryPanel = computed(() => {
  return store.state.isShowHistory
})
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 action = category.value === 'myDownload' ? '下载': '收藏'
  return '您未' + action + '本子'
})

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

//翻页
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){
    inputNode.value.focus()
  }
  targetPage.value = page.value
}

//改变展示类型
function changeCategory(){
  store.commit("_setCategory", category.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 editGalleryTag(gid, tag){
  tempTag.value = tag
  tempGid.value = gid
  isEditingTag.value = true
}
function submitGalleryTag(){
  store.dispatch("updateGalleryTag", {gid:tempGid.value, tag:tempTag.value})
  tempTag.value = ''
  tempGid.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 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 showThumbnail(gallery){
  store.commit("_changeThumbnailGallery", gallery)
  setTimeout(() => {document.querySelector(".preview > img").click()}, 1)
}

//移动端
function closeHistoryPanel(){
  store.commit("_closeHistoryPanel")
}
</script>

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