<template>
  <div>
    <YaPageContent :formData="serchformData" :formColumns="serchColumns" :tableData="tableData" :tableColumns="column"
      :leftButtons="leftButtons" searchLabelWidth="90px" :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="importVisible.showConfirm" @handleEvent="handleImportDrawerEvent"
      :drawerProps="importVisible" v-if="importVisible.showDrawer">
      <template #content>
        <YaUpload :uploadInfo="uploadInfo"
          templateUrl="./static/%E9%87%8D%E7%82%B9%E7%BD%91%E7%AB%99%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
          @handleChangeUpload="handleChangeUpload" @handleDownloadPdf="handleDownloadPdf" :auto-upload="false"
          accept=".xlsx" ref="uploadRef" :action="''">
        </YaUpload>
      </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 { downloadPDF } from "../../../utils/tools/index";
import {
  getImportDomainList,
  postImportDomainAddForm,
  postImportDomainEditForm,
  postImportDomainExport,
  postImportDomainDelete,
  postImportDomainFileCheck,
  postImportDomainFile,
} 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([]);

// 获取按钮权限
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;
        importVisible.showConfirm = false;
      },
    });
  }

  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: "importantWebName",
    type: "input",
    label: "网站名称",
    col: 8,
  },
  {
    key: "url",
    type: "input",
    label: "网址",
    col: 8,
  },
  {
    key: "unit",
    type: "input",
    label: "所属单位",
    col: 8,
  },
  {
    key: "contact",
    type: "input",
    label: "联系人",
    col: 8,
  },
  {
    key: "contactPhone",
    type: "input",
    label: "联系电话",
    isType: "number",
    col: 8,
  },
]);
const leftButtons = ref([]) as any;
const rightButtons = ref([]) as any;
let importVisible = reactive({
  showDrawer: false,
  showConfirm: 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;
  if (type === "loading") {
    _data.yaLoading = type;
  }
  getImportDomainList(_data).then((res) => {
    tableData.value = res.data.rows;
    total.value = res.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 = {
      ids: data.toString(),
    };
    const res = await postImportDomainExport(params);
    if (res) {
      downLoadFile(res, `重点网站配置`);
    }
  } catch (error) {
    console.log(error);
  }
};

// 导入
const handleImportDrawerEvent = (data) => {
  const { eventName = "" } = data;
  // 抽屉点击确定按钮
  if (eventName === "success") {
    importConfirm();
  }
};

const uploadRef = ref({});
const uploadInfo = ref({
  errorList: [],
});
/**
 * 文件导入
 * @param uploadFile {object} - 当前导入文件
 * @param uploadFiles {array} - 导入所有文件
 */
const handleChangeUpload = (uploadFile) => {
  let fd = new FormData();
  fd.append("file", uploadFile.raw);
  // 导入校验
  postImportDomainFileCheck(fd).then((res) => {
    const { code, data } = res || {};
    if (code === 200) {
      const { importStatus, message, failInfoList } = data || {};
      uploadInfo.value.type = importStatus ? "success" : "error";
      importVisible.showConfirm = importStatus ? true : false;
      uploadInfo.value.text = message;
      uploadInfo.value.errorList = failInfoList || [];
      uploadInfo.value.errorList.forEach((item) => {
        item.line = item.row;
        item.content = item.message;
      });
    }
  });
};

// 确认导入
const importConfirm = () => {
  const fileList = uploadRef.value.fileList;
  if (!fileList[0]) {
    ElMessage.warning("请先选择上传文件");
    return;
  }
  let fd = new FormData();
  fd.append("file", fileList[0].raw);
  postImportDomainFile(fd).then((res) => {
    if (res.code == 200) {
      ElMessage.success("文件导入成功");
      importVisible.showDrawer = false;
      fileList.value = reactive([]);
      search("init");
    }
  });
};

// pdf导出
const handleDownloadPdf = () => {
  downloadPDF(document.getElementById("yaPdf"), "文件错误原因");
};

// table start
const tableData = ref([]);
let selectData = ref([]);
// 表头定义
const column: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "importantWebName",
    label: "重点网站名称",
    minWidth: "170px",
    // fixed: "left",
  },
  {
    prop: "url",
    label: "网址",
    minWidth: "220px",
  },
  {
    prop: "unit",
    label: "所属单位",
    minWidth: "200px",
  },
  {
    prop: "contact",
    label: "联系人",
    minWidth: "110px",
  },
  {
    prop: "contactPhone",
    label: "联系电话",
    minWidth: "140px",
  },
  {
    prop: "configDate",
    label: "配置日期",
    width: "190px",
  },
  {
    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(() => {
    postImportDomainDelete({ 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: "importantWebName",
    type: "input",
    label: "重点网站名称",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "url",
    type: "input",
    label: "网址",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "unit",
    type: "input",
    label: "所属单位",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "contact",
    type: "input",
    label: "联系人",
    disabled: false,
    col: 24,
    clearable: true,
  },
  {
    key: "contactPhone",
    type: "input",
    label: "联系电话",
    isType: "number",
    disabled: false,
    col: 24,
    clearable: true,
  },
]);

const rules = reactive<FormRules>({
  importantWebName: [
    { required: true, message: "请输入重点网站名称", trigger: "blur" },
  ],
  url: [{ required: true, message: "请输入网址", trigger: "blur" }],
  unit: [{ required: true, message: "请输入所属单位", trigger: "blur" }],
});

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

/**
 * // 新增/修改保存 demo
 * @param data {object} - 表单数据
 */
const handleSave = (data) => {
  let url = data.id ? postImportDomainEditForm : postImportDomainAddForm;
  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("loading");
});
</script>
