<template>
  <view class="sub-page">
    <TopBar title="每日检查" show-back />

    <view class="px-4 pt-3">
      <!-- 今日任务概览 -->
      <view class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title">今日概览</text>
        </view>
        <view class="grid grid-cols-2 gap-3">
          <view class="stat-card">
            <view class="stat-bar"></view>
            <text class="stat-value">{{ todayTasks.length }}</text>
            <text class="stat-label">今日任务</text>
          </view>
          <view class="stat-card">
            <view class="stat-bar"></view>
            <text class="stat-value">{{ completedTasks }}</text>
            <text class="stat-label">已完成</text>
          </view>
        </view>
      </view>

      <!-- 今日排班 -->
      <view v-if="schedule" class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">今日排班</text>
        </view>
        <view class="info-row">
          <text class="info-label">班组</text>
          <text class="info-value">{{ schedule.teamName || '-' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">班次</text>
          <text class="info-value">{{ shiftTypeLabel(schedule.shiftType) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">分配车辆</text>
          <text class="info-value">{{ vehiclePlateNos || '未分配车辆' }}</text>
        </view>
      </view>
      <view v-else-if="!scheduleLoading" class="glass-card p-4">
        <view class="empty-wrap">
          <text class="empty-title">今日无有效排班</text>
          <text class="empty-text">当前账号所属班组今天没有排班记录，无法选择检查车辆。</text>
        </view>
      </view>

      <!-- 车辆检查 -->
      <view class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">车辆检查</text>
          <text v-if="todayRecord" class="check-state check-state-done">已完成</text>
          <text v-else class="check-state check-state-pending">待检查</text>
        </view>

        <view v-if="!todayRecord">
          <view class="form-row mb-3">
            <text class="form-label">检查日期</text>
            <picker mode="date" :value="selectedCheckDate" @change="onDateChange">
              <view class="picker-value">
                <text>{{ selectedCheckDate || '请选择检查日期' }}</text>
                <text class="uni-icons uniui-arrowright arrow-icon"></text>
              </view>
            </picker>
          </view>

          <view class="form-row mb-3">
            <text class="form-label">检查车辆</text>
            <picker
              v-if="vehicles.length > 0"
              mode="selector"
              :range="vehicleOptions"
              range-key="label"
              :value="selectedVehicleIndex"
              @change="onVehicleChange"
            >
              <view class="picker-value">
                <text>{{ selectedVehicle ? selectedVehicle.label : '请选择检查车辆' }}</text>
                <text class="uni-icons uniui-arrowright arrow-icon"></text>
              </view>
            </picker>
            <view v-else class="picker-value disabled">
              <text>{{ schedule ? '今日未分配车辆' : '无排班信息' }}</text>
            </view>
          </view>

          <view v-for="cat in uploadCategories" :key="cat" class="upload-group">
            <text class="check-group-title">{{ categoryLabels[cat] }}</text>
            <view class="upload-grid">
              <view
                v-for="(item, idx) in categoryFiles[cat]"
                :key="item.url"
                class="media-item"
              >
                <image
                  v-if="item.type === 'image'"
                  :src="item.url"
                  class="media-thumb"
                  mode="aspectFill"
                  @click="previewMedia(cat, idx)"
                />
                <view v-else class="media-thumb media-video" @click="previewMedia(cat, idx)">
                  <text class="uni-icons uniui-videocam media-video-icon"></text>
                </view>
                <view class="media-delete" @click="removeFile(cat, idx)">
                  <text class="uni-icons uniui-close"></text>
                </view>
              </view>

              <view
                v-if="categoryFiles[cat].length < maxFileCount"
                class="media-add"
                @click="chooseMedia(cat)"
              >
                <text class="uni-icons uniui-camera-filled media-add-icon"></text>
                <text class="media-add-text">{{ categoryFiles[cat].length }}/{{ maxFileCount }}</text>
              </view>
            </view>
          </view>

          <view class="mb-3">
            <text class="check-group-title">备注</text>
            <textarea
              v-model="remark"
              class="form-textarea"
              placeholder="请输入检查备注..."
              :maxlength="200"
            />
          </view>

          <button
            class="submit-btn"
            hover-class="submit-btn-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            :disabled="!canSubmit || submitting"
            @click="submitCheck"
          >
            {{ submitting ? '提交中...' : '提交检查' }}
          </button>
        </view>

        <view v-else class="done-wrap">
          <view class="done-icon">
            <text class="uni-icons uniui-checkmarkempty done-tick"></text>
          </view>
          <text class="done-text">今日车辆检查已完成</text>
          <text v-if="todayRecord.vehicleNo" class="done-meta">检查车辆：{{ todayRecord.vehicleNo }}</text>
          <text v-if="mediaSummary.photos || mediaSummary.videos" class="done-meta">
            已上传：{{ mediaSummary.photos }} 张照片 / {{ mediaSummary.videos }} 个视频
          </text>
          <text v-if="todayRecord.remark" class="done-meta">备注：{{ todayRecord.remark }}</text>
          <text class="done-meta">{{ todayRecord.checkDate || today }}</text>

          <view class="reset-link" @click="handleReset">
            <text class="uni-icons uniui-reload reset-icon mr-1"></text>
            <text class="reset-text">重新检查</text>
          </view>
        </view>
      </view>

      <!-- 今日任务列表 -->
      <view class="glass-card">
        <view class="section-head">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">今日任务列表</text>
        </view>
        <view v-if="taskStore.loading" class="py-10 text-center">
          <text class="empty-text">加载中...</text>
        </view>
        <view v-else-if="todayTasks.length === 0" class="pb-3">
          <EmptyState message="今日无任务" />
        </view>
        <view v-else>
          <view
            v-for="task in todayTasks"
            :key="task.taskId || task.id"
            class="list-row"
            hover-class="row-hover"
            :hover-start-time="0"
            :hover-stay-time="120"
            @click="goToDetail(task.taskId || task.id)"
          >
            <view class="icon-chip mr-3">
              <text class="uni-icons uniui-flag chip-glyph"></text>
            </view>
            <view class="flex-1 min-w-0 mr-2">
              <text class="row-title truncate">{{ task.taskName || task.projectName }}</text>
              <text class="row-sub truncate">{{ task.address || '暂无地址' }}</text>
            </view>
            <StatusTag :status="task.status" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useTaskStore } from '../../stores/task'
import { useAuthStore } from '../../stores/auth'
import { chooseMediaCompat } from '../../utils'
import {
  getTodaySchedule,
  getTodayCheckRecord,
  submitDailyCheck,
  type DailyCheckScheduleToday,
  type DailyCheckRecord,
} from '../../api/dailyCheck'
import { uploadFile } from '../../api/file'
import TopBar from '../../components/common/TopBar.vue'
import StatusTag from '../../components/common/StatusTag.vue'
import EmptyState from '../../components/common/EmptyState.vue'

const taskStore = useTaskStore()
const authStore = useAuthStore()

const today = new Date().toISOString().split('T')[0]
const remarkKey = `vehicle_check_remark_${today}`

interface MediaFile {
  url: string
  type: 'image' | 'video'
}

const categoryLabels: Record<string, string> = {
  vehicle: '车辆检查',
  equipment: '设备检查',
  system: '三大系统检查',
}
const uploadCategories = ['vehicle', 'equipment', 'system']
const maxFileCount = 9

const scheduleLoading = ref(false)
const submitting = ref(false)
const schedule = ref<DailyCheckScheduleToday['schedule']>(null)
const vehicles = ref<DailyCheckScheduleToday['vehicles']>([])
const selectedVehicleIndex = ref(0)
const selectedCheckDate = ref(today)
const categoryFiles = ref<Record<string, MediaFile[]>>({
  vehicle: [],
  equipment: [],
  system: [],
})
const remark = ref('')
const todayRecord = ref<DailyCheckRecord | null>(null)

const userId = computed(() => (authStore.user?.id ? Number(authStore.user.id) : 0))
const userName = computed(() => authStore.user?.name || '')

const vehicleOptions = computed(() => {
  return vehicles.value.map((v) => ({
    value: v.vehicleId,
    label: `${v.plateNo} ${v.vehicleType ? `(${v.vehicleType})` : ''}`,
  }))
})

const selectedVehicle = computed(() => {
  return vehicleOptions.value[selectedVehicleIndex.value] || null
})

const vehiclePlateNos = computed(() => {
  return vehicles.value.map((v) => v.plateNo).filter(Boolean).join('、')
})

const canSubmit = computed(() => {
  return !!(selectedCheckDate.value && selectedVehicle.value)
})

const completedTasks = computed(() => {
  return todayTasks.value.filter((t) => t.status === 'completed').length
})

const todayTasks = computed<any[]>(() => {
  return taskStore.tasks.filter(
    (t: any) => t.planDate === today || t.scheduleDate === today || t.serviceDate === today
  )
})

const mediaSummary = computed(() => {
  const photos = parseUrlList(todayRecord.value?.photoUrls).length
  const videos = parseUrlList(todayRecord.value?.videoUrls).length
  return { photos, videos }
})

function shiftTypeLabel(shiftType?: string) {
  const map: Record<string, string> = {
    day: '白班',
    night: '夜班',
    emergency: '应急班',
    month_plan: '月计划',
  }
  return map[shiftType || ''] || shiftType || '-'
}

function parseUrlList(value: unknown): string[] {
  if (!value) return []
  if (Array.isArray(value)) return value.filter(Boolean)
  if (typeof value === 'string') {
    try {
      return JSON.parse(value)
    } catch {
      return []
    }
  }
  return []
}

function onDateChange(e: any) {
  selectedCheckDate.value = e.detail.value || today
}

async function loadSchedule() {
  if (!userId.value) return
  scheduleLoading.value = true
  try {
    const data = await getTodaySchedule(userId.value)
    schedule.value = data.schedule
    vehicles.value = data.vehicles || []
    selectedVehicleIndex.value = 0
  } catch (error) {
    console.error('加载排班失败', error)
  } finally {
    scheduleLoading.value = false
  }
}

async function loadTodayRecord() {
  if (!userId.value) return
  try {
    const data = await getTodayCheckRecord(userId.value)
    todayRecord.value = data || null
  } catch (error) {
    console.error('加载今日检查记录失败', error)
  }
}

function onVehicleChange(e: any) {
  selectedVehicleIndex.value = e.detail.value || 0
}

function chooseMedia(category: string) {
  const remain = maxFileCount - categoryFiles.value[category].length
  if (remain <= 0) {
    uni.showToast({ title: `最多上传${maxFileCount}个`, icon: 'none' })
    return
  }

  chooseMediaCompat({
    count: remain,
    mediaType: ['image', 'video'],
    sourceType: ['album', 'camera'],
    success: async (res: any) => {
      const tempFiles = res.tempFiles || []
      const newItems: MediaFile[] = tempFiles.map((f: any) => ({
        url: f.tempFilePath,
        type: f.fileType || 'image',
      }))
      categoryFiles.value[category] = [...categoryFiles.value[category], ...newItems]

      let allSuccess = true
      for (const f of tempFiles) {
        const ok = await uploadOne(category, f.tempFilePath, f.fileType || 'image')
        if (!ok) allSuccess = false
      }
      if (allSuccess && tempFiles.length) {
        uni.showToast({ title: '上传成功', icon: 'success' })
      }
    },
  })
}

async function uploadOne(category: string, filePath: string, type: string): Promise<boolean> {
  try {
    const url = await uploadFile(filePath)
    const list = categoryFiles.value[category]
    const idx = list.findIndex((item) => item.url === filePath)
    if (idx >= 0) {
      list[idx] = { url, type: type as 'image' | 'video' }
      categoryFiles.value[category] = [...list]
      return true
    }
    return false
  } catch (e: any) {
    uni.showToast({ title: e.message || '上传失败', icon: 'none' })
    categoryFiles.value[category] = categoryFiles.value[category].filter((item) => item.url !== filePath)
    return false
  }
}

function removeFile(category: string, idx: number) {
  const list = [...categoryFiles.value[category]]
  list.splice(idx, 1)
  categoryFiles.value[category] = list
}

function previewMedia(category: string, idx: number) {
  const items = categoryFiles.value[category]
  const item = items[idx]
  if (!item) return

  if (item.type === 'image') {
    const urls = items.filter((i) => i.type === 'image').map((i) => i.url)
    uni.previewImage({ urls, current: item.url })
  } else {
    const sources = items
      .filter((i) => i.type === 'video')
      .map((i) => ({ url: i.url, type: 'video' as const }))
    uni.previewMedia({ sources, current: sources.findIndex((s) => s.url === item.url) })
  }
}

async function submitCheck() {
  if (!canSubmit.value) {
    uni.showToast({ title: '请选择检查日期和车辆', icon: 'none' })
    return
  }
  if (!selectedVehicle.value) {
    uni.showToast({ title: '请选择检查车辆', icon: 'none' })
    return
  }

  const allFiles = uploadCategories.flatMap((c) => categoryFiles.value[c])
  const photoUrls = allFiles.filter((f) => f.type === 'image').map((f) => f.url)
  const videoUrls = allFiles.filter((f) => f.type === 'video').map((f) => f.url)

  const payload: DailyCheckRecord = {
    checkDate: selectedCheckDate.value,
    vehicleId: selectedVehicle.value.value,
    vehicleNo: selectedVehicle.value.label.split(' ')[0],
    userId: userId.value,
    userName: userName.value,
    checkStatus: 'normal',
    checkItems: [],
    photoUrls,
    videoUrls,
    remark: remark.value,
  }

  submitting.value = true
  try {
    await submitDailyCheck(payload)
    uni.setStorageSync(remarkKey, remark.value)
    uni.showToast({ title: '提交成功', icon: 'success' })
    await loadTodayRecord()
  } catch (error) {
    console.error('提交检查失败', error)
    uni.showToast({ title: '提交失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

function handleReset() {
  todayRecord.value = null
  categoryFiles.value = { vehicle: [], equipment: [], system: [] }
  remark.value = ''
  selectedCheckDate.value = today
  selectedVehicleIndex.value = 0
}

function goToDetail(taskId: string | number) {
  if (!taskId) return
  uni.navigateTo({ url: `/subPackages/pages-construction/taskDetail?id=${taskId}` })
}

onMounted(() => {
  const savedRemark = uni.getStorageSync(remarkKey)
  if (savedRemark) {
    remark.value = savedRemark
  }

  loadSchedule()
  loadTodayRecord()
  taskStore.fetchMyTasks(today)
})
</script>

<style scoped>
.sub-page {
  max-width: 430px;
  margin: 0 auto;
  min-height: 100vh;
  background-color: #f6fbf9;
  padding-bottom: 96px;
}

.glass-card {
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  border: 1px solid rgba(164, 216, 152, 0.35);
  border-radius: 24px;
  box-shadow: 0 18px 50px -12px rgba(54, 143, 111, 0.28);
  overflow: hidden;
  margin-bottom: 12px;
}

/* 区块标题 */
.section-head {
  display: flex;
  align-items: center;
  padding: 16px 16px 12px;
}

.section-head-inner {
  display: flex;
  align-items: center;
}

.section-bar {
  width: 4px;
  height: 16px;
  border-radius: 2px;
  background: linear-gradient(180deg, #368f6f 0%, #5ab8d0 100%);
}

.section-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
}

/* 统计卡 */
.stat-card {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 88px;
  padding: 14px 6px 12px;
  border-radius: 16px;
  background-color: rgba(164, 216, 152, 0.14);
  border: 1px solid rgba(164, 216, 152, 0.3);
  overflow: hidden;
}

.stat-bar {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 26px;
  height: 3px;
  border-radius: 0 0 3px 3px;
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
}

.stat-value {
  font-size: 24px;
  font-weight: 800;
  line-height: 1.1;
  color: #368f6f;
}

.stat-label {
  margin-top: 6px;
  font-size: 12px;
  color: #6b7280;
}

/* 排班信息 */
.info-row {
  display: flex;
  align-items: center;
  padding: 6px 0;
}

.info-label {
  width: 72px;
  font-size: 13px;
  color: #6b7280;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #1f2937;
  font-weight: 500;
}

.empty-wrap {
  padding: 12px 0;
  text-align: center;
}

.empty-title {
  display: block;
  font-size: 14px;
  color: #b7791f;
  font-weight: 600;
}

.empty-text {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #9ca3af;
}

/* 检查状态 */
.check-state {
  font-size: 12px;
  font-weight: 600;
}

.check-state-done {
  color: #368f6f;
}

.check-state-pending {
  color: #b7791f;
}

.form-row {
  display: flex;
  align-items: center;
  padding: 8px 0 16px;
  border-bottom: 1px solid rgba(164, 216, 152, 0.18);
  margin-bottom: 12px;
}

.form-label {
  width: 72px;
  font-size: 14px;
  color: #4b5563;
}

.picker-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #1f2937;
}

.picker-value.disabled {
  color: #9ca3af;
}

.arrow-icon {
  font-size: 14px;
  color: #9ca3af;
}

/* 上传分组 */
.upload-group {
  margin-bottom: 16px;
  padding-top: 12px;
  border-top: 1px solid rgba(164, 216, 152, 0.18);
}

.upload-group:first-of-type {
  border-top: none;
  padding-top: 0;
}

.check-group-title {
  display: block;
  margin-bottom: 8px;
  font-size: 13px;
  font-weight: 600;
  color: #6b7280;
}

.upload-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.media-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  overflow: hidden;
  border: 1rpx solid #e5e7eb;
}

.media-thumb {
  width: 160rpx;
  height: 160rpx;
  display: block;
  object-fit: cover;
}

.media-video {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f3f4f6;
}

.media-video-icon {
  font-size: 36rpx;
  color: #ef4444;
}

.media-delete {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  background-color: #ef4444;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.media-delete text {
  font-size: 22rpx;
  color: #ffffff;
}

.media-add {
  width: 160rpx;
  height: 160rpx;
  border-radius: 16rpx;
  border: 2rpx dashed #d1d5db;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9fafb;
}

.media-add-icon {
  font-size: 40rpx;
  color: #9ca3af;
}

.media-add-text {
  font-size: 22rpx;
  color: #9ca3af;
  margin-top: 6rpx;
}

.form-textarea {
  width: 100%;
  min-height: 72px;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  background-color: #ffffff;
  font-size: 14px;
  color: #1f2937;
}

.submit-btn {
  width: 100%;
  padding: 12px 0;
  border-radius: 14px;
  font-size: 14px;
  font-weight: 600;
  color: #ffffff;
  background: linear-gradient(135deg, #368f6f 0%, #4ba98a 100%);
  box-shadow: 0 10px 24px -10px rgba(54, 143, 111, 0.7);
  line-height: 1.4;
}

.submit-btn-hover {
  opacity: 0.88;
}

.submit-btn[disabled] {
  opacity: 0.5;
}

/* 已完成态 */
.done-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 0 12px;
}

.done-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(164, 216, 152, 0.24);
  margin-bottom: 12px;
}

.done-tick {
  font-size: 28px;
  color: #368f6f;
}

.done-text {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.done-meta {
  margin-top: 4px;
  font-size: 12px;
  color: #9ca3af;
}

.reset-link {
  display: inline-flex;
  align-items: center;
  margin-top: 16px;
  padding: 8px 16px;
  border-radius: 999rpx;
  background-color: rgba(164, 216, 152, 0.2);
}

.reset-icon {
  font-size: 24rpx;
  color: #368f6f;
}

.reset-text {
  font-size: 13px;
  color: #368f6f;
  font-weight: 600;
}

/* 列表行 */
.list-row {
  display: flex;
  align-items: center;
  padding: 13px 16px;
  border-top: 1px solid rgba(164, 216, 152, 0.18);
}

.row-title {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.row-sub {
  display: block;
  margin-top: 3px;
  font-size: 12px;
  color: #9ca3af;
}

.row-hover {
  background-color: rgba(164, 216, 152, 0.3);
}

.icon-chip {
  width: 42px;
  height: 42px;
  border-radius: 12px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(164, 216, 152, 0.2);
}

.chip-glyph {
  font-size: 20px;
  color: #368f6f;
}

.empty-text {
  font-size: 13px;
  color: #9ca3af;
}
</style>
