<template>
  <a-modal
    v-model:visible="visible"
    title="单次乐跑"
    draggable
    esc-to-close
    closable
    :ok-loading="okLoading"
    @before-ok="handleBeforeOk"
    @close="onClose"
  >
    <template v-if="account">
      <p style="margin-bottom: 16px; color: var(--color-text-2)">
        为 <strong>{{ account.name }}</strong>（{{ account.student_num }}）发起单次乐跑；会先预扣所选距离的乐跑里程，结算以官方最终计算距离为准。
      </p>
      <a-form :model="form" layout="vertical">
        <a-form-item
          label="跑步距离（公里）"
          field="distance_km"
          :rules="[{ required: true, message: '请填写距离' }]"
        >
          <a-input-number
            v-model="form.distance_km"
            placeholder="1～10"
            mode="button"
            :min="1"
            :max="10"
            :step="0.5"
            :precision="2"
            style="width: 200px"
          />
          <template #extra>
            <span style="color: var(--color-text-3)">范围: 1～10 km</span>
          </template>
        </a-form-item>
        <a-form-item
          label="目标配速（每公里）"
          field="pace"
          :rules="[{ required: true, message: '请填写配速' }]"
        >
          <a-input
            v-model="form.pace"
            placeholder="如 6:00 或 360（秒/公里）"
            allow-clear
          />
          <template #extra>
            <span style="color: var(--color-text-3)">范围: 3:00～10:00 / km</span>
          </template>
        </a-form-item>
      </a-form>
    </template>
  </a-modal>
</template>

<script setup>
import { reactive, ref, watch } from 'vue'
import { lepaoRecords, singleRun } from '@/api/lepao'
import { Modal, Notification, Message } from '@arco-design/web-vue'

const visible = defineModel('visible', { type: Boolean, default: false })

const props = defineProps({
  account: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['success'])

const okLoading = ref(false)
const form = reactive({
  distance_km: 2.5,
  pace: '6:00'
})

watch(visible, (v) => {
  if (v) {
    form.distance_km = 2.5
    form.pace = '6:00'
  }
})

function onClose() {
  okLoading.value = false
}

async function handleBeforeOk(done) {
  if (!props.account?.student_num) {
    Message.error('缺少账号信息')
    return false
  }
  const d = Number(form.distance_km)
  if (!Number.isFinite(d) || d < 1 || d > 10) {
    Message.error('跑步距离须在 1～10 公里之间')
    return false
  }
  const pace = String(form.pace ?? '').trim()
  if (!pace) {
    Message.error('请填写配速')
    return false
  }

  const startSingleRun = async () => {
    okLoading.value = true
    try {
      const res = await singleRun({
        student_num: props.account.student_num,
        distance_km: d,
        pace
      })
      if (!res || res.code !== 0) {
        Notification.error({
          title: '提交乐跑任务失败',
          content: res?.msg ?? '请稍后再试'
        })
        return false
      }
      Message.success('提交乐跑任务成功！')
      emit('success')
      done()
      return true
    } catch (e) {
      Notification.error({
        title: '提交乐跑任务失败',
        content: e.message || '请稍后再试'
      })
      return false
    } finally {
      okLoading.value = false
    }
  }

  okLoading.value = true
  try {
    // 若当天已有跑步记录，二次确认再继续（避免误触导致重复预扣）
    const now = new Date()
    const start = new Date(now)
    start.setHours(0, 0, 0, 0)
    const end = new Date(start)
    end.setDate(end.getDate() + 1)

    const checkRes = await lepaoRecords({
      lepao_account: props.account.student_num,
      queryTime: [String(start.getTime()), String(end.getTime())],
      pagesize: 1,
      current: 1
    })
    const total = Number(checkRes?.pagination?.total ?? 0)

    if (checkRes && checkRes.code === 0 && total > 0) {
      okLoading.value = false
      return await new Promise((resolve) => {
        Modal.confirm({
          title: '确认继续乐跑？',
          content: `检测到该账号今天已存在跑步记录（共 ${total} 条）。继续发起单次乐跑将再次预扣里程，是否继续？`,
          okText: '继续乐跑',
          cancelText: '取消',
          onOk: async () => resolve(await startSingleRun()),
          onCancel: () => resolve(false)
        })
      })
    }

    // 检查失败/无记录：直接继续
    okLoading.value = false
    return await startSingleRun()
  } catch (e) {
    Notification.warning({
      title: '记录检测失败，已继续提交',
      content: e.message || '请稍后在记录页确认结果'
    })
    okLoading.value = false
    return await startSingleRun()
    return false
  }
}
</script>
