<!--
 * @Author: 曹文丽 caowenli@yuan-info.com
 * @Date: 2022-11-01 09:10:04
 * @LastEditors: 曹文丽 caowenli@yuan-info.com
 * @LastEditTime: 2023-08-18 17:13:47
 * @FilePath: \yuan-huoling-browser\src\views\digitalAssets\hostAssets.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE

-->
<template>
  <div class="yaBox">
    <YaPageContent
      :pageCache="true"
      :tableData="tableData"
      :tableColumns="column"
      :buttons="buttons"
      @init="initData"
      @tableBtnClick="tableBtnClick"
      @selectionChange="handleSelectionChange"
      :total="total"
      @sortChange="handleSortChange"
    >
      <template v-slot:ipv4="{ item }">
        <div class="ya-ipv" @click="goToApplication(item)">
          {{ item.ipv4 || '-' }}
        </div>
      </template>
      <template v-slot:ipv6="{ item }">
        <div class="ya-ipv" @click="goToApplication(item)">
          {{ item.ipv6 || '-' }}
        </div>
      </template>
      <template v-slot:state="{ item }">
        <div v-if="item.assetStatus == 'survive'" class="ya-status">
          <img src="../../../assets/imgs/cunhuo.png" alt="" class="ya-img" />
          <span class="ya-alive">存活</span>
        </div>
        <div v-else-if="item.assetStatus == 'offLine'" class="ya-status">
          <img src="../../../assets/imgs/lixian.png" alt="" class="ya-img" />
          <span class="ya-offline">离线</span>
        </div>
        <div v-else-if="item.assetStatus == 'abnormal'" class="ya-status">
          <img src="../../../assets/imgs/yichang.png" alt="" class="ya-img" />
          <span class="ya-abnormal">异常</span>
        </div>
        <div v-else>-</div>
      </template>
      <template v-slot:level="{ item }">
        <div v-if="item.riskLevel == 'low'" class="ya-status">
          <img src="../../../assets/imgs/diwei.png" alt="" class="ya-img" />
          <span>低危</span>
        </div>
        <div v-else-if="item.riskLevel == 'middle'" class="ya-status">
          <img src="../../../assets/imgs/middle.png" alt="" class="ya-img" />
          <span>中危</span>
        </div>
        <div v-else-if="item.riskLevel == 'high'" class="ya-status">
          <img src="../../../assets/imgs/gaowei.png" alt="" class="ya-img" />
          <span>高危</span>
        </div>
        <div v-else-if="item.riskLevel == 'safe'" class="ya-status">
          <img src="../../../assets/imgs/ssafe.png" alt="" class="ya-img" />
          <span>安全</span>
        </div>
        <div v-else-if="item.riskLevel == 'unknown'" class="ya-status">
          <img src="../../../assets/imgs/sunknow.png" alt="" class="ya-img" />
          <span>未知</span>
        </div>
        <div v-else>-</div>
      </template>
    </YaPageContent>
    <YaDialogForm
      v-if="dialogProps.showDialog"
      :dialogProps="dialogProps"
      :formColumns="formColumns"
      @submit="handleExportSubmit"
    >
    </YaDialogForm>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue';
import { usePermissions } from '../../../composables/usePermissions';
import { useRouter } from 'vue-router';
import { getDictList, downLoadFile } from '../../../utils/utils';
import { yaMessage } from '../../../utils/message';
import {
  queryHostAssets,
  batchExp,
  addDataExp,
} from '../../../api/digitalAssets/networkAssets/hostAssets';
import { ElTable } from 'element-plus';
import { getDeptData } from '../../../api/digitalAssets/networkAssets/hostAssets';
const router = useRouter();
const { permissionsButtons } = usePermissions();
// 从后端获取来的列表区域的内容
let tableData = ref([]);

//点击多选框选中的行的数据
let selectData = ref([]);
//按钮的数据
let bottomData: any = new Map();

//按钮
let buttons: any = ref([]);

//一共多少条数据
const total = ref(0);
// 搜索筛选出的条件 demo
const searchData = ref({
  column: '',
  asc: null,
});

//资产类型
const assetTypeArr = ref([]);
//资产状态
const assetStatusArr = ref([]);
//风险等级
// const riskLevelArr = ref([]);
//弹框的文件类型
const fileTypeArr = ref([]);
//网络域
const networkAreaArr = ref([]);
//所属部门
const deptIdArr = ref([]);

//列表区域的表头
const column: any[] = reactive([
  {
    type: 'selection',
    width: '65px',
  },
  {
    prop: 'ipv4',
    label: 'IPv4',
    slotName: 'ipv4',
    minWidth: '150px',
    sortable: 'custom',
    type: 'input',
  },
  {
    prop: 'ipv6',
    label: 'IPv6',
    slotName: 'ipv6',
    minWidth: '150px',
  },
  {
    prop: 'target',
    label: '资产IP',
    isType: 'ipv4',
    customType: 'ipv4',
    search: true,
    type: 'input',
    tableHide: true,
  },
  // {
  //   prop: "domain",
  //   label: "域名",
  //   minWidth: "160px",
  // },
  {
    prop: 'name',
    label: '资产名称',
    minWidth: '200px',
    type: 'input',
    search: true,
  },
  {
    prop: 'networkAreaName',
    label: '网络域',
    minWidth: '120px',
  },
  {
    prop: 'networkAreaCodeSet',
    type: 'select',
    label: '网络域',
    options: networkAreaArr,
    search: true,
    tableHide: true,
  },
  {
    prop: 'assetTypeName',
    label: '资产类型',
    minWidth: '140px',
  },
  {
    prop: 'assetTypeSet',
    type: 'select',
    label: '资产类型',
    options: assetTypeArr,
    multiple: true,
    collapseTags: true,
    clearable: true,
    search: true,
    tableHide: true,
  },
  // {
  //   prop: "os",
  //   label: "操作系统",
  //   width: "120px",
  // },
  // {
  //   prop: "gatherType",
  //   label: "采集方式",
  //   minWidth: "120px",
  // },
  {
    prop: 'assetStatus',
    label: '资产状态',
    slotName: 'state',
    width: '110px',
  },
  {
    prop: 'assetStatusSet',
    type: 'select',
    label: '资产状态',
    options: assetStatusArr,
    search: true,
    tableHide: true,
  },
  // {
  //   prop: "riskLevel",
  //   label: "风险等级",
  //   slotName: "level",
  //   width: "110px",
  // },
  // {
  //   prop: "assetTagNameSet",
  //   label: "资产标签",
  //   slotName: "tag",
  //   minWidth: "280px",
  // },
  {
    prop: 'deptName',
    label: '所属部门',
    minWidth: '130px',
  },
  {
    prop: 'deptIdSet',
    type: 'select',
    multiple: true,
    label: '所属部门',
    options: deptIdArr,
    collapseTags: true,
    clearable: true,
    search: true,
    tableHide: true,
  },
  {
    prop: 'findTime',
    type: 'daterange',
    label: '更新时间',
    valueFormat: 'YYYY-MM-DD',
    placeholder: '选择日期',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间',
    search: true,
    tableHide: true,
  },
  {
    prop: 'gmtModified',
    label: '更新时间',
    width: '190px',
  },
  {
    prop: 'oparation',
    label: '操作',
    width: '60px',
    fixed: 'right',
    buttons: [
      {
        title: '详情',
        icon: 'src/assets/imgs/do.png',
        eventName: 'detail',
        hide: () => {
          return bottomData.has(20005);
        },
      },
    ],
  },
]);

// 获取列表数据 (根据搜索条件重新渲染列表)
const initData = (data?) => {
  if (sessionStorage.getItem('YA_FORM_DATA')) {
    searchData.value = JSON.parse(sessionStorage.getItem('YA_FORM_DATA'));
    sessionStorage.removeItem('YA_FORM_DATA');
  }
  let _data = { ...searchData.value, ...data?.value };
  if (_data.findTime) {
    _data.modifiedTimeStart = _data.findTime[0];
    _data.modifiedTimeEnd = _data.findTime[1];
    delete _data.findTime;
  }
  _data.assetTypeSet = _data.assetTypeSet?.toString() || [];
  _data.deptIdSet = _data.deptIdSet?.toString() || [];
  allRequestData.value.request = { ..._data };
  queryHostAssets(_data).then((res) => {
    const { code, data = {} } = res;
    if (code == 200) {
      data.records.forEach((item) => {
        item.gatherType = '';
        item.gatherTypeNameSet.forEach((child) => {
          item.gatherType += child + '/';
        });
        item.gatherType = item.gatherType.substring(
          0,
          item.gatherType.length - 1
        );
      });
      tableData.value = data.records || [];
      total.value = data.total;
    }
  });
};
// 排序事件
const handleSortChange = (data) => {
  searchData.value.column = 'ip';
  searchData.value.asc = data.asc;
  initData();
};
//页面挂载
onMounted(() => {
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });
  getButton();
  initDict();
  // 操作处宽度的自适应
  column.length = bottomData.has(20005) ? column.length : column.length - 1;
});

//选中的行的信息
const handleSelectionChange = function (val) {
  selectData.value = val;
};
// 页面按钮事件执行
const tableBtnClick = (btn, row) => {
  let { eventName } = btn || {};
  switch (eventName) {
    case 'detail':
      sessionStorage.setItem('YA_FORM_DATA', JSON.stringify(searchData.value));
      router.push({
        path: './hostAssets/adetail',
      });
      break;
    case 'export':
      batchExport('part');
      break;
    case 'allExport':
      batchExport('all');
      break;
  }
};
/**
 * 弹窗
 */

//弹窗是否显示
let dialogProps = reactive({
  showDialog: false,
  title: '选择格式',
  size: '',
});

//弹框的表单数据
const formColumns = ref([
  {
    key: 'fileType',
    type: 'select',
    label: '选择格式',
    col: 24,
    options: fileTypeArr,
    rules: true,
  },
]);

//批量导出
let getButton = () => {
  if (bottomData.has(200011)) {
    buttons.value.push({
      custom: 'dropdown',
      title: bottomData.get(200011).label,
      customData: [
        {
          name: '批量' + bottomData.get(200011).label,
          eventName: 'export',
        },
        {
          name: '全部' + bottomData.get(200011).label,
          eventName: 'allExport',
        },
      ],
    });
  }
};
const batchCode: any = ref({});
const allRequestData: any = ref({});
let exportType = ref(true);
//导出事件
const batchExport = function (type) {
  if (tableData.value.length != 0) {
    if (type == 'part') {
      if (selectData.value.length == 0) {
        yaMessage('请选择要批量导出的数据', 'warning');
        return;
      } else {
        exportType.value = true;
        dialogProps.showDialog = true;
        batchCode.value.codeSet = selectData.value?.map((item) => item.code);
      }
    } else {
      exportType.value = false;
      dialogProps.showDialog = true;
      allRequestData.value.request = {
        ...allRequestData.value.request,
        ...searchData.value,
      };
    }
  }
};
// 导出
const handleExportSubmit = (obj, resolve) => {
  let query = exportType.value ? batchExp : addDataExp;
  let params = exportType.value ? batchCode.value : allRequestData.value;
  params.fileType = obj.fileType;
  params.fileName = '主机资产';

  query(params)
    .then((res) => {
      downLoadFile(res, '主机资产', obj.fileType);
      yaMessage('导出成功', 'success');
      dialogProps.showDialog = false;
    })
    .finally(() => {
      resolve();
    });
};

//字典
const initDict = async () => {
  fileTypeArr.value = (await getDictList('excelType')) as [];
  // riskLevelArr.value = (await getDictList("riskLevel")) as [];
  networkAreaArr.value = (await getDictList('networkArea')) as [];
  assetTypeArr.value = (await getDictList('assetType')) as [];
  assetStatusArr.value = (await getDictList('assetStatus')) as [];
  //获取所属部门下拉框数据
  getDeptData().then((res) => {
    const { data = {} } = res;
    data?.forEach((item) => {
      let obj = ref({});
      obj.value.label = item.deptName;
      obj.value.value = item.id;
      deptIdArr.value.push(obj.value);
    });
  });
};
//去应用页面
const goToApplication = function (val) {
  localStorage.setItem('YA_HOST_ASSET_DATA', JSON.stringify(val));
  router.push({
    path: './hostAssets/yappl',
  });
};
</script>
<style lang="scss" scoped>
.ya-ipv {
  color: #0095ff;
  cursor: pointer;
}
img {
  width: 18px;
  height: 18px;
  vertical-align: middle;
}
.ya-img {
  margin-right: 8px;
}
.ya-tag {
  display: flex;
  height: 100%;
  align-items: center;
  border: none;
  background-color: transparent;
}
.ya-tag1,
.ya-tag2,
.ya-tag3,
.ya-num {
  border-radius: 2px;
  line-height: 24px;
  padding: 2px 8px;
}
.ya-tag1 {
  background: rgba(#3cd597, 0.1);
  color: #3cd597;
  margin-right: 12px;
}
.ya-tag2 {
  background: #fdf6ec;
  color: #da8302;
  margin-right: 12px;
}
.ya-tag3 {
  background: #ecf5ff;
  color: #0079eb;
  margin-right: 12px;
}
.ya-num {
  background: rgba(0, 149, 255, 0.12);
  color: #0095ff;
}
.ya-alive {
  color: #55cd79;
}
.ya-offline {
  color: #afafaf;
}
.ya-abnormal {
  color: #f99c6a;
}
.ya-cursor {
  cursor: pointer;
}
.ya-status {
  display: flex;
  align-items: center;
}
</style>
