<!--
 * @Author: 曹文丽 caowenli@yuan-info.com
 * @Date: 2023-09-15 15:26:46
 * @LastEditors: 曹文丽 caowenli@yuan-info.com
 * @LastEditTime: 2023-09-21 16:30:38
 * @FilePath: \yuan-asset-module-browser\src\views\collection\assetAddress.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ref, reactive, nextTick, Ref, watch, onMounted } from 'vue';
import { usePermissions } from '../../composables/usePermissions';
import { http } from '@/utils/https';
import { getDeptData } from '../../api/digitalAssets/networkAssets/hostAssets';
import { getDictList } from '../../utils/utils';
import {
  getList,
  postAddIpLibrary,
  postModifyIpLibrary,
  getDelIpLibrary,
  postDelBatch,
  postDelAll,
  importByExcel,
  exportBatch,
  exportByQuery,
  importCheckByExcel,
} from '../../api/collection/assetAddress';
import { getLeftTreeJson } from '../../api/permission/userManagement';
import { yaMessage } from 'yuan-plus';
import { downLoadAllFile } from '../../utils/utils';
const { permissionsButtons } = usePermissions();
const multipleTableRef = ref();
const bottomData = new Map();
const buttons: any = ref([]);
//搜索栏部门下拉框
const deptIdArr = ref([]);
//抽屉搜索栏下拉框
const deptTreeList = ref([]);
const networkAreaArr = ref([]);
const column = reactive([
  {
    type: 'selection',
    width: '65px',
    fixed: 'left',
  },
  {
    prop: 'target',
    label: '资产地址',
    minWidth: '130px',
    search: true,
    type: 'input',
    slotName: 'ipAddress',
    sortable: 'customer',
  },
  {
    prop: 'targetList',
    type: 'textarea',
    label: '资产地址',
    tableHide: true,
    placeholder:
      '输入IP标准格式提示为：单个IP：192.168.1.0，198.168.1.1，FF01:0:0:0:0:0:0:1101, FF01::1101\nIP段：192.168.1.0-192.168.1.255\nIP/掩码：192.168.1.1/24',
    showWordLimit: true,
    maxlength: '20000',
    rows: 6,
    tooltip: '请输入1-20000个字符',
    drawer: true,
    rules: true,
  },
  {
    prop: 'ipv4',
    label: 'IPv4',
    tableHide: true,
    type: 'input',
    drawer: false,
    rules: true,
    isType: 'ipv4',
    customType: 'ipv4',
  },
  {
    prop: 'ipv6',
    label: 'IPv6',
    tableHide: true,
    isType: 'ipv6',
    customType: 'ipv6',
    type: 'input',
    drawer: false,
  },
  {
    prop: 'domain',
    label: '域名',
    tableHide: true,
    type: 'input',
    drawer: false,
  },
  {
    prop: 'networkAreaName',
    label: '网络域',
    minWidth: '120px',
  },
  {
    prop: 'networkAreaCodeSet',
    type: 'select',
    options: networkAreaArr,
    label: '网络域',
    tableHide: true,
    collapseTags: true,
    multiple: true,
    clearable: true,
    search: true,
  },
  {
    prop: 'networkAreaCode',
    type: 'select',
    options: networkAreaArr,
    label: '网络域',
    tableHide: true,
    drawer: true,
  },
  {
    prop: 'deptName',
    label: '所属部门',
    minWidth: '130px',
  },
  {
    prop: 'deptIdSet',
    type: 'select',
    label: '所属部门',
    tableHide: true,
    search: true,
    options: deptIdArr,
    multiple: true,
    collapseTags: true,
    clearable: true,
  },
  {
    prop: 'deptId',
    type: 'cascader',
    props: {
      checkStrictly: true,
      value: 'id',
      emitPath: false,
    },
    showAllLevels: false,
    label: '所属部门',
    options: deptTreeList,
    tableHide: true,
    drawer: true,
    rules: true,
  },
  {
    prop: 'gmtCreate',
    label: '添加时间',
    // width: '160px',
    search: true,
    type: 'daterange',
    valueFormat: 'YYYY-MM-DD',
    sortable: 'customer',
  },
  {
    label: '操作',
    width: '100px',
    fixed: 'right',
    buttons: [
      {
        title: '编辑',
        disabled: bottomData.has(90021),
        eventName: 'edit',
      },
      {
        title: '删除',
        eventName: 'delete',
        disabled: bottomData.has(90024),
      },
    ],
  },
]);
let total = ref(0);
const tableData = ref([]);
const selectedIds = ref([]);
const searchFormData = reactive({});
//页面数据初始话
const initData = (data) => {
  let params = { ...data.value, ...searchFormData };
  //资产地址的排序字段后端接收为ip
  params.column=='target'&&( params.column='ip')
  if (params.gmtCreate) {
    params.createTimeStart = params.gmtCreate[0];
    params.createTimeEnd = params.gmtCreate[1];
  }
  formData.value = params;
  getList(params).then((res) => {
    const { data, code } = res || {};
    if (code == 200 && data && data.records) {
      data.records?.map((item) => (item.targetList = item.ipv4));
      tableData.value = data.records;
      total.value = data.total;
    }
  });
};
// 表格点击事件
const tableBtnClick = (btn, row) => {
  const { eventName } = btn;
  switch (eventName) {
    case 'add':
      column.forEach((item) => {
        item.prop == 'targetList' && (item.drawer = true);
        item.prop == 'ipv4' && (item.drawer = false);
        item.prop == 'ipv6' && (item.drawer = false);
        item.prop == 'domain' && (item.drawer = false);
      });
      break;
    case 'edit':
      column.forEach((item) => {
        if (item.prop == 'targetList') {
          item.drawer = false;
        }
        if (item.prop == 'ipv4') {
          item.drawer = true;
          item.disabled = true;
        }
        if (item.prop == 'ipv6') {
          item.drawer = true;
          item.disabled = !!row.ipv6;
        }
        if (item.prop == 'domain') {
          item.drawer = true;
          item.disabled = !!row.domain;
        }
      });
      break;
    case 'allExport':
      exportByQuery({
        request: formData.value,
        fileName: '资产IP库',
        fileType: 'xlsx',
      }).then((res) => {
        downLoadAllFile(res, '资产IP库.xlsx', '.xlsx');
        yaMessage('导出成功', 'success');
      });
      break;
  }
};
const formData = ref({});
//页面按钮的点击事件
const btnSubmit = (eventName, data, cb) => {
  debugger;
  let interfaceName;
  let params;
  switch (eventName) {
    case 'uploadCheck': // 文件校验
      let fd = new FormData();
      fd.append('file', data.raw);
      importCheckByExcel(fd).then((res) => {
        if (res.code === 200) {
          cb && cb(res.data);
        }
      });
      break;
    case 'upload': // 文件上传
      let fd1 = new FormData();
      fd1.append('file', data.raw);
      importByExcel(fd1).then((res) => {
        const { code, message } = res || {};
        if (code === 200) {
          cb && cb();
          yaMessage(message, 'success');
          multipleTableRef.value.initData();
        }
      });
      break;
    case 'allDelete':
      interfaceName = postDelAll;
      params = formData.value;
      break;
    case 'batchDelete':
      interfaceName = postDelBatch;
      params = selectedIds.value;
      break;
    case 'delete':
      interfaceName = getDelIpLibrary;
      params = { id: data.id };
      break;
    case 'export':
      params = {
        idSet: selectedIds.value,
        fileName: '资产IP库',
        fileType: 'xlsx',
      };
      exportBatch(params).then((res) => {
        cb && cb(res, '资产IP库.xlsx');
        yaMessage('导出成功', 'success');
      });

      break;
    case 'edit':
      interfaceName = postModifyIpLibrary;
      params = data;
      break;
    case 'add':
      interfaceName = postAddIpLibrary;
      params = data;
      break;
  }
  interfaceName &&
    interfaceName(params).then((res) => {
      const { code, message } = res || {};
      code == 200 &&
        eventName != 'batchDelete' &&
        eventName != 'allDelete' &&
        yaMessage(message, 'success');
      cb(code == 200);
    });
};
//复选框勾选事件
const handleSelectionChange = (data) => {
  selectedIds.value = data?.map((item) => item.id);
};
//排序事件
const handleSortChange = (data) => {
  const { asc, prop } = data;
  searchFormData.column = prop;
  searchFormData.asc = asc;
  multipleTableRef.value.initData();
};
//获取页面按钮
const getButton = () => {
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });
  if (bottomData.has(90023)) {
    buttons.value.push({
      custom: 'dropdown',
      title: '导出',
      plain: true,
      customData: [
        {
          name: '批量导出',
          eventName: 'export',
        },
        {
          name: '全部导出',
          eventName: 'allExport',
        },
      ],
    });
  }
  if (bottomData.has(90024)) {
    buttons.value.push({
      custom: 'dropdown',
      title: '删除',
      plain: true,
      customData: [
        {
          name: '批量删除',
          eventName: 'delete',
        },
        {
          name: '全部删除',
          eventName: 'allDelete',
        },
      ],
    });
  }

  if (bottomData.has(90022)) {
    buttons.value.push({
      eventName: 'import',
      templateUrl: 'IpLibraryImportTemptle.xlsx',
      http,
    });
  }
  if (bottomData.has(90017)) {
    buttons.value.push({
      eventName: 'add',
    });
  }
};

/**
 * @description: 获取下拉框数据
 */
const initSelectOption = () => {
  // 网络域
  getDictList('networkArea').then((res) => {
    networkAreaArr.value = res || [];
  });
  getDeptData().then((res) => {
    const { data } = res || {};
    deptIdArr.value = data?.map((item) => {
      return {
        label: item.deptName,
        value: item.id,
      };
    });
  });
  // 获取部门层级
  getLeftTreeJson().then((res) => {
    const { code, data } = res || {};
    if (code === 200) {
      deptTreeList.value = data.treeData || [];
    }
  });
};
onMounted(() => {
  getButton();
  initSelectOption();
});
</script>

<template>
  <div class="yaBox">
    <YaPageContent
      ref="multipleTableRef"
      :total="total"
      :tableData="tableData"
      :tableColumns="column"
      :buttons="buttons"
      @submit="btnSubmit"
      @tableBtnClick="tableBtnClick"
      @init="initData"
      @selectionChange="handleSelectionChange"
      @sortChange="handleSortChange"
    >
      <template #ipAddress="{ item }">
        <div>{{ (item.ipv4 || '-')+' / '+(item.ipv6 || '-') +' / '+(item.domain || '-')}}</div>
      </template>
    </YaPageContent>
  </div>
</template>
