import dayjs from "dayjs";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import {
  getActivityList,
  getActivityById,
  createActivity,
  updateActivity,
  deleteActivity,
  publishActivity,
  pauseActivity,
  resumeActivity
} from "@/api/activity";
import { getAvailableCoupons } from "@/api/coupon";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { onMounted, reactive, ref, toRaw } from "vue";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElDatePicker,
  ElInputNumber,
  ElDescriptions,
  ElDescriptionsItem,
  ElTag,
  ElRadioGroup,
  ElRadioButton
} from "element-plus";
import { 
  initPagination, 
  handlePageSizeChange, 
  handleCurrentPageChange, 
  resetPagination,
  updatePaginationData 
} from "@/utils/paginationHelper";
import ShopSelector from "../../components/ShopSelector.vue";
import DeviceSelector from "../../components/DeviceSelector.vue";
import ProductSelector from "../../components/ProductSelector.vue";
import InviteRewardBlock from "./components/InviteRewardBlock.vue";
import type { FormItemProps } from "./types";

interface SearchFormProps {
  name: string;
  type: number | undefined;
  status: number | undefined;
}

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

  // ===== 优惠券模板列表（用于邀请活动选择器）=====
  const couponTemplateList = ref<{ id: number; name: string; discountValue: number }[]>([]);

  async function fetchCouponTemplates() {
    try {
      const { data } = await getAvailableCoupons();
      couponTemplateList.value = (data || []).map((t: any) => ({
        id: t.id,
        name: t.couponName,
        discountValue: t.discountValue
      }));
    } catch {
      couponTemplateList.value = [];
    }
  }

  type TagType = "success" | "primary" | "warning" | "info" | "danger";

  const typeMap: Record<number, { text: string; type: TagType; color: string }> = {
    1: { text: "首单立减", type: "primary", color: "#409EFF" },
    2: { text: "优惠折扣", type: "success", color: "#67C23A" },
    3: { text: "商品满减", type: "warning", color: "#E6A23C" },
    4: { text: "邀请有礼", type: "danger", color: "#F56C6C" }
  };

  const statusMap: Record<number, { text: string; type: TagType }> = {
    0: { text: "草稿", type: "info" },
    1: { text: "已发布", type: "primary" },
    2: { text: "进行中", type: "success" },
    3: { text: "已暂停", type: "warning" },
    4: { text: "已结束", type: "info" }
  };

  const applyScopeMap: Record<number, { text: string; type: TagType }> = {
    1: { text: "全部门店", type: "primary" },
    2: { text: "指定门店", type: "warning" }
  };

  const deviceScopeMap: Record<number, { text: string; type: TagType }> = {
    1: { text: "全部设备", type: "primary" },
    2: { text: "指定设备", type: "warning" }
  };

  const productScopeMap: Record<number, { text: string; type: TagType }> = {
    1: { text: "全部商品", type: "primary" },
    2: { text: "指定商品", type: "warning" }
  };

  const columns: TableColumnList = [
    {
      label: "活动ID",
      prop: "id",
      width: 80
    },
    {
      label: "活动名称",
      prop: "activityName",
      minWidth: 150
    },
    {
      label: "活动类型",
      prop: "activityType",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = typeMap[row.activityType] || { text: "未知", type: "info" };
        return <ElTag type={item.type}>{item.text}</ElTag>;
      }
    },
    {
      label: "优惠规则",
      prop: "discountValue",
      minWidth: 180,
      cellRenderer: ({ row }) => {
        if (row.activityType === 4) {
          return (
            <div>
              <div style={{ color: "#F56C6C", fontWeight: 600, marginBottom: "4px" }}>
                双向优惠券奖励
              </div>
              <div style={{ fontSize: "12px", color: "#666", lineHeight: "1.6" }}>
                <div>邀请人: {row.inviterCouponName || "未配置"}</div>
                <div>被邀请人: {row.inviteeCouponName || "未配置"}</div>
              </div>
            </div>
          );
        } else if (row.activityType === 1) {
          return `首单立减 ¥${row.discountValue || 0}`;
        } else if (row.activityType === 2) {
          return `${((row.discountValue || 0) * 10).toFixed(1)}折优惠`;
        } else if (row.activityType === 3) {
          return `满${row.minAmount || 0}减${row.discountValue || 0}`;
        }
        return "-";
      }
    },
    {
      label: "开始时间",
      prop: "startTime",
      minWidth: 160,
      formatter: ({ startTime }) =>
        startTime ? dayjs(startTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "结束时间",
      prop: "endTime",
      minWidth: 160,
      formatter: ({ endTime }) =>
        endTime ? dayjs(endTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row }) => {
        const item = statusMap[row.status] || { text: "未知", type: "info" };
        return <ElTag type={item.type}>{item.text}</ElTag>;
      }
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 160,
      formatter: ({ createTime }) =>
        createTime ? dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "操作",
      fixed: "right",
      width: 300,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    try {
      const searchParams: any = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      if (form.name) searchParams.activityName = form.name;
      if (form.type !== undefined) searchParams.activityType = form.type;
      if (form.status !== undefined) searchParams.status = form.status;
      
      const { data } = await getActivityList(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) {
    const { code } = await deleteActivity(row.id);
    if (code === 200) {
      message("删除成功", { type: "success" });
      onSearch();
    }
  }

  async function handlePublish(row) {
    const { code } = await publishActivity(row.id);
    if (code === 200) {
      message("发布成功", { type: "success" });
      onSearch();
    }
  }

  async function handlePause(row) {
    const { code } = await pauseActivity(row.id);
    if (code === 200) {
      message("暂停成功", { type: "success" });
      onSearch();
    }
  }

  async function handleResume(row) {
    const { code } = await resumeActivity(row.id);
    if (code === 200) {
      message("恢复成功", { type: "success" });
      onSearch();
    }
  }

  function handleViewDetail(row) {
    const isInviteActivity = row.activityType === 4;

    addDialog({
      title: isInviteActivity ? "邀请活动详情" : "活动详情",
      width: isInviteActivity ? "900px" : "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <div>
          <ElDescriptions column={2} border>
            <ElDescriptionsItem label="活动名称">{row.activityName}</ElDescriptionsItem>
            <ElDescriptionsItem label="活动类型">
              <ElTag type={typeMap[row.activityType]?.type}>{typeMap[row.activityType]?.text}</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="优惠规则">
              {row.activityType === 1 && `首单立减 ¥${row.discountValue}`}
              {row.activityType === 2 && `${(row.discountValue * 10).toFixed(1)}折优惠`}
              {row.activityType === 3 && `满${row.minAmount}减${row.discountValue}`}
              {row.activityType === 4 && (
                <div>
                  <div style={{ color: "#F56C6C", fontWeight: 600, marginBottom: "8px" }}>
                    双向优惠券奖励
                  </div>
                  <div style={{ fontSize: "13px", lineHeight: "2" }}>
                    <div><strong>邀请人奖励:</strong> {row.inviterCouponName || "未配置"}</div>
                    <div><strong>被邀请人奖励:</strong> {row.inviteeCouponName || "未配置"}</div>
                  </div>
                </div>
              )}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="最大优惠">
              {row.maxDiscount ? `¥${row.maxDiscount}` : "不限制"}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="开始时间">{dayjs(row.startTime).format("YYYY-MM-DD HH:mm:ss")}</ElDescriptionsItem>
            <ElDescriptionsItem label="结束时间">{dayjs(row.endTime).format("YYYY-MM-DD HH:mm:ss")}</ElDescriptionsItem>
            <ElDescriptionsItem label="状态">
              <ElTag type={statusMap[row.status]?.type}>{statusMap[row.status]?.text}</ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="活动预算">
              {row.totalBudget ? `¥${row.totalBudget}` : "不限制"}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="适用范围">
              <ElTag type={applyScopeMap[row.applyScope]?.type}>{applyScopeMap[row.applyScope]?.text}</ElTag>
            </ElDescriptionsItem>
            {!isInviteActivity && (
              <>
                <ElDescriptionsItem label="设备范围">
                  <ElTag type={deviceScopeMap[row.deviceScope]?.type}>{deviceScopeMap[row.deviceScope]?.text}</ElTag>
                </ElDescriptionsItem>
                <ElDescriptionsItem label="商品范围">
                  <ElTag type={productScopeMap[row.productScope]?.type}>{productScopeMap[row.productScope]?.text}</ElTag>
                </ElDescriptionsItem>
              </>
            )}
            {isInviteActivity && (
              <>
                <ElDescriptionsItem label="每日邀请上限">
                  {row.dailyLimit || 10} 次/天
                </ElDescriptionsItem>
                <ElDescriptionsItem label="总邀请上限">
                  {row.totalLimit ? `${row.totalLimit} 人` : "不限制"}
                </ElDescriptionsItem>
                <ElDescriptionsItem label="首单要求">
                  {row.requireFirstOrder === 1
                    ? `需完成${row.minOrderAmount ? `¥${row.minOrderAmount}以上` : ""}首单`
                    : "无要求"}
                </ElDescriptionsItem>
                <ElDescriptionsItem label="邀请码前缀">
                  {row.inviteCodePrefix || "INV"}
                </ElDescriptionsItem>
              </>
            )}
            <ElDescriptionsItem label="创建时间">{dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss")}</ElDescriptionsItem>
            <ElDescriptionsItem label="活动说明" span={2}>{row.activityDesc || "暂无说明"}</ElDescriptionsItem>
          </ElDescriptions>

          {/* ===== 通用统计数据 ===== */}
          <div class="mt-4">
            <h4 class="mb-2">统计数据</h4>
            <ElDescriptions column={3}>
              <ElDescriptionsItem label="参与人数">{row.participantCount || 0}人</ElDescriptionsItem>
              <ElDescriptionsItem label="订单数">{row.orderCount || 0}单</ElDescriptionsItem>
              <ElDescriptionsItem label="总营收">¥{row.totalRevenue || 0}</ElDescriptionsItem>
            </ElDescriptions>
          </div>

          {/* ===== 邀请活动专属：邀请数据统计 + 查看邀请记录入口 (Task 10) ===== */}
          {isInviteActivity && (
            <div class="mt-4">
              <div style={{
                background: "linear-gradient(135deg, #fef0f0 0%, #fde8e8 100%)",
                borderRadius: "8px",
                padding: "16px 20px",
                border: "1px solid #f56c6c30"
              }}>
                <h4 style={{
                  margin: "0 0 12px 0",
                  fontSize: "15px",
                  fontWeight: 600,
                  color: "#F56C6C",
                  display: "flex",
                  alignItems: "center",
                  gap: "6px"
                }}>
                  📊 邀请数据统计
                </h4>
                <ElDescriptions column={4} border style={{
                  background: "#fff",
                  borderRadius: "6px"
                }}>
                  <ElDescriptionsItem label="总邀请数">
                    <span style={{ fontWeight: 600, color: "#409EFF", fontSize: "16px" }}>
                      {row.totalInviteCount || 0}
                    </span>
                  </ElDescriptionsItem>
                  <ElDescriptionsItem label="有效邀请">
                    <span style={{ fontWeight: 600, color: "#67C23A", fontSize: "16px" }}>
                      {row.validInviteCount || 0}
                    </span>
                  </ElDescriptionsItem>
                  <ElDescriptionsItem label="奖励发放">
                    <span style={{ fontWeight: 600, color: "#E6A23C", fontSize: "16px" }}>
                      {row.rewardCount || 0}
                    </span>
                  </ElDescriptionsItem>
                  <ElDescriptionsItem label="转化率">
                    <span style={{ fontWeight: 600, color: "#909399", fontSize: "14px" }}>
                      {row.totalInviteCount > 0
                        ? ((row.validInviteCount || 0) / row.totalInviteCount * 100).toFixed(1) + "%"
                        : "-"}
                    </span>
                  </ElDescriptionsItem>
                </ElDescriptions>

                {/* 查看邀请记录按钮/链接 */}
                <div style={{
                  marginTop: "16px",
                  textAlign: "center",
                  paddingTop: "12px",
                  borderTop: "1px dashed #f56c6c40"
                }}>
                  <a
                    href="#/marketing/invite/records"
                    target="_blank"
                    style={{
                      color: "#F56C6C",
                      textDecoration: "none",
                      fontSize: "14px",
                      fontWeight: 500,
                      display: "inline-flex",
                      alignItems: "center",
                      gap: "4px",
                      padding: "6px 16px",
                      borderRadius: "4px",
                      background: "#fef0f0",
                      border: "1px solid #f56c6c30"
                    }}
                  >
                    📋 查看完整邀请记录与数据统计 →
                  </a>
                </div>
              </div>
            </div>
          )}
        </div>
      )
    });
  }

  const formStyles = `
    .activity-form {
      padding: 0;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    }
    
    /* 活动类型选择器 */
    .type-selector {
      display: flex;
      gap: 12px;
      margin-bottom: 18px;
    }
    
    .type-btn {
      flex: 1;
      padding: 16px 18px;
      border: 1px solid #e5e7eb;
      border-radius: 6px;
      background: #fff;
      cursor: pointer;
      transition: all 0.15s ease;
      text-align: center;
    }
    
    .type-btn:hover {
      border-color: #3b82f6;
    }
    
    .type-btn.active {
      border-color: #3b82f6;
      background: #eff6ff;
    }
    
    .type-btn .name {
      font-size: 15px;
      font-weight: 600;
      color: #374151;
      margin-bottom: 4px;
    }
    
    .type-btn .hint {
      font-size: 13px;
      color: #9ca3af;
    }
    
    .type-btn.active .name {
      color: #3b82f6;
    }
    
    /* 表单区块 */
    .form-block {
      margin-bottom: 18px;
    }
    
    .block-title {
      font-size: 15px;
      font-weight: 600;
      color: #374151;
      margin-bottom: 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f3f4f6;
    }
    
    /* 表单网格 */
    .form-grid-2 {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
    }
    
    /* 适用范围 - 网格布局 */
    .scope-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
    }
    
    .scope-card {
      background: #f9fafb;
      border-radius: 6px;
      padding: 14px;
    }
    
    .scope-card .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    
    .scope-card .card-label {
      font-size: 14px;
      font-weight: 500;
      color: #374151;
    }
    
    .scope-card .card-body {
      min-height: 40px;
    }
    
    .scope-card .selected-items {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      margin-top: 10px;
      max-height: 120px;
      overflow-y: auto;
    }
    
    .scope-card .selected-tag {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      padding: 4px 8px;
      background: #fff;
      border: 1px solid #e5e7eb;
      border-radius: 4px;
      font-size: 12px;
      color: #374151;
    }
    
    .scope-card .selected-tag .close {
      cursor: pointer;
      color: #9ca3af;
      font-size: 14px;
    }
    
    .scope-card .selected-tag .close:hover {
      color: #ef4444;
    }
    
    /* 优惠预览 */
    .discount-preview {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px 16px;
      background: #f9fafb;
      border-radius: 4px;
      margin-top: 12px;
      font-size: 15px;
      color: #374151;
    }
    
    .discount-preview .value {
      font-weight: 600;
    }
    
    /* 提示信息 */
    .empty-tip {
      text-align: center;
      padding: 24px;
      color: #9ca3af;
      font-size: 14px;
      background: #f9fafb;
      border-radius: 4px;
    }
    
    /* 表单项样式 */
    .activity-form .el-form-item {
      margin-bottom: 14px;
    }
    
    .activity-form .el-form-item__label {
      font-size: 14px;
      color: #6b7280;
    }
    
    .activity-form .el-input__wrapper,
    .activity-form .el-textarea__inner {
      font-size: 14px;
    }
    
    .activity-form .el-input-number {
      font-size: 14px;
    }
    
    /* 时间范围 */
    .time-range {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .time-range .el-date-editor {
      flex: 1;
    }
    
    .time-sep {
      color: #9ca3af;
      font-size: 14px;
    }
    
    /* 响应式 */
    @media (max-width: 768px) {
      .type-selector {
        flex-direction: column;
      }
      .form-grid-2 {
        grid-template-columns: 1fr;
      }
      .scope-grid {
        grid-template-columns: 1fr;
      }
    }
  `;

  function renderForm(formData: FormItemProps) {
    return (
      <div class="activity-form">
        <style>{formStyles}</style>

        {/* ===== 通用区块：活动类型选择 ===== */}
        <div class="form-block">
          <div class="block-title">活动类型</div>
          <div class="type-selector">
            {[1, 2, 3, 4].map(type => (
              <div
                class={`type-btn ${formData.activityType === type ? 'active' : ''}`}
                onClick={() => { formData.activityType = type; }}
              >
                <div class="name">{typeMap[type].text}</div>
                <div class="hint">
                  {type === 1 && "新用户首单优惠"}
                  {type === 2 && "全场折扣优惠"}
                  {type === 3 && "满额减免优惠"}
                  {type === 4 && "邀请好友双向奖励"}
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* ===== 通用区块：基本信息 ===== */}
        <div class="form-block">
          <div class="block-title">📝 基本信息</div>
          <ElForm label-width="80px" size="default">
            <div class="form-grid-2">
              <ElFormItem label="活动名称" required>
                <ElInput v-model={formData.activityName} placeholder="请输入活动名称" clearable maxlength={50} showWordLimit />
              </ElFormItem>
              <ElFormItem label="活动预算">
                <ElInputNumber v-model={formData.totalBudget} min={0} precision={2} class="w-full" placeholder="可选" />
              </ElFormItem>
            </div>
            <ElFormItem label="活动时间" required>
              <div class="time-range">
                <ElDatePicker v-model={formData.startTime} type="datetime" placeholder="开始时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" />
                <span class="time-sep">至</span>
                <ElDatePicker v-model={formData.endTime} type="datetime" placeholder="结束时间" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm:ss" />
              </div>
            </ElFormItem>
          </ElForm>
        </div>

        {/* ===== 动态区块：根据 activityType 渲染不同配置 ===== */}
        <div class="form-block">
          <div class="block-title">优惠规则</div>

          {!formData.activityType && <div class="empty-tip">请先选择活动类型</div>}

          {/* 首单立减配置 (type=1) */}
          {formData.activityType === 1 && (
            <div>
              <ElForm label-width="80px" size="default">
                <ElFormItem label="立减金额" required>
                  <ElInputNumber v-model={formData.discountValue} min={0.01} precision={2} class="w-full" placeholder="首单立减金额" />
                </ElFormItem>
              </ElForm>
              <div class="discount-preview">
                <span>预览：</span>
                <span class="value">新用户首单立减 ¥{formData.discountValue || '0.00'}</span>
              </div>
            </div>
          )}

          {/* 优惠折扣配置 (type=2) */}
          {formData.activityType === 2 && (
            <div>
              <ElForm label-width="80px" size="default">
                <div class="form-grid-2">
                  <ElFormItem label="折扣比例" required>
                    <ElInputNumber v-model={formData.discountValue} min={0.1} max={1} step={0.1} precision={1} class="w-full" placeholder="如 0.8 表示 8 折" />
                  </ElFormItem>
                  <ElFormItem label="最大优惠">
                    <ElInputNumber v-model={formData.maxDiscount} min={0} precision={2} class="w-full" placeholder="可选" />
                  </ElFormItem>
                </div>
              </ElForm>
              <div class="discount-preview">
                <span>预览：</span>
                <span class="value">全场 {formData.discountValue ? (formData.discountValue * 10).toFixed(1) : '0'} 折优惠{formData.maxDiscount && ` (最高减¥${formData.maxDiscount})`}</span>
              </div>
            </div>
          )}

          {/* 商品满减配置 (type=3) */}
          {formData.activityType === 3 && (
            <div>
              <ElForm label-width="80px" size="default">
                <div class="form-grid-2">
                  <ElFormItem label="满减门槛" required>
                    <ElInputNumber v-model={formData.minAmount} min={0} precision={2} class="w-full" placeholder="订单满多少" />
                  </ElFormItem>
                  <ElFormItem label="减免金额" required>
                    <ElInputNumber v-model={formData.discountValue} min={0.01} precision={2} class="w-full" placeholder="减免金额" />
                  </ElFormItem>
                </div>
              </ElForm>
              <div class="discount-preview">
                <span>预览：</span>
                <span class="value">满 ¥{formData.minAmount || '0'} 减 ¥{formData.discountValue || '0'}</span>
              </div>
            </div>
          )}

          {/* 邀请有礼配置 (type=4) - 使用 InviteRewardBlock 组件 */}
          {formData.activityType === 4 && (
            <InviteRewardBlock
              formData={formData}
              couponTemplateList={couponTemplateList.value}
            />
          )}
        </div>

        {/* ===== 通用区块：适用范围 ===== */}
        <div class="form-block">
          <div class="block-title">🎯 适用范围</div>
          <div class="scope-grid">
            <div class="scope-card">
              <div class="card-header">
                <span class="card-label">门店范围</span>
                <ElRadioGroup v-model={formData.applyScope} size="small">
                  <ElRadioButton value={1}>全部</ElRadioButton>
                  <ElRadioButton value={2}>指定</ElRadioButton>
                </ElRadioGroup>
              </div>
              <div class="card-body">
                {formData.applyScope === 2 && <ShopSelector v-model={formData.shopIds} />}
              </div>
            </div>
            <div class="scope-card">
              <div class="card-header">
                <span class="card-label">设备范围</span>
                <ElRadioGroup v-model={formData.deviceScope} size="small">
                  <ElRadioButton value={1}>全部</ElRadioButton>
                  <ElRadioButton value={2}>指定</ElRadioButton>
                </ElRadioGroup>
              </div>
              <div class="card-body">
                {formData.deviceScope === 2 && <DeviceSelector v-model={formData.deviceIds} />}
              </div>
            </div>
            <div class="scope-card">
              <div class="card-header">
                <span class="card-label">商品范围</span>
                <ElRadioGroup v-model={formData.productScope} size="small">
                  <ElRadioButton value={1}>全部</ElRadioButton>
                  <ElRadioButton value={2}>指定</ElRadioButton>
                </ElRadioGroup>
              </div>
              <div class="card-body">
                {formData.productScope === 2 && <ProductSelector v-model={formData.productIds} />}
              </div>
            </div>
          </div>
        </div>

        {/* ===== 通用区块：活动说明 ===== */}
        <div class="form-block">
          <div class="block-title">活动说明</div>
          <ElForm size="default">
            <ElFormItem label="">
              <ElInput v-model={formData.activityDesc} type="textarea" rows={2} placeholder="请输入活动说明（可选）" maxlength={500} showWordLimit />
            </ElFormItem>
          </ElForm>
        </div>
      </div>
    );
  }

  function validateForm(formData: FormItemProps): boolean {
    // ===== 通用校验 =====
    if (!formData.activityName) {
      message("请输入活动名称", { type: "warning" });
      return false;
    }
    if (!formData.activityType) {
      message("请选择活动类型", { type: "warning" });
      return false;
    }
    if (!formData.startTime) {
      message("请选择开始时间", { type: "warning" });
      return false;
    }
    if (!formData.endTime) {
      message("请选择结束时间", { type: "warning" });
      return false;
    }

    // ===== 根据活动类型进行特定校验 =====
    // 邀请活动特有校验 (type=4)
    if (formData.activityType === 4) {
      if (!formData.inviterCouponTemplateId) {
        message("请选择邀请人优惠券模板", { type: "warning" });
        return false;
      }
      if (formData.dailyLimit && (formData.dailyLimit < 1 || formData.dailyLimit > 100)) {
        message("每日邀请上限应在 1-100 之间", { type: "warning" });
        return false;
      }
      if (formData.totalLimit && (formData.totalLimit < 1 || formData.totalLimit > 10000)) {
        message("总邀请上限应在 1-10000 之间", { type: "warning" });
        return false;
      }
    } else {
      // 其他类型活动的优惠值校验
      if (!formData.discountValue || formData.discountValue <= 0) {
        message("请输入有效的优惠值", { type: "warning" });
        return false;
      }
      if (formData.activityType === 3 && (!formData.minAmount || formData.minAmount <= 0)) {
        message("请输入有效的满减门槛", { type: "warning" });
        return false;
      }
    }

    // ===== 适用范围校验 =====
    if (formData.applyScope === 2 && (!formData.shopIds || formData.shopIds.length === 0)) {
      message("请选择至少一个门店", { type: "warning" });
      return false;
    }
    if (formData.deviceScope === 2 && (!formData.deviceIds || formData.deviceIds.length === 0)) {
      message("请选择至少一个设备", { type: "warning" });
      return false;
    }
    if (formData.productScope === 2 && (!formData.productIds || formData.productIds.length === 0)) {
      message("请选择至少一个商品", { type: "warning" });
      return false;
    }

    return true;
  }

  function handleEdit(row) {
    const formData = reactive<FormItemProps>({
      id: row.id,
      activityName: row.activityName,
      activityType: row.activityType,
      activityDesc: row.activityDesc || "",
      startTime: row.startTime,
      endTime: row.endTime,
      status: row.status,
      discountValue: row.discountValue,
      minAmount: row.minAmount,
      maxDiscount: row.maxDiscount,
      applyScope: row.applyScope || 1,
      deviceScope: row.deviceScope || 1,
      productScope: row.productScope || 1,
      totalBudget: row.totalBudget,
      shopIds: row.shopIds || [],
      deviceIds: row.deviceIds || [],
      productIds: row.productIds || [],

      // 邀请活动特有字段的回显 (type=4)
      ...(row.activityType === 4 ? {
        inviterCouponTemplateId: row.inviterCouponTemplateId || row.inviterCouponId || null,
        inviteeCouponTemplateId: row.inviteeCouponTemplateId || row.inviteeCouponId || null,
        dailyLimit: row.dailyLimit || 10,
        totalLimit: row.totalLimit || null,
        requireFirstOrder: row.requireFirstOrder ?? 1,
        minOrderAmount: row.minOrderAmount || null,
        rewardRuleType: "fixed",
        inviteCodePrefix: row.inviteCodePrefix || "INV"
      } : {})
    });

    addDialog({
      title: `编辑${typeMap[row.activityType]?.text || ''}活动`,
      width: row.activityType === 4 ? "900px" : "700px",  // 邀请表单更宽
      draggable: true,
      fullscreen: deviceDetection(),
      contentRenderer: () => renderForm(formData),
      beforeSure: async (done) => {
        if (submitting.value) return;
        if (!validateForm(formData)) return;
        submitting.value = true;
        try {
          const { code } = await updateActivity(formData.id!, toRaw(formData));
          if (code === 200) {
            message("编辑成功", { type: "success" });
            done();
            onSearch();
          }
        } catch (error) {
          message("编辑失败", { type: "error" });
        } finally {
          submitting.value = false;
        }
      }
    });
  }

  // ===== 默认表单数据 =====
  const defaultFormData = {
    activityName: "",
    activityType: undefined as number | undefined,
    activityDesc: "",
    startTime: "",
    endTime: "",
    status: 0,
    discountValue: null as number | null,
    minAmount: null as number | null,
    maxDiscount: null as number | null,
    applyScope: 1,
    deviceScope: 1,
    productScope: 1,
    totalBudget: null as number | null,
    shopIds: [] as number[],
    deviceIds: [] as string[],
    productIds: [] as number[],
    rewardRuleType: "fixed",
    inviterCouponTemplateId: null as number | null,
    inviteeCouponTemplateId: null as number | null,
    dailyLimit: 10,
    totalLimit: null as number | null,
    requireFirstOrder: 1,
    minOrderAmount: null as number | null,
    inviteCodePrefix: "INV"
  };

  // 当前选中的活动类型（用于新增时预选）- 已移除，弹窗内选择
  // 防重复提交标志
  const submitting = ref(false);

  function handleAdd() {
    const formData = reactive<FormItemProps>({
      ...defaultFormData,

      // 邀请有礼默认值（用户可在弹窗内切换类型）
      rewardRuleType: "fixed",
      dailyLimit: 10,
      requireFirstOrder: 1
    });

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

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

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

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

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    typeMap,
    statusMap,
    applyScopeMap,
    deviceScopeMap,
    productScopeMap,
    couponTemplateList,
    submitting,
    onSearch,
    resetForm,
    handleAdd,
    handleEdit,
    handleViewDetail,
    handleDelete,
    handlePublish,
    handlePause,
    handleResume,
    handleSizeChange,
    handleCurrentChange
  };
}
