<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="userIds">
              <el-input v-model="queryParams.userIds" placeholder="请输入用户名/手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="申诉状态" prop="status">
              <el-select aria-required="true" v-model="queryParams.status" placeholder="请选择">
                <el-option v-for="dict in complaints_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="申诉时间">
              <el-date-picker
                v-model="data.queryParams.complaintTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </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="['system:complaints:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:complaints:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:complaints:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:complaints: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="complaintsList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" width="60" align="center">
          <template #default="{ $index }">
            {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="" align="center" prop="id" v-if="false" />-->
        <el-table-column label="用户名" align="center" prop="nickName" />
        <el-table-column label="用户手机号" align="center" prop="phone" />
        <el-table-column label="所属比赛" align="center" prop="tournamentName" />
        <el-table-column label="最终名次" align="center" prop="finalRank" />
        <el-table-column label="申述原因" align="center" prop="complaintReason" />
        <el-table-column label="申述时间" align="center" prop="createAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="处理时间" align="center" prop="updateAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申诉状态" align="center" prop="statusText" />
        <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="View" @click="handleSeeRank(scope.row)" v-hasPermi="['business:complaints:query']">
                查看比赛结果
              </el-button>
            </el-tooltip>
            <!-- status 为 1：显示“处理”按钮 -->
            <el-tooltip v-if="scope.row.status === 1" content="处理" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:complaints:edit']"> 处理 </el-button>
            </el-tooltip>

            <!-- status 为 2 或 3：显示“查看处理结果”按钮 -->
            <el-tooltip v-else content="处理结果" placement="top">
              <el-button link type="primary" icon="View" @click="handleUpdate2(scope.row)" v-hasPermi="['business:complaints:edit']">
                处理结果
              </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="complaintsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申诉状态" prop="advice">
          <el-select v-model="form.status" placeholder="处理结果" clearable :disabled="dialog.title === '处理结果'">
            <el-option label="已处理" :value="2" />
            <el-option label="不处理" :value="3" />
          </el-select>
        </el-form-item>
        <!-- 查看处理结果时显示处理人和处理时间 -->
        <template v-if="dialog.title === '处理结果'">
          <el-form-item label="处理人" prop="operateName"> <el-input v-model="form.operateName" disabled /> </el-form-item>
          <el-form-item label="处理时间" prop="updateAt"> <el-input v-model="form.updateAt" disabled /> </el-form-item>
        </template>
        <!-- 处理建议 - 文本域 -->
        <el-form-item label="处理建议" prop="advice">
          <el-input
            v-model="form.advice"
            type="textarea"
            :rows="4"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="请输入处理建议，最多200字"
            maxlength="200"
            show-word-limit
            :disabled="dialog.title === '处理结果'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="dialog.title !== '处理结果'">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="`${tournamentInfo.name} ${tournamentInfo.tournamentsBiId}`"
      v-model="auditDialog.visible"
      width="1000px"
      append-to-body
      @close="cancelAudit"
    >
      <!-- 查看对局记录按钮 -->
      <!--      <div class="dialog-header-actions" v-if="auditDialog.mode === 'view'">
        <el-button type="primary">查看对局记录</el-button>
      </div>-->

      <!-- 比赛信息展示 -->
      <div class="tournament-info" v-if="tournamentInfo.id">
        <p>比赛时间：{{ tournamentInfo.startTime }} ~ {{ tournamentInfo.endTime }}</p>
        <p>参加人数：{{ tournamentInfo.signNum }}人</p>
        <p v-if="tournamentInfo.isComplaints" style="color: red">本场比赛仍有选手存在异议，请处理申述后继续授作。</p>
        <!--        <p>比赛类型：{{ tournamentInfo.id }}</p>
        <p>报名条件：{{ tournamentInfo.itemsName }} x {{ tournamentInfo.itemsNum }}</p>
        <p>盲注表：{{ tournamentInfo.blindStructuresName }}</p>
        <p>报名截止等级：{{ tournamentInfo.lateRegistrationLevel }}</p>-->
      </div>

      <!-- 表格内容 -->
      <el-table :data="auditData" border style="width: 100%">
        <el-table-column prop="id" label="id" align="center" v-if="false"></el-table-column>
        <el-table-column prop="rank" label="排名" align="center"></el-table-column>
        <el-table-column prop="playerName" label="用户名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机" align="center"></el-table-column>
        <el-table-column label="奖励" align="center">
          <template #default="scope">
            <div v-for="(prize, index) in scope.row.rewardVoList" :key="index">{{ prize.itemName }} {{ prize.quantity }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <!-- 只有 claimedText 存在时才显示 -->
            <el-tag v-if="scope.row.claimedText" :type="scope.row.claimed === 3 ? 'danger' : 'primary'" size="small">
              {{ scope.row.claimedText }}
            </el-tag>
            <!-- 否则显示空 -->
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width">
          <template #default="scope">
            <div style="display: flex; justify-content: center; gap: 16px">
              <el-tooltip content="查看牌局" placement="top">
                <el-button link type="primary" icon="View" @click="handleViewHistory(scope.row)">查看牌局</el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination-container" style="margin-top: 20px; text-align: center">
        <el-pagination
          v-model:current-page="auditQueryParams.pageNum"
          v-model:page-size="auditQueryParams.pageSize"
          :total="auditTotal"
          layout="prev, pager, next"
          @current-change="getAuditData"
        />
      </div>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Complaints" lang="ts">
import {
  listComplaints,
  getComplaints,
  delComplaints,
  addComplaints,
  updateComplaints,
  getAllUserRankByTournamentId
} from '@/api/system/business/complaints';
import { ComplaintsVO, ComplaintsQuery, ComplaintsForm } from '@/api/system/business/complaints/types';
import { ref } from 'vue';
import { TournamentsVO } from '@/api/system/business/tournaments/types';
import { ClaimsVO } from '@/api/system/business/claims/types';
import { getTournaments } from '@/api/system/business/tournaments';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { complaints_status } = toRefs<any>(proxy?.useDict('complaints_status'));

const complaintsList = ref<ComplaintsVO[]>([]);
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 complaintsFormRef = ref<ElFormInstance>();

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

const initFormData: ComplaintsForm = {
  id: undefined,
  userId: undefined,
  tournamentId: undefined,
  finalRank: undefined,
  complaintReason: undefined,
  createAt: undefined,
  updateAt: undefined,
  status: 2,
  statusText: undefined
};
const data = reactive<PageData<ComplaintsForm, ComplaintsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    tournamentId: undefined,
    finalRank: undefined,
    complaintReason: undefined,
    createAt: undefined,
    updateAt: undefined,
    status: undefined,
    statusText: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});
const tournamentInfo = ref<Partial<TournamentsVO>>({
  id: '',
  startTime: '',
  endTime: '',
  itemsNum: 0,
  itemsName: '',
  blindStructureId: 0,
  blindStructuresName: '',
  lateRegistrationLevel: 0,
  tournamentsBiId: '',
  signNum: 0,
  isComplaints: false
});
const { queryParams, form, rules } = toRefs(data);

/** 查询用户申诉列表 */
const getList = async () => {
  loading.value = true;
  const res = await listComplaints(queryParams.value);
  complaintsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  const timeRange = data.queryParams.complaintTimeRange;
  if (timeRange && timeRange.length === 2) {
    data.queryParams.tournamentBeginTime = timeRange[0];
    data.queryParams.tournamentEndTime = timeRange[1];
  } else {
    data.queryParams.tournamentBeginTime = null;
    data.queryParams.tournamentEndTime = null;
  }
  getList();
};

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ComplaintsVO[]) => {
  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?: ComplaintsVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getComplaints(_id);
  const data = res.data;
  Object.assign(form.value, res.data);
  // 判断状态：如果是 1，则自动设置为 2（处理中）
  if (data.status === 1) {
    form.value.status = 2;
  } else {
    // 否则保持接口返回的状态（或其他默认逻辑）
    form.value.status = data.status;
    // 或者你希望用户手动选择：form.value.status = null;
  }
  dialog.visible = true;
  dialog.title = '处理申诉';
};
const handleUpdate2 = async (row?: ComplaintsVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getComplaints(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '处理结果';
};

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/complaints/export',
    {
      ...queryParams.value
    },
    `complaints_${new Date().getTime()}.xlsx`
  );
};
const auditDialog = ref({
  visible: false,
  title: '',
  mode: 'view' as 'view' | 'audit'
});

const auditData = ref<ClaimsVO[]>([]);
// 创建新的查询参数对象，不影响原始 queryParams
const auditQueryParams = {
  pageNum: 1,
  pageSize: 10,
  tournamentId: null as number | null
};
const auditTotal = ref(0);
// 模拟打开对话框并获取数据
const handleSeeRank = async (row: ComplaintsVO) => {
  auditDialog.value.visible = true;
  const _id = row?.tournamentId || ids.value[0];
  auditQueryParams.tournamentId = Number(_id);
  await getAuditData(1);

  try {
    const res = await getTournaments(_id);
    if (res.code === 200) {
      tournamentInfo.value = res.data;
    }
  } catch (error) {
    console.error('获取数据失败', error);
  }
};
const getAuditData = async (pageNum: number) => {
  try {
    auditQueryParams.pageNum = pageNum;
    const res = await getAllUserRankByTournamentId(auditQueryParams);
    auditData.value = res.rows;
    auditTotal.value = res.total;
  } catch (error) {
    console.error('获取审核数据失败', error);
  }
};
// 关闭对话框
const cancelAudit = () => {
  auditDialog.value.visible = false;
};
const handleViewHistory = (row: ComplaintsVO) => {
  const tournamentId = row.tournamentId;
  const playerId = row.id;

  // 判断 playerId 是否有效（非 null、undefined）
  const playerIdStr = playerId != null ? String(playerId) : '';

  proxy?.$router.push({
    path: '/service/history',
    query: {
      tournamentId: String(tournamentId),
      playerId: playerIdStr
    }
  });

  auditDialog.value.visible = false;
};
onMounted(() => {
  getList();
});
</script>
