<template>
    <div class="side">
      <div v-show="loadComplete" class="load_complete">
        <el-scrollbar max-height="80vh">
          <div v-if="currentTasks.length === 0">
            {{emptyText}}
          </div>
          <div v-for="gallery in currentTasks" :style="{'height': '20vh', 'background': isDark() ? '': 'FloralWhite', 'border-radius': '1%',
          'margin-bottom': '10px'}"
               @click="viewInfo(gallery)" id="gallery">
            <el-image :src="gallery.thumb_link"
                    style="height: 20vh; width: 35vw; float:left"
                  fit="contain"
                  loading="lazy"
            ></el-image>
            <div style="font: bold 16px semi-condensed;">
              {{adjustGalleryName(gallery.name, 95)}}<br>
              页数:{{gallery.pages}}<br>
              语言:{{gallery.language}}
              <span v-if="gallery.status !== '下载完成'">
                下载进度: {{gallery.progress}}
              </span>
            </div>
          </div>
        </el-scrollbar>
        <el-col>
          <el-row>
            <el-button @click="store.state.isShowHistory = true">三</el-button>
            <el-select style="width: 22vw" v-model="type">
              <el-option value="link" label="链接"/>
              <el-option value="keyword" label="关键字"/>
            </el-select>
            <el-input style="width: 60vw" v-model="param" placeholder="搜索">
              <template #append>
                <el-button @click="queryLocalTask">搜索</el-button>
              </template>
            </el-input>
          </el-row>
        </el-col>

        <el-row class="pageChanger">
          <el-col v-if="username !== 'test'">
          <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-dialog v-model="isViewing" width="100%" top="0" style="padding: 0">
    <div style="height: 20vh; font: bold 16px semi-expanded">
        <el-image :src="currentGallery.thumb_link"
                  style="float: left; width: 40vw; height: 20vh" fit="contain"/>
      {{adjustGalleryName(currentGallery.name, 150)}}
    </div>
    <div style="font: bold 20px semi-expanded">
      页数:{{currentGallery.pages}}                 <br>
      语言:{{currentGallery.language}}              <br>
      下载时间:{{currentGallery.createTimeDisplay}}  <br>
      大小:{{currentGallery.fileSize}}              <br>
      分辨率:{{currentGallery.resolution}}          <br>
      链接:<a :href="currentGallery.link">link</a>  <br>
      下载链接:<a :href="currentGallery.download">link</a><br>
      <span v-show="isLion">
        downloader:{{currentGallery.downloader}}
      </span>
      <span v-if="currentGallery.download === undefined">
        下载进度: {{currentGallery.progress}}
      </span>
    </div>
    <template #footer>
      <el-button @click="downloadTask(currentGallery.download)" :disabled="currentGallery.status !== '下载完成'" size="large">下载</el-button>
      <el-button @click="deleteGallery(currentGallery.gid)" :disabled="currentGallery.status !== '下载完成'" size="large">删除</el-button>
      <el-button @click="changeGalleryCollect(currentGallery.gid, currentGallery.isCollect)" :disabled="currentGallery.status !== '下载完成'"
                 size="large">{{currentGallery.isCollect ? '取消收藏' : '收藏'}}</el-button>
      <el-button @click="readOnlineGallery(currentGallery)" size="large">在线看</el-button>
    </template>
  </el-dialog>

  <OnlineReader/>
</template>

<script setup>
import store from "../store";
import {computed, ref} from "vue";
import OnlineReader from "./OnlineReader.vue";

//输入
let inputNode = ref(null)
//是否正在编辑页数
let isEditingPage = ref(false)
//是否查看详情
let isViewing = ref(false)

let category = computed(() => {
  return store.state.category
})
let galleryNameType = computed(() => {
  return store.state.galleryNameType
})
let sortType = computed(() => {
  return store.state.sortType
})
let targetPage = ref(1)                     // 当前页数
let username = computed(() => {
  return store.state.username
})

//查询相关
let type = ref("keyword")
let param = ref("")

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

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

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 currentGallery = ref({name:"name"})

//翻页
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(value){
  store.commit("_setCategory", 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 queryLocalTask(){
  switch (type.value){
    case "link":
      store.commit("_searchLocalByLink", param.value)
      break
    case "keyword":
      store.commit("_searchLocalByKeyword", param.value)
      break
  }
}

//下载，删除，在线看
function downloadTask(link){
  window.open(link)
}
function deleteGallery(gid){
  store.dispatch("deleteGallery", gid).then(() => {
    isViewing.value = false
  })
}
function readOnlineGallery(gallery){
  store.dispatch("readOnlineGallery", gallery)
}
function viewInfo(gallery){
  currentGallery.value = gallery
  isViewing.value = true;
}

function adjustGalleryName(name, length) {
  let truncated = '';
  let bytesCount = 0;

  for (const char of name) {
    const charCode = char.charCodeAt(0);
    const byteLength = charCode < 0x80 ? 1 : charCode < 0x800 ? 2 : 3;

    if (bytesCount + byteLength <= length) {
      truncated += char;
      bytesCount += byteLength;
    } else {
      truncated += "..."
      break;
    }
  }
  return truncated;
}

function isDark(){
  return document.querySelector('html').classList.contains('dark')
}
</script>

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