<template>
  <div class="table-box button-table">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :data-callback="dataCallback">
      <template #operation="scope">
        <el-button type="primary" link @click="toDetail(scope.row)"> 查看详情 </el-button>
        <!-- 待审核状态显示通过和拒绝按钮 -->
        <template v-if="scope.row.status == 0">
          <el-button type="success" link @click="handleApprove(scope.row)"> 通过 </el-button>
          <el-button type="danger" link @click="handleReject(scope.row)"> 拒绝 </el-button>
        </template>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="personnel">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getPersonnelList, approvePersonnel, rejectPersonnel } from "@/api/modules/operationManagement";
import { localGet } from "@/utils";

const router = useRouter();
const proTable = ref<ProTableInstance>();

// 报名情况枚举：0-待审核, 1-拒绝, 2-通过
const registrationStatusEnum = [
  { label: "待审核", value: 0 },
  { label: "拒绝", value: 1 },
  { label: "通过", value: 2 }
];

const columns = reactive<ColumnProps<any>[]>([
  { prop: "userName", label: "姓名", minWidth: 220 },
  { prop: "phone", label: "联系方式", width: 300 },
  {
    prop: "activityName",
    label: "所属活动",
    width: 300,
    fieldNames: { label: "label", value: "value" },
    search: {
      el: "input",
      props: { placeholder: "请输入活动名称" },
      order: 2
    }
  },
  {
    prop: "status",
    label: "报名情况",
    width: 300,
    enum: registrationStatusEnum,
    fieldNames: { label: "label", value: "value" },
    search: { el: "select", props: { placeholder: "请选择" }, order: 1 },
    render: (scope: any) => {
      // 状态值：0-待审核, 1-拒绝, 2-通过
      const status = scope.row.status;
      if (status == 2) return "通过";
      if (status == 1) return "拒绝";
      return "待审核";
    }
  },
  { prop: "operation", label: "操作", fixed: "right", minWidth: 200 }
]);

const initParam = reactive({
  storeId: localGet("createdId")
});

const dataCallback = (data: any) => ({
  list: data?.records ?? [],
  total: data?.total ?? 0
});

const getTableList = async (params: any) => {
  // 显示全屏loading
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "加载中...",
    background: "rgba(0, 0, 0, 0.7)"
  });

  try {
    // 转换参数格式以匹配新接口
    const newParams: any = {
      storeId: params.storeId || localGet("createdId"),
      pageNum: params.page || params.pageNum || 1,
      pageSize: params.size || params.pageSize || 10
    };

    // 如果有状态筛选，添加状态参数（注意：搜索字段名是 status）
    if (params.status) {
      newParams.status = params.status;
    }

    // 如果有活动类型筛选，添加活动类型参数
    if (params.activityType) {
      newParams.activityType = params.activityType;
    }

    // 如果有活动名称筛选，添加活动名称参数
    if (params.activityName) {
      newParams.activityName = params.activityName;
    }

    const result = await getPersonnelList(newParams);
    return result;
  } finally {
    // 关闭loading
    loadingInstance.close();
  }
};

const toDetail = (row: any) => {
  router.push(`/operationManagement/personnelDetail?id=${row.id}`);
};

// 审核通过
const handleApprove = async (row: any) => {
  try {
    await ElMessageBox.confirm("确定要通过该报名吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    const res: any = await approvePersonnel({ id: Number(row.id) });
    if (res.code == 200) {
      ElMessage.success("审核通过成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || res?.message || "审核通过失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "审核通过失败");
    }
  }
};

// 审核拒绝
const handleReject = async (row: any) => {
  try {
    const { value: rejectReason } = await ElMessageBox.prompt("请输入拒绝原因", "审核拒绝", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputType: "textarea",
      inputPlaceholder: "请输入拒绝原因",
      inputValidator: (value: string) => {
        if (!value || value.trim() === "") {
          return "拒绝原因不能为空";
        }
        return true;
      }
    });

    // 再次验证拒绝原因（防止用户绕过验证）
    if (!rejectReason || rejectReason.trim() === "") {
      ElMessage.warning("拒绝原因不能为空");
      return;
    }

    const res: any = await rejectPersonnel({
      id: Number(row.id),
      rejectReason: rejectReason.trim()
    });
    if (res.code == 200) {
      ElMessage.success("审核拒绝成功");
      proTable.value?.getTableList();
    } else {
      ElMessage.error(res?.msg || res?.message || "审核拒绝失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "审核拒绝失败");
    }
  }
};
</script>
