<template>
  <div class="table-box button-table">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :key="activeName"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <div class="table-header-btn">
          <div class="header-actions">
            <!-- 优惠券：状态 Tab（全部、未开始、进行中、已下架、已结束、已清库，不含草稿） -->
            <el-tabs v-if="activeName === '2'" v-model="couponStatusTab" class="status-tabs" @tab-click="onCouponStatusTabChange">
              <el-tab-pane v-for="tab in couponStatusTabOptions" :key="tab.value" :label="tab.label" :name="tab.value" />
            </el-tabs>
          </div>
        </div>
      </template>
      <template #tableHeaderRight="scope">
        <el-button :icon="Plus" class="button" type="primary" @click="newCoupon" v-if="type"> 新建优惠券 </el-button>
        <!--        <div class="action-buttons">-->
        <!--          <el-button :icon="Plus" class="button" type="primary" @click="newGroupBuying" v-if="type"> 新建代金券 </el-button>-->
        <!--          <el-button :icon="Plus" class="button" type="primary" @click="newCoupon" v-if="type"> 新建优惠券 </el-button>-->
        <!--        </div>-->
      </template>
      <template #status="scope">
        <!-- 代金券：显示状态和审核状态两行 -->
        <template v-if="activeName === '1'">
          <p style="margin: 0; line-height: 1.5">
            状态：{{ scope.row.dataType === 1 ? "草稿" : scope.row.statusName ? scope.row.statusName : "--" }}
          </p>
          <p style="margin: 0; line-height: 1.5" v-if="scope.row.dataType == 0">审核状态：{{ scope.row.reviewType || "--" }}</p>
        </template>
        <!-- 优惠券：只显示状态一行 -->
        <template v-else>
          <span>{{ getStatusLabel(scope.row.status) }}</span>
        </template>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button v-if="canShowAction(scope.row, '上架')" link type="primary" @click="changeTypes(scope.row, 5)">
          上架
        </el-button>
        <el-button v-if="canShowAction(scope.row, '下架')" link type="primary" @click="changeTypes(scope.row, 6)">
          下架
        </el-button>
        <el-button v-if="canShowAction(scope.row, '修改库存')" link type="primary" @click="changeInventory(scope.row)">
          修改库存
        </el-button>
        <el-button v-if="canShowAction(scope.row, '查看详情')" link type="primary" @click="toDetail(scope.row)">
          查看详情
        </el-button>
        <el-button v-if="canShowAction(scope.row, '编辑')" link type="primary" @click="editRow(scope.row)"> 编辑 </el-button>
        <el-button v-if="canShowAction(scope.row, '删除')" link type="primary" @click="deleteRow(scope.row)"> 删除 </el-button>
        <el-button v-if="canShowAction(scope.row, '查看拒绝原因')" link type="primary" @click="viewRejectReason(scope.row)">
          查看拒绝原因
        </el-button>
      </template>
    </ProTable>
    <el-dialog v-model="dialogFormVisible" title="修改库存" width="500" append-to-body class="inventory-dialog-ios-fix">
      <el-form ref="ruleFormRef" :model="formInventory" :rules="rules" @submit.prevent>
        <el-form-item label="套餐名">
          {{ formInventory.name }}
        </el-form-item>
        <el-form-item label="剩余库存"> {{ formInventory.singleQty }}张 </el-form-item>
        <el-form-item label="修改库存" prop="newInventory">
          <el-input
            v-model="formInventory.newInventory"
            placeholder="请输入"
            inputmode="numeric"
            pattern="[0-9]*"
            autocomplete="off"
            @focus="onInventoryInputFocus"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog"> 取消 </el-button>
          <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看拒绝原因弹窗 -->
    <el-dialog v-model="rejectReasonDialogVisible" title="查看拒绝原因" width="600px">
      <div class="reject-reason-content">
        <div class="reject-reason-item">
          <div class="reject-reason-label">代金券名称：</div>
          <div class="reject-reason-value">
            {{ rejectReasonData.name || "--" }}
          </div>
        </div>
        <div class="reject-reason-item">
          <div class="reject-reason-label">拒绝原因：</div>
          <div class="reject-reason-value reject-reason-text">
            {{ rejectReasonData.approvalComments || "暂无拒绝原因" }}
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeRejectReasonDialog"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="voucherManagement">
import { computed, nextTick, onActivated, onMounted, reactive, ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { Plus } from "@element-plus/icons-vue";
import { delThaliById, getThaliList, updateNum, updateStatus } from "@/api/modules/voucherManagement";
import { delCouponById, getStoreAllCouponList, updateCouponSingleQty, updateCouponStatus } from "@/api/modules/couponManagement";
import { ElMessageBox } from "element-plus/es";
import { localGet, usePermission } from "@/utils";
import { formatCurrency } from "@/utils/formatCurrency";

const router = useRouter();
const route = useRoute();
const dialogFormVisible = ref(false);
const formInventory: any = ref({
  id: "",
  name: "",
  singleQty: "",
  newInventory: ""
});
const activeName = ref("2");
// 查看拒绝原因弹窗相关
const rejectReasonDialogVisible = ref(false);
const rejectReasonData = ref<any>({
  name: "",
  approvalComments: ""
});
// 定义表单类型
interface RuleForm {
  newInventory: string;
}
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  newInventory: [
    { required: true, message: "请输入库存数量", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "请输入整数,不允许输入小数,负数",
      trigger: "blur"
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          const numValue = Number(value);
          if (!isNaN(numValue) && numValue > 10000) {
            callback(new Error("库存不得大于10000"));
            return;
          }
          // 验证新库存值不能小于剩余库存
          const currentQty = Number(formInventory.value.singleQty) || 0;
          if (numValue < currentQty) {
            callback(new Error(`新库存值不能小于剩余库存(${currentQty})张`));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ]
});
const statusEnum = [
  { label: "草稿", value: "0" },
  { label: "进行中", value: "5" },
  { label: "未开始", value: "2" },
  { label: "已下架", value: "6" },
  { label: "已售罄", value: "4" },
  { label: "已结束", value: "7" }
];
const statusEnumY = [
  { label: "未开始", value: "2" },
  { label: "进行中", value: "0" },
  { label: "已下架", value: "3" },
  { label: "已结束", value: "1" },
  { label: "已清库", value: "4" }
];
// 优惠券状态 Tab 选项（不含草稿）
const couponStatusTabOptions = [
  { label: "全部", value: "0" },
  { label: "进行中", value: "1" },
  // { label: "草稿", value: "3" },
  { label: "已结束", value: "2" },
  { label: "已下架", value: "5" },
  { label: "未开始", value: "4" },
  { label: "已清库", value: "6" }
];
const couponStatusTab = ref("0");
// 优惠券类型枚举（满减券、折扣券）
const couponTypeEnum = [
  { label: "满减券", value: "1" },
  { label: "折扣券", value: "2" }
];
// ProTable 实例（需要在使用它的地方之前定义）
const proTable = ref<ProTableInstance>();

// 代金券表格列配置
const voucherColumns = reactive<ColumnProps<any>[]>([
  {
    prop: "name",
    label: "券名称",
    search: {
      el: "input"
    }
  },
  {
    prop: "price",
    label: "价格",
    render: (scope: any) => {
      return formatCurrency(scope.row.price, 2, "￥") || "--";
    }
  },
  {
    prop: "saleNum",
    label: "已售",
    render: scope => {
      return scope.row.saleNum === null || scope.row.saleNum === undefined || scope.row.saleNum === "" ? 0 : scope.row.saleNum;
    }
  },
  {
    prop: "singleQty",
    label: "剩余库存",
    render: scope => {
      return scope.row.singleQty === null || scope.row.singleQty === undefined || scope.row.singleQty === ""
        ? 0
        : scope.row.singleQty + "张";
    }
  },
  {
    prop: "validDate",
    label: "结束时间",
    render: (scope: any) => {
      return scope.row.validDate?.replace(/-/g, "/") || "--";
    }
  },
  {
    prop: "status",
    label: "状态",
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: statusEnum,
    fieldNames: { label: "label", value: "value" }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 优惠券表格列配置（参考商家端：优惠券名称、剩余库存、结束时间、状态、类型、操作）
const couponColumns = reactive<ColumnProps<any>[]>([
  {
    prop: "name",
    label: "优惠券名称",
    search: {
      el: "input",
      props: { placeholder: "请输入" }
    }
  },
  {
    prop: "singleQty",
    label: "剩余库存",
    render: scope => {
      return scope.row.singleQty === null || scope.row.singleQty === undefined || scope.row.singleQty === ""
        ? 0
        : scope.row.singleQty;
    }
  },
  {
    prop: "validDate",
    label: "结束时间",
    render: (scope: any) => {
      return scope.row.validDate?.replace(/-/g, "/") || "--";
    }
  },
  {
    prop: "status",
    label: "状态"
  },
  {
    prop: "couponType",
    label: "类型",
    search: {
      el: "select",
      props: { placeholder: "请选择" }
    },
    enum: couponTypeEnum,
    fieldNames: { label: "label", value: "value" },
    render: (scope: any) => getCouponTypeLabel(scope.row.couponType)
  },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
]);

// 根据当前选中的tab动态返回列配置
const columns = computed(() => {
  return activeName.value === "1" ? voucherColumns : couponColumns;
});

const allTabOptions = [
  { label: "代金券", name: "1" },
  { label: "优惠券", name: "2" }
];

// 状态枚举： 1待审核 2未开始 3审核拒绝 4已售罄 5进行中 6已下架 7已结束
const VO_STATUS = {
  待审核: 1,
  未开始: 2,
  审核拒绝: 3,
  已售罄: 4,
  进行中: 5,
  已下架: 6,
  已结束: 7
} as const;

// 状态枚举：0进行中 1已结束 2未开始 3已下架 4已售罄 5草稿
const CO_STATUS = {
  进行中: 0,
  已结束: 1,
  未开始: 2,
  已下架: 3,
  已售罄: 4,
  草稿: 5
} as const;

// 按「状态 → 可执行操作」配置，与产品表一致，一目了然
// 代金券：各状态下的操作列表（草稿用 dataType==1 单独判断）
const VOUCHER_ACTIONS_BY_STATUS: Record<number, string[]> = {
  [VO_STATUS.待审核]: ["查看详情", "查看拒绝原因"],
  [VO_STATUS.未开始]: ["查看详情", "上架", "修改库存", "删除"],
  [VO_STATUS.审核拒绝]: ["查看详情", "编辑", "删除", "查看拒绝原因"],
  [VO_STATUS.进行中]: ["查看详情", "下架", "修改库存"],
  [VO_STATUS.已售罄]: ["查看详情", "编辑", "修改库存", "删除"],
  [VO_STATUS.已下架]: ["查看详情", "上架", "编辑", "删除"],
  [VO_STATUS.已结束]: ["编辑", "删除"]
};
// 代金券草稿（dataType==1）仅显示：编辑、删除
const VOUCHER_DRAFT_ACTIONS = ["编辑", "删除"];

// 优惠券：各状态下的操作列表（完全按产品表）
const COUPON_ACTIONS_BY_STATUS: Record<number, string[]> = {
  [CO_STATUS.草稿]: ["查看详情", "编辑", "删除"],
  [CO_STATUS.未开始]: ["查看详情", "修改库存"],
  [CO_STATUS.进行中]: ["下架", "查看详情", "修改库存"],
  [CO_STATUS.已下架]: ["上架", "查看详情", "修改库存"],
  [CO_STATUS.已结束]: ["查看详情", "删除"],
  [CO_STATUS.已售罄]: ["查看详情", "编辑", "删除"]
};

/** 判断当前行是否显示某操作按钮（代金券/优惠券通用） */
const canShowAction = (row: any, actionName: string): boolean => {
  if (activeName.value === "1") {
    if (row.dataType === 1) return VOUCHER_DRAFT_ACTIONS.includes(actionName);
    const actions = VOUCHER_ACTIONS_BY_STATUS[row.status];
    return actions != null && actions.includes(actionName);
  }
  const actions = COUPON_ACTIONS_BY_STATUS[row.status];
  return actions != null && actions.includes(actionName);
};

// 判断是否为代金券
const isVoucher = computed(() => activeName.value === "1");

// 判断是否为优惠券
const isCoupon = computed(() => activeName.value === "2");

// 获取状态标签
const getStatusLabel = (status: any) => {
  const statusEnumMap = CO_STATUS;
  for (const [label, value] of Object.entries(statusEnumMap)) {
    if (value === status) {
      return label;
    }
  }
  return "--";
};

// 优惠券类型展示（满减券/折扣券）
const getCouponTypeLabel = (type: number | string) => {
  const t = type === undefined || type === null ? "" : String(type);
  const item = couponTypeEnum.find(e => e.value === t);
  return item ? item.label : "--";
};

// 如果表格需要初始化请求参数，直接定义传给 ProTable
// 注意：不用 couponType，避免与搜索项「类型」(满减券/折扣券) 冲突，用 listType 表示 代金券(1)/优惠券(2)
const initParam = reactive({
  storeId: localGet("createdId") || "",
  groupType: localGet("businessSection") || "1",
  listType: activeName
});
const type = ref(false);
const typeCoupon = ref(false);
// 恢复 activeName 的函数
const restoreActiveName = () => {
  const savedActiveName = sessionStorage.getItem("ticketManagement_activeName");
  if (savedActiveName && (savedActiveName === "1" || savedActiveName === "2")) {
    activeName.value = savedActiveName;
    // 恢复后清除 sessionStorage，避免影响其他场景
    sessionStorage.removeItem("ticketManagement_activeName");
  }
};

// 页面加载时触发查询
onMounted(async () => {
  type.value = await usePermission("新建优惠券");
  // typeCoupon.value = await usePermission("新建优惠券");
  // 从 sessionStorage 恢复 activeName
  restoreActiveName();
  proTable.value?.getTableList();
});

// 从其他页面返回时触发查询
onActivated(() => {
  // 从 sessionStorage 恢复 activeName
  restoreActiveName();
  proTable.value?.getTableList();
});

// 监听路由变化，当从详情页或编辑页返回时恢复 activeName
watch(
  () => route.path,
  (newPath, oldPath) => {
    // 如果当前路径是列表页，且之前路径是详情页或编辑页，则恢复 activeName
    if (
      newPath.includes("/ticketManagement") &&
      !newPath.includes("/detail") &&
      !newPath.includes("/newVoucher") &&
      !newPath.includes("/newCoupon") &&
      (oldPath?.includes("/ticketManagement/detail") ||
        oldPath?.includes("/ticketManagement/couponDetail") ||
        oldPath?.includes("/ticketManagement/newVoucher") ||
        oldPath?.includes("/ticketManagement/newCoupon"))
    ) {
      restoreActiveName();
    }
  },
  { immediate: false }
);

// dataCallback 是对于返回的表格数据做处理
const dataCallback = (data: any) => {
  if (activeName.value === "1") {
    return {
      list: data.couponList?.records || [],
      total: data.couponList?.total || 0
    };
  } else {
    // 优惠券：新接口 getStoreAllCouponList 返回格式兼容 data.data 或 data.records
    const raw = data?.data ?? data;
    return {
      list: raw?.records ?? raw?.list ?? [],
      total: raw?.total ?? 0
    };
  }
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (activeName.value === "1") {
    // 代金券：使用 voucherManagement 接口，listType 即 代金券/优惠券 区分
    newParams.couponType = newParams.listType;
    if (newParams.status === "0") {
      newParams.dataType = 1; // 草稿
    } else if (newParams.status) {
      newParams.dataType = 0;
    } else {
      newParams.dataType = 2;
    }
    return getThaliList(newParams);
  } else {
    // 优惠券：使用 getStoreAllCouponList，搜索项 name、couponType 需一并传入
    return getStoreAllCouponList({
      storeId: newParams.storeId || localGet("createdId") || "",
      tab: couponStatusTab.value || "",
      size: newParams.pageSize || 10,
      page: newParams.pageNum || 1,
      couponName: newParams.name ?? "",
      couponType: newParams.couponType ?? "",
      couponsFromType: 1
    });
  }
};
const newGroupBuying = () => {
  router.push(`/ticketManagement/newVoucher?type=add`);
};
const newCoupon = () => {
  router.push(`/ticketManagement/newCoupon?type=add`);
};
// 跳转详情页 - 根据类型跳转不同页面
const toDetail = (row: any) => {
  // 保存当前 activeName 到 sessionStorage
  sessionStorage.setItem("ticketManagement_activeName", activeName.value);
  const path = isVoucher.value ? `/ticketManagement/detail?id=${row.id}` : `/ticketManagement/couponDetail?id=${row.id}`;
  router.push(path);
};
// 编辑行数据
const editRow = (row: any) => {
  // 保存当前 activeName 到 sessionStorage
  sessionStorage.setItem("ticketManagement_activeName", activeName.value);
  const path = isVoucher.value
    ? `/ticketManagement/newVoucher?id=${row.id}&type=edit`
    : `/ticketManagement/newCoupon?id=${row.id}&type=edit`;
  router.push(path);
};
// 删除行数据
const deleteRow = (row: any) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      if (isVoucher.value) {
        // 代金券删除逻辑
        const params = {
          id: row.id,
          groupType: localGet("businessSection")
        };
        return delThaliById(params);
      } else {
        // 优惠券删除逻辑
        const params = {
          id: row.id,
          groupType: localGet("businessSection")
        };
        return delCouponById(params);
      }
    })
    .then(() => {
      ElMessage.success("删除成功");
      proTable.value?.getTableList();
    })
    .catch(() => {
      // 用户取消删除，不做任何操作
    });
};
// Tab切换处理
const handleClick = () => {};

// 优惠券状态 Tab 切换
// 优惠券状态 Tab 切换（tab-click 触发时 v-model 尚未更新，用 nextTick 等绑定更新后再请求）
const onCouponStatusTabChange = () => {
  nextTick(() => {
    proTable.value?.getTableList();
  });
};

// 修改状态（上架/下架）
const changeTypes = async (row: any, status: number) => {
  if (isVoucher.value) {
    // 代金券上架/下架逻辑
    const res = await updateStatus({ id: row.id, status: status, approvalComments: "" });
    if (res && Number((res as any).code) === 200) {
      ElMessage.success("操作成功");
      proTable.value?.getTableList();
    }
  } else {
    // 优惠券上架/下架逻辑
    const res = await updateCouponStatus({ counponId: row.id });
    if (res && Number((res as any).code) === 200) {
      ElMessage.success("操作成功");
      proTable.value?.getTableList();
    }
  }
};
// 修改库存
const changeInventory = (row: any) => {
  formInventory.value = {
    id: row.id,
    name: row.name,
    singleQty: row.singleQty,
    newInventory: ""
  };
  dialogFormVisible.value = true;
};

// 提交修改库存
const handleSubmit = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async valid => {
    if (valid) {
      const params = {
        id: formInventory.value.id,
        singleQty: formInventory.value.newInventory
      };
      if (isVoucher.value) {
        const res = await updateNum(params);
        if (res && Number((res as any).code) === 200) {
          ElMessage.success("修改成功");
          closeDialog();
          proTable.value?.getTableList();
        }
      } else {
        const res = await updateCouponSingleQty(params);
        if (res && Number((res as any).code) === 200) {
          ElMessage.success("修改成功");
          closeDialog();
          proTable.value?.getTableList();
        }
      }
    }
  });
};

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false;
  formInventory.value = {
    id: "",
    name: "",
    singleQty: "",
    newInventory: ""
  };
};

// iOS 上输入框获焦时滚动到可视区域，避免键盘遮挡底部按钮
const onInventoryInputFocus = (e: Event) => {
  const target = e.target as HTMLElement;
  if (!target) return;
  requestAnimationFrame(() => {
    target.scrollIntoView({ behavior: "smooth", block: "center" });
  });
};

// 查看拒绝原因
const viewRejectReason = (row: any) => {
  rejectReasonData.value = {
    name: row.name,
    approvalComments: row.approvalComments
  };
  rejectReasonDialogVisible.value = true;
};
// 关闭拒绝原因弹窗
const closeRejectReasonDialog = () => {
  rejectReasonDialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
/* iOS 上修改库存弹窗：避免键盘弹起时遮挡底部，弹窗可滚动 */
:deep(.inventory-dialog-ios-fix) {
  .el-dialog__body {
    max-height: 60vh;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }
}

// 在组件样式中添加
.date-range {
  display: block; // 确保换行生效
  padding: 0 8px; // 可选：增加内边距
  word-wrap: break-word; // 长单词内换行
  white-space: normal; // 允许自然换行
}
.table-header-btn {
  .header-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .status-tabs {
      flex: 0 0 auto;
      :deep(.el-tabs__header) {
        margin-bottom: 0;
      }
      :deep(.el-tabs__nav-wrap::after) {
        height: 0;
      }
    }
    .button {
      margin-bottom: 0;
    }
  }
}
.action-buttons {
  display: flex;
  flex: 0 0 auto;
  gap: 10px;
  margin-right: 20px;
  .button {
    margin-bottom: 0;
  }
}
.reject-reason-content {
  padding: 20px 0;
  .reject-reason-item {
    display: flex;
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    .reject-reason-label {
      flex-shrink: 0;
      min-width: 100px;
      font-size: 14px;
      font-weight: 500;
      color: #606266;
    }
    .reject-reason-value {
      flex: 1;
      font-size: 14px;
      color: #303133;
      word-break: break-word;
      &.reject-reason-text {
        min-height: 80px;
        padding: 12px;
        line-height: 1.6;
        white-space: pre-wrap;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }
  }
}
</style>
