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 {
  getLocaleListAPI,
  deleteLocaleAPI,
  postAddLocaleAPI,
  putUpdateLocaleAPI,
  getI18nHandleListAPI
} from "@/api/i18n";

import jsyaml from "js-yaml";

export const useLocale = (tableRef: Ref) => {
  /**
   * 查询表单
   */
  const form = reactive({
    name: "",
    code: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref(null);
  /**
   * 数据列表
   */
  const dataList = ref<LanguageInfo[]>([]);
  /**
   * 加载状态
   */
  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: "语言编码",
      prop: "code"
    },
    {
      label: "语言名称",
      prop: "name"
    },
    {
      label: "创建时间",
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];

  /**
   * 初次查询
   */
  const onSearch = async () => {
    loading.value = true;
    const res = await getLocaleListAPI({
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      name: form.name,
      code: form.code
    });
    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 deleteLocaleAPI(row.id);
    if (res.success) {
      onSearch();
    }
    message(res.msg, {
      type: res.success ? "success" : "error"
    });
  };
  /**
   * 处理每页数量变化
   */
  const handleSizeChange = async (val: number) => {
    const res = await getLocaleListAPI({
      page: pagination.currentPage,
      pageSize: val,
      name: form.name,
      code: form.code
    });
    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 getLocaleListAPI({
      page: val,
      pageSize: pagination.pageSize,
      name: form.name,
      code: form.code
    });
    if (res.code === 200) {
      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 openDialog = async (title = "新增", row?: LanguageInfo) => {
    addDialog({
      title: `${title}国际化项`,
      props: {
        formInline: {
          title: title,
          name: row?.name ?? "",
          code: row?.code ?? ""
        }
      },
      width: "45%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          formInline: {
            title: title,
            name: row?.name ?? "",
            code: row?.code ?? ""
          },
          ref: formRef
        }),
      beforeSure: async (done, {}) => {
        const FormData = formRef.value.newFormInline;
        let form = {
          name: FormData.name ?? "",
          code: FormData.code ?? ""
        };
        if (title === "新增") {
          const res = await postAddLocaleAPI(form);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        } else {
          const res = await putUpdateLocaleAPI(form, row.id);
          if (res.success) {
            done();
            await onSearch();
          }
          message(res.msg, { type: res.success ? "success" : "error" });
        }
      }
    });
  };

  /**
   * 导出 YAML 文件
   */
  const export_to_yaml = async (row: LanguageInfo) => {
    const res = await getI18nHandleListAPI(row.id); // 调用 API 获取数据
    if (res.success) {
      // 将 JSON 转换为 YAML
      const yamlString = jsyaml.dump(res.data.data);

      // 创建 Blob 对象
      const blob = new Blob([yamlString], { type: "text/yaml" });

      // 生成下载链接
      const url = URL.createObjectURL(blob);

      // 创建 <a> 元素并触发下载
      const link = document.createElement("a");
      link.href = url;
      link.download = `${row.code}.yaml`; // 设置下载文件名
      document.body.appendChild(link); // 将 <a> 元素添加到 DOM 中
      link.click(); // 模拟点击下载

      // 清理 URL 对象
      URL.revokeObjectURL(url);
      document.body.removeChild(link); // 移除 <a> 元素
    }
  };
  /**
   * 页面加载执行
   */
  onMounted(async () => {
    await onSearch();
  });

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