import { computed, onMounted, ref } from "vue";
import {
  type ButtonsCallBackParams,
  type PageInfo,
  type PlusColumn,
  useTable
} from "plus-pro-components";
import { ElMessage } from "element-plus";
import { RegSource, StatusEnum, YesOrNoEnum } from "@/model/enums";
import { api } from "@/api/serveApi";
import { hasPerms } from "@/utils/auth";
import { PermCode } from "@/utils/perm";

export function useServeApi() {
  const isAdd = ref(false);

  // ========= search form =========

  // 查询表单对象
  const searchFormData = ref({
    apiName: "",
    status: "",
    pageIndex: 1,
    pageSize: 10
  });

  // 查询表单字段定义
  const searchFormColumns: PlusColumn[] = [
    {
      label: "接口名称",
      prop: "apiName"
    },
    {
      label: "状态",
      prop: "status",
      width: 80,
      valueType: "select",
      options: [
        {
          label: "启用",
          value: StatusEnum.ENABLE,
          color: "green"
        },
        {
          label: "禁用",
          value: StatusEnum.DISABLE,
          color: "red"
        }
      ]
    }
  ];

  // ========= table =========

  // 表格对象
  const {
    tableData,
    total,
    pageInfo,
    buttons: actionButtons
  } = useTable<any[]>();
  // 默认每页条数,默认10
  pageInfo.value.pageSize = 10;

  // 表格字段定义
  const tableColumns: PlusColumn[] = [
    {
      label: "所属应用",
      prop: "application",
      minWidth: 150
    },
    {
      label: "接口名称",
      prop: "apiName",
      minWidth: 200
    },
    {
      label: "版本号",
      prop: "apiVersion",
      minWidth: 80
    },
    {
      label: "接口描述",
      prop: "description",
      minWidth: 100
    },
    {
      label: "备注",
      prop: "remark"
    },
    {
      label: "需要授权",
      prop: "isPermission",
      width: 100,
      valueType: "select",
      options: [
        {
          label: "否",
          value: 0
        },
        {
          label: "是",
          value: 1,
          color: "green"
        }
      ]
    },
    {
      label: "需要token",
      prop: "isNeedToken",
      width: 100,
      valueType: "select",
      options: [
        {
          label: "否",
          value: 0
        },
        {
          label: "是",
          value: 1,
          color: "green"
        }
      ]
    },
    {
      label: "公共参数",
      prop: "hasCommonResponse",
      width: 100,
      valueType: "select",
      options: [
        {
          label: "无",
          value: 0,
          color: "red"
        },
        {
          label: "有",
          value: 1
        }
      ]
    },
    {
      label: "注册来源",
      prop: "regSource",
      width: 100,
      valueType: "select",
      options: [
        {
          label: "系统",
          value: 1,
          color: "blue"
        },
        {
          label: "手动",
          value: 2,
          color: "green"
        }
      ]
    },
    {
      label: "状态",
      prop: "status",
      width: 80,
      valueType: "select",
      options: [
        {
          label: "启用",
          value: StatusEnum.ENABLE,
          color: "green"
        },
        {
          label: "禁用",
          value: StatusEnum.DISABLE,
          color: "red"
        }
      ]
    },
    {
      width: 120,
      label: "添加时间",
      prop: "addTime"
    },
    {
      width: 120,
      label: "修改时间",
      prop: "updateTime"
    }
  ];
  // 表格按钮权限
  const btnCode = PermCode.api;
  // 表格按钮定义
  actionButtons.value = [
    {
      // 修改
      text: "修改",
      code: "edit",
      props: {
        type: "primary"
      },
      onClick(params: ButtonsCallBackParams) {
        isAdd.value = false;
        editFormData.value = Object.assign({}, params.row);
        dlgTitle.value = "修改接口";
        dlgShow.value = true;
      },
      show: () => hasPerms(btnCode.update)
    },
    {
      // 启用/禁用
      text: row => (row.status === StatusEnum.ENABLE ? "禁用" : "启用"),
      code: "delete",
      confirm: {
        message: data => {
          const opt = data.row.status === StatusEnum.ENABLE ? "禁用" : "启用";
          return `确定${opt}吗？`;
        },
        options: { draggable: false }
      },
      onConfirm(params: ButtonsCallBackParams) {
        const data = {
          id: params.row.id,
          status:
            params.row.status === StatusEnum.ENABLE
              ? StatusEnum.DISABLE
              : StatusEnum.ENABLE
        };
        api.updateStatus(data).then(() => {
          ElMessage.success("修改成功");
          search();
        });
      },
      show: () => hasPerms(btnCode.updateStatus)
    }
  ];

  // ========= dialog form =========

  // 弹窗显示
  const dlgShow = ref(false);
  const dlgTitle = ref("");
  // 表单值
  const editFormDataGen = () => {
    return {
      application: "",
      apiName: "",
      apiVersion: "",
      status: 1,
      isPermission: 0,
      description: "",
      regSource: RegSource.CUSTOM,
      isNeedToken: 0
    };
  };

  const editFormData = ref<any>(editFormDataGen());
  const editFormRules = {
    application: [{ required: true, message: "请输入应用名称" }],
    apiName: [{ required: true, message: "请输入接口名称" }],
    apiVersion: [{ required: true, message: "请输入版本号" }]
  };
  const isCustomRegSource = computed(() => {
    return editFormData.value.regSource === RegSource.CUSTOM;
  });

  // 表单内容
  const editFormColumns: PlusColumn[] = [
    {
      label: "所属应用",
      prop: "application",
      valueType: "text"
    },
    {
      label: "接口名称",
      prop: "apiName",
      valueType: "text"
    },
    {
      label: "版本号",
      prop: "apiVersion",
      valueType: "text"
    },
    {
      label: "接口描述",
      prop: "description",
      valueType: "text"
    },
    {
      label: "备注",
      prop: "remark",
      valueType: "textarea",
      fieldProps: {
        maxlength: 5000,
        showWordLimit: true,
        autosize: { minRows: 2, maxRows: 4 }
      }
    },
    {
      label: "需要授权",
      prop: "isPermission",
      valueType: "radio",
      options: [
        {
          label: "否",
          value: YesOrNoEnum.NO,
          color: "red"
        },
        {
          label: "是",
          value: YesOrNoEnum.YES,
          color: "green"
        }
      ]
    },
    {
      label: "需要token",
      prop: "isNeedToken",
      valueType: "radio",
      options: [
        {
          label: "否",
          value: YesOrNoEnum.NO,
          color: "red"
        },
        {
          label: "是",
          value: YesOrNoEnum.YES,
          color: "green"
        }
      ]
    },
    {
      label: "状态",
      prop: "status",
      valueType: "radio",
      options: [
        {
          label: "禁用",
          value: StatusEnum.DISABLE,
          color: "red"
        },
        {
          label: "启用",
          value: StatusEnum.ENABLE,
          color: "green"
        }
      ]
    }
  ];

  // ========= event =========

  // 添加按钮事件
  const handleAdd = () => {
    isAdd.value = true;
    editFormData.value = editFormDataGen();
    dlgTitle.value = "新增接口";
    dlgShow.value = true;
  };

  // 保存按钮事件,校验成功后触发
  const handleSave = () => {
    const postData = editFormData.value;
    const pms = isAdd.value ? api.add(postData) : api.update(postData);
    pms.then(() => {
      ElMessage.success("保存成功");
      dlgShow.value = false;
      search();
    });
  };

  // 点击查询按钮
  const handleSearch = () => {
    pageInfo.value.page = 1;
    search();
  };

  // 分页事件
  const handlePaginationChange = (_pageInfo: PageInfo): void => {
    pageInfo.value = _pageInfo;
    search();
  };

  // 查询
  const search = async () => {
    try {
      const { data } = await doSearch();
      tableData.value = data.list;
      total.value = data.total;
    } catch (error) {}
  };
  // 请求接口
  const doSearch = async () => {
    // 查询参数
    const data = searchFormData.value;
    // 添加分页参数
    data.pageIndex = pageInfo.value.page;
    data.pageSize = pageInfo.value.pageSize;

    return api.page(data);
  };

  // 页面加载
  onMounted(() => {
    search();
  });

  return {
    actionButtons,
    dlgShow,
    dlgTitle,
    editFormColumns,
    editFormData,
    editFormRules,
    handleAdd,
    handlePaginationChange,
    handleSave,
    handleSearch,
    isCustomRegSource,
    pageInfo,
    searchFormColumns,
    searchFormData,
    tableColumns,
    tableData,
    total
  };
}
