<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="赛事ID" prop="tournamentId">
              <el-input v-model="queryParams.tournamentId" placeholder="请输入赛事ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属联赛" prop="leagueTournamentId">
              <el-select v-model="queryParams.leagueTournamentId" placeholder="请选择联赛">
                <el-option v-for="item in leagueTournamentOptions" :key="item.id" :label="item.title" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="提交时间" prop="createdAt">
              <el-date-picker
                v-model="queryParams.createdAt"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['physical:tournamentsRegistration:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate()"
              v-hasPermi="['physical:tournamentsRegistration:edit']"
              >修改</el-button
            >
          </el-col>-->
          <!--          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['physical:tournamentsRegistration:remove']"
              >删除</el-button
            >
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:tournamentsRegistration:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="tournamentsRegistrationList">
        <el-table-column label="提交日期" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="登录名称" align="center" prop="userName" />
        <el-table-column label="用户姓名" align="center" prop="realName" />
        <el-table-column label="预报名比赛" align="center" prop="leagueTournamentName" />
        <el-table-column label="审核图片" align="center" width="90">
          <template #default="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              style="width: 40px; height: 40px; border-radius: 4px; cursor: zoom-in"
              :preview-src-list="[scope.row.imageUrl]"
              :preview-teleported="true"
              fit="cover"
            />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.autoStatus, scope.row.status)" size="small">
              {{ getStatusText(scope.row.autoStatus, scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <!--        <el-table-column label="审核备注" align="center" prop="remark" />-->
        <el-table-column label="审核时间" align="center" width="180">
          <template #default="{ row }">
            <span v-if="row.auditedAt">
              {{ parseTime(row.auditedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审核人姓名" align="center" prop="auditorName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!--            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:tournamentsRegistration:edit']"
              ></el-button>
            </el-tooltip>-->
            <!--            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:tournamentsRegistration:remove']"
              ></el-button>
            </el-tooltip>-->
            <!-- 待审核状态显示审核按钮 -->
            <template v-if="scope.row.status === 'pending'">
              <el-button
                type="success"
                link
                size="small"
                @click="handleAudit(scope.row, 'approved')"
                v-hasPermi="['physical:tournamentsRegistration:edit']"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                link
                size="small"
                @click="handleAudit(scope.row, 'rejected')"
                v-hasPermi="['physical:tournamentsRegistration:edit']"
              >
                拒绝
              </el-button>
            </template>
            <!-- 已审核状态不显示操作按钮 -->
            <template v-else>
              <span>-</span>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改预报名对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="tournamentsRegistrationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="锦标联赛-赛事ID" prop="leagueTournamentId">
          <el-input v-model="form.leagueTournamentId" placeholder="请输入锦标联赛-赛事ID" />
        </el-form-item>
        <el-form-item label="上传的审核图片地址" prop="imageUrl">
          <el-input v-model="form.imageUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="审核备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TournamentsRegistration" lang="ts">
import {
  listTournamentsRegistration,
  getTournamentsRegistration,
  delTournamentsRegistration,
  addTournamentsRegistration,
  updateTournamentsRegistration,
  auditTournamentsRegistration
} from '@/api/system/physical/tournamentsRegistration';
import { selectPhysicalLeagueTournamentSelList } from '@/api/system/physical/leagueTournament';
import {
  TournamentsRegistrationVO,
  TournamentsRegistrationQuery,
  TournamentsRegistrationForm
} from '@/api/system/physical/tournamentsRegistration/types';
import { ElSelect } from 'element-plus';
import { LeagueTournamentVO } from '@/api/system/physical/leagueTournament/types';
import { parseTime } from '@/utils/dateUtils';
import { useRoute } from 'vue-router';
import { onMounted } from 'vue';
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;


const tournamentsRegistrationList = ref<TournamentsRegistrationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const tournamentsRegistrationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TournamentsRegistrationForm = {
  id: undefined,
  userId: undefined,
  leagueTournamentId: undefined,
  imageUrl: undefined,
  status: undefined,
  remark: undefined,
  createdAt: undefined,
  auditedAt: undefined,
  auditorId: undefined,
  auditorName: undefined
};
const data = reactive<PageData<TournamentsRegistrationForm, TournamentsRegistrationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    tournamentId: undefined,
    leagueTournamentId: undefined,
    imageUrl: undefined,
    status: undefined,
    createdAt: [undefined, undefined],
    auditedAt: undefined,
    auditorId: undefined,
    auditorName: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '预报名ID不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    leagueTournamentId: [{ required: true, message: '锦标联赛-赛事ID不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '审核状态：pending=待审核，approved=已通过，rejected=已拒绝不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预报名列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTournamentsRegistration(queryParams.value);
  tournamentsRegistrationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 页面加载时检查路由参数
onMounted(() => {
  if (route.query.tournamentId) {
    queryParams.value.tournamentId = route.query.tournamentId;
    getList();
  }
});

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  tournamentsRegistrationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  // 手动拆分日期范围
  if (queryParams.value.createdAt && queryParams.value.createdAt.length === 2) {
    queryParams.value.createdAtStart = queryParams.value.createdAt[0];
    queryParams.value.createdAtEnd = queryParams.value.createdAt[1];
  } else {
    queryParams.value.createdAtStart = undefined;
    queryParams.value.createdAtEnd = undefined;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TournamentsRegistrationVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加预报名';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TournamentsRegistrationVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTournamentsRegistration(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改预报名';
};

/** 提交按钮 */
const submitForm = () => {
  tournamentsRegistrationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTournamentsRegistration(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTournamentsRegistration(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TournamentsRegistrationVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除预报名编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTournamentsRegistration(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/tournamentsRegistration/export',
    {
      ...queryParams.value
    },
    `预报名审核${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};
onMounted(() => {
  getList();
  loadLeagueTournamentOptions();
});
/** 获取状态文本 */
const getStatusText = (autoStatus: number, status: string) => {
  if (autoStatus === 1) {
    return '自动绑定';
  }
  switch (status) {
    case 'pending':
      return '待审核';
    case 'approved':
      return '已通过';
    case 'rejected':
      return '已拒绝';
    case 'cancel':
      return '已取消';
    default:
      return status;
  }
};

/** 获取状态标签类型 */
const getStatusTagType = (autoStatus: number, status: string) => {
  if (autoStatus === 1) {
    return 'info'; // 或者使用其他颜色表示自动绑定
  }

  switch (status) {
    case 'pending':
      return 'warning'; // 黄色标签表示待审核
    case 'approved':
      return 'success'; // 绿色标签表示已通过
    case 'rejected':
      return 'danger'; // 红色标签表示已拒绝
    case 'cancel':
      return 'primary';
    default:
      return 'info';
  }
};
/** 审核操作 */
const handleAudit = async (row: TournamentsRegistrationVO, status: string) => {
  const actionText = status === 'approved' ? '通过' : '拒绝';
  const confirmMsg = `是否确认${actionText}该预报名申请？`;
  try {
    await proxy?.$modal.confirm(confirmMsg);

    // 更新审核状态
    const auditData = {
      id: row.id,
      status: status
    };
    await auditTournamentsRegistration(auditData);
    proxy?.$modal.msgSuccess(`${actionText}成功`);
    await getList(); // 刷新列表
  } catch (error) {
    console.error('审核失败:', error);
  }
};
// 响应式变量
const leagueTournamentOptions = ref<LeagueTournamentVO[]>([]);

const loadLeagueTournamentOptions = async () => {
  try {
    const res = await selectPhysicalLeagueTournamentSelList();
    if (res.code === 200 && Array.isArray(res.data)) {
      leagueTournamentOptions.value = res.data;
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
</script>
