<template>
  <view class="app-container pb-24">
    <TopBar title="每日任务" show-back />

    <view class="px-4 py-4 gap-y-4">
      <!-- 今日任务概览 -->
      <view class="card p-4">
        <view class="detail-section-title mb-4">
          <text class="uni-icons uniui-calendar-filled text-primary mr-2"></text>
          <text>今日概览</text>
        </view>
        <view class="grid grid-cols-2 gap-3">
          <view class="bg-blue-50 rounded-xl p-4 text-center">
            <text class="text-2xl font-bold text-blue-600 block">{{ todayTasks.length }}</text>
            <text class="text-xs text-gray-500 mt-1 block">今日任务</text>
          </view>
          <view class="bg-green-50 rounded-xl p-4 text-center">
            <text class="text-2xl font-bold text-green-500 block">{{ completedTasks }}</text>
            <text class="text-xs text-gray-500 mt-1 block">已完成</text>
          </view>
        </view>
      </view>

      <!-- 车辆检查 -->
      <view class="card p-4">
        <view class="detail-section-title mb-4">
          <text class="uni-icons uniui-cart-filled text-primary mr-2"></text>
          <text>车辆检查</text>
          <view class="ml-auto">
            <text v-if="vehicleCheckStatus" class="text-xs text-success">已完成</text>
            <text v-else class="text-xs text-warning">待检查</text>
          </view>
        </view>

        <view v-if="!vehicleCheckStatus">
          <!-- 常规检查 -->
          <view class="mb-3">
            <text class="text-sm font-medium text-gray-700 mb-2 block">常规检查</text>
            <view class="space-y-2">
              <view
                v-for="item in checkItems"
                :key="item.key"
                class="flex items-center justify-between py-2"
                @click="toggleCheck(item.key)"
              >
                <text class="text-sm text-gray-600">{{ item.label }}</text>
                <view
                  class="w-6 h-6 rounded-full border-2 flex items-center justify-center"
                  :class="checks[item.key] ? 'bg-primary border-primary' : 'border-gray-300'"
                >
                  <text v-if="checks[item.key]" class="uni-icons uniui-checkmarkempty text-white text-xs"></text>
                </view>
              </view>
            </view>
          </view>

          <!-- 设备检查 -->
          <view class="mb-3 border-t border-gray-100 pt-3">
            <text class="text-sm font-medium text-gray-700 mb-2 block">设备检查</text>
            <view class="space-y-2">
              <view
                v-for="item in equipmentItems"
                :key="item.key"
                class="flex items-center justify-between py-2"
                @click="toggleCheck(item.key)"
              >
                <text class="text-sm text-gray-600">{{ item.label }}</text>
                <view
                  class="w-6 h-6 rounded-full border-2 flex items-center justify-center"
                  :class="checks[item.key] ? 'bg-primary border-primary' : 'border-gray-300'"
                >
                  <text v-if="checks[item.key]" class="uni-icons uniui-checkmarkempty text-white text-xs"></text>
                </view>
              </view>
            </view>
          </view>

          <!-- 三大系统检查 -->
          <view class="mb-3 border-t border-gray-100 pt-3">
            <text class="text-sm font-medium text-gray-700 mb-2 block">三大系统检查</text>
            <view class="space-y-2">
              <view
                v-for="item in systemItems"
                :key="item.key"
                class="flex items-center justify-between py-2"
                @click="toggleCheck(item.key)"
              >
                <text class="text-sm text-gray-600">{{ item.label }}</text>
                <view
                  class="w-6 h-6 rounded-full border-2 flex items-center justify-center"
                  :class="checks[item.key] ? 'bg-primary border-primary' : 'border-gray-300'"
                >
                  <text v-if="checks[item.key]" class="uni-icons uniui-checkmarkempty text-white text-xs"></text>
                </view>
              </view>
            </view>
          </view>

          <!-- 备注 -->
          <view class="mb-3">
            <text class="form-label">备注</text>
            <textarea
              v-model="remark"
              class="w-full p-3 bg-surface rounded-xl text-sm text-gray-700 border border-gray-200"
              placeholder="请输入检查备注..."
              :maxlength="200"
            />
          </view>

          <button
            class="w-full py-3 btn-primary rounded-xl text-sm font-medium"
            :disabled="!vehicleCheckStatus"
            @click="submitCheck"
          >
            提交检查
          </button>
        </view>

        <view v-else class="text-center py-8">
          <view class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3">
            <text class="uni-icons uniui-checkmarkempty text-green-500 text-2xl"></text>
          </view>
          <text class="text-sm text-gray-600 font-medium">今日车辆检查已完成</text>
          <text v-if="remark" class="text-xs text-gray-400 mt-1 block">备注：{{ remark }}</text>
          <text class="text-xs text-gray-400 mt-1 block">{{ today }}</text>
        </view>
      </view>

      <!-- 今日任务列表 -->
      <view class="card p-4">
        <view class="detail-section-title mb-4">
          <text class="uni-icons uniui-flag-filled text-primary mr-2"></text>
          <text>今日任务列表</text>
        </view>
        <view v-if="taskStore.loading" class="py-10 text-center">
          <text class="text-gray-400">加载中...</text>
        </view>
        <view v-else-if="todayTasks.length === 0">
          <EmptyState message="今日无任务" />
        </view>
        <view v-else class="space-y-3">
          <TaskCard
            v-for="task in todayTasks"
            :key="task.id"
            :task="task"
            @click="goToDetail(task.id)"
          />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useTaskStore } from '../../stores/task'
import TopBar from '../../components/common/TopBar.vue'
import TaskCard from '../../components/task/TaskCard.vue'
import EmptyState from '../../components/common/EmptyState.vue'

const taskStore = useTaskStore()

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

const checkItems = [
  { key: 'exterior', label: '车辆外观检查' },
  { key: 'tire', label: '轮胎气压检查' },
  { key: 'fluid', label: '油液检查' },
  { key: 'brake', label: '刹车系统检查' },
  { key: 'safety', label: '安全设备检查' },
]

const equipmentItems = [
  { key: 'pump', label: '抽水泵检查' },
  { key: 'hose', label: '高压水管检查' },
  { key: 'tool', label: '施工工具检查' },
  { key: 'protective', label: '防护用品检查' },
]

const systemItems = [
  { key: 'power', label: '动力系统' },
  { key: 'hydraulic', label: '液压系统' },
  { key: 'electrical', label: '电气系统' },
]

const allItems = [...checkItems, ...equipmentItems, ...systemItems]

const initialChecks: Record<string, boolean> = {}
allItems.forEach((item) => {
  initialChecks[item.key] = false
})

const checks = ref<Record<string, boolean>>({ ...initialChecks })
const remark = ref('')

const vehicleCheckStatus = computed(() => {
  return allItems.every((item) => checks.value[item.key])
})

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

const todayTasks = computed(() => {
  return taskStore.tasks.filter((t) => t.scheduleDate === today || t.serviceDate === today)
})

function toggleCheck(type: string) {
  checks.value[type] = !checks.value[type]
  uni.setStorageSync(storageKey, JSON.stringify(checks.value))
}

function submitCheck() {
  if (!vehicleCheckStatus.value) {
    uni.showToast({ title: '请完成所有检查项', icon: 'none' })
    return
  }
  uni.setStorageSync(storageKey, JSON.stringify(checks.value))
  uni.setStorageSync(remarkKey, remark.value)
  uni.showToast({ title: '提交成功', icon: 'success' })
}

function goToDetail(taskId: string) {
  taskStore.setCurrentTask(taskId)
  uni.navigateTo({ url: '/subPackages/pages-construction/taskDetail' })
}

onMounted(() => {
  const saved = uni.getStorageSync(storageKey)
  if (saved) {
    try {
      checks.value = JSON.parse(saved)
    } catch {
      // 解析失败则使用默认值
    }
  }
  const savedRemark = uni.getStorageSync(remarkKey)
  if (savedRemark) {
    remark.value = savedRemark
  }

  taskStore.fetchTasks()
})
</script>
