import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import EnhancedImage from "../components/EnhancedImage.vue";
import {
  getProductList,
  addProduct,
  updateProduct,
  deleteProduct,
  syncProduct,
  setProductShelfStatus,
  getDeviceProducts
} from "@/api/product";
import { type Ref, ref, toRaw, reactive, onMounted } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadioButton,
  ElMessageBox
} from "element-plus";
import type { ProductItem, ProductSearchForm } from "./types";

export function useProduct(tableRef: Ref) {
  const form = reactive<ProductSearchForm>({
    name: "",
    barcode: "",
    category: "",
    syncStatus: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  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 categoryOptions = [
    { label: "饮料", value: "drink" },
    { label: "零食", value: "snack" },
    { label: "日用品", value: "daily" },
    { label: "其他", value: "other" }
  ];

  const columns: TableColumnList = [
    {
      label: "商品 ID",
      prop: "id",
      width: 70
    },
    {
      label: "商品图片",
      prop: "imageUrl",
      width: 80,
      cellRenderer: ({ row }) => (
        <EnhancedImage
          src={row.imageUrl || "/img/placeholder.png"}
          alt={row.name}
          width={50}
          height={50}
          fit="cover"
          preview={true}
          lazy={true}
        />
      )
    },
    {
      label: "商品名称",
      prop: "name",
      minWidth: 120
    },
    {
      label: "商品编码",
      prop: "code",
      minWidth: 100
    },
    {
      label: "条码",
      prop: "barcode",
      minWidth: 100
    },
    {
      label: "商品分类",
      prop: "category",
      minWidth: 80,
      formatter: ({ category }) => {
        const item = categoryOptions.find(c => c.value === category);
        return item?.label || category;
      }
    },
    {
      label: "适用设备",
      prop: "applyStatus",
      minWidth: 100,
      formatter: ({ applyStatus }) => {
        if (!applyStatus) return "-";
        const statusMap: Record<string, string> = {
          "ALL": "全部柜",
          "STATIC": "静态柜",
          "DYNAMIC": "动态柜"
        };
        return statusMap[applyStatus] || applyStatus;
      }
    },
    {
      label: "统一售价 (元)",
      prop: "retailPrice",
      minWidth: 85,
      formatter: ({ retailPrice }) => 
        retailPrice ? retailPrice.toFixed(2) : "-"
    },
    {
      label: "进价 (元)",
      prop: "costPrice",
      minWidth: 85,
      formatter: ({ costPrice }) => 
        costPrice ? costPrice.toFixed(2) : "-"
    },
    {
      label: "同步状态",
      prop: "syncStatus",
      minWidth: 85,
      cellRenderer: ({ row }) => {
        const statusMap: Record<number, { label: string; type: string }> = {
          0: { label: "未同步", type: "info" },
          1: { label: "同步中", type: "warning" },
          2: { label: "已同步", type: "success" },
          3: { label: "同步失败", type: "danger" }
        };
        const status = statusMap[row.syncStatus] || { label: "未知", type: "info" };
        return <el-tag type={status.type as any}>{status.label}</el-tag>;
      }
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : "-"
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }
  ];

  // 商品表单
  const productForm = reactive({
    name: "",
    barcode: "",
    category: "",
    price: 0,
    costPrice: 0,
    imageUrl: "",
    description: "",
    specification: "",
    unit: "个",
    status: 1
  });

  // 搜索
  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      // 只添加非空的搜索条件
      if (form.name) searchParams.name = form.name;
      if (form.barcode) searchParams.barcode = form.barcode;
      if (form.category) searchParams.category = form.category;
      if (form.syncStatus !== "") {
        searchParams.syncStatus = parseInt(form.syncStatus, 10);
      }
      
      const { data } = await getProductList(searchParams as {
        page?: number;
        pageSize?: number;
        name?: string;
        barcode?: string;
        category?: string;
        syncStatus?: number;
      });
      dataList.value = data.list;
      pagination.total = Number(data.total);
    } catch (error) {
      console.error("获取商品列表失败:", error);
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    }
  }

  // 重置表单
  const resetForm = formEl => {
    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 openDialog(title = "新增", row?: ProductItem) {
    Object.assign(productForm, {
      name: row?.name ?? "",
      barcode: row?.barcode ?? "",
      category: row?.category ?? "",
      price: row?.price ? row.price / 100 : 0,
      costPrice: row?.costPrice ? row.costPrice / 100 : 0,
      imageUrl: row?.imageUrl ?? "",
      description: row?.description ?? "",
      specification: row?.specification ?? "",
      unit: row?.unit ?? "个",
      status: row?.status ?? 1
    });

    addDialog({
      title: `${title}商品`,
      width: "50%",
      draggable: true,
      fullscreen: deviceDetection(),
      closeOnClickModal: false,
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={productForm} label-width="100px">
          <ElFormItem
            label="商品名称"
            prop="name"
            rules={[{ required: true, message: "请输入商品名称", trigger: "blur" }]}
          >
            <ElInput v-model={productForm.name} placeholder="请输入商品名称" clearable />
          </ElFormItem>
          <ElFormItem
            label="条码"
            prop="barcode"
            rules={[{ required: true, message: "请输入条码", trigger: "blur" }]}
          >
            <ElInput v-model={productForm.barcode} placeholder="请输入条码" clearable />
          </ElFormItem>
          <ElFormItem label="分类" prop="category">
            <ElSelect v-model={productForm.category} placeholder="请选择分类" class="w-full!">
              {categoryOptions.map(item => (
                <ElOption key={item.value} label={item.label} value={item.value} />
              ))}
            </ElSelect>
          </ElFormItem>
          <ElFormItem
            label="售价(元)"
            prop="price"
            rules={[{ required: true, message: "请输入售价", trigger: "blur" }]}
          >
            <ElInputNumber
              v-model={productForm.price}
              min={0}
              precision={2}
              class="w-full!"
            />
          </ElFormItem>
          <ElFormItem label="成本价(元)" prop="costPrice">
            <ElInputNumber
              v-model={productForm.costPrice}
              min={0}
              precision={2}
              class="w-full!"
            />
          </ElFormItem>
          <ElFormItem label="商品图片" prop="imageUrl">
            <ElInput v-model={productForm.imageUrl} placeholder="请输入图片 URL" clearable />
          </ElFormItem>
          <ElFormItem label="规格" prop="specification">
            <ElInput v-model={productForm.specification} placeholder="请输入规格" clearable />
          </ElFormItem>
          <ElFormItem label="单位" prop="unit">
            <ElInput v-model={productForm.unit} placeholder="请输入单位" clearable />
          </ElFormItem>
          <ElFormItem label="描述" prop="description">
            <ElInput
              v-model={productForm.description}
              type="textarea"
              placeholder="请输入商品描述"
              rows={3}
            />
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) return;

        try {
          const submitData = {
            ...toRaw(productForm),
            price: Math.round(productForm.price * 100),
            costPrice: Math.round(productForm.costPrice * 100)
          };

          if (title === "新增") {
            const res = await addProduct(submitData);
            if (res.code === 200 || res.code === 0) {
              message(`新增商品 ${productForm.name} 成功`, { type: "success" });
              done();
              onSearch();
            } else {
              message(res.message || "新增失败", { type: "error" });
            }
          } else {
            const res = await updateProduct(row.id, submitData);
            if (res.code === 200 || res.code === 0) {
              message(`修改商品 ${productForm.name} 成功`, { type: "success" });
              done();
              onSearch();
            } else {
              message(res.message || "修改失败", { type: "error" });
            }
          }
        } catch (error) {
          message("操作失败", { type: "error" });
        }
      }
    });
  }

  // 删除商品
  async function handleDelete(row: ProductItem) {
    try {
      const res = await deleteProduct(row.id);
      if (res.code === 200 || res.code === 0) {
        message(`已成功删除商品 ${row.name}`, { type: "success" });
        onSearch();
      } else {
        message(res.message || "删除失败", { type: "error" });
      }
    } catch (error) {
      message("删除失败", { type: "error" });
    }
  }

  // 同步商品
  async function handleSync(row: ProductItem) {
    try {
      await ElMessageBox.confirm(`确认要同步商品 ${row.name} 到设备吗?`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      });

      const res = await syncProduct(row.id);
      if (res.code === 200 || res.code === 0) {
        row.syncStatus = 1;
        message(`商品 ${row.name} 同步成功`, { type: "success" });
      } else {
        message(res.message || "同步失败", { type: "error" });
      }
    } catch (error) {
      // 用户取消或请求失败
    }
  }

  // 商品上下架
  async function handleShelfStatus(row: ProductItem) {
    const shelfForm = reactive({
      deviceId: "",
      goodsCode: row.code || "",
      salesType: "IN"
    });

    addDialog({
      title: `商品上下架 - ${row.name}`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <ElForm ref={ruleFormRef} model={shelfForm} label-width="100px">
          <ElFormItem
            label="设备ID"
            prop="deviceId"
            rules={[{ required: true, message: "请输入设备SN号", trigger: "blur" }]}
          >
            <ElInput v-model={shelfForm.deviceId} placeholder="设备SN号" clearable />
          </ElFormItem>
          <ElFormItem label="操作类型" prop="salesType">
            <ElRadioGroup v-model={shelfForm.salesType}>
              <ElRadioButton value="IN">上架</ElRadioButton>
              <ElRadioButton value="OUT">下架</ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
        </ElForm>
      ),
      beforeSure: async (done) => {
        try {
          const res = await setProductShelfStatus({
            deviceId: shelfForm.deviceId,
            goodsCode: shelfForm.goodsCode,
            salesType: shelfForm.salesType
          });
          if (res.code === 200 || res.code === 0) {
            const action = shelfForm.salesType === "IN" ? "上架" : "下架";
            message(`商品 ${row.name} ${action}成功`, { type: "success" });
            done();
            onSearch();
          } else {
            message(res.message || "操作失败", { type: "error" });
          }
        } catch (error) {
          message("操作失败", { type: "error" });
        }
      }
    });
  }

  // 查看设备商品列表
  async function handleDeviceProducts() {
    const deviceForm = reactive({ deviceId: "" });
    const deviceProductList: any = ref([]);

    const loadDeviceProducts = async () => {
      if (!deviceForm.deviceId) return;
      try {
        const { data } = await getDeviceProducts(deviceForm.deviceId);
        deviceProductList.value = data || [];
      } catch {
        deviceProductList.value = [];
      }
    };

    addDialog({
      title: "设备商品列表",
      width: "50%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <div>
          <div style="display: flex; gap: 8px; margin-bottom: 12px;">
            <ElInput v-model={deviceForm.deviceId} placeholder="请输入设备SN号" style="flex:1" />
            <el-button type="primary" onClick={loadDeviceProducts}>查询</el-button>
          </div>
          <div v-loading={false}>
            {deviceProductList.value.length === 0 ? (
              <div style="text-align: center; padding: 40px; color: #999;">
                {deviceForm.deviceId ? "该设备暂无商品" : "请输入设备SN号查询"}
              </div>
            ) : (
              <div style="display: flex; flex-direction: column; gap: 4px;">
                {deviceProductList.value.map((item: any) => (
                  <div style="display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; background: #f9f9f9; border-radius: 6px;">
                    <span style="font-weight: 500;">{item.name || "-"}</span>
                    <span style="color: #999; font-size: 13px;">{item.barcode || "-"}</span>
                    <span style="color: var(--el-color-primary);">¥{item.price || 0}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      ),
      hideFooter: true
    });
  }

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    categoryOptions,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleSync,
    handleShelfStatus,
    handleDeviceProducts,
    handleSizeChange,
    handleCurrentChange
  };
}
