<template>
  <div class="DashBoard" v-show="loadComplete">
    <span>E站额度本周已用:{{weekUsed.weekUsedAmount}} <br>上次重置时间:{{weekUsed.lastResetAmountTime}}</span><br>
    <el-button @click="queryWeekUsedAmount">查询用量</el-button>
    <hr>
    <el-row>
      <el-col>
        查询参数类型: <el-select style="width: 125px" v-model="type" @change="resetLocalQuery()">
        <el-option value="link" label="链接"/>
        <el-option value="keyword" label="关键字"/>
        <el-option value="tag" label="标签"/>
      </el-select>
        参数:
        <el-input style="width: 250px;" v-model="param" class="el-input"></el-input>
      </el-col>
      <el-col>
        <el-button @click="queryRemoteTask" v-show="type === 'link'">远程查询</el-button>
        <el-button @click="queryLocalTask">当前页查询</el-button>
      </el-col>
    </el-row>
    <hr>
    <el-button @click="openPanel">打开面板</el-button>
    <el-button @click="isQuerying = true">里站搜索</el-button><br><br>
    <el-button @click="isAlterAuthCode = true">修改授权码</el-button>
    <el-button @click="deleteAuthCode">删除本地授权码</el-button>
    <br>
    <div v-show="thumbnailGallery !== {}">
      <span>
        {{thumbnailGallery.shortName}}
      </span><br>
      <picture>
        <el-image :src="thumbnailGallery.url" :preview-src-list="[thumbnailGallery.url,]" :initial-index="0" class="preview" style="height: 30vh"/>
      </picture>
    </div>
  </div>

  <el-dialog title="查询本子" v-model="chosenGallery" width="100%">
    <table>
      <tr>本子名字:{{chosenGallery.name}}</tr>
      <tr>本子页数:{{chosenGallery.pages}}</tr>
      <tr>本子语言:{{chosenGallery.language}}</tr>
      <tr>本子大小:{{chosenGallery.fileSize}}</tr>
      <tr>本子状态:{{chosenGallery.status}}</tr>
      <tr v-if="chosenGallery.availableResolution">
        目标分辨率:<el-select v-model="targetResolution">
          <el-option v-for="(fileSize, resolution) in chosenGallery.availableResolution" :value="resolution"
                     :label="resolution + '  ' + fileSize">
          </el-option>
        </el-select>
      </tr>
    </table>
    <el-button @click="postTask" v-if="chosenGallery.availableResolution">下载</el-button>
    <tr v-if="chosenGallery.status === '下载完成'">
      <el-button @click="onlineGalleryReader(chosenGallery.gid)">在线预览</el-button>
      <el-button @click="showThumbnail(chosenGallery)">查看封面图</el-button>
      <el-button @click="deleteGallery">删除</el-button>
    </tr>
  </el-dialog>


  <el-dialog title="里站搜索" v-model="isQuerying" top="0" style="margin-bottom: 0" width="100%" class="el-dialogClass">
    <div style="text-align: center">
      <el-input v-model="keyword" style="width: 50vw"></el-input> <el-button @click="queryGalleries(null)">查询</el-button> <div id="loading"/>
    </div>
    <el-scrollbar height="65vh">
      <div style="height: 20vh; width: 100%; background-color: #f5f5f5; border-radius: 5px" v-for="gallery in galleries">
        <el-image alt="picture" :preview-src-list="['http://downloader.lionwebsite.xyz/query/image?path=' + gallery.thumbnailUrl,]"
                  :src="'http://downloader.lionwebsite.xyz/query/image?path=' + gallery.thumbnailUrl"
                  style="height:20vh;width:35vw;float: left;"
                  fit="contain"
                  loading="lazy"
        />
        <div style="font: bold 10px semi-condensed; margin-top: 1vh; padding-left: 40vw; padding-top: 2vw">
          <span>{{gallery.name}}</span><br>
          <span>上传时间：{{gallery.uploadTime}}</span><br>
          <span>页数：{{gallery.page}}</span><br>
          <span class="ct6">类型：{{gallery.type}}</span><br>
          <a :href="gallery.link">链接</a><br>
          <el-button style="position: relative; margin-left: 65%;" @click="param=gallery.link; queryRemoteTask()" type="primary">下载</el-button>
        </div>
      </div><br>
    </el-scrollbar>
    <div style="padding-top: 10px; text-align: center">
      <el-button @click="queryGalleries(queryPage.first)" :disabled="queryPage.first === undefined">首页</el-button>
      <el-button @click="queryGalleries(queryPage.previous)" :disabled="queryPage.previous === undefined">上一页</el-button>
      <el-button @click="queryGalleries(queryPage.next)" :disabled="queryPage.next === undefined">下一页</el-button>
      <el-button @click="queryGalleries(queryPage.last)" :disabled="queryPage.last === undefined">尾页</el-button>
    </div>
  </el-dialog>

  <el-dialog title="修改授权码" v-model="isAlterAuthCode" width="100%">
    <el-form>
      <el-form-item>
        <template #label>当前授权码</template>
        <template #default>{{realAuthCode}}</template>
      </el-form-item>
      <el-form-item>
        <template #label>新的授权码</template>
        <template #default>
          <el-input v-model="newAuthCode"></el-input>
        </template>
      </el-form-item>
      <el-form-item>
        <template #label>再次输入授权码</template>
        <template #default>
          <el-input v-model="tempAuthCode"></el-input>
        </template>
      </el-form-item>
    </el-form>
    <el-footer>
      <el-button @click="alterAuthCode">提交</el-button>
    </el-footer>
  </el-dialog>


  <div class="DashBoard" v-show="!loadComplete">
    <div class="validate">
      <el-input v-model="AuthCode"  placeholder="请输入授权码" />
      <el-checkbox v-model="isRemember" >是否记住授权码</el-checkbox><br>
      <el-button @click="validate" type="primary" @keydown.enter="validate">验证</el-button>
    </div>
  </div>
</template>

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

//授权码相关
let AuthCode = ref("")
let isRemember = ref(false)
let isAlterAuthCode = ref(false)
let newAuthCode = ref("")
let tempAuthCode = ref("")

let isQuerying = ref(false)
let keyword = ref("furry yaoi")
let galleries = ref([])
let queryPage = ref({})

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

let targetResolution = ref("")

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

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

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

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

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

//修改授权码
function alterAuthCode(){
  if(newAuthCode.value.trim() === "" || tempAuthCode.value.trim() === "" || newAuthCode.value !== tempAuthCode.value)
    ElMessage("请检查授权码输入是否错误")
  else {
    store.dispatch("alterAuthCode", newAuthCode.value)
    isAlterAuthCode.value = false
    newAuthCode.value = ""
    tempAuthCode.value = ""
  }
}

//查询用量
function queryWeekUsedAmount(){
  store.dispatch("loadWeekUsedAmount")
}

function postTask(){
  if(!validateLink(param.value)){
    ElMessage("链接错误")
    return
  }
  if(targetResolution.value === ''){
    ElMessage("请选择分辨率再提交")
    return
  }
  let tempLink = coverLink(param.value)
  store.dispatch("postGalleryTask", {link: tempLink, targetResolution: targetResolution.value})
  targetResolution.value = ""
}

//查询任务
function queryRemoteTask(){
  if(!validateLink(param.value)){
    ElMessage("链接错误")
    return
  }
  let tempLink = coverLink(param.value)
  store.dispatch("queryGalleryTask", tempLink)
}
function queryLocalTask(){
  switch (type.value){
    case "link":
      store.commit("_searchLocalByLink", param.value)
      break
    case "keyword":
      store.commit("_searchLocalByKeyword", param.value)
      break
    case "tag":
      store.commit("_searchLocalByTag", param.value.includes(",") ? param.value.split(","): [param.value])
      break
  }
}
function resetLocalQuery(){
  store.commit("_searchLocalByKeyword", "")
  store.commit("_searchLocalByTag", [''])
  param.value = ""
}
function queryGalleries(link){
  let tempParam
  if(link !== null) {
    let url = new URL(link)
    tempParam = url.search.replace("?f_search=", "")
  }else{
    tempParam = keyword.value
  }
  tempParam = tempParam.replace(" ", "+")
  document.getElementById("loading").style.display = "inline-block";

  axios.get("http://downloader.lionwebsite.xyz/query?keyword=" + tempParam)
      .then((res) => {
        document.getElementById("loading").style.display = "none";
        if (res.data.result === "success") {
          let tempGalleries = JSON.parse(res.data.data)
          queryPage.value.first = 'first' in res.data ? res.data.first : undefined
          queryPage.value.previous = 'previous' in res.data ? res.data.previous : undefined
          queryPage.value.next = 'next' in res.data ? res.data.next : undefined
          queryPage.value.last = 'last' in res.data ? res.data.last : undefined

          galleries.value.splice(0)
          tempGalleries.forEach((gallery) => {
            galleries.value.push(gallery)
          })
        }else {
          ElMessage({message: res.data.data, type: "error"})
        }
      })
}

//删除任务
function deleteGallery(){
  store.dispatch("deleteGallery", chosenGallery.value.gid)
}

//验证授权码
function validate(){
  if(AuthCode.value.trim() === ""){
    ElMessage("请输入授权码后再验证")
  }
  else{
    store.dispatch("validate", AuthCode.value)
    if(isRemember.value)
      localStorage.setItem("auth", AuthCode.value)
  }
}

//验证链接以及伪装链接
function validateLink(rawLink){
  if(rawLink.trim() === "")
    return false
  if(rawLink.includes("hentai"))
    return rawLink.includes("/g/")
  else
    return false
}
function coverLink(rawLink){
  return rawLink.replace("exhentai.org", "element-plus.org").replace("e-hentai.org", "element.org");
}

//打开面板以及在线阅读
function openPanel(){
  store.commit("_openHistoryPanel")
}
function onlineGalleryReader(gid){
  store.dispatch("queryOnlineLinks", gid)
}

function deleteAuthCode(){
  localStorage.removeItem('auth')
  ElMessage("删除授权码完成")
}

//显示缩略图
function showThumbnail(gallery){
  store.commit("_changeThumbnailGallery", gallery)
  setTimeout(() => {document.querySelector(".preview > img").click()}, 1)
}

onMounted(() => {
  const auth = localStorage.getItem("auth")
  if(auth !== null){
    store.dispatch("validate", auth)
  }
})
</script>

<style>
  .DashBoard{
    width: auto;
    height: 90vh;
    background-color: ghostwhite;
    text-align: center;
  }

  .validate{
    width: 50vw;
    background-color: ghostwhite;
    display: block;
    padding-top: 200px;
    padding-left: 20vw;
    text-align: center;
  }
  .el-input{
    width: 25vw;
  }
  .el-dialogClass .el-dialog__body{
    padding-left: 0;
    padding-right: 0;
  }
  #loading {
    width: 25px;
    height: 25px;
    border: 2px solid #ccc;
    border-top-color: #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    display: none;
  }

  @keyframes spin {
    to { transform: rotate(360deg); }
  }
</style>