<!--
 * @Description: 重要域名管理
 * @Author: xuch
 * @Date: 2022-08-25 14:19:18
 * @LastEditTime: 2023-08-31 10:24:28
 * @LastEditors: 曹文丽
-->
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElIcon } from "element-plus";
import { WarningFilled } from "@element-plus/icons-vue";
import {
  getList,
  exportRequest,
  addDomin,
  editDomin,
  delDomin,
  addUploadFile,
} from "../../../api/monitoring/domain/importantDomainManagement";
import { downLoadFile } from "../../../utils/utils";

onMounted(() => {
  init();
});

// 分页参数
const page = ref(1);
const total = ref(5);
const size = ref(20);
const dialogVisible = ref(false);

/**
 * @description: 初始化方法
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const init = () => {
  getTableData("init");
  getLeftButtons();
};

/**
 * @description: 获取按钮
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const buttons = ref([]) as any;
const getLeftButtons = () => {
  buttons.value = [
    {
      plain: true,
      text: "批量导出",
    },
    {
      plain: true,
      text: "导入",
      eventName: function () {
        handleImport();
      },
    },
  ];
};

// 查询参数
const queryColumns = reactive([
  {
    key: "siteName",
    type: "input",
    label: "站点名称",
    placeholder: "请输入站点名称",
    col: 8,
  },
  {
    key: "domainName",
    type: "input",
    label: "域名",
    placeholder: "请输入域名",
    col: 8,
  },
]);
const queryFormData = reactive({
  siteName: "",
  domain: "",
});

// 表格数据
const tableData = ref([]) as any;
const tableColumn: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "siteName",
    label: "站点名称",
    fixed: "left",
  },
  {
    prop: "domainName",
    label: "域名",
  },
  {
    prop: "recordIp",
    label: "备案IP",
  },
  {
    prop: "sponsor",
    label: "主办单位",
  },
  {
    prop: "licenseCode",
    label: "备案许可证",
  },
  {
    width: "130px",
    label: "操作",
    buttons: [
      {
        title: "修改",
        eventName: function (row) {
          edit(row);
        },
      },
      {
        title: "删除",
        eventName: function (row) {
          deletedata(row);
        },
      },
    ],
  },
];

/**
 * @description: 表格多选操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const selectData = ref([]);
const handleSelect = (data) => {
  selectData.value = data;
};

/**
 * @description: 查询操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const search = () => {
  getTableData("init");
};

/**
 * @description: 重置操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const reset = () => {
  console.log("调用 reset");
  getTableData("init");
};

/**
 * @description: 获取表格数据
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const getTableData = async (type) => {
  console.log("调用 search", type);

  if (type === "init") {
    page.value = 1;
  }

  try {
    const params = {
      pageNum: page.value,
      pageSize: size.value,
      ...queryFormData,
    };

    const res = await getList(params);
    if (res.code !== 200) return;
    if (res.data) {
      tableData.value = res.data.rows || [];
      total.value = res.data.total;
    }
  } catch (error) {
    console.log(error);
  }
};

/**
 * @description: 页面容量切换
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const sizeChange = function (val: number) {
  size.value = val;
  page.value = 1;
  getTableData("page");
};

/**
 * @description: 分页切换
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const currentChange = function (val: number) {
  page.value = val;
  getTableData("page");
};

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

  if (type === "all" && tableData.value.length === 0) {
    return;
  }
  // @ts-ignore
  const data = selectData.value.map((item) => item.id);

  handleExportRequest(data);
};

/**
 * @description: 批量 / 全部 导出请求
 * @param {*} data
 * @return {*}
 * @author: xuch
 */
const handleExportRequest = async (data) => {
  console.log(data);
  try {
    const params = {
      ids: data.toString(),
    };
    const res = await exportRequest(params);
    if (res) {
      downLoadFile(res, `重要域名管理`);
      getTableData("");
    }
  } catch (error) {
    console.log(error);
  }
};

/**
 * @description: 导入按钮事件
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const handleImport = () => {
  dialogVisible.value = true;
};
const tableBtnClick = (btn, row) => {
  console.log(btn);
  if (btn.text == "批量导出") {
    handleExport(btn);
  } else if (btn.text == "导入") {
    importVisible.showDrawer = true;
    fileList.value = [];
  } else {
    btn.eventName(row);
  }
};

let formData = reactive({
  siteName: "",
  domainName: "",
  recordIp: "",
  sponsor: "",
  licenseCode: "",
});
const formColumns = reactive([
  {
    key: "siteName",
    type: "input",
    label: "站点名称",
    col: 24,
    tooltip: "请输入站点名称",
    placeholder: "请输入站点名称",
    disabled: false,
    clearable: true,
  },
  {
    key: "domainName",
    type: "input",
    label: "域名",
    col: 24,
    tooltip: "例：baidu.com或baidu.com.cn或www.baidu.com",
    placeholder: "请输入域名",
    disabled: false,
    clearable: true,
  },
  {
    key: "recordIp",
    type: "input",
    label: "备案IP",
    col: 24,
    tooltip: "xxx.xxx.xxx.xxx(每段数字为0-255)",
    placeholder: "请输入备案IP",
    disabled: false,
    clearable: true,
  },
  {
    key: "sponsor",
    type: "input",
    label: "主办单位",
    col: 24,
    tooltip: "请输入主办单位",
    placeholder: "请输入主办单位",
    disabled: false,
    clearable: true,
  },
  {
    key: "licenseCode",
    type: "input",
    label: "备案许可证号",
    col: 24,
    tooltip:
      "省简称+" +
      "ICP备案8位数字号" +
      "或省简称+" +
      "ICP备案" +
      "8位数字" +
      "号-" +
      "+1~9或省简称" +
      "ICP证" +
      "6位数字" +
      "号",
    placeholder: "请输入备案许可证号",
    disabled: false,
    clearable: true,
  },
]);
const rules = reactive<FormRules>({
  siteName: [{ required: true, message: "请输入站点名称", trigger: "blur" }],
  domainName: [{ required: true, message: "请输入域名", trigger: "blur" }],
  recordIp: [{ required: true, message: "请输入备案IP", trigger: "blur" }],
  sponsor: [{ required: true, message: "请输入主办单位", trigger: "blur" }],
  licenseCode: [
    { required: true, message: "请输入备案许可证号", trigger: "blur" },
  ],
});
let drawerProps = reactive({
  showDrawer: false,
  title: "新增",
  size: "big",
});
const dialogForm = ref({});
const drawerFormDisabled = ref(false);
const addData = () => {
  drawerFormDisabled.value = false;
  drawerProps.showDrawer = true;
  drawerProps.title = "新增";
  formData.siteName = "";
  formData.domainName = "";
  formData.recordIp = "";
  formData.sponsor = "";
  formData.licenseCode = "";
};
const handleDrawerEvent = (data) => {
  const { eventName = "" } = data;
  // 抽屉点击确定按钮
  console.log(eventName);
  if (eventName === "success") {
    handleConfirm();
  }
};
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
const handleCloseDrawer = async (done) => {
  // if (dialogForm.value) {
  //   await dialogForm.value.resetForm(dialogForm.value.ruleFormRef);
  // }
  done();
};
const handleEvent = (data) => {
  if (data.eventName == "errorSubmit") {
    return;
  }

  if (data.eventName === "successSubmit") {
    handleFormSuccess();
    return;
  }
};
const handleFormSuccess = async () => {
  if (formData.enterpriseId) {
    formData.enterpriseId = formData.enterpriseId.toString();
  }
  let requir = "";
  if (drawerProps.title == "新增") {
    if (formData.id) {
      delete formData.id;
    }
    requir = addDomin;
  } else if (drawerProps.title == "编辑") {
    requir = editDomin;
  }
  let parms = {
    ...formData,
  };
  let res = await requir(parms);
  if (res.code == 200) {
    if (drawerProps.title == "新增") {
      ElMessage.success("新增成功");
    } else {
      ElMessage.success("编辑成功");
    }
    drawerProps.showDrawer = false;
    search();
  }
  console.log(res);
};
// 编辑
const edit = (row) => {
  drawerProps.title = "编辑";
  drawerFormDisabled.value = false;
  setTimeout(() => {
    nextTick(() => {
      drawerProps.showDrawer = true;
      formData.siteName = row.siteName;
      formData.domainName = row.domainName;
      formData.recordIp = row.recordIp;
      formData.sponsor = row.sponsor;
      formData.licenseCode = row.licenseCode;
      formData.id = row.id;
    });
  }, 200);
};
// 删除
const deletedata = (row) => {
  ElMessageBox.confirm("此操作不可逆，是否要确认删除？", "提示", {
    customClass: "message-warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    delDomin({ ids: row.id }).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        search();
      }
    });
  });
};
const rightButtons = ref([
  {
    text: "新增",
    type: "primary",
    eventName: function () {
      addData();
    },
  },
]);

let importVisible = reactive({
  showDrawer: false,
  title: "导入文件",
  size: "big",
});
const handleImportDrawerEvent = (data) => {
  const { eventName = "" } = data;
  // 抽屉点击确定按钮
  if (eventName === "success") {
    // importConfirm();
  }
};
const handleCloseImportDrawer = async (done) => {
  done();
  getTableData("init");
};

const upfile = () => {
  window.location.href = "/static/域名导入模板.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 requre = "";
    let res = await addUploadFile(fd);
    if (res.code == 200) {
      formData.informFile = res.message;
      fileList.value[fileList.value.length - 1].informFile = res.message;
    } else {
      let _data = fileList.value.findIndex((item) => {
        return item.name == uploadFile.name;
      });
      fileList.value.splice(_data, 1);
    }
  }
};
</script>

<template>
  <div>
    <YaPageContent :formData="queryFormData" :formColumns="queryColumns" :tableData="tableData"
      :tableColumns="tableColumn" searchLabelWidth="70px" @search="search" @reset="reset" :currentPage="page"
      :pageSize="size" :total="total" @sizeChange="sizeChange" @selectionChange="handleSelect"
      :rightButtons="rightButtons" @currentChange="currentChange" :leftButtons="buttons" @tableBtnClick="tableBtnClick">
    </YaPageContent>
    <!-- 新增/编辑角色 -->
    <ya-drawer :drawerProps="drawerProps" @handleEvent="handleDrawerEvent" 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">
          <ElIcon class="custom-upload-tip-icon">
            <WarningFilled />
          </ElIcon>
          <div class="custom-upload-tip-right">
            <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 :limit="1" :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>

<style scoped lang="scss">
.custom-upload-tip {
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
  display: flex;
  background: rgba(0, 149, 255, 0.08);
  border-radius: 3px;

  .custom-upload-tip-icon {
    font-size: 16px;
    color: #0095ff;
    margin-right: 4px;
    margin-top: 2px;
  }

  .custom-upload-tip-right {
    p {
      line-height: 22px;
      margin-block-start: 0;
      margin-block-end: 0;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
    }

    .download-template {
      display: inline-flex;
      width: auto;
      height: 18px;
      text-align: center;
      cursor: pointer;
      color: #0095ff;
      border-bottom: 1.5px solid #0095ff;
    }
  }
}

.custom-upload-block {
  width: 100%;
  margin-top: 16px;
}
</style>
