import dayjs from "dayjs";
import editForm from "../components/form.vue";
import { message } from "@/utils/message";
import { type Ref, ref, reactive, onMounted, h, toRaw } from "vue";
import type { ConfigInfo } from "types/system";
import type { PaginationProps } from "@pureadmin/table";
import { addDialog } from "@/components/ReDialog";
import {
  deleteConfigAPI,
  deleteConfigListAPI,
  getConfigListAPI,
  postAddConfigAPI,
  putUpdateConfigAPI
} from "@/api/system";
import { getKeyList } from "@pureadmin/utils";

export const useConfig = (tableRef: Ref) => {
  /**
   * 查询表单
   */
  const form = reactive({
    name: "",
    key: "",
    type: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref(null);
  /**
   * 数据列表
   */
  const dataList = ref<ConfigInfo[]>([]);
  /**
   * 加载状态
   */
  const loading = ref(true);
  /**
   * 已选数量
   */
  const selectedNum = ref<number>(0);
  /**
   * 分页参数
   */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  /**
   * 表格列设置
   */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "参数名称",
      prop: "name"
    },
    {
      label: "参数键名",
      prop: "key"
    },
    {
      label: "参数键值",
      prop: "value"
    },
    {
      label: "系统内置",
      prop: "type",
      formatter: ({ type }) => {
        return type ? "是" : "否";
      }
    },
    {
      label: "创建时间",
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }
  ];
  /**
   * 初次查询
   */
  const onSearch = async () => {
    loading.value = true;
    const res = await getConfigListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...toRaw(form)
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
      pagination.pageSize = res.data.pageSize;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
    loading.value = false;
  };
  /**
   * 重置表单
   * @param formEl 表单ref
   * @returns
   */
  const resetForm = async (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    await onSearch();
  };
  /**
   * 处理删除
   * @param row
   */
  const handleDelete = async (row: ConfigInfo) => {
    const res = await deleteConfigAPI(row.id);
    if (res.success) {
      onSearch();
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /**
   * 处理每页数量变化
   */
  const handleSizeChange = async (val: number) => {
    loading.value = true;
    const res = await getConfigListAPI({
      page: pagination.currentPage,
      pageSize: val,
      ...toRaw(form)
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
      pagination.pageSize = res.data.pageSize;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
    loading.value = false;
  };

  /**
   * 处理页码变化
   * @param val
   */
  const handleCurrentChange = async (val: number) => {
    loading.value = true;
    const res = await getConfigListAPI({
      page: val,
      pageSize: pagination.pageSize,
      ...toRaw(form)
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
      pagination.pageSize = res.data.pageSize;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
    loading.value = false;
  };
  /** 当CheckBox选择项发生变化时会触发该事件 */
  const handleSelectionChange = async (val: any) => {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  };

  /** 取消选择 */
  const onSelectionCancel = async () => {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  };
  /**
   * 批量删除
   */
  const onbatchDel = async () => {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const res = await deleteConfigListAPI({
      ids: getKeyList(curSelected, "id")
    });
    if (res.code === 200) {
      message(`已删除项目名称为 ${getKeyList(curSelected, "name")} 的数据`, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } else {
      message(res.msg, { type: "error", duration: 5000 });
    }
  };
  const openDialog = async (title = "新增", row?: ConfigInfo) => {
    addDialog({
      title: `${title}配置`,
      props: {
        formInline: {
          /** 主键ID */
          id: row?.id ?? "",
          /** 创建人 */
          create_by: row?.create_by ?? "",
          /** 创建时间 */
          create_time: row?.create_time ?? "",
          /** 更新人 */
          update_by: row?.update_by ?? "",
          /** 更新时间 */
          update_time: row?.update_time ?? "",
          /**配置名称 */
          name: row?.name ?? "",
          /**配置键 */
          key: row?.key ?? "",
          /**配置值 */
          value: row?.value ?? "",
          /**系统配置 */
          type: row?.type ?? true,
          /**备注 */
          remark: row?.remark ?? ""
        }
      },
      width: "45%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          formInline: {
            /** 主键ID */
            id: row?.id ?? "",
            /** 创建人 */
            create_by: row?.create_by ?? "",
            /** 创建时间 */
            create_time: row?.create_time ?? "",
            /** 更新人 */
            update_by: row?.update_by ?? "",
            /** 更新时间 */
            update_time: row?.update_time ?? "",
            /**配置名称 */
            name: row?.name ?? "",
            /**配置键 */
            key: row?.key ?? "",
            /**配置值 */
            value: row?.value ?? "",
            /**系统配置 */
            type: row?.type ?? true,
            /**备注 */
            remark: row?.remark ?? ""
          },
          ref: formRef
        }),
      beforeSure: async (done, {}) => {
        const FormData = formRef.value.newFormInline;
        let form = {
          key: FormData.key ?? "",
          name: FormData.name ?? "",
          value: FormData.value ?? "",
          type: FormData.type ?? true,
          remark: FormData.remark ?? ""
        };
        if (title === "新增") {
          const res = await postAddConfigAPI(form);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        } else {
          const res = await putUpdateConfigAPI(form, row.id);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        }
      }
    });
  };
  /**
   * 页面加载执行
   */
  onMounted(async () => {
    await onSearch();
  });
  return {
    form,
    dataList,
    loading,
    pagination,
    columns,
    selectedNum,
    openDialog,
    onSearch,
    resetForm,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    onbatchDel
  };
};
