<script setup>

import {computed, onMounted, ref, watch} from "vue";
import store from "../../store/index.js";
import {useRouter} from "vue-router";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import Util from "../../Util/index.js";

let router = useRouter()
let currentSiteId = ref()
let hostname = ref('')
let domain = ref('')
let reverseProxyPrefix = ref('')
let size = ref(0)
let sizeUnit = ref("GB")
let storagePath = ref("")
let sites = computed(() => {
  return store.getters.getSites
})
let currentSite = computed(() => {
  let s
  sites.value.forEach((site) => {
    if(site.id === currentSiteId.value)
      s = site
  })
  return s
})
function switchSite(id){
  currentSiteId.value = id
  router.replace("/index/siteManage/?id=" + currentSiteId.value)
}
function submit(){
  let site = currentSite.value
  let alterSite = {id:site.id}
  let adjustSize
  if(!isNaN(parseInt(size.value)) && size.value !== 0) {
    adjustSize = Util[sizeUnit.value] * size.value

    if (adjustSize < 0)  //减少
      if (currentSite.availableSpace + adjustSize < 0) {
        ElMessage.error("减少空间不能小于可分配空间，可以考虑回收用户空间")
        return
      }
    alterSite.availableSpace = adjustSize
  }

  if(hostname.value.trim() !== '')
    alterSite.hostname = hostname.value

  if(domain.value.trim() !== '')
    alterSite.domain = domain.value

  if(reverseProxyPrefix.value.trim() !== '')
    alterSite.reverseProxyPrefix = reverseProxyPrefix.value

  if(storagePath.value.trim() !== '') {
      alterSite.storagePath = storagePath.value

    ElMessageBox.confirm("修改服务器存储路径会导致服务器重启，是否继续？", '警告',
        { confirmButtonText: "继续",
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(() => {
      axios.post(store.state.config.host + "manage/site/alter?" + qs.stringify({
        ...alterSite}))
          .then((res) => {
            if(res.data.result === 'success') {
              ElMessage.success(res.data.data)
              store.dispatch('loadSites')
              hostname.value = ""
              domain.value = ""
              reverseProxyPrefix.value = ""
              size.value = 0
            }
            else
              ElMessage.error(res.data.data)
          })
    })
    return
  }

  axios.post(store.state.config.host + "manage/site/alter?" + qs.stringify({
    ...alterSite}))
      .then((res) => {
        if(res.data.result === 'success') {
          ElMessage.success(res.data.data)
          store.dispatch('loadSites')
          hostname.value = ""
          domain.value = ""
          reverseProxyPrefix.value = ""
          size.value = 0
        }
        else
          ElMessage.error(res.data.data)
      })
}
function unpair(){
  axios.post(store.state.config.host + "manage/site/unpair?" + qs.stringify({passcode:store.state.config.passcode,
  id:currentSiteId.value}))
      .then((res) => {
        if(res.data.result === 'success') {
          ElMessage.success(res.data.data)
          store.dispatch('loadSites')
        }
        else
          ElMessage.error(res.data.data)
      })
}

watch(router.currentRoute , (value, oldValue)=>{
  if(value.path !== oldValue.path && value.path.startsWith('/index/siteManage/')) {
    if (router.currentRoute.value.query.id === undefined) {
      router.replace(`/index/siteManage/?id=${sites.value[0].id}`)
      currentSiteId.value = sites.value[0].id
    } else
      currentSiteId.value = Number(router.currentRoute.value.query.id)
  }
})
onMounted(() => {
  if(router.currentRoute.value.query.id === undefined) {
    router.replace(`/index/siteManage/?id=${sites.value[0].id}`)
    currentSiteId.value = sites.value[0].id
  }else
    currentSiteId.value = Number(router.currentRoute.value.query.id)
})
</script>

<template>
  <el-menu mode="horizontal" :default-active="currentSiteId">
    <el-menu-item v-for="site in sites" :index="site.id" @click="switchSite(site.id)" >
      {{site.hostname}}
    </el-menu-item>
  </el-menu>

  <div v-if="currentSite !== undefined" style="background-color: white; padding-bottom:410px; padding-left: 25px">
    <el-row>
      <el-col :span="8">
        服务器id:{{currentSite.id}}
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        服务器ip:{{currentSite.ip}}
      </el-col>
      <el-col :span="8">
        域名跟反代前缀，若要去除，直接填"空"
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        当前存储路径:{{currentSite.storagePath}}
      </el-col>
      <el-col :span="8">
        <el-input v-model="storagePath">
          <template #prepend>存储路径</template>
        </el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        当前服务器名:{{currentSite.hostname}}
      </el-col>
      <el-col :span="8">
        <el-input v-model="hostname">
          <template #prepend>
            服务器名
          </template>
        </el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        当前服务器总预分配空间:{{Util.formatSize(currentSite.totalSpace)}} <br>
        当前服务器可分配空间:{{Util.formatSize(currentSite.availableSpace)}}
      </el-col>
      <el-col :span="8" style="line-height: 40px">
        <el-input v-model="size">
          <template #prepend>
            容量调整
          </template>
          <template #append>
            <el-select placeholder="单位" v-model="sizeUnit">
              <el-option value="KB"/>
              <el-option value="MB"/>
              <el-option value="GB"/>
            </el-select>
          </template>
        </el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        当前服务器域名:{{currentSite.domain===undefined?"无":currentSite.domain}}
      </el-col>
      <el-col :span="8">
        <el-input v-model="domain">
          <template #prepend>
            服务器域名
          </template>
        </el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        当前服务器反向代理前缀:{{currentSite.reverseProxyPrefix===undefined?"无":currentSite.reverseProxyPrefix}}
      </el-col>
      <el-col :span="8">
        <el-input v-model="reverseProxyPrefix">
          <template #prepend>
            反向代理前缀
          </template>
        </el-input>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="8">

      </el-col>
      <el-col :span="5">
        <el-button type="danger" v-if="currentSiteId !== 1" @click="unpair">删除服务器</el-button>
        <el-button type="primary" @click="submit">提交修改</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>

</style>