<template>
  <el-dialog
    class="dialog_box check_status_dialog"
    title="连接状态检测"
    v-model="dialogVisible"
    width="1024px"
    @closed="resetDialog">
    <div class="main">
      <div class="title" v-if="props.enter == 0">主机分组名称：{{ props.checkStatusData.host_name }}</div>
      <div class="loading-container">
        <span class="icon_box" :class="{ ic_animation: stateValue == 0 }"
          ><bg-icon :class="getClassName(stateValue)" :icon="getIcon(stateValue)"
        /></span>
        <span>{{ getText(stateValue) }}</span>
      </div>
      <div class="table-container">
        <div class="table-top">
          <span>异常状态列表</span>
          <el-button type="primary" @click="exportFile" :disabled="stateValue == 0 || tableTotal == 0">
            导出
          </el-button>
        </div>
        <div class="status-lists">
          <div class="table">
            <bg-table
              :empty-text="'无异常数据'"
              :height="300"
              ref="taskTable"
              :headers="taskHeaders"
              :rows="taskRows"
              :isIndex="true"
              :stripe="true">
              <template v-slot:voucher_type="{ row }">
                {{ row.voucher_type == 0 ? "密码验证" : "密钥验证" }}
              </template>
            </bg-table>
          </div>
          <bg-pagination
            v-if="taskRows.length > 0"
            :page="filter.page"
            :size="filter.size"
            :total="tableTotal"
            @change-page="changePage"
            @change-size="changeSize">
          </bg-pagination>
        </div>
      </div>
    </div>
    <template v-slot:footer>
      <div class="apaas_button">
        <el-button type="default" @click="dialogVisible = false">{{ props.enter == 0 ? "关闭" : "取消" }}</el-button>
        <el-button :disabled="stateValue != 1" v-if="props.enter != 0" type="primary" @click="save"
          >剔除异常数据并保存</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onBeforeMount, getCurrentInstance, computed, watch, nextTick, watchEffect } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const { $api } = proxy;
const router = useRouter();
const route = useRoute();
const props = defineProps({
  modelValue: {
    type: Boolean,
  },
  checkStatusData: {
    type: Object,
  },
  //   0：列表页   1：详情页
  enter: {
    type: Number,
  },
});
const emit = defineEmits(["update:modelValue"]);

const dialogVisible = computed({
  get() {
    if (props.modelValue) {
      postHostManageState();
    }
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

const stateUUID = ref("");
const postHostManageState = () => {
  const formData = new FormData();
  formData.append("detection_type", props.checkStatusData.detection_type);
  switch (props.checkStatusData.detection_type) {
    case 1:
      formData.append("id", props.checkStatusData.id);
      break;
    case 2:
      formData.append("host_manage_list", JSON.stringify(props.checkStatusData.host_manage_list));
      break;
    case 3:
      formData.append("file_name", props.checkStatusData.file_name);
      break;
  }
  $api.autoMaintenance.postHostManageState(formData).then((res) => {
    if (res.data.code == 200) {
      let data = res.data.data;
      stateUUID.value = data;
      stateValue.value = 1;
      getTableRows();
    } else {
      stateValue.value = 2;
      ElMessage.error(res.data.data);
    }
  });
};

const exportFile = () => {
  let params = {
    detection_type: props.enter == 0 ? 1 : 0,
  };
  switch (params.detection_type) {
    case 1:
      params.id = props.checkStatusData.id;
      break;
    case 0:
      params.uuid = stateUUID.value;
      break;
  }
  ElMessage.success("开始导出");
  let url = `/v1/api/automated_mainten/host_manage/export?`;
  const paramsArray = [];
  for (const [key, value] of Object.entries(params)) {
    paramsArray.push(`${key}=${value}`);
  }
  url += paramsArray.join("&");

  const a = document.createElement("a");
  const event = new MouseEvent("click");
  a.href = url;
  a.dispatchEvent(event);
};

const stateValue = ref(0);
const getIcon = (stateValue = 0) => {
  const icons = ["#bg-ic-s-circle-restart", "#bg-ic-s-circle-check", "#bg-ic-s-circle-close"];
  return icons[stateValue];
};
const getClassName = (stateValue = 0) => {
  const classNames = ["pending", "success", "error"];
  return classNames[stateValue];
};
const getText = (stateValue = 0) => {
  const text = ["状态检测中", "状态检测完成", "状态检测失败"];
  return text[stateValue];
};

const taskHeaders = [
  {
    prop: "ip",
    label: "IP",
  },
  {
    prop: "port",
    label: "端口",
  },
  {
    prop: "voucher_type",
    label: "凭证类型",
  },
  {
    prop: "user_name",
    label: "用户名",
  },
  {
    prop: "password",
    label: "密码",
  },
];
const taskRows = ref([]);
const filter = ref({
  page: 1,
  size: 10,
});
const tableTotal = ref(0);
const changePage = (page) => {
  filter.value.page = page;
  getTableRows();
}; // 改变页码

const changeSize = (size) => {
  filter.value.size = size;
  changePage(1);
}; // 改变每页条数

const getTableRows = () => {
  let params = {
    detection_type: props.enter == 0 ? 1 : 2,
  };
  switch (params.detection_type) {
    case 1:
      params.id = props.checkStatusData.id;
      params.page = filter.value.page;
      params.page_size = filter.value.size;
      break;
    case 2:
      params.uuid = stateUUID.value;
      params.page = filter.value.page;
      params.page_size = filter.value.size;
      break;
  }
  $api.autoMaintenance.getHostManageIPExceptionList(params).then((res) => {
    if (res.data.code == 200) {
      let data = res.data.data || [];
      taskRows.value = data;
      tableTotal.value = res.data.total;
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
const save = () => {
  let data = {
    uuid: stateUUID.value,
  };
  if (props.checkStatusData.detection_type == 3) {
    data.host_file_url = props.checkStatusData.host_file_url;
  }
  if (route.query.id) {
    // 编辑
    data.id = Number(route.query.id);
    $api.autoMaintenance.putHostManageEdit(data).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("保存成功");
        router.back();
      } else {
        ElMessage.error(res.data.data);
      }
    });
  } else {
    // 新增
    data.host_name = props.checkStatusData.host_name;
    $api.autoMaintenance.postHostManageAdd(data).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("保存成功");
        router.back();
      } else {
        ElMessage.error(res.data.data);
      }
    });
  }
};

const resetDialog = () => {
  stateValue.value = 0;
  taskRows.value = [];
  tableTotal.value = 0;
  filter.value.page = 1;
  filter.value.size = 10;
};
</script>

<style lang="scss" scoped>
.dialog_box {
  .main {
    .title {
      text-align: left;
      margin-bottom: 10px;
      font-weight: bold;
      font-size: 16px;
    }
    .loading-container {
      margin: auto;
      text-align: center;
      width: 200px;
      background-color: #eaedf5;
      border-radius: 4px;
      font-size: 14px;
      color: #404a62;
      padding: 10px 0;
      .icon_box {
        margin-right: 8px;
        display: inline-block;
      }
      .pending {
        font-size: 14px;
        color: #3759be;
      }
      .success {
        font-size: 14px;
        color: #429e8a;
      }
      .error {
        font-size: 14px;
        color: #d75138;
      }
      .ic_animation {
        animation: loading-rotate 1.5s linear infinite;
      }
      @keyframes loading-rotate {
        100% {
          transform: rotate(360deg);
        }
      }
    }
    .table-container {
      .table-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 10px 0;
        font-weight: bold;
        font-size: 16px;
      }
      .status-lists {
        margin-top: 16px;
        overflow: hidden;
        padding-bottom: 10px;
      }
    }
  }
}
</style>

<style lang="scss">
.check_status_dialog {
  .el-dialog__footer {
    border-top: 1px solid #e6e9ef;
  }
  .bg-table .el-table__empty-block {
    height: unset !important;
    .empty_container {
      height: unset;
      padding-top: 46px;
    }
  }
}
</style>
