<template>
  <div>
    <CommonTabs :tabs="tabs" v-model:tabValue="currentTabName" :roundOptions="[]">
    </CommonTabs>
    <YaPageContent v-if="isShow" :formData="serchformData" :formColumns="serchColumns" :tableData="tableData"
      :tableColumns="column" :leftButtons="leftButtons" searchLabelWidth="90px" :rightButtons="rightButtons"
      @search="search('init')" @reset="reset" @tableBtnClick="tableBtnClick" @selectionChange="handleSelectionChange"
      :currentPage="page" :pageSize="pageSize" :total="total" @sizeChange="sizeChange" @currentChange="currentChange">
    </YaPageContent>
    <!-- 新增 -->
    <ya-drawer v-if="drawerProps.showDrawer" :drawerProps="drawerProps" @handleEvent="handleEvent" destroy-on-close
      :before-close="handleCloseDrawer">
      <template #content>
        <ya-form label-position="top" @handleEvent="handleEvent" :formColumns="formColumns" labelWidth="100px"
          :formData="formData" :rules="rules" :ref="(el) => {
            if (el) dialogForm = el;
          }
            ">
        </ya-form>
      </template>
    </ya-drawer>
    <!-- 详情 -->
    <ya-drawer :drawerProps="drawerPropsTable" destroy-on-close :showConfirm="false">
      <template #content>
        <ya-table :data="drawerTableData" :column="drawerTableColumn" :currentPage="tablePage" :pageSize="tableSize"
          :total="tableTotal" @sizeChange="tableSizeChange" @currentPageChange="tableCurrentChange">
        </ya-table>
      </template>
    </ya-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, Ref, watch, onMounted, unref } from "vue";
import { ElMessageBox, ElMessage, FormRules } from "element-plus";
import { WarningFilled } from "@element-plus/icons-vue";
import { getDictTypeList } from "../../../api/common";
import {
  getWebSearchList,
  postWebSearchExport,
  postFullList,
  postFullExport,
  getDetailData,
} from "../../../api/monitoring/website/securityAnalysis";
import { handleGetIndex } from "../../../utils/tools";
import { usePermissions } from "../../../composables/usePermissions";
import { useRouter } from "vue-router";
import { downLoadFile } from "../../../utils/utils";
import CommonTabs from "../../../components/CommonTabs/CommonTabs.vue";
import { data } from "dom7";

const tableData = ref([]);
let selectData = ref([]);
const currentTabName = ref(1);
const isShow = ref(true);
const butomData = ref([]);
const safeLevel = ref([]);
const scanType = ref([]);
const fullLevel = ref([]);
const router = useRouter();
const { permissionsButtons } = usePermissions();
usePermissions();
const page = ref(1);
const total = ref(0);
const pageSize = ref(20);
const formData = reactive({});
const leftButtons = ref([]) as any;
const rightButtons = ref([]) as any;
let drawerProps = reactive({
  showDrawer: false,
  title: "新增",
  size: "small",
});
let drawerPropsTable = reactive({
  showDrawer: false,
  title: "详情",
  size: "big",
});
let dialogForm = ref();
let importVisible = reactive({
  showDrawer: false,
  title: "导入文件",
  size: "big",
});
const tabs = ref([
  {
    title: "网站事件类型查询",
    value: 1,
  },
  {
    title: "网站漏洞类型查询",
    value: 2,
  },
]);
// 搜索栏
const serchformData = ref({});
/**
 * @description:网站事件类型搜索表头
 */
const serchColumnsOne = [
  {
    key: "time",
    type: "daterange",
    label: "时间范围",
    valueFormat: "YYYY-MM-DD",
    startPlaceholder: "开始时间",
    endPlaceholder: "结束时间",
    col: 8,
  },
  {
    key: "webUrl",
    type: "input",
    label: "网站名称",
    col: 8,
  },
  {
    key: "detailsUrl",
    type: "input",
    label: "网站域名",
    col: 8,
  },
  {
    key: "eventType",
    type: "select",
    label: "事件类型",
    options: scanType,
    col: 8,
  },
  {
    key: "safetyLevel",
    type: "select",
    label: "安全等级",
    options: safeLevel,
    col: 8,
  },
];
/**
 * @description:网站漏洞类型查询
 */
const serchColumnsTwo = [
  {
    key: "time",
    type: "daterange",
    label: "时间范围",
    valueFormat: "YYYY-MM-DD",
    startPlaceholder: "开始时间",
    endPlaceholder: "结束时间",
    col: 8,
  },
  {
    key: "webUrl",
    type: "input",
    label: "网站名称",
    col: 8,
  },
  {
    key: "holeUrl",
    type: "input",
    label: "网站域名",
    col: 8,
  },
  // {
  //   key: "holeType",
  //   type: "input",
  //   label: "漏洞类型",
  //   col: 8,
  // },
  // {
  //   key: "holeLevel",
  //   type: "select",
  //   label: "漏洞等级",
  //   options: fullLevel,
  //   col: 8,
  // },
];
/**
 * @description: 监听tab切换
 */
watch(currentTabName, () => {
  isShow.value = false;
  nextTick(() => {
    isShow.value = true;
    if (unref(currentTabName) == 1) {
      column.value = columnOne;
      serchColumns.value = serchColumnsOne;
    } else {
      column.value = columnTwo;
      serchColumns.value = serchColumnsTwo;
    }
  });
  tableData.value = [];
  selectData.value = [];
  serchformData.value = {};
  search("init");
});

/**
 * @description: 获取字典
 */
const initDict = () => {
  getDictTypeList({ dictType: "safetyLevel", pid: 144 }).then((res) => {
    res.forEach((item) => {
      item.value = item.dictKey;
      item.label = item.dictName;
    });
    safeLevel.value = res;
  });
  getDictTypeList({ dictType: "eventType", pid: 147 }).then((res) => {
    res.forEach((item) => {
      item.value = item.dictKey;
      item.label = item.dictName;
    });
    scanType.value = res;
  });

  getDictTypeList({ dictType: "holeLevel", pid: 1470 }).then((res) => {
    if (!res) return;
    res.forEach((item) => {
      item.value = item.dictKey;
      item.label = item.dictName;
    });
    fullLevel.value = res;
  });
};

/**
 * @description:获取按钮权限
 */
let getButton = () => {
  let i = handleGetIndex(columnTwo, "prop", "oparation");
  if (butomData.value.indexOf("导出") > -1) {
    leftButtons.value.push({
      text: "批量导出",
      plain: true,
      eventName: function () {
        handleExport();
      },
    });
  }
};
/**
 * @description:获取列表数据
 * @param type {string} - 初始化
 */
const search = (type?) => {
  if (type === "init") {
    page.value = 1;
  }
  let _data = JSON.parse(JSON.stringify(serchformData.value));
  if (_data.time) {
    const [start, end] = _data.time;
    _data["startTime"] = start;
    _data["endTime"] = end;
    delete _data.time;
  }
  _data.pageSize = pageSize.value;
  _data.pageNum = page.value;
  let send;
  if (currentTabName.value == 2) {
    send = postFullList;
  } else {
    send = getWebSearchList;
  }
  if (type === "loading") {
    _data.yaLoading = type;
  }
  send(_data).then((res) => {
    const { code, data } = res || {};
    if (code === 200 && data) {
      tableData.value = data.rows || [];
      total.value = data.total;
    }
  });
};
/**
 * @description:重置
 */
const reset = () => {
  serchformData.value = {};
  search("init");
};
/**
 * @description: 批量导出
 * @param {*} type batch | all
 * @return {*}
 * @author: xuch
 */
const handleExport = async () => {
  if (selectData.value.length === 0) {
    ElMessage.warning("请选择要批量导出的数据");
    return;
  }
  // @ts-ignore
  const data = selectData.value.map((item) => item.id);
  handleExportRequest(data);
};

/**
 * @description: 批量 / 全部 导出请求
 * @param {*} data
 * @return {*}
 * @author: xuch
 */
const handleExportRequest = async (data) => {
  try {
    const params = {
      id: data,
    };
    let send;
    if (currentTabName.value == 2) {
      send = postFullExport;
    } else {
      send = postWebSearchExport;
    }
    const res = await send(params);
    if (res) {
      if (currentTabName.value == 2) {
        downLoadFile(res, `网站漏洞类型查询`);
      } else {
        downLoadFile(res, `网站事件类型查询`);
      }
    }
  } catch (error) {
    console.log(error);
  }
};
/**
 * @description: 网站事件类型查询表头
 */
const columnOne: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "monitorTime",
    label: "监测时间",
    width: "190px",
  },
  {
    prop: "webUrl",
    label: "网站名称",
    minWidth: "120px",
  },
  {
    prop: "detailsUrl",
    label: "网站域名",
    minWidth: "340px",
  },
  {
    prop: "scanType",
    label: "扫描类型",
    minWidth: "120px",
  },
  {
    prop: "eventType",
    label: "事件类型",
    minWidth: "140px",
  },
  {
    prop: "safetyLevel",
    label: "安全等级",
    width: "110px",
  },
  {
    prop: "eventDescribe",
    label: "事件描述",
    minWidth: "220px",
  },
];
/**
 * @description: 网站漏洞类型查询表头
 */
const columnTwo: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "monitorTime",
    label: "监测时间",
    width: "190px",
  },
  {
    prop: "webUrl",
    label: "网站名称",
    width: "120px",
  },
  {
    prop: "holeUrl",
    label: "网站域名",
  },
  {
    prop: "scanType",
    label: "扫描类型",
    width: "120px",
  },
  {
    prop: "holeCount",
    label: "漏洞数量",
    width: "110px",
  },
  {
    prop: "oparation",
    label: "操作",
    width: "80px",
    fixed: "right",
    buttons: [
      {
        title: "详情",
        eventName: function (row) {
          handleOpenDrawer(row.holeDetailUrl);
        },
      },
    ],
  },
  // {
  //   prop: "holeType",
  //   label: "漏洞类型",
  //   width: "140px",
  // },
  // {
  //   prop: "holeLevel",
  //   label: "漏洞等级",
  //   width: "120px",
  // },
  // {
  //   prop: "holeDescribe",
  //   label: "漏洞描述",
  // },
];
const column = ref(columnOne);
const serchColumns = ref(serchColumnsOne);
/**
 * @description: 表格按钮操作
 */
const tableBtnClick = (btn, row) => {
  btn.eventName(row);
};
/**
 * @description: 复选框选中数据
 */
const handleSelectionChange = function (val) {
  selectData.value = val;
};
/**
 * @description:分页查询
 */
const sizeChange = function (val: Number) {
  pageSize.value = val;
  page.value = 1;
  search();
};
/**
 * @description:当前页码切换查询
 */
const currentChange = function (val: Number) {
  page.value = val;
  search();
};

/**
 *
 * @param state {boolean} - false-新增/true-编辑
 * @param data
 */
const handleToggleDrawer = (state?, data?) => {
  drawerProps.title = state ? "修改" : "新增";
  if (data) {
    dialogForm.value = data;
  } else {
    dialogForm.value = {};
  }
  drawerProps.showDrawer = true;
};

// 关闭抽屉
const handleCloseDrawer = async (done) => {
  console.log(11111111111111);

  if (dialogForm.value) {
    await dialogForm.value.resetForm(dialogForm.value.ruleFormRef);
  }
  done();
};

// 抽屉事件
const handleEvent = function (data) {
  if (data.eventName == "errorSubmit") {
    return;
  } else if (data.eventName == "success") {
    handleConfirm();
    return;
  }
};
/**
 * @description:表单内容
 */
const formColumns = reactive([
  {
    key: "eyym",
    type: "input",
    label: "恶意网站地址",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "wz",
    type: "select",
    label: "恶意类型",
    disabled: false,
    options: [],
    col: 24,
    clearable: true,
  },
  {
    key: "ssdw",
    type: "input",
    label: "来源",
    disabled: false,
    col: 24,
    clearable: true,
  },
]);
/**
 * @description 表单规则
 */
const rules = reactive<FormRules>({
  eyym: [{ required: true, message: "请输入恶意网站地址", trigger: "blur" }],
  wz: [{ required: true, message: "请选择恶意类型", trigger: "change" }],
});

/**
 * @description 表单确认
 */
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};

/**
 * @description:页面渲染结束时触发
 */
onMounted(() => {
  permissionsButtons.map((item) => {
    butomData.value.push(item.label);
  });
  getButton();
  search("loading");
  initDict();
});
//打开抽屉
const drawerTableData = ref([]);
const drawerTableColumn = ref([
  {
    prop: "holeUrl",
    label: "网站url",
  },
  {
    prop: "holeType",
    label: "漏洞类型",
  },
  {
    prop: "holeLevel",
    label: "漏洞等级",
    width: "110px",
  },
  {
    prop: "holeDescribe",
    label: "漏洞描述",
  },
]);
//table的分页
const tableTotal = ref(0);
const tableSize = ref(20);
const tablePage = ref(1);
const selectedUrl = ref("");
const tableSizeChange = (val) => {
  tableSize.value = val;
  getTableData(selectedUrl.value);
};
const tableCurrentChange = (val) => {
  tablePage.value = val;
  getTableData(selectedUrl.value);
};
const handleOpenDrawer = (val) => {
  selectedUrl.value = val;
  getTableData(val);
  drawerPropsTable.showDrawer = true;
};
const getTableData = (val) => {
  let params = {
    pageSize: tableSize.value,
    pageNum: tablePage.value,
    holeDetailUrl: val,
  };
  getDetailData(params).then((res) => {
    const { code, data } = res || {};
    if (code === 200 && data) {
      drawerTableData.value = data.rows || [];
      tableTotal.value = data.total;
    }
  });
};
</script>
