<script lang="ts" setup>
import type {serverValueItem} from "~/components/SettingCard.vue";
import {useMainLayoutStore} from "~/strores/UseMainLayoutStore";
import {useToast} from "vue-toastification";

type alertConfigs={
  "alertType": string,
  "serverId": string,
  "notify": string,
  "warning": string,
  "typeName": string,
  "description": string
}
const mainLayoutStore=useMainLayoutStore()
const toast=useToast()
const alertConfig = ref<alertConfigs[]>([])
const ServerValues = ref<serverValueItem[]>([])
const selectServer=ref<string>("")
const serverIds = ref<string[]>([])
const selectedDataName = ref<string>("")
const Description = ref<string>()
const Notify = ref<string>("50")
const Warning = ref<string>("80")
onMounted(()=>{
  config()
})
const config=()=>{
  $fetch('/Api/Config/GetAlertConfig', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': "Bearer " + useCookie('token').value
    },
    baseURL: useRuntimeConfig().public.baseUrl
  }).then(res => {
    alertConfig.value = res as alertConfigs[]
  })
}
onMounted(() => {
  $fetch('/Api/Job/GetJobList', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + useCookie('token').value
    },
    params: {
      serverId: mainLayoutStore.SelectServer.id
    },
    baseURL: useRuntimeConfig().public.baseUrl
  }).then(res => {
    ServerValues.value = res as serverValueItem[];
    ServerValues.value.sort((a, b) => {
      return a.dataName.localeCompare(b.dataName);
    })
    //提取serverValues的唯一serverId
    serverIds.value = ServerValues.value.map(item => item.serverId)
    serverIds.value=[...new Set(serverIds.value)]
    selectServer.value =serverIds.value[0]
    selectedDataName.value=ServerValues.value.filter(x=>x.serverId===selectServer.value)[0].dataType
  })
})
const addAlertVisible= ref(false)
watch(()=>selectServer.value,(newValue)=>{
  selectedDataName.value=ServerValues.value.filter(x=>x.serverId===newValue)[0].dataType
})
const saveAlertVisible=()=>{

  const data={
    ServerId:selectServer.value,
    DataType:selectedDataName.value,
    Description:Description.value,
    Notify:Notify.value,
    Warning:Warning.value,
    DataName:ServerValues.value.filter(x=>x.dataType===selectedDataName.value)[0].dataName
  }
  const isEmpty = (value:any) => value === null || value === undefined || value === '';
  if (!Object.values(data).every(value => !isEmpty(value))) {
    toast.error("请填写完整")
    return
  }
  $fetch('/Api/Config/AddAlertConfig', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': "Bearer " + useCookie('token').value
    },
    body: data,
    baseURL: useRuntimeConfig().public.baseUrl
  }).then(res => {
    console.log(res);
    toast.success("创建成功 "+res)
    setTimeout(()=>{
      addAlertVisible.value=false
      config()
    },2000)
  }).catch(err=>{
    toast.error("创建失败"+err)
  })
}
const deleteAlert=(alert:alertConfigs)=>{
  $fetch('/Api/Config/DeleteAlertConfig', {
    method:'DELETE',
    params:{
      DataType:alert.alertType,
      ServerId:alert.serverId
    },
    headers: {
      'Content-Type': 'application/json',
      'Authorization': "Bearer " + useCookie('token').value
    },
    baseURL: useRuntimeConfig().public.baseUrl
  }).then(res=>{
    toast.success(res)
    setTimeout(()=>{ config()},1000)
  }).catch(err=>{
    toast.error(err)
  })
}
const confirm = useConfirm();
const confirm2 = (alert:alertConfigs) => {
  confirm.require({
    message: '你真的打算删除这个警告么？',
    header: '警告',
    rejectLabel: 'Cancel',
    accept: () => {
      deleteAlert(alert)
    },
  });
};
</script>

<template>
  <div class="alert-setting-layout">
    <ConfirmDialog></ConfirmDialog>
    <Dialog
        v-model:visible="addAlertVisible"
        :pt="{
         root: {
          style:'border:unset;background-color:unset;'
        },
        mask: {
            style: 'backdrop-filter: blur(20px)'
        }
    }"
        modal
    >
       <div class="add-alert-box">
          <h3>新的告警</h3>
          <div class="form-item">
            <label>监控对象</label>
            <select v-model="selectedDataName">
              <option v-for="item in ServerValues.filter(x=>x.serverId===selectServer)" :value="item.dataType">{{item.dataName}}</option>
            </select>
          </div>
         <div class="form-item">
           <label>监控服务器</label>
           <select v-model="selectServer">
             <option v-for="item in serverIds">{{item}}</option>
           </select>
         </div>
          <div class="form-item">
            <label>告警描述</label>
            <input type="text" placeholder="告警描述" v-model="Description" required/>
          </div>
         <div class="form-item">
           <label>通知阈值</label>
           <input type="number" placeholder="通知阈值" v-model="Notify" required/>
         </div>
         <div class="form-item">
           <label>报警阈值</label>
           <input type="number" placeholder="报警阈值" v-model="Warning" required/>
         </div>
          <div class="form-item">
            <button @click="saveAlertVisible">保存</button>
            <button @click="addAlertVisible=false">取消</button>
          </div>
       </div>
    </Dialog>
    <div class="tool-bar">
      <h3>告警设置</h3>
      <div class="actions">
        <button @click="config">
        <Icon name="RefreshCw" />
          <p>刷新</p>
        </button>
        <button>
          <Icon name="RotateCcw"/>
          <p>重载配置</p>
        </button>
        <button @click="addAlertVisible=true">
          <Icon name="Plus"/>
          <p>新的告警</p>
        </button>
      </div>
    </div>
    <div class="alert-configs-box">
      <div v-for="alert in alertConfig" class="alert-item">
        <Icon name="TriangleAlert" :stroke-width="2" :size="45"/>
        <div>
          <p>{{alert.typeName}}</p>
          <p>介绍：{{alert.description}}</p>
          <p>监控服务器：{{alert.serverId}}</p>
          <p>通知阈值：{{alert.notify}}</p>
          <p>警告阈值：{{alert.warning}}</p>
        </div>
        <Icon name="X" :stroke-width="2" @click="confirm2(alert)"/>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "base";

.alert-setting-layout {
  display: flex;
  padding: $padding;
  width: 100%;
  flex-direction: column;

  * {
    @include SC_Font
  }
}

.tool-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .actions{
    display: flex;
    gap: $gap*1.5;
    align-items: center;
  }
  button {
    display: flex;
    align-items: center;
    border: $border;
    gap: $gap;
    padding: $padding*.3 $padding*.5;
    border-radius: $radius*.5;
    background: $primary-color;
    color: #fff;
    cursor: pointer;
  }
}
.alert-configs-box{
  display: flex;
  padding: $padding $padding*.5;
  gap: $gap*2;
  .alert-item{
    display: flex;
    gap: $gap;
    padding: $padding;
    background: $light-bg-underline-color;
    border-radius: $radius;
    border: $border;

  }
}
.add-alert-box{
  display: flex;
  flex-direction: column;
  gap: $gap;
  .form-item{
    display: flex;
    gap: $gap;
    align-items: center;
    label{
      width: 120px;
    }
    input,select{
      flex: 1;
      border: $border;
      background: $light-bg-underline-color;
      padding: $padding*.5;
      border-radius: $radius;
    }
    button{
      padding: $padding*.5 $padding;
      border-radius: $radius;
      border: $border;
      margin-top: 20px;
      &:first-of-type{
        margin-left: auto;
      }
    }
  }
}
</style>