import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import EnhancedImage from "../../components/EnhancedImage.vue";
import { getMasterProductList, addToMerchantProducts } from "@/api/product";
import { type Ref, ref, reactive, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import type { MasterProductItem, MasterProductSearchForm } from "./types";

export function useMasterLibrary(tableRef: Ref) {
  const form = reactive<MasterProductSearchForm>({
    productName: "",
    barcode: "",
    code: "",
    deviceAdapt: ""
  });
  const formRef = ref();
  const dataList = ref<MasterProductItem[]>([]);
  const loading = ref(true);
  const selectedRows = ref<MasterProductItem[]>([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100],
    layout: "total, sizes, prev, pager, next, jumper"
  });

  const deviceAdaptOptions = [
    { label: "全部", value: "" },
    { label: "静态柜", value: "STATIC" },
    { label: "动态柜", value: "DYNAMIC" }
  ];

  const columns: TableColumnList = [
    {
      type: "selection",
      width: 50
    },
    {
      label: "商品图片",
      prop: "pic",
      width: 80,
      cellRenderer: ({ row }) => (
        <EnhancedImage
          src={row.pic || "/img/placeholder.png"}
          alt={row.name}
          width={50}
          height={50}
          fit="cover"
          preview={true}
          lazy={true}
        />
      )
    },
    {
      label: "商品编码",
      prop: "code",
      minWidth: 100
    },
    {
      label: "商品名称",
      prop: "name",
      minWidth: 120
    },
    {
      label: "条码",
      prop: "barcode",
      minWidth: 100
    },
    {
      label: "适用设备",
      prop: "deviceAdapt",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const parts: string[] = [];
        if (row.static_status === "1") parts.push("静态柜");
        if (row.dynamic_status === "1") parts.push("动态柜");
        return <span>{parts.join("、") || "-"}</span>;
      }
    },
  ];

  async function onSearch() {
    loading.value = true;
    selectedRows.value = [];
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      if (form.productName) searchParams.productName = form.productName;
      if (form.barcode) searchParams.barcode = form.barcode;
      if (form.code) searchParams.code = form.code;
      if (form.deviceAdapt) searchParams.deviceAdapt = form.deviceAdapt;

      const { data } = await getMasterProductList(searchParams);
      dataList.value = (data.list || []) as MasterProductItem[];
      pagination.total = Number(data.total ?? 0);
    } catch (error) {
      console.error("获取商品总库列表失败:", error);
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    pagination.currentPage = 1;
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(rows: MasterProductItem[]) {
    selectedRows.value = rows;
  }

  async function handleAddToMerchant() {
    if (selectedRows.value.length === 0) {
      message("请先选择要添加的商品", { type: "warning" });
      return;
    }

    const codes = selectedRows.value.map(r => r.code);
    try {
      await ElMessageBox.confirm(
        `确认将以下 ${codes.length} 个商品添加到商家商品库？`,
        "系统提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      );

      const res = await addToMerchantProducts({
        codeList: codes.join(",")
      });
      if (res.code === 200 || res.code === 0) {
        message(`成功添加 ${codes.length} 个商品到商家商品库`, {
          type: "success"
        });
        onSearch();
      } else {
        message(res.message || "添加失败", { type: "error" });
      }
    } catch (error) {
      // 用户取消或请求失败
      if (error !== "cancel") {
        message("添加失败", { type: "error" });
      }
    }
  }

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

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    pagination,
    selectedRows,
    deviceAdaptOptions,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleAddToMerchant
  };
}
