import dayjs from "dayjs";
import { message } from "@/utils/message";
import { useRouter } from "vue-router";
import type { PaginationProps } from "@pureadmin/table";
import {
  getArchiveList,
  deleteArchive,
  getEnumOptions
} from "@/api/shopArchive";
import { type Ref, ref, reactive, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import type { ShopArchive, ShopArchiveQuery, EnumOption } from "./types";
import {
  initPagination,
  handlePageSizeChange,
  handleCurrentPageChange,
  resetPagination
} from "@/utils/paginationHelper";

export function useShopArchive(tableRef: Ref) {
  const router = useRouter();
  const form = reactive<ShopArchiveQuery>({
    shopName: "",
    contractNo: "",
    contractStatus: "",
    businessStatus: "",
    billingMode: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>(initPagination());

  // 枚举选项
  const contractStatusOptions = ref<EnumOption[]>([]);
  const businessStatusOptions = ref<EnumOption[]>([]);
  const billingModeOptions = ref<EnumOption[]>([]);

  const columns: TableColumnList = [
    {
      label: "门店名称",
      prop: "shopName",
      minWidth: 150
    },
    {
      label: "合同编号",
      prop: "contractNo",
      minWidth: 120,
      formatter: ({ contractNo }) => contractNo || "-"
    },
    {
      label: "合同状态",
      prop: "contractStatus",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const statusMap: Record<string, { label: string; type: string }> = {
          NORMAL: { label: "正常", type: "success" },
          EXPIRING: { label: "即将到期", type: "warning" },
          EXPIRED: { label: "已过期", type: "info" },
          TERMINATED: { label: "已终止", type: "danger" }
        };
        const status = statusMap[row.contractStatus] || {
          label: row.contractStatusLabel || "未知",
          type: "info"
        };
        return <el-tag type={status.type as any}>{status.label}</el-tag>;
      }
    },
    {
      label: "经营状态",
      prop: "businessStatus",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const statusMap: Record<string, { label: string; type: string }> = {
          NORMAL: { label: "正常", type: "success" },
          SUSPENDED: { label: "暂停", type: "warning" },
          WITHDRAWN: { label: "已撤场", type: "danger" }
        };
        const status = statusMap[row.businessStatus] || {
          label: row.businessStatusLabel || "未知",
          type: "info"
        };
        return <el-tag type={status.type as any}>{status.label}</el-tag>;
      }
    },
    {
      label: "计费模式",
      prop: "billingMode",
      minWidth: 100,
      formatter: ({ billingMode }) => {
        const modeMap: Record<string, string> = {
          ELECTRICITY: "电费",
          COMMISSION: "提成",
          RENT: "租金"
        };
        return modeMap[billingMode] || billingMode || "-";
      }
    },
    {
      label: "每月租金",
      prop: "monthlyRent",
      minWidth: 100,
      formatter: ({ monthlyRent }) =>
        monthlyRent ? `¥${monthlyRent.toFixed(2)}` : "-"
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  // 加载枚举选项
  async function loadEnumOptions() {
    try {
      const [contractRes, businessRes, billingRes] = await Promise.all([
        getEnumOptions("contractStatus"),
        getEnumOptions("businessStatus"),
        getEnumOptions("billingMode")
      ]);
      contractStatusOptions.value = contractRes.data || [];
      businessStatusOptions.value = businessRes.data || [];
      billingModeOptions.value = billingRes.data || [];
    } catch (error) {
      console.error("加载枚举选项失败:", error);
    }
  }

  // 搜索
  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };

      if (form.shopName) searchParams.shopName = form.shopName;
      if (form.contractNo) searchParams.contractNo = form.contractNo;
      if (form.contractStatus) searchParams.contractStatus = form.contractStatus;
      if (form.businessStatus) searchParams.businessStatus = form.businessStatus;
      if (form.billingMode) searchParams.billingMode = form.billingMode;

      const { data } = await getArchiveList(searchParams);
      dataList.value = data.list || [];
      pagination.total = Number(data.total) || 0;
    } catch (error) {
      console.error("获取门店档案列表失败:", error);
      dataList.value = [];
      pagination.total = 0;
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  // 重置表单
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    resetPagination(pagination, onSearch);
  };

  // 分页
  function handleSizeChange(val: number) {
    handlePageSizeChange(val, pagination, onSearch);
  }

  function handleCurrentChange(val: number) {
    handleCurrentPageChange(val, pagination, onSearch);
  }

  // 新增
  function handleAdd() {
    router.push({ path: "/operation/shop-archive/detail", query: { mode: "create" } });
  }

  // 编辑
  function handleUpdate(row: ShopArchive) {
    router.push(`/operation/shop-archive/detail/${row.id}?mode=edit`);
  }

  // 查看
  function handleView(row: ShopArchive) {
    router.push(`/operation/shop-archive/detail/${row.id}`);
  }

  // 删除
  async function handleDelete(row: ShopArchive) {
    try {
      await ElMessageBox.confirm(
        `确认要删除门店档案 ${row.shopName} 吗？`,
        "系统提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      const res = await deleteArchive(row.id);
      if (res.code === 0 || res.code === 200) {
        message(`已成功删除门店档案 ${row.shopName}`, { type: "success" });
        onSearch();
      } else {
        message(res.message || "删除失败", { type: "error" });
      }
    } catch (error) {
      // 用户取消或请求失败
    }
  }

  onMounted(() => {
    loadEnumOptions();
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    contractStatusOptions,
    businessStatusOptions,
    billingModeOptions,
    onSearch,
    resetForm,
    handleAdd,
    handleUpdate,
    handleView,
    handleDelete,
    handleSizeChange,
    handleCurrentChange
  };
}
