<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="name">
              <el-input v-model="queryParams.name" placeholder="请输入裁判姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工作年限" prop="workYears">
              <el-input v-model="queryParams.workYears" 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:judge:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:judge:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:judge:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Upload" @click="openImportDialog" v-hasPermi="['physical:judge:export']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:judge: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="judgeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="true" />
        <el-table-column label="裁判图片" align="center" width="90">
          <template #default="scope">
            <el-image
              v-if="scope.row.peopleIconUrl"
              :src="scope.row.peopleIconUrl"
              style="width: 40px; height: 40px; border-radius: 4px; cursor: zoom-in"
              :preview-src-list="[scope.row.peopleIconUrl]"
              :preview-teleported="true"
              fit="cover"
            />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="裁判编号" align="center" prop="judgeNumber" />
        <el-table-column label="裁判姓名" align="center" prop="name" />
        <el-table-column label="工作年限" align="center" prop="workYears" />
        <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="['physical:judge:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['physical:judge: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="500px" append-to-body>
      <el-form ref="judgeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="裁判姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入裁判姓名" />
        </el-form-item>
        <el-form-item label="裁判图片" prop="peopleIconUrl">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleJudgeIconChange"
              :on-remove="handleJudgeIconRemove"
              :file-list="judgeFileList"
              :auto-upload="false"
              accept="image/*"
            >
              <template #trigger>
                <el-button type="primary">点击选择图片</el-button>
              </template>

              <!-- 预览图区域 -->
              <template #default>
                <div class="preview-area" @click="handleJudgePreviewClick">
                  <!-- 只有当 judgeIconPreviewUrl 或 form.peopleIconUrl 存在时才显示 img -->
                  <img
                    v-if="judgeIconPreviewUrl || form.peopleIconUrl"
                    :src="judgeIconPreviewUrl || form.peopleIconUrl"
                    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="judgeFileList.length > 0">当前已选文件：{{ judgeFileList[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="工作年限" prop="workYears">
          <el-input v-model="form.workYears" placeholder="请输入工作年限" />
        </el-form-item>
        <el-form-item label="机构" prop="workYears">
          <el-input v-model="form.organization" placeholder="请输入机构" />
        </el-form-item>
        <el-form-item label="职务选择" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择职务">
            <el-option v-for="item in positionOptions" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </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="judgeDialogVisible" title="图片预览" width="50%">
      <img :src="judgePreviewSrc" alt="预览图片" style="max-width: 100%; max-height: 80vh" />
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="importDialog.title" v-model="importDialog.visible" width="500px" append-to-body>
      <el-form ref="importFormRef" :model="importForm" :rules="importRules" label-width="100px">
        <el-form-item label="选择文件" prop="file">
          <div class="upload-container">
            <el-upload
              class="upload-demo"
              action="#"
              :on-change="handleImportFileChange"
              :on-remove="handleImportFileRemove"
              :file-list="importFileList"
              :auto-upload="false"
              :limit="1"
              accept=".xlsx,.xls"
            >
              <!-- 触发上传按钮 -->
              <template #trigger>
                <el-button type="primary">点击选择文件</el-button>
              </template>

              <!-- 自定义文件列表 -->
              <template #file="{ file }">
                <div style="display: flex; align-items: center">
                  <span class="el-upload__tip">{{ file.name }}</span>
                  <el-button type="text" icon="Delete" @click.stop="() => handleImportFileRemove(file)" style="margin-left: auto"> 删除 </el-button>
                </div>
              </template>

              <!-- 提示信息 -->
              <template #tip>
                <div class="el-upload__tip">
                  <el-link type="primary" @click="downloadTemplate"> <i class="el-icon-download"></i> 模板下载 </el-link>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="importLoading" type="primary" @click="submitImportForm">确 定</el-button>
          <el-button @click="closeImportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Judge" lang="ts">
import { listJudge, getJudge, delJudge, addJudge, updateJudge, downloadImportTemplates, uploadJudgeFileImport } from '@/api/system/physical/judge';
import { JudgeVO, JudgeQuery, JudgeForm } from '@/api/system/physical/judge/types';
import { uploadTournament } from '@/api/system/business/tournaments';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { parseTime } from '@/utils/dateUtils';
import { selectJudgePositionSelList } from '@/api/system/physical/judgePosition';
const judgeList = ref<JudgeVO[]>([]);
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 judgeFormRef = ref<ElFormInstance>();

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

const initFormData: JudgeForm = {
  id: undefined,
  name: undefined,
  peopleIconUrl: undefined,
  workYears: undefined
};
const data = reactive<PageData<JudgeForm, JudgeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    peopleIconUrl: undefined,
    workYears: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '裁判姓名不能为空', trigger: 'blur' }]
  }
});

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

/** 查询裁判管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listJudge(queryParams.value);
  judgeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  judgeFileList.value = [];
  // 清除预览图和临时链接
  judgeIconPreviewUrl.value = '';
  judgeFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: JudgeVO[]) => {
  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?: JudgeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getJudge(_id);
  Object.assign(form.value, res.data);

  // 如果有图片URL，创建虚拟文件对象以便显示
  if (res.data.peopleIconUrl) {
    judgeFileList.value = [
      {
        name: '已上传图片',
        url: res.data.peopleIconUrl,
        status: 'success'
      }
    ];
    judgeIconPreviewUrl.value = res.data.peopleIconUrl;
  } else {
    judgeFileList.value = [];
    judgeIconPreviewUrl.value = '';
  }

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/judge/export',
    {
      ...queryParams.value
    },
    `裁判列表${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};

onMounted(() => {
  getList();
  loadPositionOptions();
});
// 裁判图片上传相关
const judgeIconPreviewUrl = ref('');
const judgeFileList = ref([]);

// 预览弹窗相关
const judgeDialogVisible = ref(false);
const judgePreviewSrc = ref('');
// 裁判图片上传处理函数
const handleJudgeIconChange = async (file) => {
  const index = judgeFileList.value.findIndex((f) => f.uid === file.uid);
  judgeFileList.value = [];

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

  if (index === -1) {
    // 如果文件不在列表中，则添加进去
    judgeFileList.value.push(file);
  }

  try {
    const rawFile = file.raw;
    // 这里需要根据你的上传API进行调整，假设有一个上传图片的API
    const res = await uploadTournament(rawFile); // 使用现有的上传API或替换为你的API
    if (res.code === 200) {
      // 更新文件状态为成功
      judgeFileList.value[index] = {
        ...file,
        status: 'success',
        response: res.data.url
      };
      form.value.peopleIconUrl = judgeFileList.value[index].response;
      judgeIconPreviewUrl.value = judgeFileList.value[index].response;
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg);
    }
  } catch (error) {
    // 更新文件状态为失败
    judgeFileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};

// 删除裁判图片处理函数
const handleJudgeIconRemove = (file, updatedFileList) => {
  judgeFileList.value = updatedFileList;
  // 清除预览图和临时链接
  judgeIconPreviewUrl.value = '';
  // 同时清空表单数据中的图片链接
  form.value.peopleIconUrl = undefined;
};

// 点击预览图触发放大
const handleJudgePreviewClick = () => {
  const currentSrc = judgeIconPreviewUrl.value || form.value.peopleIconUrl;
  if (currentSrc) {
    judgePreviewSrc.value = currentSrc;
    judgeDialogVisible.value = true;
  }
};

// 打开预览弹窗
const openJudgePreview = (src: string) => {
  judgePreviewSrc.value = src;
  judgeDialogVisible.value = true;
};
const downloadTemplate = async () => {
  try {
    const response = await downloadImportTemplates();
    // 创建 Blob 对象（直接使用 response）
    // 确保正确获取 blob 数据
    const blobData = new Blob([response.data || response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    // 创建对象 URL
    const urlBlob = window.URL.createObjectURL(blobData);
    const link = document.createElement('a');
    link.href = urlBlob;
    link.setAttribute('download', '裁判模板.xlsx');
    document.body.appendChild(link);

    // 触发点击事件并稍作延迟，确保链接生效
    link.click();
    setTimeout(() => {
      link.remove();
      window.URL.revokeObjectURL(urlBlob);
    }, 0);
  } catch (error) {
    console.error('Download error:', error); // 输出具体的错误信息
    ElMessage.error('下载失败，请重试');
  }
};
// 导入相关数据
const importDialog = reactive({
  visible: false,
  title: '导入裁判数据'
});

const importForm = ref({
  file: undefined
});

const importRules = {
  file: [{ required: true, message: '请选择要上传的文件', trigger: 'change' }]
};

const importFileList = ref([]);
const importLoading = ref(false);
const importFormRef = ref<ElFormInstance>();

// 导入相关函数
const openImportDialog = () => {
  importForm.value = { file: undefined };
  importFileList.value = [];
  importDialog.visible = true;
};

const closeImportDialog = () => {
  importDialog.visible = false;
  importFormRef.value?.clearValidate();
};

const handleImportFileChange = (file) => {
  const index = importFileList.value.findIndex((f) => f.uid === file.uid);
  // 如果文件不存在于列表中，则添加进去
  if (index === -1) {
    importFileList.value.push(file);
    // 同步到表单数据
    importForm.value.file = file.raw;
  }
};

// 删除文件处理函数
const handleImportFileRemove = (file) => {
  const index = importFileList.value.findIndex((f) => f.uid === file.uid);
  if (index > -1) {
    const newFileList = [...importFileList.value];
    newFileList.splice(index, 1);
    importFileList.value = newFileList;
  }
};

const submitImportForm = () => {
  importFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (importFileList.value.length === 0) {
        proxy?.$modal.msgError('请先选择文件');
        return;
      }

      importLoading.value = true;
      try {
        const formData = new FormData();
        formData.append('file', importFileList.value[0].raw);

        // 调用导入API（需要在API文件中添加importJudge函数）
        const res = await uploadJudgeFileImport(formData);
        if (res.code === 200) {
          proxy?.$modal.msgSuccess('导入成功');
          importDialog.visible = false;
          await getList(); // 重新加载数据
        } else {
          proxy?.$modal.msgError(res.msg || '导入失败');
        }
      } catch (error) {
        console.error('导入失败:', error);
        proxy?.$modal.msgError('导入失败，请重试');
      } finally {
        importLoading.value = false;
      }
    }
  });
};

const positionOptions = ref<{ id: number; label: string }[]>([]);
const loadPositionOptions = async () => {
  try {
    const res = await selectJudgePositionSelList();
    if (res.code === 200) {
      // 使用 unknown 中间类型进行类型转换
      const data = res.data as unknown as { id: number; name: string }[];
      const list = [];
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        list.push({
          id: item.id,
          label: item.name
        });
      }
      positionOptions.value = list;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
</script>
