<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>
    <br>
    <el-button @click="openPanel">打开面板</el-button>
    <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.availableResolution">
      <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="chosenVideo" width="100">
    <table>
      <tr>视频名字:{{chosenVideo.name}}</tr>
      <tr>视频网站: <el-link :href="chosenVideo.website">{{chosenVideo.website}}</el-link> </tr>
      <tr>视频链接: <el-link :href="chosenVideo.link">{{chosenVideo.link}}</el-link></tr>
      <tr>视频状态:{{chosenVideo.status}}</tr>
      <tr v-if="!chosenVideo.resolution">
        目标分辨率: <el-select v-model="targetResolution">
        <el-option v-for="(resolution) in chosenVideo.availableResolution" :value="resolution" :label="resolution"/>
      </el-select>
      </tr>
    </table>
    <el-button @click="postTask" v-if="!chosenVideo.resolution">下载</el-button>
    <el-button @click="deleteVideo" v-if="chosenVideo.resolution">删除</el-button>
  </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">
      <el-input v-model="AuthCode" class="validate" placeholder="请输入授权码">
      </el-input>
      <el-checkbox v-model="isRemember">是否记住授权码</el-checkbox><br>
      <el-button @click="validate" type="primary" @keydown.enter="validate">验证</el-button>
  </div>
</template>

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

let AuthCode = ref("")
let isRemember = ref(false)
let isAlterAuthCode = ref(false)
let newAuthCode = ref("")
let tempAuthCode = 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 chosenVideo = computed(() => {
  return store.state.chosenVideo
})

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

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

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)
  if(param.value.includes("hentai"))
    store.dispatch("postGalleryTask", {link: tempLink, targetResolution: targetResolution.value})
  else
    store.dispatch("postVideoTask", {link: tempLink, targetResolution: targetResolution.value})

  targetResolution.value = ""
}

//查询任务
function queryRemoteTask(){
  if(!validateLink(param.value)){
    ElMessage("链接错误")
    return
  }
  let tempLink = coverLink(param.value)
  if(param.value.includes("hentai"))
    store.dispatch("queryGalleryTask", tempLink)
  else
    store.dispatch("queryVideoTask", 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("_searchLocalByTaf", [''])
  param.value = ""
}

//删除任务
function deleteVideo(){
  store.dispatch("deleteVideo", chosenVideo.value.id)
}
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 if(rawLink.includes("xvideos.com")){
    return true
  }
  else if(rawLink.includes("pornhub.com")){
    return rawLink.includes("view_video.php")
  }
  else if(rawLink.includes("xhamster") && rawLink.includes(".com")){
    return true
  }
}
function coverLink(rawLink){
  if(rawLink.includes("xhamster"))
    rawLink = "https://zh.xhamster" + rawLink.substring(rawLink.indexOf(".com"))
  let url = new URL(rawLink)
  maskDomain.value.forEach((mask) => {
    if(url.host === mask['raw'])
      rawLink = rawLink.replace(mask['raw'], mask['mask'])
  })
  return rawLink;
}

//打开面板以及在线阅读
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 scoped>
  .DashBoard{
    width: auto;
    height: 90vh;
    background-color: ghostwhite;
    text-align: center;
  }

  .validate{
    width: auto;
    background-color: ghostwhite;
    display: block;
    padding-left: 100px;
    padding-top: 200px;
  }
  .el-input{
    width: 250px;
  }
</style>