<!--
* @Description: 异常特征样本
* @Author: tqh
* @Date: 2022-08-31 17:00
-->

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, unref, nextTick } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { downLoadFile, deepCopy } from '../../../utils/utils';
import { usePermissions } from '../../../composables/usePermissions';
import { useRoute, useRouter } from 'vue-router';
import {
  getList,
  confirmBatch,
  queryPorts,
  queryPortsListByPortName,
  delOne,
  delAll,
} from '../../../api/collection/assetsFound/propertyAudit';
import { getDeptData } from '../../../api/digitalAssets/networkAssets/hostAssets';
import { getLeftTreeJson } from '../../../api/permission/userManagement';
import { getDictTypeList, getDeptList } from '../../../api/common';
import RecordDialog from "../components/recordDialog.vue";
const router = useRouter();
const { permissionsButtons } = usePermissions();
const bottomData = new Map();
const rightButtons = ref([]);
const leftButtons = ref([]);

const getButton = () => {
  if (bottomData.has(400132)) {
    leftButtons.value.push({
      eventName: 'delete',
    });
  }
  // if (bottomData.has(400144)) {
  //   leftButtons.value.push({
  //     text: '批量' + bottomData.get(400144).label,
  //     plain: true,
  //     eventName: 'put',
  //   });
  // }
};
//获取所属部门下拉框数据
const getDepteEvent = () => {
  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);
    });
  });
};
onMounted(() => {
  btnPower();
  getButton();
  getDictList();
  getDepteEvent();
});
/**
 * 按钮权限
 */
const btnPower = () => {
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });
};
// 分页参数
const page = ref(1);
const total = ref(0);
const size = ref(20);

//所属部门
const deptIdArr = ref([]);
const queryFormData = reactive({
  column: '',
  asc: null,
});

// 表格数据
const tableData = ref([]) as any;
const tableColumn: any[] = reactive([
  {
    type: 'selection',
    width: '65px',
    fixed: 'left',
  },
  {
    prop: 'ip',
    type: 'input',
    label: '资产地址',
    search: true,
    tableHide: true,
  },
  {
    prop: 'showIp',
    label: '资产地址',
    minWidth: '180px',
  },
  {
    prop: 'networkAreaCode',
    type: 'select',
    label: '网络域',
    col: 6,
    multiple: true,
    clearable: true,
    collapseTags: true,
    options: [],
    search: true,
    tableHide: true,
  },
  {
    prop: 'networkAreaName',
    label: '网络域',
    minWidth: '180px',
  },
  {
    label: '开放端口数',
    slotName: 'port',
    minWidth: '200px',
  },
  {
    prop: 'assetStatus',
    type: 'select',
    label: '资产状态',
    col: 6,
    multiple: true,
    clearable: true,
    collapseTags: true,
    options: [],
    search: true,
    slotName: 'assetStatus',
    minWidth: '200px',
  },
  {
    prop: 'sourceTypeName',
    label: '资产来源',
    minWidth: '180px',
  },
  {
    prop: 'deptName',
    label: '所属部门',
    minWidth: '180px',
  },
  {
    prop: 'gmtCreate',
    label: '发现时间',
    minWidth: '200px',
    sortable: 'custom',
  },
  {
    prop: 'dept',
    type: 'select',
    multiple: true,
    label: '所属部门',
    options: deptIdArr,
    collapseTags: true,
    clearable: true,
    search: true,
    tableHide: true,
  },
  {
    prop: 'time',
    type: 'daterange',
    label: '发现时间',
    col: 6,
    valueFormat: 'YYYY-MM-DD',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间',
    search: true,
    tableHide: true,
  },
  {
    label: '操作',
    fixed: 'right',
    width: '100px',
    buttons: [
      {
        title: '入库',
        disabled: function (row) {
          // if (bottomData.has(400133)) {
          //   return false;
          // } else {
          //   return true;
          // }
        },
        eventName: 'putStore',
      },
      {
        title: '删除',
        eventName: 'delete',
        disabled: function (row) {
          if (bottomData.has(400132)) {
            return false;
          } else {
            return true;
          }
        },
      },
    ],
  },
]);
/**
 * @description: 表格多选操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const selectData = ref([]);
const handleSelect = (data) => {
  selectData.value = data;
};
/**
 * @description: 获取表格数据
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const getTableData = async (type) => {
  let _data = JSON.parse(JSON.stringify(type))._value;
  if (_data && _data.time) {
    let begin = _data.time[0] + ' 00:00:00';
    let End = _data.time[1] + ' 23:59:59';
    _data.createTimeStart = begin;
    _data.createTimeEnd = End;
    delete _data.time;
  }
  try {
    const params = {
      ..._data,
      ...queryFormData,
    };
    const res = await getList(params);
    if (res.code !== 200) return;
    tableData.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
  }
};
// 排序事件
const handleSortChange = (data) => {
  queryFormData.column = 'ip';
  queryFormData.asc = data.asc;
  multipleTableRef.value.initData();
};
const tableBtnClick = (btn, row) => {
  const { eventName } = btn;
  switch (eventName) {
    case 'put':
    if (selectData.value.length == 0)
        return ElMessage.warning('请选择要入库的数据');
      codeList.value = selectData.value.map((item) => {
        return item.assetCode;
      });
      let isDeptId = Array.from(selectData.value).every((item) => {
        return item.deptId;
      });
      if (!isDeptId) {
        someformData.value = {};
        drawerProps.showDrawer = true;
      } else {
        putStorage();
      }
      break;
    case 'putStore':
      router.push({
        path: './assetsPut',
        query: {
          title: '资产入库',
          code: row.assetCode,
          companyId: row.companyId,
          deptId: row.deptId,
          ipv4: row.ipv4,
          ipv6: row.ipv6,
          networkAreaCode: row.networkAreaCode
        },
      });
      break;
  }
};
const codeList = ref([]);
/**
 * @description 模板提交事件
 * @param eventName 事件名称 export: 批量导出
 * @param data 表单提交数据
 * @param cb  { Function } 组件回调  （ 新增，编辑，删除，上传需要参数: Boolean true(关闭loading,弹窗)/false(关闭loading) ）
 */
 const btnSubmit = (eventName, data, cb) => {
  switch (eventName) {
    case 'batchDelete':
      let ids = selectData.value.map((item) => {
        return item.assetCode;
      });
      handleDel(ids, 'some');
      break;
    case 'delete':
      handleDel(data.assetCode, 'one');
      break;
    case 'add':
      break;
    case 'edit':
      break;
  }
};
/**
 * @description 批量入库
 */
const isSubmitLoading = ref(false);
const putStorage = () => {
  isSubmitLoading.value = true;
  confirmBatch({
    codeList: codeList.value,
    deptId: someformData.value.deptId,
  })
    .then((res) => {
      if (res.code == 200) {
        ElMessage.success('入库成功');
        multipleTableRef.value.initData();
        drawerProps.showDrawer = false;
      }
    })
    .finally(() => {
      isSubmitLoading.value = false;
    });
};
const drawerPropsPort = reactive({
  showDrawer: false,
  title: 'IP信息',
  size: 'small',
  total: 0,
});
const handleDel = async (id, type) => {
  if (type == 'one') {
    delOne({
      code: id,
    }).then((res) => {
      if (res.code == 200) {
        ElMessage.success('删除成功');
        multipleTableRef.value.initData();
      }
    });
  } else {
    delAll(id).then((res) => {
      if (res.code == 200) {
        ElMessage.success('删除成功');
        multipleTableRef.value.initData();
      }
    });
  }
};
/**
 * @description: 字典数据初始化
 */
const resetDictData = (e) => {
  let list = e.map((item) => {
    return {
      label: item.dictName,
      value: item.dictValue,
    };
  });
  return list;
};
/**
 * @description: 获取字典数据
 */
const getDictList = () => {
  // 网络域
  getDictTypeList({ dictType: 'networkArea' }).then((res) => {
    if (res.code == 200) {
      tableColumn.forEach((item) => {
        if (item.prop == 'networkAreaCode') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });

  // 资产状态
  getDictTypeList({ dictType: 'assetStatus' }).then((res) => {
    if (res.code == 200) {
      tableColumn.forEach((item) => {
        if (item.prop == 'assetStatus') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
    // 获取部门层级
    getLeftTreeJson().then((res) => {
    const { code, data } = res || {};
    if (code === 200) {
      someformColumns.value.forEach((item) => {
        if (item.key == 'deptId') {
          data.treeData &&
            data.treeData.forEach((child) => {
              child.value = child.id;
            });
          item.options = data.treeData || [];
        }
      });
      // deptListArr.value = data.treeData || [];
    }
  });
};
const tableDataPort = ref([]);
const columnPort = ref([
  {prop: 'id', label: '序号'},
{ prop: 'port', label: '端口',sortable:'custom' },
  { prop: 'serve', label: '服务' },
]);
const tablePage = ref(1);
const totalPort = ref(0);
const childDialog=ref()
const assetCode = ref('');
const handlerPortDrawer = (data) => {
  assetCode.value = data.assetCode;
  getPortTable();
  childDialog.value.dialogProps.title="开放端口信息";
  childDialog.value.openDialog();
};
//获取端口
const getPortTable = (data?) => {
  let params = {
    ...data,
    hostCode: assetCode.value,
    pageIndex:tablePage.value,
    pageSize:20
  };
  queryPorts(params).then((res) => {
    if (res.code == 200) {
      tableDataPort.value = res.data.records;
      res.data.records?.forEach((item, index) => {
        tableDataPort.value[index].serve = item.feature.serviceName;
        item.id =  Number(
            (tablePage.value - 1) * 20 + index + 1 > 9
              ? (tablePage.value - 1) *  20 + index + 1
              : `${(tablePage.value - 1) *  20 + index + 1}`
          );
      });
      totalPort.value = res.data.total;
    }
  });
};

//ip信息的翻页
const tableCurrentChange=(val:number)=>{
  tablePage.value=val
  getPortTable()
}
//input框值变化查询
const getPortSearch=(e,sort,prop)=>{
  getPortTable({
    port:e,
    asc:sort,
    column:prop
  })
}
//排序事件
const handlerToSort=(e,sort,prop)=>{
  getPortTable({
    port:e,
    asc:sort,
    column:prop
  })
}
const someformData = ref({});
const someformColumns = ref([
  {
    key: 'deptId',
    type: 'cascader',
    props: {
      checkStrictly: true,
      value: 'id',
      emitPath: false,
    },
    showAllLevels: false,
    label: '所属部门',
    col: 24,
    placeholder: '请选择所属部门',
    options: [],
    clearable: true,
  },
]);
const somerules = reactive<FormRules>({
  deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
});

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 清空选择的值
const clearSelect = () => {
  multipleTableRef.value.getTableMethods().clearSelection();
};
const drawerProps = reactive({
  showDrawer: false,
  title: '入库',
  size: 'small',
});
const somedialogForm = ref();
const somehandleConfirm = () => {
  somedialogForm.value.submitForm(somedialogForm.value.ruleFormRef);
};
const handleDrawerEvent = (data) => {
  const { eventName = '' } = data;
  // 抽屉点击确定按钮
  console.log(eventName);
  if (eventName === 'success') {
    somehandleConfirm(somedialogForm.value);
  } else if (data.eventName == 'successSubmit') {
    putStorage();
  }
};
const handleCloseDrawer = async (done) => {
  done();
};
</script>

<template>
  <div>
    <YaPageContent
      ref="multipleTableRef"
      :total="total"
      :tableData="tableData"
      :tableColumns="tableColumn"
      :buttons="leftButtons"
      :rightButtons="rightButtons"
      @sortChange="handleSortChange"
      @init="getTableData"
      @tableBtnClick="tableBtnClick"
      @selectionChange="handleSelect"
      @submit="btnSubmit"
    >
      <!-- 开放端口数 -->
      <template #port="{item}">
        <div
          class="colection-obj text-hover"
          v-if="item.feature.portNum"
          @click="handlerPortDrawer(item)"
        >
          {{ item.feature.portNum }}
        </div>
        <div v-else>-</div>
      </template>
      <!-- 资产来源 -->
      <!-- <template #sourceType="{ item }">
        <div v-if="item.sourceTypeName">
          {{ item.sourceTypeName }}
          <span v-if="item.feature.sourceTaskName">-</span>
          {{ item.feature.sourceTaskName }}
        </div>
        <div v-else>-</div>
      </template> -->
      <!-- 资产状态 -->
      <template #assetStatus="{ item }">
        <div class="survival" v-if="item.assetStatus == 'survive'">
          <img
            src="../../../assets/image/collection/survive.png"
            class="position-survive"
            alt=""
          />
          存活
        </div>
        <div class="offline" v-if="item.assetStatus == 'offLine'">
          <img
            src="../../../assets/image/collection/offLine.png"
            class="position-survive"
            alt=""
          />
          离线
        </div>
        <div class="abnormal" v-if="item.assetStatus == 'abnormal'">
          <img
            src="../../../assets/image/collection/abnormal.png"
            class="position-survive"
            alt=""
          />
          异常
        </div>
      </template>
    </YaPageContent>
      <!-- 开放端口数 -->
      <RecordDialog ref="childDialog" :type="2" placeholder="请输入端口"
      :tableDataList="tableDataPort" :tableColumn="columnPort" layout=" prev, pager, next"
      :tableTotal="totalPort" :tablePage="tablePage"  @onSearch="getPortSearch"
      @currentChangeOne="tableCurrentChange" @sortChange="handlerToSort"/>
    <ya-drawer
      size="480px"
      :drawerProps="drawerProps"
      @handleEvent="handleDrawerEvent"
      destroy-on-close
      :before-close="handleCloseDrawer"
      :loading="isSubmitLoading"
    >
      <template #content>
        <ya-form
          label-position="left"
          @handleEvent="handleDrawerEvent"
          :formColumns="someformColumns"
          labelWidth="100px"
          :formData="someformData"
          :rules="somerules"
          :ref="
            (el) => {
              if (el) somedialogForm = el;
            }
          "
        >
        </ya-form>
      </template>
    </ya-drawer>
  </div>
</template>

<style scoped lang="scss">
@import '../../../style/popUp.scss';
.survival {
  color: var(--el-color-success);
}
.offline {
  color: var(--el-color-info);
}
.abnormal {
  color: #f99c6a;
}
.position-survive {
  position: relative;
  top: 5px;
}
.colection-obj {
  color: var(--el-color-primary);
  font-size: 14px;
  font-weight: 400;
  text-decoration: underline;
}

.colection-obj:hover {
  cursor: pointer;
}

.collection-type {
  width: 100%;
}
::v-deep .el-radio {
  margin-bottom: 8px;
  margin-right: 10px;
}
.login-content {
  width: 100%;
  .login-content-center {
    background: var(--el-bg-color);
    border-radius: 4px;
    padding: 15px;
  }
  .new-form-item-input {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    width: 100%;
    ::v-deep .el-form-item__label {
      margin-bottom: 0 !important;
      width: 100px !important;
    }
  }
  .login-content-center .new-form-item-input:last-child {
    margin-bottom: 0;
  }
}
.gatherType-label {
  font-size: var(--el-form-label-font-size);
  color: var(--el-text-color-primary);
  width: 100px;
}

.gather-label {
  ::v-deep .el-form-item__content {
    display: block !important;
    margin-bottom: 16px;
  }
  ::v-deep .el-form-item__error {
    left: 100px;
  }
}
.slot-flex {
  display: flex;
  .m-l-12 {
    // margin-left: 12px;
  }
  .m-l-25 {
    margin-left: 25px;
  }
}
.label-form,
.label-form-item {
  font-size: var(--el-form-label-font-size);
  color: var(--el-text-color-primary);
  font-weight: 400;
  width: 100px;
  display: flex;
  align-items: center;
  height: 32px;
  line-height: 1.2;
  padding-right: 12px;
  box-sizing: border-box;
}
.label-form::before {
  content: '*';
  color: var(--el-color-danger);
  margin-right: 4px;
}
.QuestionFilled {
  position: relative;
  top: 2px;
  fill: rgba(0, 0, 0, 0.8);
}
.mb-16 {
  margin-bottom: 12px;
}
.tcp-radio {
  margin-right: 10px;
}
.mt-12 {
  margin-bottom: 12px;
}
.mb-5 {
  margin-bottom: 5px;
}
.scan-port-chose {
  display: flex;
  align-items: center;
  .scan-switch {
    margin: 0 5px;
  }
}
.QuestionFilled1 {
  position: relative;
  left: 4px;
}
.flex-bt {
  display: flex;
  justify-content: space-between;
  ::v-deep .el-checkbox__label {
    width: 112px;
  }
}
.ping-port {
  display: flex;
  ::v-deep .el-input {
    width: 91%;
  }
}
.flex-one {
  flex: 1;
}
.mt-6 {
  margin-top: 8px;
}
.flex-st-x {
  display: flex;
  align-items: center;
}
.port-list {
  color: var(--el-color-primary);
  font-weight: 400;
  text-decoration: underline;
  cursor: pointer;
}
.mt-8 {
  margin-bottom: 8px;
}
::v-deep .el-form > .el-form-item {
  margin-bottom: 16px;
}
.login-content-show {
  position: relative;
  left: -100px;
  width: calc(100% + 100px);
}
.flex-x-bt {
  display: flex;
}
.m-l-12 {
  // margin-left: 12px;
}

::v-deep .el-form-item__label {
  align-items: center;
  line-height: 1.2;
}
.m-t-12 {
  margin-top: 12px;
}
.custom-left {
  position: relative;
  top: 6px;
  align-items: flex-start;
}
.custom-svg {
  left: -4px;
}
</style>
