<script setup lang="ts">
import type { ExamBatchCreateMarkingTaskRecordRequest, ExamMarkingTaskHistoryRecord } from '@/api'
import { useMutation } from '@tanstack/vue-query'
import { examMarkingTaskApi } from '@/api'

interface EditData {
  currentScore: number
  recordTask: ExamMarkingTaskHistoryRecord
}

// 对话框状态
const show = ref(false)
const editScore = ref(0)
const fullScore = ref(0)
const recordTask = ref<ExamMarkingTaskHistoryRecord>()

// 解析器
let resolvePromise: ((value: any) => void) | null = null
let rejectPromise: ((reason?: any) => void) | null = null

// 修改分数的mutation
const { mutate: updateScore, isPending } = useMutation({
  mutationFn: async (params: { recordTask: ExamMarkingTaskHistoryRecord, score: number }) => {
    // 调用批量更新阅卷记录接口
    const request: ExamBatchCreateMarkingTaskRecordRequest = {
      batch_data: [{
        id: params.recordTask.id!,
        scan_info_id: params.recordTask.scan_info_id!,
        question_id: params.recordTask.question_id!,
        record_id: params.recordTask.id!,
        task_id: params.recordTask.task_id!,
        duration: params.recordTask.duration || 0,
        remark: params.recordTask.remark || '',
        page_mode: 'single',
        is_excellent: params.recordTask.is_excellent || 0,
        is_model: params.recordTask.is_model || 0,
        is_problem: params.recordTask.is_problem || 0,
        score: params.score,
      }],
      is_review: true, // 标记为回评操作
    }
    return examMarkingTaskApi.batchCreate(request)
  },
  onSuccess: () => {
    uni.showToast({
      title: '分数修改成功',
      icon: 'success',
    })
    handleConfirm(editScore.value)
  },
})

// 打开对话框
function open(data: EditData): Promise<number | null> {
  return new Promise((resolve, reject) => {
    editScore.value = data.currentScore
    fullScore.value = data.recordTask.full_score
    recordTask.value = data.recordTask
    show.value = true

    resolvePromise = resolve
    rejectPromise = reject
  })
}

// 确认修改
function handleConfirm(score: number) {
  show.value = false
  resolvePromise?.(score)
  cleanup()
}

// 取消修改
function handleCancel() {
  show.value = false
  rejectPromise?.('cancel')
  cleanup()
}

// 清理
function cleanup() {
  resolvePromise = null
  rejectPromise = null
}

// 提交分数修改
function handleSubmit() {
  if (editScore.value < 0 || editScore.value > fullScore.value) {
    uni.showToast({
      title: `分数必须在0-${fullScore.value}之间`,
      icon: 'none',
    })
    return
  }

  updateScore({
    recordTask: recordTask.value!,
    score: editScore.value,
  })
}

// 快捷分数按钮
const quickScoreButtons = computed(() => {
  const buttons = []
  const step = fullScore.value <= 10 ? 1 : Math.ceil(fullScore.value / 10)

  for (let i = 0; i <= fullScore.value; i += step) {
    if (i <= fullScore.value) {
      buttons.push(i)
    }
  }

  // 确保包含满分
  if (buttons[buttons.length - 1] !== fullScore.value) {
    buttons.push(fullScore.value)
  }

  return buttons
})

// 分数调整
function adjustScore(delta: number) {
  const newScore = editScore.value + delta
  if (newScore >= 0 && newScore <= fullScore.value) {
    editScore.value = newScore
  }
}

// 监听对话框关闭
watch(show, (newValue) => {
  if (!newValue && rejectPromise) {
    handleCancel()
  }
})

// 暴露方法
defineExpose({
  open,
})
</script>

<template>
  <wd-popup
    v-model="show"
    position="bottom"
    round
    closable
    safe-area-inset-bottom
    @close="handleCancel"
  >
    <view class="score-edit-dialog">
      <!-- 拖拽指示器 -->
      <view class="drag-indicator" />

      <!-- 标题区域 -->
      <view class="dialog-header">
        <text class="title">修改分数</text>
        <text class="subtitle">请为当前题目设置分数</text>
      </view>

      <!-- 当前分数显示 -->
      <view class="current-score">
        <view class="score-container">
          <view class="score-display">
            <text class="score">{{ editScore }}</text>
            <text class="separator">/</text>
            <text class="total">{{ fullScore }}</text>
          </view>
          <text class="score-label">当前分数</text>
        </view>
      </view>

      <!-- 分数调整器 -->
      <view class="score-adjuster">
        <wd-button
          type="primary"
          size="small"
          round
          :disabled="editScore <= 0"
          custom-class="adjust-btn minus-btn"
          @click="adjustScore(-1)"
        >
          -1
        </wd-button>

        <view class="score-input-container">
          <wd-input
            v-model.number="editScore"
            :min="0"
            :max="fullScore"
            :precision="0"
            size="large"
            custom-class="score-input"
          />
        </view>

        <wd-button
          type="primary"
          size="small"
          round
          :disabled="editScore >= fullScore"
          custom-class="adjust-btn plus-btn"
          @click="adjustScore(1)"
        >
          +1
        </wd-button>
      </view>

      <!-- 快捷分数按钮 -->
      <view class="quick-scores">
        <text class="section-title">快捷分数</text>
        <view class="quick-buttons">
          <wd-button
            v-for="score in quickScoreButtons"
            :key="score"
            size="small"
            round
            :type="editScore === score ? 'primary' : 'default'"
            :custom-class="editScore === score ? 'quick-btn active' : 'quick-btn'"
            @click="editScore = score"
          >
            {{ score }}
          </wd-button>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="dialog-actions">
        <wd-button
          size="large"
          round
          :disabled="isPending"
          custom-class="cancel-btn"
          @click="handleCancel"
        >
          取消
        </wd-button>
        <wd-button
          type="primary"
          size="large"
          round
          :loading="isPending"
          custom-class="confirm-btn"
          @click="handleSubmit"
        >
          确定修改
        </wd-button>
      </view>
    </view>
  </wd-popup>
</template>

<style lang="scss" scoped>
.score-edit-dialog {
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 20px 20px 0 0;
  padding: 0;
  position: relative;
  max-height: 85vh;
  overflow: hidden;
}

/* 拖拽指示器 */
.drag-indicator {
  width: 40px;
  height: 4px;
  background: #e1e5e9;
  border-radius: 2px;
  margin: 12px auto 0;
}

/* 标题区域 */
.dialog-header {
  text-align: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #ffffff;
}

.title {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.subtitle {
  display: block;
  font-size: 14px;
  color: #6b7280;
}

/* 当前分数显示 */
.current-score {
  padding: 32px 24px;
  background: #ffffff;
}

.score-container {
  text-align: center;
}

.score-display {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 8px;
  margin-bottom: 8px;
}

.score {
  font-size: 48px;
  font-weight: 700;
  color: #dc2626;
  line-height: 1;
  text-shadow: 0 2px 4px rgba(220, 38, 38, 0.1);
}

.separator {
  font-size: 24px;
  color: #9ca3af;
  font-weight: 500;
}

.total {
  font-size: 24px;
  color: #4b5563;
  font-weight: 600;
}

.score-label {
  font-size: 13px;
  color: #6b7280;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 分数调整器 */
.score-adjuster {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  padding: 24px;
  background: #f8f9fa;
}

.score-input-container {
  background: #ffffff;
  border-radius: 12px;
  padding: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
}

/* 快捷分数按钮区域 */
.quick-scores {
  padding: 24px;
  background: #ffffff;
  border-top: 1px solid #f0f0f0;
}

.section-title {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16px;
  letter-spacing: 0.3px;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #d1d5db transparent;
}

.quick-buttons::-webkit-scrollbar {
  width: 4px;
}

.quick-buttons::-webkit-scrollbar-track {
  background: transparent;
}

.quick-buttons::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 2px;
}

/* 操作按钮 */
.dialog-actions {
  padding: 24px;
  background: #ffffff;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 12px;
}

/* 自定义按钮样式 */
:deep(.adjust-btn) {
  min-width: 44px;
  height: 44px;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
  transition: all 0.2s ease;
}

:deep(.adjust-btn:active) {
  transform: scale(0.95);
}

:deep(.score-input) {
  border: none !important;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  width: 120px;

  &::after {
    display: none;
  }
}

:deep(.quick-btn) {
  min-width: 44px;
  height: 36px;
  transition: all 0.2s ease;
  font-weight: 500;
}

:deep(.quick-btn.active) {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

:deep(.cancel-btn) {
  flex: 1;
  height: 48px;
  background: #f3f4f6 !important;
  color: #374151 !important;
  border: 1px solid #e5e7eb !important;
  font-weight: 500;
}

:deep(.confirm-btn) {
  flex: 1;
  height: 48px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%) !important;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  font-weight: 600;
  transition: all 0.2s ease;
}

:deep(.confirm-btn:active) {
  transform: translateY(1px);
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.3);
}

/* 动画效果 */
.score-edit-dialog {
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 分数变化动画 */
.score {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 响应式设计 */
@media (max-height: 600px) {
  .current-score {
    padding: 20px 24px;
  }

  .score {
    font-size: 36px;
  }

  .quick-buttons {
    max-height: 80px;
  }
}
</style>
