<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="赛事标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入赛事标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="赛事开始时间" prop="startTime">
              <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择赛事开始时间" />
            </el-form-item>
            <el-form-item label="赛事结束时间" prop="endTime">
              <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择赛事结束时间" />
            </el-form-item>
            <el-form-item label="比赛地址" prop="location">
              <el-input v-model="queryParams.location" placeholder="请输入比赛地址" 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:leagueTournament:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:leagueTournament:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['physical:leagueTournament:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:leagueTournament: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="leagueTournamentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="锦标赛联赛ID" align="center" prop="id" v-if="true" />
        <el-table-column label="赛事标题" align="center" prop="title" />
        <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" width="300">
          <template #default="scope">
            <span>
              {{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
              ~
              {{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="预报名时间" align="center" width="300">
          <template #default="scope">
            <span v-if="scope.row.registrationBeginTime && scope.row.registrationEndTime">
              {{ parseTime(scope.row.registrationBeginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
              ~
              {{ parseTime(scope.row.registrationEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
            </span>
            <span v-else> - </span>
          </template>
        </el-table-column>
        <el-table-column label="比赛项目" align="center" prop="gameVariant">
          <template #default="scope">
            {{ getGameVariantText(scope.row.gameVariant) }}
          </template>
        </el-table-column>
        <el-table-column label="比赛地址" align="center" prop="location" />
        <el-table-column label="下级比赛" align="center">
          <template #default="scope">
            <el-button type="text" @click="handleViewSubTournaments(scope.row.id)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="120">
          <template #default="scope">
            <span v-if="scope.row.status === 'open'">开启</span>
            <span v-else-if="scope.row.status === 'closed'">关闭</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column label="是否需预报名" align="center" width="120">
          <template #default="scope">
            <span v-if="scope.row.isRegistration === 1">是</span>
            <span v-else-if="scope.row.isRegistration === 0">否</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <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="更新时间" align="center" prop="updatedAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 状态切换按钮 -->
            <el-button
              :type="scope.row.status === 'open' ? 'info' : 'success'"
              :icon="scope.row.status === 'open' ? 'Lock' : 'Unlock'"
              size="small"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 'open' ? '关闭' : '开启' }}
            </el-button>
            <!-- 修改按钮 -->
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['physical:leagueTournament:edit']"></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['physical:leagueTournament:remove']"
              ></el-button>
            </el-tooltip>
          </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="600px" append-to-body>
      <el-form ref="leagueTournamentFormRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="赛事标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入赛事标题" />
        </el-form-item>
        <el-form-item label="比赛项目" prop="gameVariant">
          <el-select aria-required="true" v-model="form.gameVariant" placeholder="请选择">
            <el-option v-for="dict in game_variant_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片" prop="imageUrl">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleIconChange"
              :on-remove="handleIconRemove"
              :file-list="fileList"
              :auto-upload="false"
              accept="image/*"
            >
              <template #trigger>
                <el-button type="primary">点击选择图片</el-button>
              </template>

              <!-- 预览图区域 -->
              <template #default>
                <div class="preview-area" @click="handlePreviewClick">
                  <img
                    v-if="iconPreviewUrl || form.imageUrl"
                    :src="iconPreviewUrl || form.imageUrl"
                    alt="预览图"
                    style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer"
                  />
                  <div v-else style="margin-top: 10px; color: #999">无图片</div>
                </div>
              </template>

              <template #tip>
                <div class="el-upload__tip">
                  <span v-if="fileList.length > 0">当前已选文件：{{ fileList[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="赛事开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择赛事开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="赛事结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择赛事结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否需要预报名" prop="isPreRegistration">
          <el-select aria-required="true" v-model="form.isRegistration" placeholder="请选择">
            <el-option label="否" :value="0"> </el-option>
            <el-option label="是" :value="1"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预报名开始时间" prop="registrationBeginTime">
          <el-date-picker
            clearable
            v-model="form.registrationBeginTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择赛事开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预报名结束时间" prop="registrationEndTime">
          <el-date-picker
            clearable
            v-model="form.registrationEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择赛事结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="比赛地址" prop="location">
          <el-input v-model="form.location" type="textarea" :rows="3" 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>
    <el-dialog v-model="dialogVisible" title="图片预览" width="60%">
      <img :src="iconPreviewUrl || form.imageUrl" alt="预览" style="max-width: 100%; max-height: 80vh" />
    </el-dialog>
  </div>
</template>

<script setup name="LeagueTournament" lang="ts">
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import {
  listLeagueTournament,
  getLeagueTournament,
  delLeagueTournament,
  addLeagueTournament,
  updateLeagueTournament,
  updateOpenOrCloseByBo
} from '@/api/system/physical/leagueTournament';
import { LeagueTournamentVO, LeagueTournamentQuery, LeagueTournamentForm } from '@/api/system/physical/leagueTournament/types';
import { uploadTournament } from '@/api/system/business/tournaments';
import { parseTime } from '@/utils/dateUtils';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { game_variant_type, tournaments_time, physical_tournaments_type } = toRefs<any>(
  proxy?.useDict('game_variant_type', 'tournaments_time', 'physical_tournaments_type')
);
const leagueTournamentList = ref<LeagueTournamentVO[]>([]);
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 leagueTournamentFormRef = ref<ElFormInstance>();

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

const initFormData: LeagueTournamentForm = {
  id: undefined,
  title: undefined,
  imageUrl: undefined,
  startTime: undefined,
  endTime: undefined,
  gameType: undefined,
  location: undefined,
  status: 'closed',
  createdAt: undefined,
  updatedAt: undefined
};
const data = reactive<PageData<LeagueTournamentForm, LeagueTournamentQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    imageUrl: undefined,
    startTime: undefined,
    endTime: undefined,
    gameType: undefined,
    location: undefined,
    status: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '锦标赛联赛ID不能为空', trigger: 'blur' }],
    title: [{ required: true, message: '赛事标题不能为空', trigger: 'blur' }],
    gameVariant: [{ required: true, message: '比赛项目不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '赛事开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '赛事结束时间不能为空', trigger: 'blur' }],
    registrationBeginTime: [{ required: true, message: '预报名开始时间不能为空', trigger: 'blur' }],
    registrationEndTime: [{ required: true, message: '预报名结束时间不能为空', trigger: 'blur' }],
    /*  gameType: [{ required: true, message: '比赛项目不能为空', trigger: 'change' }],*/
    location: [{ required: true, message: '比赛地址不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

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

/** 查询锦标赛联赛列表 */
const getList = async () => {
  loading.value = true;
  const res = await listLeagueTournament(queryParams.value);
  leagueTournamentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  // 清空文件列表
  fileList.value = [];
  iconPreviewUrl.value = '';
  dialog.visible = true;
  dialog.title = '添加锦标赛联赛';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: LeagueTournamentVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getLeagueTournament(_id);
  Object.assign(form.value, res.data);
  form.value.gameVariant = String(res.data.gameVariant);
  dialog.visible = true;
  dialog.title = '修改锦标赛联赛';
  // 清空文件列表，避免残留
  fileList.value = [];
  // 如果有图片URL，创建虚拟文件对象以便显示
  if (res.data.imageUrl) {
    fileList.value = [
      {
        name: '已上传',
        url: res.data.imageUrl,
        status: 'success'
      }
    ];
  }
};

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/leagueTournament/export',
    {
      ...queryParams.value
    },
    `leagueTournament_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
// 图片上传相关
const fileList = ref([]); // ← 新增
const iconPreviewUrl = ref(''); // ← 新增
const dialogVisible = ref(false); // ← 新增

// 处理图片上传变化
const handleIconChange = async (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  fileList.value = [];

  if (file.raw) {
    iconPreviewUrl.value = URL.createObjectURL(file.raw);
  }

  if (index === -1) {
    fileList.value.push(file);
  }

  try {
    const rawFile = file.raw;
    if (!rawFile) return;

    const res = await uploadTournament(rawFile);
    if (res.code === 200 && res.data?.url) {
      fileList.value[index] = {
        ...file,
        status: 'success',
        response: res.data.url
      };
      form.value.imageUrl = res.data.url;
      iconPreviewUrl.value = res.data.url;
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg || '上传失败');
    }
  } catch (error) {
    fileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};

// 删除图片处理
const handleIconRemove = (file, updatedFileList) => {
  fileList.value = updatedFileList;
  iconPreviewUrl.value = '';
  form.value.imageUrl = '';
};

// 点击预览图放大
const handlePreviewClick = () => {
  if (iconPreviewUrl.value || form.value.imageUrl) {
    dialogVisible.value = true;
  }
};
const getGameVariantText = (value: string | number | null | undefined): string => {
  const numValue = Number(value);
  switch (numValue) {
    case 0:
      return '德州扑克';
    case 1:
      return '奥马哈';
    case 2:
      return '短牌';
    default:
      return '未知';
  }
};
const handleViewSubTournaments = (leagueTournamentId: number) => {
  proxy?.$router.push({
    path: '/physical/tournaments',
    query: {
      leagueTournamentId: String(leagueTournamentId) // 转为字符串以兼容 URL 参数
    }
  });
};
/** 处理状态变更 */
/** 处理状态变更 */
const handleStatusChange = async (row: LeagueTournamentVO) => {
  try {
    // 显示确认对话框
    const confirmMsg = row.status === 'open' ? '确认要关闭此赛事吗？' : '确认要开启此赛事吗？';

    await proxy?.$modal.confirm(confirmMsg);

    // 获取新的状态值
    const newStatus = row.status === 'open' ? 'closed' : 'open';

    // 构建更新数据
    const updateData: LeagueTournamentForm = {
      ...row,
      status: newStatus
    };

    // 调用接口更新状态
    await updateOpenOrCloseByBo(updateData);

    // 更新本地状态
    row.status = newStatus;
    getList();
    proxy?.$modal.msgSuccess(`状态已${newStatus === 'open' ? '开启' : '关闭'}`);
  } catch (error) {
    console.error('状态更新失败:', error);
    // 用户取消操作时不显示错误消息
    if (error !== 'cancel') {
      proxy?.$modal.msgError('状态更新失败，请重试');
    }
  }
};
</script>
