<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, unref } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import CommonTabs from "../../../components/CommonTabs/CommonTabs.vue";
import { downLoadFile } from "../../../utils/utils";
import { usePermissions } from "../../../composables/usePermissions";
import {
  getSystemList,
  getCustomList,
  createPort,
  modifyPort,
  deletePort,
  resetPort,
  isSystemPort,
  exportSome,
} from "../../../api/safetyMangement/portPolicy";
const { permissionsButtons } = usePermissions();
const butomData = ref([]);
const rightButtons = ref([]);
const leftButtons = ref([]);
const tableData = ref([]);
/**
 * @description: 分页参数
 */
const page = ref(1);
const total = ref(0);
const size = ref(20);

/**
 * @description:表格头部数据
 */
let tableColumn: any[] = [
  {
    prop: "service",
    label: "服务名",
    align: "left",
  },
  {
    prop: "port",
    label: "端口",
  },
  {
    prop: "protocol",
    label: "协议",
  },
];
/**
 * @description: 表格操作
 */
const tableBtnClick = (btn, row) => {
  console.log(123213)
  if (btn.text == "批量导出") {
    // handleDel(btn);
    autoBtn("export");
  } else {
    if (btn.text == '新增') {
      autoBtn("add");
    }
  }
};
/**
 * @description: 删除
 * @return {*}
 */
const handleDel = async (id) => {
  ElMessageBox.confirm("此操作不可逆，是否要确认删除？", "提示", {
    customClass: "message-warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    deletePort({
      id: id,
    }).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        getTableData();
      }
    });
  });
};
/**
 * @description: 重置操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const reset = () => {
  getTableData("init");
};
/**
 * @description: 获取表格数据
 * @param {*}
 * @return {*}
 */
const getTableData = async (type) => {
  if (type === "init") {
    page.value = 1;
  }
  let send;
  if (currentTabName.value == 1) {
    send = getSystemList;
  } else {
    send = getCustomList;
  }
  try {
    const params = {
      pageIndex: page.value,
      pageSize: size.value,
    };
    const res = await send(params);
    if (res.code !== 200) return;
    tableData.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
  }
};
/**
 * @description: 页面容量切换
 * @param {*}
 * @return {*}
 */
const sizeChange = function (val: number) {
  size.value = val;
  page.value = 1;
  getTableData("page");
};
/**
 * @description: 分页切换
 * @param {*}
 * @return {*}
 */
const currentChange = function (val: number) {
  page.value = val;
  getTableData("page");
};
/**
 * @description: tab选项
 */
const tabs = ref([
  {
    title: "系统端口",
    value: 1,
  },
  {
    title: "自定义端口",
    value: 2,
  },
]);
const isShow = ref(true);

const currentTabName = ref(1);
watch(currentTabName, () => {
  isShow.value = false;
  getTableData("init");
  rightButtons.value = [];
  leftButtons.value = [];
  tableData.value = [];
  if (currentTabName.value == 2) {
    nextTick(() => {
      isShow.value = true;
      resetTable(true);
    });
  } else {
    nextTick(() => {
      isShow.value = true;
      resetTable(false);
    });
  }
});
/**
 * @description: 重置table表头
 */
const resetTable = (e) => {
  page.value = 1;
  size.value = 20;
  if (e) {
    tableColumn.unshift({
      type: "selection",
      width: "65px",
    });
    tableColumn.push({
      label: "操作",
      fixed: "right",
      width: "160px",
      buttons: [
        {
          title: "编辑",
          hide: () => {
            if (butomData.value.indexOf("编辑") > -1) {
              return true;
            }
          },
          eventName: function (row) {
            autoBtn("edit", row);
          },
        },
        {
          title: "删除",
          hide: () => {
            if (butomData.value.indexOf("删除") > -1) {
              return true;
            }
          },
          eventName: function (row) {
            autoBtn("del", row);
          },
        },
      ],
    });
    if (butomData.value.indexOf("批量导出") > -1) {
      leftButtons.value.push({
        text: "批量导出",
        type: "primary",
        eventName: function () {
          autoBtn("export");
        },
      });
    }
    if (butomData.value.indexOf("新增") > -1) {
      rightButtons.value.push({
        text: "新增",
        type: "primary",
        eventName: function () {
          autoBtn("add");
        },
      });
    }
  } else {
    tableColumn.splice(0, 1);
    tableColumn.splice(3, 1);
    if (butomData.value.indexOf("系统端口恢复") > -1) {
      rightButtons.value.push({
        text: "系统端口恢复",
        type: "primary",
        eventName: function () {
          autoBtn("reset");
        },
      });
    }
  }
};
/**
 * @description: 新增抽屉
 */
const drawerProps = reactive({
  showDrawer: false,
  title: "新增",
  size: "small",
});
const dialogForm = ref();
const formData = ref({});
const formColumns = reactive([
  {
    key: "service",
    type: "input",
    label: "服务名",
    placeholder: "请输入服务名",
    clearable: true,
  },
  {
    key: "port",
    type: "input",
    label: "端口",
    placeholder: "请输入端口",
    clearable: true,
    disabled: false,
  },
  {
    key: "protocol",
    label: "协议",
    type: "select",
    clearable: true,
    col: 24,
    options: [
      {
        label: "TCP",
        value: "TCP",
      },
      {
        label: "UDP",
        value: "UDP",
      },
    ],
  },
]);
/**
 * @description: 新增规则
 */
var checkMoney = (rule, value, callback) => {
  if (value < 1) {
    callback(new Error("范围在1-65535"));
  } else if (value > 65535) {
    callback(new Error("范围在1-65535"));
  } else {
    callback();
  }
};
const rules = reactive<FormRules>({
  service: [
    { required: true, message: "服务名不能为空", trigger: "change" },
    { min: 1, message: "服务名至少1位" },
    { max: 18, message: "服务名最多18位" },
    {
      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
      message: "不允许输入空格等特殊符号",
    },
  ],
  port: [
    { required: true, message: "端口号不能为空", trigger: "change" },
    { validator: checkMoney, trigger: "blur" },
    { pattern: /^[0-9\u4e00-\u9fa5]+$/, message: "请输入数字" },
  ],
  protocol: [{ required: true, message: "协议不能为空", trigger: "change" }],
});
/**
 * @description: 关闭抽屉
 */
const handleCloseDrawer = async () => {
  formData.value = {};
  drawerProps.showDrawer = false;
};
// 抽屉事件
const handleEvent = function (data) {
  if (data.eventName == "errorSubmit") {
    return;
  } else if (data.eventName == "success") {
    console.log(dialogForm.value, 'dialogForm.value')
    dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
    return;
  } else if (data.eventName == "successSubmit") {
    handleSubmit();
    return;
  }
};
/**
 * @description 新增/编辑确认
 */
const handleSubmit = () => {
  if (!formData.value.id) {
    isSystemPort({ port: formData.value.port }).then((res) => {
      console.log(res, "ss");
      if (res.data) {
        ElMessageBox.confirm("系统端口中已存在，是否需要添加？", "系统端口", {
          customClass: "message-warning",
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          handleSendData();
        });
      } else {
        handleSendData();
      }
    });
  } else {
    handleSendData();
  }
};
/**
 * @description 新增/编辑提交
 */
const handleSendData = () => {
  let send;
  if (formData.value.id) {
    send = modifyPort;
  } else {
    send = createPort;
  }
  send(formData.value).then((res) => {
    if (res.code == 200) {
      getTableData("init");
      drawerProps.showDrawer = false;
      ElMessage.success(formData.value.id ? "编辑" : "新增" + "成功!");
    }
  });
};
/**
 * @description: 表格多选操作
 */
const selectData = ref([]);
const handleSelect = (data) => {
  selectData.value = data;
};
/**
 * @description: 新增/编辑提交
 *  @param {'add': 新增, 'reset': '系统重置', 'export': '批量导出', 'edit': '编辑', 'del': '删除'}
 */
const autoBtn = (e, row) => {
  switch (e) {
    case "reset":
      ElMessageBox.confirm("重置系统端口, 是否继续？", "提示", {
        customClass: "message-warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        resetPort().then((res) => {
          ElMessage.success("系统端口恢复成功！");
          getTableData("init");
        });
      });
      break;
    case "add":
      drawerProps.title = "新增";
      formData.value = {};
      drawerProps.showDrawer = true;
      nextTick(() => {
        formColumns[1].disabled = false;
      });
      break;
    case "export":
      if (selectData.value.length === 0) {
        ElMessage.warning("请选择要批量删除的数据");
        return;
      }
      let ids = selectData.value.map((item) => {
        return item.id;
      });
      exportSome(ids).then((res) => {
        if (res.code != 2003) downLoadFile(res, "自定义端口");
      });
      break;
    case "edit":
      drawerProps.title = "编辑";
      drawerProps.showDrawer = true;
      unref(formData).id = row.id;
      unref(formData).port = row.port;
      unref(formData).protocol = row.protocol;
      unref(formData).service = row.service;
      console.log(row);
      nextTick(() => {
        formColumns[1].disabled = true;
      });
      break;
    case "del":
      handleDel(row.id);
      break;
  }
};
/**
 * 按钮权限
 */
const btnPower = () => {
  permissionsButtons.map((item) => {
    butomData.value.push(item.label);
  });
  if (butomData.value.indexOf("系统端口恢复") > -1) {
    rightButtons.value.push({
      text: "系统端口恢复",
      type: "primary",
      eventName: function () {
        autoBtn("reset");
      },
    });
  }
};
/**
 * @description: 页面渲染结束后执行
 */
onMounted(() => {
  btnPower();
  getTableData("init");
});
</script>
<template>
  <div>
    <CommonTabs
      :tabs="tabs"
      v-model:tabValue="currentTabName"
      :roundOptions="[]"
    >
    </CommonTabs>
    <YaPageContent
      v-if="isShow"
      searchLabelWidth="100px"
      :tableData="tableData"
      :tableColumns="tableColumn"
      :currentPage="page"
      :pageSize="size"
      :total="total"
      :leftButtons="leftButtons"
      :rightButtons="rightButtons"
      @sizeChange="sizeChange"
      @currentChange="currentChange"
      @selectionChange="handleSelect"
      @reset="reset"
      @tableBtnClick="tableBtnClick"
    >
    </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>
  </div>
</template>
