<template>
  <div class="DashBoard" v-show="loadComplete">
    <span>本周已用额度:{{weekUsed.weekUsedAmount}} 上次重置时间:{{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-select>
        <el-input style="width: 200px;" v-model="param">
          <template #prepend>
            参数:
          </template>
        </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>
    <br>
    <hr>
    <el-button @click="isAlterAuthCode = true">修改授权码</el-button>
    <el-button @click="deleteAuthCode">删除本地授权码</el-button>
    <el-button @click="isConfig = true">配置</el-button>
    <span style="display: inline">夜间模式</span>
    <el-switch @click="toggleStyle" v-model="isDark">夜间模式</el-switch>
    <hr>
    <el-button @click="isQuerying = true">在线搜索</el-button>
    <hr>
    <el-button v-if="isLion" @click="resetUndone">重置任务</el-button>
    <div v-show="thumbnailGallery.thumb_link !== undefined">
      <span>
        {{thumbnailGallery.shortName}}<br>
      </span><br>
      <picture>
        <el-image :src="thumbnailGallery.thumb_link" :preview-src-list="[thumbnailGallery.thumb_link, ]" class="preview"
        style="width: 300px; height: 250px" fit="contain"/>
      </picture>
    </div>
  </div>

  <el-dialog title="查询" v-model="chosenGallery" style="height: 350px">
    <el-image v-show='chosenGallery.thumb_link !== undefined'
              style="float: right; width: 250px; height: 250px;" fit="contain"
              :src="chosenGallery.thumb_link !== undefined ? 'https://downloader.lionwebsite.xyz/GalleryManage/ehThumbnail?path=' + chosenGallery.thumb_link: ''"/>
    <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" style="width: 200px">
          <el-option v-for="(fileSize, resolution) in chosenGallery.availableResolution" :value="resolution"
                     :label="resolution + '  ' + fileSize">
          </el-option>
        </el-select>
      </tr>
    </table>
    <template #footer>
      <el-button @click="postTask" v-if="chosenGallery.availableResolution">下载</el-button>
      <el-button @click="window.open(chosenGallery.download)" v-else>下载文件</el-button>
      <el-button @click="readOnlineGallery(chosenGallery)">在线预览</el-button>
      <el-button v-if="chosenGallery.status === '下载完成'" @click="deleteGallery">删除</el-button>
    </template>
  </el-dialog>

  <el-dialog title="修改授权码" v-model="isAlterAuthCode">
    <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>

  <HentaiSearch v-model:is-querying="isQuerying"  @close="isQuerying = false"></HentaiSearch>

  <el-dialog title="配置" v-model="isConfig">
    <div>
      夜间模式<br>
      <span style="display: inline-block">夜间模式跟随系统</span>
      <el-switch v-model="darkConfig.followSystem"></el-switch><hr>
    </div>
    <div>
      在线预览<br>
      <span style="display: inline-block">在线预览分页页数:</span>
      <input v-model="lengthPerPage"><hr>
    </div>
    <div>
      默认设置<br>
      <span style="display: inline-block">分类:</span>
      <el-select v-model="category" default-first-option>
        <el-option label="全部" value="total"/>
        <el-option label="我的下载" value="myDownload"/>
        <el-option label="我的收藏" value="myCollect"/>
      </el-select> <br>
      <span style="display: inline-block">排序方式:</span>
      <el-select v-model="sortType" default-first-option>
        <el-option label="名字" value="name"/>
        <el-option label="简洁名字" value="shortName"/>
        <el-option label="任务创建时间" value="createTime"/>
      </el-select> <br>
      <span style="display: inline-block">显示类型:</span>
      <el-select v-model="galleryNameType" default-first-option>
        <el-option label="名字" value="name"/>
        <el-option label="简洁名字" value="shortName"/>
      </el-select> <br>
    </div>
    <template #footer>
      <el-button type="primary" @click="saveConfig">保存</el-button>
    </template>
  </el-dialog>

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

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

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

let isQuerying = ref(false)
let isConfig = ref(false)
let isDark = ref(false)
let keyword = ref("")
let darkConfig = ref({})
let lengthPerPage = ref(0)
let category = ref("")
let sortType = ref("")
let galleryNameType = ref("")

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

let targetResolution = ref("")

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

let chosenGallery = computed(() => {
  param.value = ''
  targetResolution.value = ''
  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
})

let isLion = computed(() => {
  return store.state.userId === 3
})

//修改授权码
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(chosenGallery.value.link)){
    ElMessage("链接错误")
    return
  }
  if(targetResolution.value === ''){
    ElMessage("请选择分辨率再提交")
    return
  }
  store.dispatch("postGalleryTask",
      {link: chosenGallery.value.link,
              targetResolution: targetResolution.value})
}

//查询任务
function queryRemoteTask(){
  if(!validateLink(param.value)){
    ElMessage("链接错误")
    return
  }
  if(param.value.includes("e-hentai"))
    param.value = param.value.replace("e-hentai", "exhentai")
  store.dispatch("queryGalleryTask", param.value)
}
function queryLocalTask(){
  switch (type.value){
    case "link":
      store.commit("_searchLocalByLink", param.value)
      break
    case "keyword":
      store.commit("_searchLocalByKeyword", param.value)
      break
  }
}

function resetLocalQuery(){
  store.commit("_searchLocalByKeyword", "")
  param.value = ""
}

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 readOnlineGallery(gallery){
  store.dispatch("readOnlineGallery", gallery)
}

//重新给节点发送未完成任务
function resetUndone(){
  store.dispatch("resetUndone").then()
}
function deleteAuthCode(){
  localStorage.removeItem('auth')
  ElMessage("删除授权码完成")
}
function toggleStyle(){
  if(isDark.value)
    dark()
  else
    light()
}

onMounted(() => {
  const auth = localStorage.getItem("auth")
  adjustForStyle()
  store.state.lengthPerPage = localStorage.getItem("lengthPerPage")
  store.state.lengthPerPage = store.state.lengthPerPage === null ? 30: Number(store.state.lengthPerPage)
  category.value = store.state.category = localStorage.getItem("category") === null ? "myDownload" : localStorage.getItem("category")
  sortType.value = store.state.sortType = localStorage.getItem("sortType") === null ? "createTime" : localStorage.getItem("sortType")
  galleryNameType.value = store.state.galleryNameType = localStorage.getItem("galleryNameType") === null ? "shortName" : localStorage.getItem("galleryNameType")
  lengthPerPage.value = store.state.lengthPerPage

  if(auth !== null){
    store.dispatch("validate", auth)
    AuthCode.value = localStorage.getItem("auth")
  }
})

function adjustForStyle(){
  let darkConfigStr = localStorage.getItem("darkConfig")
  if(darkConfigStr !== null) {
    darkConfig.value = JSON.parse(darkConfigStr)
    if (darkConfig.value.followSystem && isSystemDark())
      dark()
    else
      light()
  }else {
    light()
    darkConfig.value = {'followSystem': false}
  }
}
function isSystemDark(){
  return window.matchMedia('(prefers-color-scheme: dark)').matches
}
function dark(){
  isDark.value = true
  let html = document.querySelector("html")
  if(!html.classList.contains("dark"))
    html.classList.add('dark')
  document.querySelector(".DashBoard").style.setProperty("background-color", null)
  document.querySelector(".app").style.setProperty("background-color", null)
}
function light(){
  isDark.value = false
  let html = document.querySelector("html")
  if(html.classList.contains("dark"))
    html.classList.remove('dark')

  document.querySelector(".DashBoard").style.setProperty("background-color", "ghostwhite")
  document.querySelector(".app").style.setProperty("background-color", "#c6e2ff")
}
function saveConfig(){
  if(lengthPerPage.value < 0 || lengthPerPage.value > 30) {
    ElMessage("分页页数设置错误，范围1~30")
    lengthPerPage.value = 30
  }
  else {
    store.state.lengthPerPage = Number(lengthPerPage.value)
    localStorage.setItem("lengthPerPage", lengthPerPage.value)
  }
  localStorage.setItem("darkConfig", JSON.stringify(darkConfig.value))
  localStorage.setItem("category", category.value)
  localStorage.setItem("sortType", sortType.value)
  localStorage.setItem("galleryNameType", galleryNameType.value)

  store.commit("_setCategory", category.value)
  store.commit("_setSortType", sortType.value)
  store.commit("_setGalleryNameType", galleryNameType.value)

  isConfig.value = false
  adjustForStyle()
}
</script>

<style scoped>
  .DashBoard{
    width: auto;
    height: 92vh;
    text-align: center;
  }
  .el-input{
    width: 200px;
  }
</style>