<template>
  <ya-drawer
    v-if="drawerProps.showDrawer"
    :drawerProps="drawerProps"
    @handleEvent="handleEvent"
    destroy-on-close
    :before-close="handleCloseDrawer"
  >
    <template #content>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="报告导入" :name="0" v-if="showInAdd"></el-tab-pane>
        <el-tab-pane label="模板导入" :name="1" v-if="showInAdd"></el-tab-pane>
        <el-tab-pane label="手动添加" :name="2"></el-tab-pane>
      </el-tabs>
      <template v-if="showForm">
        <ya-form
          label-position="top"
          @handleEvent="handleEvent"
          :formColumns="formColumns"
          labelWidth="100px"
          :formData="formData"
          :rules="rules"
          :ref="
            (el) => {
              if (el) dialogForm = el;
            }
          "
        >
        </ya-form>
      </template>
      <template v-if="activeName == 0 || activeName == 1">
        <div class="custom-upload-block">
          <YaUpload
            :loading="loading"
            :templateUrl="url"
            :limit="1"
            :before-upload="beforeAvatarUpload"
            :file-list="fileList.length > 0 ? fileList : []"
            @handleChangeUpload="handleChangeUpload"
            :auto-upload="false"
            :accept="uploadFileType || '.xlsx, .xls'"
            drag
            ref="uploadRef"
            :action="''"
          >
          </YaUpload>
        </div>
      </template>
    </template>
  </ya-drawer>
</template>

<script setup lang="ts">
import {
  createVul,
  modifyVul,
  importData,
  importReportData,
} from "../../../../api/digitalAssets/assetRisk/vulnerabilityAddition";
import { getDictList } from "../../../../utils/utils";
import { handleGetIndex } from "../../../../utils/tools";
import { defineExpose, nextTick, ref, watch, reactive, onMounted } from "vue";
import { yaMessage } from "../../../../utils/message";
const props = defineProps({
  pageIndex: Number,
  initData: Function,
});
const url = ref("报告导入的模板下载地址");
let showInAdd = ref(true);
const uploadFileType = ref("");
const fileList = ref([]);
let dialogForm = ref();
const showForm = ref(true);
const formColumns: any = ref([]);
let drawerProps = reactive({
  showDrawer: false,
  title: "添加漏洞",
  size: "small",
});
const loading = ref(false);
// //默认为1
// let sourceNum = ref(1);
const activeName = ref(0);
const rules = ref({});

const formData: any = ref({});

enum FileType {
  "",
  ".zip, .rar",
  ".rar, .zip",
  ".xls, .xlsx",
  ".docx, .doc",
  ".html",
}
/**
 *@description: 获取字典
 */
const flawTypeArr = ref([]);
const riskLevelArr = ref([]);
const networkAreaArr = ref([]);
const riskSourceArr = ref([]);
const initDict = async () => {
  flawTypeArr.value = (await getDictList("flawType")) as [];
  riskLevelArr.value = (await getDictList("flawLevel")) as [];
  networkAreaArr.value = (await getDictList("networkArea")) as [];
  riskSourceArr.value = (await getDictList("flawSource")) as [];
};
//报告导入的表单
const formColumns1 = [
  {
    key: "source",
    type: "select",
    label: "风险来源",
    disabled: false,
    col: 24,
    options: riskSourceArr,
    clearable: true,
  },
];
//报告导入的表单规则
const rules1 = reactive({
  source: [{ required: true, message: "请选择", trigger: "change" }],
});
//模板导入的表单
const formColumns2 = ref([
  {
    key: "name",
    type: "text",
    label: "漏洞名称",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "networkAreaCode",
    type: "select",
    label: "网络域",
    disabled: false,
    col: 24,
    options: networkAreaArr,
    clearable: true,
  },
  {
    key: "asset",
    type: "text",
    label: "关联资产",
    disabled: false,
    col: 24,
    options: [],
    clearable: true,
  },
  {
    key: "port",
    type: "text",
    label: "相关端口",
    disabled: false,
    col: 24,
    options: [],
    clearable: true,
  },
  {
    key: "type",
    type: "select",
    label: "漏洞类型",
    disabled: false,
    col: 24,
    options: flawTypeArr,
    clearable: true,
  },
  {
    key: "classification",
    type: "input",
    label: "漏洞分类",
    disabled: true,
    col: 24,
    options: [],
    clearable: true,
  },
  {
    key: "level",
    type: "select",
    label: "漏洞等级",
    disabled: false,
    col: 24,
    options: riskLevelArr,
    clearable: true,
  },
  {
    key: "flag",
    type: "input",
    label: "漏洞标识",
    disabled: false,
    col: 24,
    options: [],
    clearable: true,
  },
  {
    key: "cvss",
    type: "input",
    label: "CVSS分值",
    disabled: false,
    col: 24,
    options: [],
    clearable: true,
  },
  {
    key: "detail",
    type: "input",
    label: "漏洞细节",
    disabled: false,
    col: 24,
    options: [],
    clearable: true,
  },
  {
    key: "describe",
    type: "input",
    label: "漏洞描述",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "repairAdvice",
    type: "input",
    label: "修复建议",
    disabled: false,
    col: 24,
    clearable: true,
  },
]);
//模板导入的表单规则
const rules2 = ref({
  name: [{ required: true, message: "请输入", trigger: "change" }],
  networkAreaCode: [{ required: true, message: "请选择", trigger: "change" }],
  asset: [{ required: true, message: "请选择", trigger: "change" }],
  port: [{ required: false, message: "请输入", trigger: "change" }],
  type: [{ required: true, message: "请选择", trigger: "change" }],
  classification: [{ message: "请选择", trigger: "change" }],
  level: [{ required: true, message: "请选择", trigger: "change" }],
  flag: [{ message: "请选择", trigger: "change" }],
  CVSS: [{ message: "请输入", trigger: "change" }],
  detail: [{ message: "请输入", trigger: "change" }],
  describe: [{ message: "请输入", trigger: "change" }],
  repairAdvice: [{ message: "请输入", trigger: "change" }],
});
/**
 * @describtion 表单数据初始化
 */
const resetFormData = () => {
  formData.value = {};
};
watch(
  () => activeName.value,
  (value) => {
    resetFormData();
    fileList.value = [];
    formData.value = {
      source: riskSourceArr.value.length ? riskSourceArr.value[0].value : null,
    };
    showForm.value = false;
    if (value === 0 || value === 2) {
      formColumns.value = value === 0 ? formColumns1 : formColumns2;
      rules.value = value === 0 ? rules1 : rules2;
      nextTick(() => {
        showForm.value = true;
      });
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => formData.value.type,
  (val) => {
    const index = handleGetIndex(formColumns2.value, "key", "classification");
    if (val == 2) {
      rules2.value.port[0].required = true;
      formColumns2.value[index].disabled = false;
    } else {
      rules2.value.port[0].required = false;
      formColumns2.value[index].disabled = true;
    }
  }
);
watch(
  () => formData.value.source,
  (val) => {
    // sourceNum.value = val;
    uploadFileType.value = FileType[val];
  }
);

let beforeOpen = () => {
  nextTick(() => {
    dialogForm.value.resetForm();
  });
};

//抽屉的事件
const handleEvent = function (data) {
  if (data.eventName == "errorSubmit") {
    return;
  } else if (data.eventName == "success") {
    if (activeName.value == 0 || activeName.value == 1) {
      handleUploadFile();
    }
    //确定按钮的事件
    handleConfirm();
    return;
  } else if (data.eventName == "successSubmit") {
    //需要表单验证的时候触发的事件
    handleSubmit();
    return;
  }
};
// 关闭抽屉
const handleCloseDrawer = async (done) => {
  if (dialogForm.value) {
    await dialogForm.value.resetForm(dialogForm.value.ruleFormRef);
  }
  done();
};
//手动添加漏洞
const handAdd = function () {
  let params = formData.value;
  createVul(params).then((res) => {
    const { code } = res;
    if (code === 200) {
      drawerProps.showDrawer = false;
      props.pageIndex = 1;
      props.initData();
      yaMessage("添加成功", "success");
    }
  });
};

// 漏洞重新编辑后的提交
const editSubmit = function () {
  let params = JSON.parse(JSON.stringify(formData.value));
  modifyVul(params).then((res) => {
    const { code } = res;
    if (code === 200) {
      drawerProps.showDrawer = false;
      props.pageIndex = 1;
      props.initData();
      yaMessage("修改成功", "success");
    }
  });
};
/**
 *漏洞添加和漏洞编辑的事件
 * @param data
 */
const handleToggleDrawer = (data?) => {
  //showInAdd编辑的时候仅显示手动添加的tab，报告导入和模板导入的tab都需隐藏
  drawerProps.title = data ? "编辑" : "新增";
  if (data) {
    showInAdd.value = false;
    activeName.value = 2;
    nextTick(() => {
      formData.value = JSON.parse(JSON.stringify(data));
      formData.value.id = data.id;
    });
  } else {
    activeName.value = 0;
    showInAdd.value = true;
    formData.value = {
      source: riskSourceArr.value.length ? riskSourceArr.value[0].value : null,
    };
  }
  drawerProps.showDrawer = true;
};
//不需要表单验证的时候
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};

// 表单提交，需要做表单验证
const handleSubmit = () => {
  if (activeName.value == 2) {
    if (formData.value.id) {
      editSubmit();
    } else {
      handAdd();
    }
  }
};
watch(
  () => activeName.value,
  (val) => {
    if (val == 0) {
      url.value = "报告导入的模板下载地址";
    } else if (val == 1) {
      url.value = "flawImport.xlsx";
    }
  }
);

const handleChangeUpload = async (uploadFile, uploadFiles) => {
  let flg = beforeAvatarUpload(uploadFile);
  if (flg) {
    fileList.value = uploadFiles;
  }
};
//对导入的文件做限制
const beforeAvatarUpload = (file) => {
  if (file.size / 1024 / 1024 > 200) {
    yaMessage("单个文件最多只能上传200MB!", "error");
    nextTick(() => {
      let _data = fileList.value.findIndex((item) => {
        return item.name == file.name;
      });
      fileList.value.splice(_data, 1);
    });
    return false;
  }
  return true;
};
// 文件上传
const handleUploadFile = () => {
  if (fileList.value.length === 0) {
    yaMessage("请先选择上传文件", "error");
    return;
  }
  let fd = new FormData();
  fileList.value.forEach(async (item) => {
    fd.append("file", item.raw);
    let importEvent = activeName.value == 1 ? importData : importReportData; //后面接口地址要换掉
    importEvent(fd).then((res) => {
      if (res.code == 200) {
        fileList.value = [];
        props.initData();
        yaMessage("上传成功", "success");
      }
    });
  });
};
onMounted(() => {
  initDict();
});
defineExpose({
  handleToggleDrawer,
});
</script>
<style scoped lang="scss"></style>
