import dayjs from "dayjs";
import editForm from "../components/form.vue";
import { message } from "@/utils/message";
import { type Ref, ref, reactive, onMounted, h } from "vue";
import type { LanguageInfo, TranslationInfo } from "types/system";
import type { PaginationProps } from "@pureadmin/table";
import { addDialog } from "@/components/ReDialog";
import {
  deleteI18nAPI,
  deleteI18nListAPI,
  getI18nListAPI,
  getLocaleListAPI,
  postAddI18nAPI,
  putUpdateI18nAPI
} from "@/api/i18n";
import { getKeyList } from "@pureadmin/utils";

export const useI18n = (tableRef: Ref) => {
  /**
   * 查询表单
   */
  const form = reactive({
    key: "",
    locale_id: "",
    translation: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref(null);
  /**
   * 数据列表
   */
  const dataList = ref<TranslationInfo[]>([]);
  /**
   * 加载状态
   */
  const loading = ref(true);
  /**
   * 已选数量
   */
  const selectedNum = ref<number>(0);
  /**
   * 分页参数
   */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 30, 40, 50]
  });
  /**
   * 表格列设置
   */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "国际化key",
      prop: "key"
    },
    {
      label: "国际化值",
      prop: "translation"
    },
    {
      label: "语言编码",
      prop: "locale_code"
    },
    {
      label: "语言名称",
      prop: "locale_name"
    },
    {
      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 getI18nListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      key: form.key,
      locale_id: form.locale_id,
      translation: form.translation
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
    loading.value = false;
  };
  /**
   * 重置表单
   * @param formEl 表单ref
   * @returns
   */
  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  /**
   * 处理删除
   * @param row
   */
  const handleDelete = async (row: TranslationInfo) => {
    const res = await deleteI18nAPI(row.id);
    if (res.success) {
      onSearch();
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /**
   * 处理每页数量变化
   */
  const handleSizeChange = async (val: number) => {
    const res = await getI18nListAPI({
      page: pagination.currentPage,
      pageSize: val,
      key: form.key,
      locale_id: form.locale_id,
      translation: form.translation
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };

  /**
   * 处理页码变化
   * @param val
   */
  const handleCurrentChange = async (val: number) => {
    const res = await getI18nListAPI({
      page: val,
      pageSize: pagination.pageSize,
      key: form.key,
      locale_id: form.locale_id,
      translation: form.translation
    });
    if (res.success) {
      dataList.value = res.data.result;
      pagination.total = res.data.total;
      pagination.currentPage = res.data.page;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /** 当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 deleteI18nListAPI(getKeyList(curSelected, "id"));
    if (res.success) {
      message(res.msg, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    } else {
      message(res.msg, { type: "error", duration: 5000 });
    }
  };

  const openDialog = async (title = "新增", row?: TranslationInfo) => {
    addDialog({
      title: `${title}国际化项`,
      props: {
        formInline: {
          title: title,
          key: row?.key ?? "",
          locale_id: row?.locale_id ?? "",
          translation: row?.translation ?? ""
        }
      },
      width: "45%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          formInline: {
            title: title,
            key: row?.key ?? "",
            locale_id: row?.locale_id ?? "",
            translation: row?.translation ?? ""
          },
          ref: formRef
        }),
      beforeSure: async (done, {}) => {
        const FormData = formRef.value.newFormInline;
        let form = {
          key: FormData.key ?? "",
          locale_id: FormData.locale_id ?? "",
          translation: FormData.translation ?? ""
        };
        if (title === "新增") {
          const res = await postAddI18nAPI(form);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        } else {
          const res = await putUpdateI18nAPI(form, row.id);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        }
      }
    });
  };

  /**语言类型 */
  const localeList = ref<LanguageInfo[]>([]);

  /**
   * 获取语言类型
   */
  const getLocaleList = async () => {
    const res = await getLocaleListAPI({
      page: 1,
      pageSize: 9999
    });
    if (res.success) {
      localeList.value = res.data.result;
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /**
   * 页面加载执行
   */
  onMounted(async () => {
    await onSearch();
    await getLocaleList();
  });

  return {
    form,
    formRef,
    dataList,
    loading,
    pagination,
    columns,
    selectedNum,
    localeList,
    onSearch,
    openDialog,
    resetForm,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    onbatchDel,
    getLocaleList
  };
};
