<template>
  <div class="detail-warp">
    <div :class="showBtn?'detail-content':'detail-content-top'">
      <div class="detail-top">
        <YaTabs
          v-if="showBtn"
          :tabs="detailTabs"
          v-model="detailCurrentName"
          @tabChange="detailTabChange"
        ></YaTabs>
        <div class="detail-top-btn" v-if="showBtn">
          <ya-button
            type="primary"
            @click="operation('study')"
            v-if="baseInfo.status == 0 && butomData.has(220101)"
            >研判</ya-button
          >
          <ya-button
            type="primary"
            @click="operation('issure')"
            v-if="baseInfo.status == 1 && butomData.has(220102)"
            >下发</ya-button
          >
          <ya-button
          @click="download"
            type="primary"
            :loading="isLoading"
            >下载pcap包</ya-button
          >
          <div class="detail-top-back" >
            <div class="detail-top-back-icon" :class="btnTop?'detail-top-back-icon-active':''" @click="btnTop?checkPage('top'):''">
              <el-icon><Back /></el-icon>
            </div>
            <div class="detail-top-back-icon" :class="btnBottom?'detail-top-back-icon-active':''" @click="btnBottom?checkPage('bottom'):''">
              <el-icon><Right /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ThreatAlarmsDetail
      ref="detailRef"
      @getValue="getValue"
      :baseInfo="baseInfo"
      :origin="origin"
      v-if="detailCurrentName == 1"
    ></ThreatAlarmsDetail>
    <Rawlog ref="RawlogRef" :originalInfo="detailInfo" :origin="origin" v-if="detailCurrentName == 2"></Rawlog>
    <ResponseDisposal  ref="ResponseDisposalRef" :originalInfo="detailInfo" v-if="detailCurrentName == 3"></ResponseDisposal>
    <SourceIpEvent
      ref="SourceIpEventRef"
      :originalInfo="detailInfo"
      v-if="detailCurrentName == 4 || detailCurrentName == 5"
      :tab="detailCurrentName == 4 ? 1 : 2"
    ></SourceIpEvent>

    <ya-drawer
      v-if="drawerProps.showDrawer"
      :drawerProps="drawerProps"
      @handleEvent="handleEvent"
      destroy-on-close
      size="450px"
      :before-close="handleCloseDrawer"
      :loading="isLoadingBtn"
    >
      <template #content>
        <div style="margin-top: 16px">
          <OperateDialog
          @resetLoading="resetLoading"
          :loading="isLoadingBtn"
            ref="operateDialogRef"
            :info="operateInfo"
            :type="drawerProps.title == '研判' ? 1 : 2"
            @closeF="handleCloseDrawer"
          ></OperateDialog>
        </div>
      </template>
    </ya-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, unref, defineProps, reactive, defineEmits, nextTick } from "vue";
import { Right, Back } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage, FormRules } from "element-plus";
import ThreatAlarmsDetail from "./threatAlarmsDetail.vue";
import ResponseDisposal from "./ResponseDisposal.vue";
import SourceIpEvent from "./SourceIpEvent.vue";
import Rawlog from "./Rawlog.vue";
import OperateDialog from "./componets/operateDialog.vue";
import { usePermissions } from "../../composables/usePermissions";
import {downLoadAllFile} from "../../utils/utils"
import {
  getBasicInfo,
  getPage,
  getIpCorrelationInfo,
  getDisposalInfo,
  getNext,
  getPcap
} from "../../api/threatAlarms/threatAlarms";
import { debug } from "console";
const { permissionsButtons } = usePermissions();
const butomData: any = ref(new Map());
interface Props {
  searchObj?:Object, // 搜索条件
  info?:Object; // 详情查询数据
  original?: Object; // 原始日志数据
  showBtn?: Boolean; // 
  origin?: String; // flow--探针  situation--感知平台
}
const { showBtn = true, origin = "situation", info = {}, original = {}, searchObj = {} } = defineProps<Props>();
const emit = defineEmits(["closeF",'resetLoading']);
let tabFlowList = [
  { title: "基本信息", value: 1 },
  { title: "源IP关联事件", value: 4 },
  { title: "目的IP关联事件", value: 5 },
  { title: "原始日志", value: 2 },
  { title: "响应处置", value: 3 },
];
let tabFlowList1 = [
  { title: "基本信息", value: 1 },
  { title: "原始日志", value: 2 },
  { title: "响应处置", value: 3 },
];
const detailTabs = ref(tabFlowList1);
if (unref(origin) == "situation") {
  detailTabs.value = tabFlowList;
} else {
  detailTabs.value = tabFlowList1;
}

const detailCurrentName = ref(1);
const detailTabChange = (name) => {
  console.log("detailTabChange", name);
  init()
};
/**
 * @description 获取研判状态
 */
const getValueInfo = ref({
  status: "",
  isDown: "",
});
const getValue = (e) => {
  getValueInfo.value = e;
};
/**
 * @description 操作
 */
const detailRef = ref(null);
const operation = (e) => {
  if (e == "study") {
    drawerProps.title = "研判";
    drawerProps.showDrawer = true;
  } else {
    drawerProps.title = "下发";
    drawerProps.showDrawer = true;
  }
};
// 获取按钮权限
const getButton = () => {
  permissionsButtons.map((item) => {
    butomData.value.set(item.menuId, item);
  });
};
/**
 * @description 初始化调用接口
 */
const baseInfo = ref({});
const detailInfo = ref({});
const operateInfo = ref({
  ids: [],
  dates: []
})
const btnTop = ref(false);
const btnBottom = ref(false);
const alarmTime = ref('')
const objInfo = ref({
  id: '',
  date: '',
})
const init = ()=> {
  switch (detailCurrentName.value) {
    case 1:
      getBasicInfo({id:objInfo.value.id,date:objInfo.value.date}).then(res=>{
        if(res.code == 200) {
          alarmTime.value = res.data.alarmTime;
          baseInfo.value = res.data;
        }
      })
      break;
    case 4:
      nextTick(()=>{
        SourceIpEventRef.value.init()
      })
    break
    case 5:
      nextTick(()=>{
        SourceIpEventRef.value.init()
      })
    break
  }
}

// 弹窗
const drawerProps = reactive({
  showDrawer: false,
  title: "研判",
  size: "small",
});
/**
 * @description 关闭抽屉
 */
const handleCloseDrawer = async () => {
  drawerProps.showDrawer = false;
  init();
  emit("closeF");
};
const operateDialogRef = ref();
/**
 * @description 抽屉事件
 */
const isLoadingBtn = ref(false);
const handleEvent = function (data) {
  // isLoadingBtn.value = true;
  operateDialogRef.value.handleEvent(data);
};
const resetLoading = () => {
  isLoadingBtn.value = !isLoadingBtn.value;
  emit("resetLoading")
}
/**
 * @description 分页切换
 */
const RawlogRef = ref(null);
const ResponseDisposalRef = ref(null);
const SourceIpEventRef = ref(null)
const checkPage = (e) => {
  let next = true;
  if(e == 'top') {
    next = false
  } else {
    next = true
  }
  let parms = {
    ...unref(searchObj)
  }
  parms.id = objInfo.value.id
  getNext({
    ...parms,
    date:alarmTime.value,
    next: next
  }).then((res)=>{
    if(res.code == 200) {
      btnTop.value = res.data.top;
      btnBottom.value = res.data.bottom;
      objInfo.value.id = res.data.id;
      objInfo.value.date = res.data.alarmTime;
      detailInfo.value = res.data;
      operateInfo.value.ids = [res.data.id];
      operateInfo.value.dates = [res.data.alarmTime];
      init()
      if(detailCurrentName.value == 2) {
        nextTick(()=>{
          RawlogRef.value.init('')
        })
      } else if (detailCurrentName.value == 3) {
        nextTick(()=>{
          ResponseDisposalRef.value.init()
        })
      } else if (detailCurrentName.value == 4 || detailCurrentName.value == 5) {
        nextTick(()=>{
          SourceIpEventRef.value.init()
        })
      }
    }
  })
}
/**
 * @description 数据初始值
 */
const resetData = () => {
  detailInfo.value = unref(info);
  btnTop.value = detailInfo.value.top;
  btnBottom.value = detailInfo.value.bottom;
  operateInfo.value.ids.push(detailInfo.value.id);
  operateInfo.value.dates.push(detailInfo.value.alarmTime);
  objInfo.value.id = unref(info).id;
  objInfo.value.date = unref(info).alarmTime;
  alarmTime.value = unref(info).alarmTime;
}
/**
 * @descripiton pcap下载
 */
const isLoading = ref(false)
const download = async() => {
  isLoading.value = true;
  getPcap({
    eventId: baseInfo.value.eventId,
    date: baseInfo.value.alarmTime,
  }).then((res)=>{
    isLoading.value = false;
    const reader = new FileReader()
      reader.readAsText(res, 'utf-8')
      reader.addEventListener('loadend', function () {
        if (typeof reader.result === 'string') {
          try {
          let data = JSON.parse(reader.result)
          if(data.code == 200) {
            downLoadAllFile(res, baseInfo.value.eventName+'.pcap');
          } else {
            ElMessage.error(data.message)
          }
          } catch (error) {
            downLoadAllFile(res, baseInfo.value.eventName+'.pcap');
          }
        }
      })
  }).catch(()=>{
    isLoading.value = false;
  })
  try {
    // let res = await getPcap({
    //   eventId: baseInfo.value.eventId,
    //   date: baseInfo.value.alarmTime,
    // });
    // console.log(res)
    // const reader = new FileReader()
    //   reader.readAsText(res, 'utf-8')
    //   reader.addEventListener('loadend', function () {
    //     if (typeof reader.result === 'string') {
    //       try {
    //       let data = JSON.parse(reader.result)
    //       if(data.code == 200) {
    //         downLoadAllFile(res, baseInfo.value.eventName+'.pcap');
    //       } else {
    //         ElMessage.error(target.message)
    //       }
    //       } catch (error) {w
    //         console.log('捕捉到json错误 :>> ', error)
    //       }
    //     }
    //   })


    // const fileReader = new FileReader()
    // fileReader.readAsText(res, 'utf-8');
    // fileReader.onload = function (result) {
    //   try {
    //     let target = JSON.parse(result.target.result);
    //     if (target.code == 200) {
    //       downLoadAllFile(res, baseInfo.value.eventName+'.pcap');
    //     } else {
    //       ElMessage.error(target.message)
    //     }
    //   } catch (err) {
    //     downLoadAllFile(res, baseInfo.value.eventName+'.pcap');
    //   }
    // }
  } catch (error) {

  }
}
onMounted(() => {
  resetData()
  getButton();
  init()
});
</script>
<style lang="scss" scoped>
.detail-warp {
  // padding-top: 20px;
  .detail-content-top {
    padding-top: 20px;
  }
  .detail-content {
    position: sticky;
    top: 0px;
    background: var(--el-bg-color-panel);
    height: 50px;
    z-index: 10;
    margin-bottom: 12px;
    padding-top: 10px;
  }
  .detail-top {
    position: relative;
    .detail-top-btn {
      position: absolute;
      right: 0;
      top: 0;
      display: flex;
      align-items: center;
    }
    .detail-top-back {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 33px;
      .detail-top-back-icon {
        width: 32px;
        height: 32px;
        background: #bac8cd;
        box-shadow: 0px 0px 8px 0px rgba(24, 90, 126, 0.24);
        border-radius: 50%;
        font-size: 24px;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 23px;
      }
      .detail-top-back-icon-active {
        background: var(--el-color-primary);
        cursor: pointer;
      }
    }
  }
}
</style>
