<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <bg-filter-group @search="changeSearch" v-model="filter.search" placeholder="请输入关键字">
        <template v-slot:left_action>
          <div class="apaas_button">
            <el-button type="primary" @click="add">
              <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
              新增
            </el-button>
            <el-button type="default" @click="deleteAllTips"> 批量删除 </el-button>
            <span class="header_info"
              >已选择 <span style="color: #202531; font-weight: bold"> {{ state.selected.length }} </span> 项
            </span>
            <span class="header_info can_click_text" @click="clearSelected">清空</span>
          </div>
        </template>
        <template v-slot:filter_group>
          <div class="left-filter filter_list">
            <div class="filter_item">
              <span class="filter_title">创建时间</span>
              <el-date-picker
                v-model="filter.time"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期" />
            </div>
          </div>
          <div class="right-action apaas_button">
            <el-button type="primary" @click="filterAction"> 查询 </el-button>
            <el-button type="default" @click="filterClear"> 重置 </el-button>
          </div>
        </template>
      </bg-filter-group>
      <div class="table_container">
        <div class="table bg-scroll">
          <bg-table
            ref="dataTable"
            :headers="headers"
            :rows="tableRows"
            @selectAc="selectRows"
            :isIndex="true"
            :select="true"
            :stripe="true">
            <template v-slot:host_name="{ row }">
              <span class="can_click_text" @click="goToDetail(row)">
                {{ row.host_name }}
              </span>
            </template>
            <template v-slot:ip_number="{ row }">
              <span> {{ row.ip_cnt_err }}/{{ row.ip_cnt }} </span>
            </template>
            <template v-slot:create_time="{ row }">
              {{ row.create_time.split("+")[0].replace("T", " ").replace("Z", " ") }}
            </template>
            <template v-slot:action="{ row }">
              <bg-table-btns2 :limit="3" :tableData="tableRows">
                <bg-table-btn @click="editRow(row)">编辑</bg-table-btn>
                <bg-table-btn @click="checkRow(row)">状态检测</bg-table-btn>
                <bg-table-btn :disabled="row.ip_cnt_err == 0" @click="exportRow(row)">导出异常</bg-table-btn>
                <bg-table-btn @click="deleteRow(row)">删除</bg-table-btn>
              </bg-table-btns2>
            </template>
          </bg-table>
        </div>
        <bg-pagination
          :page="filter.page"
          :size="filter.page_size"
          :total="tableTotal"
          @change-page="changePage"
          @change-size="changeSize">
        </bg-pagination>
      </div>
    </div>
    <checkStatusDialog v-model="checkStatusVisible" :enter="0" :checkStatusData="checkStatusData"></checkStatusDialog>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeMount, toRefs, getCurrentInstance, watch } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import checkStatusDialog from "./components/check-status-dialog.vue";

const { proxy } = getCurrentInstance();
const { $api } = proxy;
const router = useRouter();
const route = useRoute();
const dataTable = ref(null);
const headers = [
  {
    label: "主机分组名称",
    prop: "host_name",
  },
  {
    label: "IP数量（异常/全部）",
    prop: "ip_number",
  },
  {
    label: "任务数量",
    prop: "task_cnt",
  },
  {
    label: "创建人",
    prop: "create_user",
  },
  {
    label: "创建时间",
    prop: "create_time",
    width: 220,
  },
  {
    label: "操作",
    prop: "action",
    width: 200,
    fixed: "right",
  },
];

const state = reactive({
  tableRows: [], // 表格数据
  selected: [], //选择数据
  tableTotal: 0, // 表格数据条数
  filter: {
    time: "",
    search: "",
    page: 1,
    page_size: 10,
  }, // 表格筛选项
});

const selectRows = (data) => {
  state.selected = data.selection;
};

const clearSelected = () => {
  dataTable.value.clearTable();
};

const deleteAllTips = () => {
  if (state.selected.length == 0) {
    return ElMessage.warning("请选择数据");
  }
  let data = {
    id: state.selected.map((item) => {
      return item.id;
    }),
  };
  $api.autoMaintenance.deleteHostManage(data).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      changePage(1);
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const exportRow = (row) => {
  let params = {
    detection_type: 1,
    id: row.id,
  };
  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 deleteRow = (row) => {
  let data = {
    id: [row.id],
  };
  $api.autoMaintenance.deleteHostManage(data).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功");
      changePage(1);
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const editRow = (row) => {
  router.push({
    path: "/auto-maintenance/host-manage/edit",
    query: {
      id: row.id,
    },
  });
};

const checkStatusVisible = ref(false);
const checkStatusData = ref({});
const checkRow = (row) => {
  checkStatusData.value = {
    host_name: row.host_name,
    detection_type: 1,
    id: row.id,
  };
  checkStatusVisible.value = true;
};
watch(
  () => checkStatusVisible.value,
  (val) => {
    if (!val) {
      getTableRows();
    }
  }
);

const goToDetail = (row) => {
  router.push({
    path: "/auto-maintenance/host-manage/detail",
    query: {
      id: row.id,
    },
  });
};

const changeSearch = (val) => {
  state.filter.search = val;
  changePage(1);
}; // 表格关键字筛选

const filterAction = () => {
  changePage(1);
}; // 查询按钮

const filterClear = () => {
  state.filter = {
    time: "",
    search: "",
    page_size: 10,
    page: 1,
  };
  changePage(1);
}; // 重置筛选项

const getTableRows = () => {
  let params = { ...state.filter };
  if (params.time) {
    params.create_date_from = params.time[0];
    params.create_date_to = params.time[1];
  }
  delete params.time;

  $api.autoMaintenance.getHostManageList(params).then((res) => {
    if (res.data.code == 200) {
      let data = res.data.data || [];
      state.tableRows = data;
      state.tableTotal = res.data.total;
    } else {
      ElMessage.error(res.data.data);
    }
  });
}; // 获取表格数据

const changePage = (page) => {
  state.filter.page = page;
  clearSelected();
  getTableRows();
}; // 改变页码

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

const add = () => {
  router.push("/auto-maintenance/host-manage/add");
}; // 新增字典按钮

onBeforeMount(() => {
  getTableRows();
});

const { tableRows, tableTotal, filter } = toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  padding: 0 24px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .main_container {
    height: 100%;
    .filter-group {
      .left-filter {
        flex: 1;
        display: flex;
        justify-content: start;
        flex-wrap: wrap;
      }
      .right-action {
        width: 144px;
        padding-bottom: 16px;
        .el-button {
          width: 64px;
        }
      }
    }

    .table_container {
      height: calc(100% - 70px);
      width: 100%;
      padding: 0 16px;
    }
  }

  .bg_form {
    width: 100%;
    box-sizing: border-box;
    .el-form-item {
      margin-bottom: 24px;
      :deep().el-form-item__label {
        line-height: 36px;
        height: 36px;
      }
      .el-form-item__content {
        width: 100%;
        .el-textarea {
          :deep().el-input__count {
            bottom: -16px;
            right: 4px;
            font-family: Roboto-Regular;
            color: #a9b1c7;
          }
        }
        .bg-switch-ele {
          width: 52px;
          height: 24px;
          :deep().el-switch__core {
            width: 100%;
            height: 24px;
            .el-switch__inner,
            .el-switch__action {
              top: 3px;
            }
          }
        }
      }
    }
  }
}
</style>
