<template>
  <div>
    <YaPageContent :formData="serchformData" :formColumns="serchColumns" :tableData="tableData" :tableColumns="column"
      :leftButtons="leftButtons" searchLabelWidth="100px" :rightButtons="rightButtons" @search="search('init')"
      @reset="reset" @tableBtnClick="tableBtnClick" @selectionChange="handleSelectionChange" :currentPage="page"
      :pageSize="pageSize" :total="total" @sizeChange="sizeChange" @currentChange="currentChange">
    </YaPageContent>
    <!-- 新增 -->
    <ya-drawer v-if="drawerProps.showDrawer" :drawerProps="drawerProps" @handleEvent="handleEvent" destroy-on-close
      :before-close="handleCloseDrawer">
      <template #content>
        <ya-form label-position="top" @handleEvent="handleEvent" :formColumns="formColumns" labelWidth="100px"
          :formData="formData" :rules="rules" :ref="(el) => {
            if (el) dialogForm = el;
          }
            ">
        </ya-form>
      </template>
    </ya-drawer>

    <!-- 导入 -->
    <ya-drawer ref="importadd" :showConfirm="false" @handleEvent="handleImportDrawerEvent"
      :before-close="handleCloseImportDrawer" :drawerProps="importVisible">
      <template #content>
        <div class="custom-upload-tip ya-fill-color">
          <ElIcon class="custom-upload-tip-icon">
            <WarningFilled />
          </ElIcon>
          <div class="custom-upload-tip-right ya-regular-text">
            <p>1）仅支持后缀为.xlsx的文件，数据不合法时将丢弃该记录。</p>
            <p>2）文件的大小不能超过200M。</p>
            <p>
              3）可点击<span @click.stop="upfile" class="download-template">下载模板</span>
            </p>
          </div>
        </div>
        <div class="custom-upload-block">
          <YaUpload :before-upload="beforeAvatarUpload" :file-list="fileList.length > 0 ? fileList : []"
            :on-change="handleChange" :auto-upload="false" accept=".xlsx" drag ref="uploadRef" :action="''">
          </YaUpload>
        </div>
      </template>
    </ya-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, Ref, watch, onMounted } from "vue";
import { ElMessageBox, ElMessage, FormRules } from "element-plus";
import { WarningFilled } from "@element-plus/icons-vue";
import { getDictTypeList } from "../../../api/common";
import {
  getMalicNetList,
  postMalicNetAddForm,
  postMalicNetEditForm,
  postMalicNetExport,
  postMalicNetDelete,
  postMalicNetFile,
} from "../../../api/monitoring/website/securityAnalysis";
import { handleGetIndex } from "../../../utils/tools";
import { usePermissions } from "../../../composables/usePermissions";
import { useRouter } from "vue-router";
import { downLoadFile } from "../../../utils/utils";
const { permissionsButtons } = usePermissions();
const router = useRouter();
usePermissions();
const butomData = ref([]);
// 获取字典项
const badType = ref([]);
const initDict = () => {
  getDictTypeList({ dictType: "恶意类型" }).then((res) => {
    res.forEach((item) => {
      item.value = item.dictValue;
      item.label = item.dictValue;
    });
    badType.value = res;
  });
};

// 获取按钮权限
let getButton = () => {
  let i = handleGetIndex(column, "prop", "oparation");
  if (butomData.value.indexOf("导出") > -1) {
    leftButtons.value.push({
      text: "批量导出",
      plain: true,
      eventName: function () {
        handleExport();
      },
    });
  }
  if (butomData.value.indexOf("导入") > -1) {
    leftButtons.value.push({
      text: "批量导入",
      plain: true,
      eventName: function () {
        importVisible.showDrawer = true;
        fileList.value = [];
      },
    });
  }

  if (butomData.value.indexOf("新增") > -1) {
    rightButtons.value.push({
      text: "新增",
      type: "primary",
      green: true,
      iconType: "add",
      eventName: function () {
        handleToggleDrawer();
      },
    });
  }

  if (butomData.value.indexOf("修改") > -1) {
    let j = handleGetIndex(column[i].buttons, "title", "修改");
    column[i].buttons[j].hide = false;
  }

  if (butomData.value.indexOf("删除") > -1) {
    let j = handleGetIndex(column[i].buttons, "title", "删除");
    column[i].buttons[j].hide = false;
  }
};

// 搜索栏
const serchformData = ref({});
const serchColumns = reactive([
  {
    key: "time",
    type: "daterange",
    label: "时间范围",
    valueFormat: "YYYY-MM-DD",
    startPlaceholder: "开始时间",
    endPlaceholder: "结束时间",
    col: 8,
  },
  {
    key: "maliciousType",
    type: "select",
    label: "恶意类型",
    options: badType,
    col: 8,
  },
  {
    key: "maliciousWebsiteAddress",
    type: "input",
    label: "恶意网站地址",
    col: 8,
  },
  {
    key: "source",
    type: "input",
    label: "来源",
    col: 8,
  },
]);
const leftButtons = ref([]) as any;
const rightButtons = ref([]) as any;
let importVisible = reactive({
  showDrawer: false,
  title: "导入文件",
  size: "big",
});

/**
 * 获取列表数据
 * @param type {string} - 初始化
 */
const search = (type?) => {
  if (type === "init") {
    page.value = 1;
  }
  let _data = JSON.parse(JSON.stringify(serchformData.value));
  if (_data.time) {
    const [start, end] = _data.time;
    _data["startTime"] = start;
    _data["endTime"] = end;
    delete _data.time;
  }
  _data.pageSize = pageSize.value;
  _data.pageNum = page.value;
  getMalicNetList(_data).then((res) => {
    const { code, data } = res || {};
    if (code === 200 && data) {
      tableData.value = data.rows || [];
      total.value = data.total;
    }
  });
};

// 重置
const reset = () => {
  serchformData.value = {};
  search("init");
};

/**
 * @description: 批量导出
 * @param {*} type batch | all
 * @return {*}
 * @author: xuch
 */
const handleExport = async () => {
  if (selectData.value.length === 0) {
    ElMessage.warning("请选择要批量导出的数据");
    return;
  }
  // @ts-ignore
  const data = selectData.value.map((item) => item.id);

  handleExportRequest(data);
};

/**
 * @description: 批量 / 全部 导出请求
 * @param {*} data
 * @return {*}
 * @author: xuch
 */
const handleExportRequest = async (data) => {
  try {
    const params = {
      idList: data,
    };
    const res = await postMalicNetExport(params);
    if (res) {
      downLoadFile(res, `恶意网站配置`);
    }
  } catch (error) {
    console.log(error);
  }
};

// 导入
const handleImportDrawerEvent = (data) => {
  const { eventName = "" } = data;
  // 抽屉点击确定按钮
  if (eventName === "success") {
    // importConfirm();
  }
};
const handleCloseImportDrawer = async (done) => {
  done();
  search("init");
};
const upfile = () => {
  window.location.href =
    "/static/%E6%81%B6%E6%84%8F%E7%BD%91%E7%AB%99%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx";
};

const fileList = ref([]);
const beforeAvatarUpload = (file) => {
  let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
  const extension2 = testmsg === "xlsx";
  if (!extension2) {
    ElMessage.error("文件只能上传xlsx格式");
    return false;
  } else if (file.size / 1024 / 1024 > 200) {
    ElMessage.error("单个文件最多只能上传200MB!");
    nextTick(() => {
      let _data = fileList.value.findIndex((item) => {
        return item.name == file.name;
      });
      fileList.value.splice(_data, 1);
    });

    return false;
  }
  return true;
};
const handleChange = async (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles;
  console.log(fileList.value);
  let flg = beforeAvatarUpload(uploadFile);
  if (flg) {
    let fd = new FormData();
    fd.append("file", uploadFile.raw);
    let res = await postMalicNetFile(fd);
    if (res.code == 200) {
      formData.value.informFile = res.message;
      fileList.value[fileList.value.length - 1].informFile = res.message;
      ElMessage.success(res.message);
    } else {
      let _data = fileList.value.findIndex((item) => {
        return item.name == uploadFile.name;
      });
      fileList.value.splice(_data, 1);
    }
  }
};

// table start
const tableData = ref([]);
let selectData = ref([]);
// 表头定义
const column: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "maliciousWebsiteAddress",
    label: "恶意网站地址",
    // width: "300px",
    // fixed: "left",
  },
  {
    prop: "maliciousType",
    label: "恶意类型",
    width: "150px",
  },
  {
    prop: "source",
    label: "来源",
    // width: "120px",
  },
  {
    prop: "configTime",
    label: "配置日期",
    // width: "120px",
  },
  {
    prop: "oparation",
    label: "操作",
    width: "130px",
    // align: "center",
    fixed: "right",
    buttons: [
      {
        title: "修改",
        hide: true,
        eventName: function (row) {
          handleToggleDrawer(true, row);
        },
      },
      {
        title: "删除",
        hide: true,
        eventName: function (row) {
          batchDelete(row.id);
        },
      },
    ],
  },
];
const tableBtnClick = (btn, row) => {
  btn.eventName(row);
};

// 列表删除
const batchDelete = (id) => {
  ElMessageBox.confirm("此操作不可逆，是否要确认删除？", "提示", {
    customClass: "message-warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    postMalicNetDelete({ id }).then((res) => {
      if (res.code == 200) {
        // page.value = 1;
        ElMessage.success("删除成功");
        search();
      }
    });
  });
};

const handleSelectionChange = function (val) {
  selectData.value = val;
};

const page = ref(1);
const total = ref(0);
const pageSize = ref(20);
const sizeChange = function (val: Number) {
  pageSize.value = val;
  page.value = 1;
  search();
};

const currentChange = function (val: Number) {
  page.value = val;
  search();
};

// table end

// dialog start
let drawerProps = reactive({
  showDrawer: false,
  title: "新增",
  size: "small",
});

let dialogForm = ref();

/**
 *
 * @param state {boolean} - false-新增/true-编辑
 * @param data
 */
const handleToggleDrawer = (state?, data?) => {
  drawerProps.title = state ? "修改" : "新增";
  if (data) {
    formData.value = JSON.parse(JSON.stringify(data));
  } else {
    formData.value = {};
  }
  drawerProps.showDrawer = true;
};

// 关闭抽屉
const handleCloseDrawer = async (done) => {
  if (dialogForm.value) {
    await dialogForm.value.resetForm(dialogForm.value.ruleFormRef);
  }
  done();
};

// 抽屉事件
const handleEvent = function (data) {
  if (data.eventName == "errorSubmit") {
    return;
  } else if (data.eventName == "success") {
    handleConfirm();
    return;
  } else if (data.eventName === "successSubmit") {
    handleSave(data.data);
  }
};

const formData = ref({});

const formColumns = reactive([
  {
    key: "maliciousWebsiteAddress",
    type: "input",
    label: "恶意网站地址",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "maliciousType",
    type: "select",
    label: "恶意类型",
    disabled: false,
    options: badType,
    col: 24,
    clearable: true,
  },
  {
    key: "source",
    type: "input",
    label: "来源",
    disabled: false,
    col: 24,
    clearable: true,
  },
]);

const rules = reactive<FormRules>({
  maliciousWebsiteAddress: [
    { required: true, message: "请输入恶意网站地址", trigger: "blur" },
  ],
  maliciousType: [
    { required: true, message: "请选择恶意类型", trigger: "change" },
  ],
});

// 表单确认
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};

/**
 * // 新增/修改保存 demo
 * @param data {object} - 表单数据
 */
const handleSave = (data) => {
  let url = data.id ? postMalicNetEditForm : postMalicNetAddForm;
  url(data).then((res) => {
    const { code, message } = res || {};
    if (code === 200) {
      search();
      drawerProps.showDrawer = false;
      ElMessage.success(message);
    }
  });
};
// dialog end

onMounted(() => {
  permissionsButtons.map((item) => {
    butomData.value.push(item.label);
  });
  console.log(butomData, "butomData");
  getButton();
  search();
  initDict();
});
</script>
