import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import {
  getTimedDiscountList,
  getTimedDiscountById,
  createTimedDiscount,
  updateTimedDiscount,
  updateTimedDiscountStatus,
  deleteTimedDiscount,
  executeTimedDiscount,
  getTimedDiscountRecords,
  getTimedDiscountRecordById,
  getPriceAdjustmentLogs,
  getTimedDiscountStatistics,
  getTimedDiscountDailyStatistics
} from "@/api/timedDiscount";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { onMounted, reactive, ref, toRaw, h } from "vue";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElSelect,
  ElOption,
  ElTimePicker,
  ElInputNumber,
  ElSwitch,
  ElDescriptions,
  ElDescriptionsItem,
  ElTable,
  ElTableColumn,
  ElTag,
  ElTabs,
  ElTabPane,
  ElDatePicker,
  ElStatistic
} from "element-plus";
import { 
  initPagination, 
  handlePageSizeChange, 
  handleCurrentPageChange, 
  resetPagination,
  updatePaginationData 
} from "@/utils/paginationHelper";
import type { SearchFormProps, RecordSearchFormProps, FormDataProps, TimedDiscountActivity, TimedDiscountRecord, PriceAdjustmentLog } from "./types";
import ShopSelector from "@/views/marketing/components/ShopSelector.vue";
import DeviceSelector from "@/views/marketing/components/DeviceSelector.vue";
import ProductSelector from "@/views/marketing/components/ProductSelector.vue";

const discountTypeMap = {
  1: { text: "固定折扣", type: "primary" },
  2: { text: "阶梯折扣", type: "success" },
  3: { text: "固定价格", type: "warning" }
};

const statusMap = {
  0: { text: "已禁用", type: "danger" },
  1: { text: "已启用", type: "success" }
};

const executeStatusMap = {
  1: { text: "成功", type: "success" },
  2: { text: "部分成功", type: "warning" },
  3: { text: "失败", type: "danger" }
};

const restoreStatusMap = {
  0: { text: "未恢复", type: "warning" },
  1: { text: "已恢复", type: "success" },
  2: { text: "已售出", type: "primary" }
};

const productTypeOptions = [
  { label: "自制餐品", value: "自制餐品" },
  { label: "盒饭", value: "盒饭" },
  { label: "水饮", value: "水饮" },
  { label: "副食", value: "副食" },
  { label: "零食", value: "零食" },
  { label: "饮料", value: "饮料" }
];

export function useTimedDiscount() {
  const form = reactive<SearchFormProps>({
    activityName: "",
    status: undefined,
    discountType: undefined
  });
  const loading = ref(true);
  const dataList = ref<TimedDiscountActivity[]>([]);
  const pagination = reactive<PaginationProps>(initPagination());

  const columns: TableColumnList = [
    {
      label: "活动ID",
      prop: "id",
      width: 80
    },
    {
      label: "活动名称",
      prop: "activityName",
      minWidth: 150
    },
    {
      label: "折扣类型",
      prop: "discountType",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = discountTypeMap[row.discountType] || { text: "未知", type: "info" };
        return <el-tag type={item.type}>{item.text}</el-tag>;
      }
    },
    {
      label: "折扣值",
      prop: "discountValue",
      minWidth: 100,
      formatter: ({ discountType, discountValue }) => {
        if (discountType === 1) {
          return `${(discountValue * 100).toFixed(0)}%`;
        } else if (discountType === 3) {
          return `¥${discountValue}`;
        }
        return discountValue;
      }
    },
    {
      label: "开始时间",
      prop: "startTime",
      minWidth: 100,
      formatter: ({ startTime }) => startTime || ""
    },
    {
      label: "结束时间",
      prop: "endTime",
      minWidth: 100,
      formatter: ({ endTime }) => endTime || "次日营业"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={item.type}>{item.text}</el-tag>;
      }
    },
    {
      label: "自动执行",
      prop: "autoExecute",
      minWidth: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={row.autoExecute === 1 ? "success" : "info"}>
          {row.autoExecute === 1 ? "是" : "否"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "操作",
      fixed: "right",
      width: 280,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      if (form.activityName) searchParams.activityName = form.activityName;
      if (form.status !== undefined) searchParams.status = form.status;
      if (form.discountType !== undefined) searchParams.discountType = form.discountType;
      
      const { data } = await getTimedDiscountList(searchParams);
      if (data) {
        dataList.value = data.list || [];
        updatePaginationData(pagination, data);
      }
    } finally {
      loading.value = false;
    }
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    resetPagination(pagination, onSearch);
  }

  async function handleDelete(row: TimedDiscountActivity) {
    const { code } = await deleteTimedDiscount(row.id);
    if (code === 200) {
      message("删除成功", { type: "success" });
      onSearch();
    }
  }

  async function handleToggleStatus(row: TimedDiscountActivity) {
    const newStatus = row.status === 1 ? 0 : 1;
    const { code } = await updateTimedDiscountStatus(row.id, newStatus);
    if (code === 200) {
      message(newStatus === 1 ? "已启用" : "已禁用", { type: "success" });
      onSearch();
    }
  }

  async function handleExecute(row: TimedDiscountActivity) {
    const { code } = await executeTimedDiscount(row.id);
    if (code === 200) {
      message("执行成功", { type: "success" });
    }
  }

  function handleViewDetail(row: TimedDiscountActivity) {
    addDialog({
      title: "活动详情",
      width: "900px",
      draggable: true,
      fullscreen: deviceDetection(),
      alignCenter: true,
      contentRenderer: () => (
        <div>
          <ElDescriptions column={2} border>
            <ElDescriptionsItem label="活动名称">{row.activityName}</ElDescriptionsItem>
            <ElDescriptionsItem label="折扣类型">
              <el-tag type={discountTypeMap[row.discountType]?.type}>
                {discountTypeMap[row.discountType]?.text}
              </el-tag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="开始时间">{row.startTime}</ElDescriptionsItem>
            <ElDescriptionsItem label="结束时间">{row.endTime || "次日营业开始"}</ElDescriptionsItem>
            <ElDescriptionsItem label="折扣值">
              {row.discountType === 1 ? `${(row.discountValue * 100).toFixed(0)}%` : `¥${row.discountValue}`}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="最低折扣价">
              {row.minDiscountPrice ? `¥${row.minDiscountPrice}` : "不限制"}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="适用范围">{row.applyScopeLabel}</ElDescriptionsItem>
            <ElDescriptionsItem label="商品范围">{row.productScopeLabel}</ElDescriptionsItem>
            <ElDescriptionsItem label="适用商品分类" span={2}>
              {row.productTypes || "全部"}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="优先商品分类" span={2}>
              {row.priorityProductTypes || "无"}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="最低库存阈值">{row.minStock}</ElDescriptionsItem>
            <ElDescriptionsItem label="最高库存阈值">{row.maxStock || "不限制"}</ElDescriptionsItem>
            <ElDescriptionsItem label="状态">
              <el-tag type={statusMap[row.status]?.type}>{statusMap[row.status]?.text}</el-tag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="自动执行">{row.autoExecute === 1 ? "是" : "否"}</ElDescriptionsItem>
            <ElDescriptionsItem label="活动说明" span={2}>{row.activityDesc || "暂无说明"}</ElDescriptionsItem>
          </ElDescriptions>
        </div>
      )
    });
  }

  function handleEdit(row: TimedDiscountActivity) {
    const formData = reactive<FormDataProps>({
      id: row.id,
      activityName: row.activityName,
      activityDesc: row.activityDesc || "",
      startTime: row.startTime,
      endTime: row.endTime || "",
      discountType: row.discountType,
      discountValue: row.discountValue,
      minDiscountPrice: row.minDiscountPrice || null,
      applyScope: row.applyScope,
      deviceScope: row.deviceScope || 1,
      productScope: row.productScope,
      productTypes: row.productTypes || "",
      priorityProductTypes: row.priorityProductTypes || "",
      minStock: row.minStock || 1,
      maxStock: row.maxStock || null,
      autoExecute: row.autoExecute,
      notifyOnExecute: row.notifyOnExecute || 0,
      shopIds: row.shopIds || [],
      deviceIds: row.deviceIds || [],
      productIds: row.productIds || []
    });

    addDialog({
      title: "编辑活动",
      width: "1100px",
      draggable: true,
      fullscreen: deviceDetection(),
      alignCenter: true,
      contentRenderer: () => renderForm(formData),
      beforeSure: async (done) => {
        if (!validateForm(formData)) return;
        try {
          const { code } = await updateTimedDiscount(formData.id!, toRaw(formData));
          if (code === 200) {
            message("编辑成功", { type: "success" });
            done();
            onSearch();
          }
        } catch (error) {
          message("编辑失败", { type: "error" });
        }
      }
    });
  }

  function handleAdd() {
    const formData = reactive<FormDataProps>({
      activityName: "",
      activityDesc: "",
      startTime: "20:00:00",
      endTime: "23:59:59",
      discountType: 1,
      discountValue: 0.5,
      minDiscountPrice: 1,
      applyScope: 1,
      deviceScope: 1,
      productScope: 2,
      productTypes: "自制餐品,盒饭",
      priorityProductTypes: "自制餐品,盒饭",
      minStock: 1,
      maxStock: null,
      autoExecute: 1,
      notifyOnExecute: 0,
      shopIds: [],
      deviceIds: [],
      productIds: []
    });

    addDialog({
      title: "新增活动",
      width: "1100px",
      draggable: true,
      fullscreen: deviceDetection(),
      alignCenter: true,
      contentRenderer: () => renderForm(formData),
      beforeSure: async (done) => {
        if (!validateForm(formData)) return;
        try {
          const { code } = await createTimedDiscount(toRaw(formData));
          if (code === 200) {
            message("新增成功", { type: "success" });
            done();
            onSearch();
          }
        } catch (error) {
          message("新增失败", { type: "error" });
        }
      }
    });
  }

  const formStyles = `
    .form-container {
      padding: 8px 0;
    }
    .form-block {
      margin-bottom: 24px;
      padding-bottom: 20px;
      border-bottom: 1px solid #f0f0f0;
    }
    .form-block:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }
    .form-block-title {
      font-size: 15px;
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 16px;
      padding-left: 10px;
      border-left: 3px solid #3b82f6;
    }
    .form-row {
      display: flex;
      gap: 20px;
      margin-bottom: 16px;
    }
    .form-row .el-form-item {
      flex: 1;
      margin-bottom: 0;
    }
    .scope-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
    }
    .scope-card {
      background: #f9fafb;
      border-radius: 6px;
      padding: 14px;
    }
    .scope-card-header {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }
    .scope-card-title {
      font-size: 14px;
      font-weight: 500;
      color: #374151;
    }
    .scope-card-body {
      min-height: 36px;
    }
    .inline-switch {
      display: flex;
      align-items: center;
      gap: 12px;
    }
    .inline-switch-label {
      font-size: 14px;
      color: #374151;
    }
    @media (max-width: 900px) {
      .scope-grid {
        grid-template-columns: 1fr;
      }
      .form-row {
        flex-direction: column;
        gap: 16px;
      }
    }
  `;

  function renderForm(formData: FormDataProps) {
    return (
      <div class="form-container">
        <style>{formStyles}</style>
        
        <div class="form-block">
          <div class="form-block-title">基本信息</div>
          <div class="form-row">
            <ElFormItem label="活动名称" required>
              <ElInput v-model={formData.activityName} placeholder="请输入活动名称" clearable />
            </ElFormItem>
            <ElFormItem label="自动执行">
              <div class="inline-switch">
                <ElSwitch v-model={formData.autoExecute} active-value={1} inactive-value={0} />
                <span class="inline-switch-label">{formData.autoExecute === 1 ? "开启" : "关闭"}</span>
              </div>
            </ElFormItem>
          </div>
          <ElFormItem label="活动说明">
            <ElInput v-model={formData.activityDesc} type="textarea" rows={2} placeholder="请输入活动说明" />
          </ElFormItem>
        </div>

        <div class="form-block">
          <div class="form-block-title">时间设置</div>
          <div class="form-row">
            <ElFormItem label="开始时间" required>
              <ElTimePicker
                v-model={formData.startTime}
                placeholder="选择开始时间"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                class="w-full"
              />
            </ElFormItem>
            <ElFormItem label="结束时间">
              <ElTimePicker
                v-model={formData.endTime}
                placeholder="选择结束时间（空表示次日营业）"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                class="w-full"
                clearable
              />
            </ElFormItem>
          </div>
        </div>

        <div class="form-block">
          <div class="form-block-title">折扣设置</div>
          <div class="form-row">
            <ElFormItem label="折扣类型" required>
              <ElSelect v-model={formData.discountType} placeholder="请选择折扣类型" class="w-full">
                <ElOption label="固定折扣" value={1} />
                <ElOption label="阶梯折扣" value={2} />
                <ElOption label="固定价格" value={3} />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="折扣值" required>
              <ElInputNumber
                v-model={formData.discountValue}
                min={0}
                max={formData.discountType === 1 ? 1 : 9999}
                step={formData.discountType === 1 ? 0.1 : 1}
                precision={formData.discountType === 1 ? 2 : 0}
                class="w-full"
                placeholder={formData.discountType === 1 ? "折扣比例（如0.5表示5折）" : "固定价格"}
              />
            </ElFormItem>
          </div>
          <div class="form-row">
            <ElFormItem label="最低折扣价">
              <ElInputNumber
                v-model={formData.minDiscountPrice}
                min={0}
                precision={2}
                class="w-full"
                placeholder="最低折扣价格（防止价格过低）"
              />
            </ElFormItem>
            <div></div>
          </div>
        </div>

        <div class="form-block">
          <div class="form-block-title">适用范围</div>
          <div class="scope-grid">
            <div class="scope-card">
              <div class="scope-card-header">
                <span class="scope-card-title">门店范围</span>
              </div>
              <div class="scope-card-body">
                <ElSelect v-model={formData.applyScope} placeholder="请选择适用范围" class="w-full">
                  <ElOption label="全部门店" value={1} />
                  <ElOption label="指定门店" value={2} />
                </ElSelect>
                {formData.applyScope === 2 && (
                  <div style="margin-top: 10px;">
                    <ShopSelector v-model={formData.shopIds} />
                  </div>
                )}
              </div>
            </div>
            <div class="scope-card">
              <div class="scope-card-header">
                <span class="scope-card-title">设备范围</span>
              </div>
              <div class="scope-card-body">
                <ElSelect v-model={formData.deviceScope} placeholder="请选择设备范围" class="w-full">
                  <ElOption label="全部设备" value={1} />
                  <ElOption label="指定设备" value={2} />
                </ElSelect>
                {formData.deviceScope === 2 && (
                  <div style="margin-top: 10px;">
                    <DeviceSelector v-model={formData.deviceIds} />
                  </div>
                )}
              </div>
            </div>
            <div class="scope-card">
              <div class="scope-card-header">
                <span class="scope-card-title">商品范围</span>
              </div>
              <div class="scope-card-body">
                <ElSelect v-model={formData.productScope} placeholder="请选择商品范围" class="w-full">
                  <ElOption label="全部商品" value={1} />
                  <ElOption label="指定分类" value={2} />
                  <ElOption label="指定商品" value={3} />
                </ElSelect>
                {formData.productScope === 2 && (
                  <div style="margin-top: 10px;">
                    <ElSelect
                      v-model={formData.productTypes}
                      multiple
                      filterable
                      allow-create
                      placeholder="请选择商品分类"
                      class="w-full"
                    >
                      {productTypeOptions.map(item => (
                        <ElOption key={item.value} label={item.label} value={item.value} />
                      ))}
                    </ElSelect>
                  </div>
                )}
                {formData.productScope === 3 && (
                  <div style="margin-top: 10px;">
                    <ProductSelector v-model={formData.productIds} />
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        <div class="form-block">
          <div class="form-block-title">库存与优先级</div>
          <div class="form-row">
            <ElFormItem label="优先商品分类">
              <ElSelect
                v-model={formData.priorityProductTypes}
                multiple
                filterable
                allow-create
                placeholder="请选择优先商品分类"
                class="w-full"
              >
                {productTypeOptions.map(item => (
                  <ElOption key={item.value} label={item.label} value={item.value} />
                ))}
              </ElSelect>
            </ElFormItem>
          </div>
          <div class="form-row">
            <ElFormItem label="最低库存阈值">
              <ElInputNumber v-model={formData.minStock} min={1} class="w-full" placeholder="低于此数量不参与优惠" />
            </ElFormItem>
            <ElFormItem label="最高库存阈值">
              <ElInputNumber v-model={formData.maxStock} min={1} class="w-full" placeholder="高于此数量不参与优惠（空不限制）" />
            </ElFormItem>
          </div>
        </div>
      </div>
    );
  }

  function validateForm(formData: FormDataProps): boolean {
    if (!formData.activityName) {
      message("请输入活动名称", { type: "warning" });
      return false;
    }
    if (!formData.startTime) {
      message("请选择开始时间", { type: "warning" });
      return false;
    }
    if (!formData.discountType) {
      message("请选择折扣类型", { type: "warning" });
      return false;
    }
    if (!formData.discountValue) {
      message("请输入折扣值", { type: "warning" });
      return false;
    }
    return true;
  }

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

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

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    discountTypeMap,
    statusMap,
    onSearch,
    resetForm,
    handleAdd,
    handleEdit,
    handleViewDetail,
    handleDelete,
    handleToggleStatus,
    handleExecute,
    handleSizeChange,
    handleCurrentChange
  };
}

export function useTimedDiscountRecord() {
  const form = reactive<RecordSearchFormProps>({
    activityId: undefined,
    executeDateStart: "",
    executeDateEnd: "",
    shopId: undefined,
    deviceId: "",
    status: undefined
  });
  const loading = ref(true);
  const dataList = ref<TimedDiscountRecord[]>([]);
  const pagination = reactive<PaginationProps>(initPagination());

  const columns: TableColumnList = [
    {
      label: "记录ID",
      prop: "id",
      width: 80
    },
    {
      label: "活动名称",
      prop: "activityName",
      minWidth: 120
    },
    {
      label: "执行日期",
      prop: "executeDate",
      minWidth: 100
    },
    {
      label: "执行时间",
      prop: "executeTime",
      minWidth: 160,
      formatter: ({ executeTime }) =>
        executeTime ? dayjs(executeTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "门店",
      prop: "shopName",
      minWidth: 120
    },
    {
      label: "设备",
      prop: "deviceName",
      minWidth: 120
    },
    {
      label: "商品数",
      prop: "totalProducts",
      minWidth: 80
    },
    {
      label: "优先商品",
      prop: "priorityProducts",
      minWidth: 80
    },
    {
      label: "总库存",
      prop: "totalStock",
      minWidth: 80
    },
    {
      label: "原价总值",
      prop: "originalValue",
      minWidth: 100,
      formatter: ({ originalValue }) => `¥${originalValue?.toFixed(2) || "0.00"}`
    },
    {
      label: "优惠金额",
      prop: "savedValue",
      minWidth: 100,
      formatter: ({ savedValue }) => `¥${savedValue?.toFixed(2) || "0.00"}`
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: ({ row }) => {
        const item = executeStatusMap[row.status] || { text: "未知", type: "info" };
        return <el-tag type={item.type}>{item.text}</el-tag>;
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      if (form.activityId) searchParams.activityId = form.activityId;
      if (form.executeDateStart) searchParams.executeDateStart = form.executeDateStart;
      if (form.executeDateEnd) searchParams.executeDateEnd = form.executeDateEnd;
      if (form.shopId) searchParams.shopId = form.shopId;
      if (form.deviceId) searchParams.deviceId = form.deviceId;
      if (form.status !== undefined) searchParams.status = form.status;
      
      const { data } = await getTimedDiscountRecords(searchParams);
      if (data) {
        dataList.value = data.list || [];
        updatePaginationData(pagination, data);
      }
    } finally {
      loading.value = false;
    }
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    resetPagination(pagination, onSearch);
  }

  function handleViewDetail(row: TimedDiscountRecord) {
    addDialog({
      title: "执行记录详情",
      width: "1000px",
      draggable: true,
      fullscreen: deviceDetection(),
      alignCenter: true,
      contentRenderer: () => (
        <div>
          <ElDescriptions column={3} border class="mb-4">
            <ElDescriptionsItem label="活动名称">{row.activityName}</ElDescriptionsItem>
            <ElDescriptionsItem label="执行日期">{row.executeDate}</ElDescriptionsItem>
            <ElDescriptionsItem label="执行时间">
              {dayjs(row.executeTime).format("YYYY-MM-DD HH:mm:ss")}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="门店">{row.shopName || "全部"}</ElDescriptionsItem>
            <ElDescriptionsItem label="设备">{row.deviceName || "全部"}</ElDescriptionsItem>
            <ElDescriptionsItem label="状态">
              <el-tag type={executeStatusMap[row.status]?.type}>
                {executeStatusMap[row.status]?.text}
              </el-tag>
            </ElDescriptionsItem>
          </ElDescriptions>
          
          <div class="grid grid-cols-4 gap-4 mb-4">
            <ElStatistic title="处理商品数" value={row.totalProducts} />
            <ElStatistic title="优先商品数" value={row.priorityProducts} />
            <ElStatistic title="总库存" value={row.totalStock} />
            <ElStatistic title="优惠金额" value={row.savedValue} prefix="¥" precision={2} />
          </div>
          
          <h4 class="mb-2">价格调整明细</h4>
          <PriceAdjustmentTable recordId={row.id} />
        </div>
      )
    });
  }

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

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

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    executeStatusMap,
    onSearch,
    resetForm,
    handleViewDetail,
    handleSizeChange,
    handleCurrentChange
  };
}

const PriceAdjustmentTable = (props: { recordId: number }): any => {
  const loading = ref(true);
  const dataList = ref<PriceAdjustmentLog[]>([]);
  const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 });

  async function loadData() {
    loading.value = true;
    try {
      const { data } = await getPriceAdjustmentLogs(props.recordId, {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      });
      if (data) {
        dataList.value = data.list || [];
        pagination.total = Number(data.total) || 0;
      }
    } finally {
      loading.value = false;
    }
  }

  onMounted(loadData);

  const columns: TableColumnList = [
    { label: "商品名称", prop: "productName", minWidth: 120 },
    { label: "商品分类", prop: "productType", minWidth: 80 },
    { label: "库存", prop: "stock", width: 60 },
    { 
      label: "原价", 
      prop: "originalPrice", 
      width: 80,
      formatter: ({ originalPrice }) => `¥${originalPrice?.toFixed(2)}`
    },
    { 
      label: "折扣价", 
      prop: "discountedPrice", 
      width: 80,
      formatter: ({ discountedPrice }) => `¥${discountedPrice?.toFixed(2)}`
    },
    { 
      label: "优先", 
      prop: "isPriority", 
      width: 60,
      cellRenderer: ({ row }) => (
        <el-tag type={row.isPriority === 1 ? "warning" : "info"} size="small">
          {row.isPriority === 1 ? "是" : "否"}
        </el-tag>
      )
    },
    { 
      label: "恢复状态", 
      prop: "restoreStatus", 
      width: 80,
      cellRenderer: ({ row }) => (
        <el-tag type={restoreStatusMap[row.restoreStatus]?.type} size="small">
          {restoreStatusMap[row.restoreStatus]?.text}
        </el-tag>
      )
    },
    { 
      label: "售出数量", 
      prop: "saleQuantity", 
      width: 80 
    }
  ];

  return () => (
    <ElTable
      data={dataList.value}
      v-loading={loading.value}
      style={{ width: "100%" }}
      {...{ columns, pagination: {
        currentPage: pagination.currentPage,
        pageSize: pagination.pageSize,
        total: pagination.total,
        onCurrentChange: (val: number) => {
          pagination.currentPage = val;
          loadData();
        }
      }}}
    />
  );
}
