<script setup lang="ts">
import { ref, reactive, nextTick, Ref, watch, onMounted } from "vue";
import { ElMessage, FormRules } from "element-plus";
import { WarningFilled } from "@element-plus/icons-vue";
import { getDictTypeList, getDeptList } from "../../../api/common";
import {
  getList,
  add,
  update,
  delOne,
  delAll,
  importByExcel,
  exportBatch,
  importCheckByExcel,
} from "../../../api/collection/assetsFound/ipAsset";
import { http } from "@/utils/https";
import { getLeftTreeJson } from "../../../api/permission/userManagement";
import { usePermissions } from "../../../composables/usePermissions";
import { downLoadFile } from "../../../utils/utils";
import { yaConfirmMessage } from 'yuan-plus';
import { getDeptData } from "../../../api/digitalAssets/networkAssets/hostAssets";
const { permissionsButtons } = usePermissions();
const bottomData = new Map();
const leftButtons = ref([]);
//所属部门
const deptIdArr = ref([]);
const serchformData = reactive({});
// 列表数据获取
const search = (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
  }
  let parms = {
    ..._data,
    ...serchformData
  };
  getList(parms).then((res) => {
    const { code, data = {} } = res || {};
    if (code === 200) {
      tableData.value = res.data.records;
      total.value = res.data.total;
    }
  });
};
// 表格数据定义
const column: any[] = reactive([
  {
    type: "selection",
    width: "65px",
    fixed: "left",
  },
  {
    prop: "target",
    type: "input",
    label: "资产IP",
    tableHide: true,
    search: true,
  },
  {
    prop: "targetList",
    type: "textarea",
    label: "资产IP",
    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",
    fixed: "left",
    minWidth: "160px",
    sortable: "custom",
    type: "input",
    drawer: false,
    rules: true,
    tableHide:true
  },
  {
    prop: "ipv6",
    label: "IPv6",
    fixed: "left",
    minWidth: "160px",
    type: "input",
    drawer: false,
  },
  {
    prop: "networkAreaName",
    label: "网络域",
    fixed: "left",
    type: "select",
    minWidth: "120px",
  },
  {
    prop: "networkAreaCodeSet",
    type: "select",
    label: "网络域",
    tableHide: true,
    collapseTags: true,
    multiple: true,
    clearable: true,
    search: true
  },
  {
    prop: "networkAreaCode",
    type: "select",
    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: [],
    tableHide: true,
    drawer: true,
    rules: true
  },
  {
    prop: "time",
    label: "添加时间",
    type: 'daterange',
    width: "190px",
    valueFormat: "YYYY-MM-DD",
    search: true,
    tableHide: true
  },
  {
    prop: "gmtCreate",
    label: "添加时间",
    width: "190px",
  },
  {
    label: "操作",
    width: '100px',
    fixed: "right",
    buttons: [
      {
        title: '编辑',
        disabled: function (row) {
          if (bottomData.has(400126)) {
            return false;
          } else {
            return true;
          }
        },
        eventName: 'edit',
      },
      {
        title: '删除',
        eventName: 'delete',
        disabled: function (row) {
          if (bottomData.has(400124)) {
            return false;
          } else {
            return true;
          }
        },
      },
    ]
  },
]);
const tableData = ref([]);
let selectData = ref([]);
const total = ref(0);
// 列表删除
const delBtn = (id) => {
  let idValue = id;
    let func;
    if (!id) {
      func = delAll;
      console.log(selectData.value);
      let idSet = selectData.value.map((item) => {
        return item.id;
      });
      idValue = idSet;
    } else {
      func = delOne;
      idValue = {
        id: id,
      };
    }
    func(idValue).then((res) => {
      if (res.code == 200) {
        // page.value = 1;
        ElMessage.success("删除成功");
        multipleTableRef.value.initData();
      }
    });
};
// 表格点击事件
const tableBtnClick = (btn, row) => {
  const { eventName } = btn;
  switch (eventName) {
    case 'add':
      column.forEach((item)=>{
        if(item.prop == 'targetList') {
          item.drawer = true
        }
        if(item.prop == 'ipv4') {
          item.drawer = false
        }
        if(item.prop == 'ipv6') {
          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
        }
      })
      break;
  }
};
// 全选
const handleSelectionChange = function (val) {
  selectData.value = val;
};
//-------------
// 排序事件
const handleSortChange = (data) => {
  serchformData.column = "ip";
  serchformData.asc = data.asc;
  multipleTableRef.value.initData();
};
onMounted(() => {
  getDictList();
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });
  getButton();
  getDepteEvent();
});
//获取所属部门下拉框数据
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);
    });
  });
};
/**
 *@description: 初始化
 */
const init = () => {};
// 获取按钮权限
const getButton = () => {
  if (bottomData.has(400124)) {
    leftButtons.value.push({
      eventName: 'delete'
    });
  }
  if (bottomData.has(400123)) {
    leftButtons.value.push({
      eventName: 'export',
    });
  }
  if (bottomData.has(400122)) {
    leftButtons.value.push({
      eventName: 'import',
      templateUrl: 'IpLibraryImportTemptle.xlsx',
      http
    });
  }
  if (bottomData.has(400121)) {
    leftButtons.value.push({
      eventName: 'add',
    });
  }
};
// 导出
const batchImport = function () {
  let idSet = selectData.value.map((item) => {
    return item.id;
  });
  exportBatch({
    idSet: idSet,
    fileName: "资产IP库",
    fileType: "xlsx",
  }).then((res) => {
    clearSelect()
    downLoadFile(res, "资产IP库.xlsx");
  });
};
/**
 * @description: 字典数据初始化
 */
const resetDictData = (e) => {
  let list = e.map((item) => {
    return {
      label: item.dictName,
      value: item.dictValue,
    };
  });
  return list;
};
const deptList = ref([]);
/**
 * @description: 获取字典数据
 */
const getDictList = () => {
  // 网络域
  getDictTypeList({ dictType: "networkArea" }).then((res) => {
    if (res.code == 200) {
      column.forEach((item) => {
        if (item.prop == "networkAreaCodeSet" || item.prop == "networkAreaCode") {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
  // 获取部门层级
  getLeftTreeJson().then((res) => {
    const { code, data } = res || {};
    if (code === 200) {
      column.forEach((item) => {
        if (item.key == "deptId") {
          item.options = data.treeData || [];
        }
      });
      deptList.value = data.treeData || [];
    }
  });
};

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 清空选择的值
const clearSelect = () => {
  multipleTableRef.value.getTableMethods()?.clearSelection();
};
/**
 * @description 模板提交事件
 * @param eventName 事件名称 export: 批量导出
 * @param data 表单提交数据
 * @param cb  { Function } 组件回调  （ 新增，编辑，删除，上传需要参数: Boolean true(关闭loading,弹窗)/false(关闭loading) ）
 */
 const btnSubmit = (eventName, data, cb) => {
  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)=>{
        if (res.code === 200) {
          cb && cb()
          ElMessage.success(res.message)
          multipleTableRef.value.initData();
        }
      })
      break;
    case 'batchDelete':  // 批量删除
      delBtn('')
      break;
    case 'delete':
      delBtn(data.id)
      break;
    case 'export': // 批量导出
      batchImport()
      break;
    case 'edit': // 编辑
      handleSubmit(eventName,data,cb)
      break;
    case 'add': // 新增
      handleSubmit(eventName,data,cb)
      break;
  }
}
/**
 * @description 新增/编辑资产ip确认事件
 */
 const handleSubmit = (eventName,data,cb) => {
  let func;
  if (eventName == 'edit') {
    func = update;
  } else {
    func = add;
  }
  func(data).then((res) => {
    const { code, data = {} } = res || {};
    if (code == 200) {
      ElMessage.success(res.message);
      cb(true)
    } else {
      cb(false)
    }
  }).catch((error) => {
    cb(false)
  });
};
</script>

<template>
  <div>
    <YaPageContent ref="multipleTableRef" :total="total" :tableData="tableData" :tableColumns="column" :buttons="leftButtons"  @submit="btnSubmit" @init="search" @tableBtnClick="tableBtnClick" @selectionChange="handleSelectionChange" @sortChange="handleSortChange"></YaPageContent>
  </div>
</template>
