<template>
  <view class="sub-page">
    <TopBar title="排班管理" show-back />

    <view class="px-4 pt-3">
      <!-- 日历卡片 -->
      <view class="glass-card p-4">
        <!-- 月份切换 -->
        <view class="flex items-center justify-between mb-3">
          <view class="flex items-center">
            <view class="month-arrow" hover-class="month-arrow-hover" :hover-start-time="0" :hover-stay-time="120" @click="changeMonth(-1)">
              <text class="uni-icons uniui-arrowleft month-arrow-icon"></text>
            </view>
            <text class="month-title">{{ currentYear }}年{{ currentMonth }}月</text>
            <view class="month-arrow" hover-class="month-arrow-hover" :hover-start-time="0" :hover-stay-time="120" @click="changeMonth(1)">
              <text class="uni-icons uniui-arrowright month-arrow-icon"></text>
            </view>
          </view>
          <view class="today-btn" hover-class="month-arrow-hover" :hover-start-time="0" :hover-stay-time="120" @click="goToToday">
            <text class="uni-icons uniui-calendar-filled today-icon mr-1"></text>
            <text class="today-text">今天</text>
          </view>
        </view>

        <!-- 星期标题 -->
        <view class="flex mb-2">
          <view v-for="day in weekDays" :key="day" class="flex-1 text-center">
            <text class="week-label">{{ day }}</text>
          </view>
        </view>

        <!-- 日期 -->
        <view v-for="(week, weekIndex) in calendarWeeks" :key="weekIndex" class="flex mb-2">
          <view
            v-for="(date, dateIndex) in week"
            :key="dateIndex"
            class="date-cell"
            :class="{
              'date-other': date.isOtherMonth,
              'date-today': date.isToday && !isSelected(date),
              'date-selected': isSelected(date),
            }"
            @click="selectDate(date)"
          >
            <text
              class="date-num"
              :class="{
                'date-num-today': date.isToday && !isSelected(date),
                'date-num-selected': isSelected(date),
              }"
            >
              {{ date.day }}
            </text>
            <view
              v-if="date.hasSchedule"
              class="schedule-dot"
              :class="isSelected(date) ? 'schedule-dot-on' : ''"
            ></view>
          </view>
        </view>
      </view>

      <!-- 排班列表 -->
      <view class="glass-card">
        <view class="section-head">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">{{ selectedDate }} 排班</text>
          <view class="add-btn" hover-class="month-arrow-hover" :hover-start-time="0" :hover-stay-time="120" @click="addSchedule">
            <text class="uni-icons uniui-plusempty add-icon mr-1"></text>
            <text class="add-text">新增排班</text>
          </view>
        </view>

        <view v-if="loading" class="py-10 text-center">
          <text class="empty-text">加载中...</text>
        </view>

        <view v-else-if="daySchedules.length === 0" class="pb-3">
          <EmptyState message="该日无排班" />
        </view>

        <view v-else>
          <view
            v-for="schedule in daySchedules"
            :key="schedule.scheduleId"
            class="list-row"
          >
            <view class="icon-chip mr-3">
              <text class="uni-icons uniui-calendar-filled chip-glyph"></text>
            </view>
            <view class="flex-1 min-w-0 mr-2">
              <text class="row-title truncate">{{ schedule.taskName }}</text>
              <text class="row-sub truncate">{{ schedule.staffName }} | {{ schedule.vehicleNo || '未分配车辆' }}</text>
            </view>
            <text class="status-tag flex-shrink-0" :class="getStatusTagClass(schedule.status)">
              {{ getStatusText(schedule.status) }}
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import TopBar from '../../components/common/TopBar.vue'
import EmptyState from '../../components/common/EmptyState.vue'
import { getScheduleList } from '../../api/schedule'

const loading = ref(false)
const schedules = ref<any[]>([])
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1)
const selectedDate = ref('')

const weekDays = ['日', '一', '二', '三', '四', '五', '六']

const calendarWeeks = computed(() => {
  const year = currentYear.value
  const month = currentMonth.value
  const firstDay = new Date(year, month - 1, 1)
  const lastDay = new Date(year, month, 0)
  const firstWeekDay = firstDay.getDay()
  const daysInMonth = lastDay.getDate()

  const weeks: any[] = []
  let currentWeek: any[] = []

  const prevMonthDays = new Date(year, month - 1, 0).getDate()
  for (let i = firstWeekDay - 1; i >= 0; i--) {
    currentWeek.push({
      day: prevMonthDays - i,
      isOtherMonth: true,
      isToday: false,
      hasSchedule: false,
    })
  }

  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    const isToday = dateStr === new Date().toISOString().split('T')[0]
    const hasSchedule = schedules.value.some(s => s.scheduleDate === dateStr)

    currentWeek.push({
      day,
      isOtherMonth: false,
      isToday,
      hasSchedule,
      dateStr,
    })

    if (currentWeek.length === 7) {
      weeks.push(currentWeek)
      currentWeek = []
    }
  }

  if (currentWeek.length > 0) {
    for (let i = 1; currentWeek.length < 7; i++) {
      currentWeek.push({
        day: i,
        isOtherMonth: true,
        isToday: false,
        hasSchedule: false,
      })
    }
    weeks.push(currentWeek)
  }

  return weeks
})

const daySchedules = computed(() => {
  if (!selectedDate.value) return []
  return schedules.value.filter(s => s.scheduleDate === selectedDate.value)
})

function changeMonth(delta: number) {
  let newMonth = currentMonth.value + delta
  if (newMonth > 12) {
    newMonth = 1
    currentYear.value++
  } else if (newMonth < 1) {
    newMonth = 12
    currentYear.value--
  }
  currentMonth.value = newMonth
}

function goToToday() {
  const now = new Date()
  currentYear.value = now.getFullYear()
  currentMonth.value = now.getMonth() + 1
  selectedDate.value = now.toISOString().split('T')[0]
}

function selectDate(date: any) {
  if (!date.isOtherMonth) {
    selectedDate.value = date.dateStr
  }
}

function isSelected(date: any): boolean {
  return date.dateStr === selectedDate.value
}

function getStatusText(status: string) {
  const map: Record<string, string> = {
    scheduled: '已排班',
    completed: '已完成',
    cancelled: '已取消',
  }
  return map[status] || status
}

function getStatusTagClass(status: string) {
  const map: Record<string, string> = {
    scheduled: 'status-tag-blue',
    completed: 'status-tag-green',
    cancelled: 'status-tag-red',
  }
  return map[status] || 'status-tag-gray'
}

function addSchedule() {
  uni.showToast({ title: '排班功能开发中', icon: 'none' })
}

async function fetchSchedules() {
  loading.value = true
  try {
    const res = await getScheduleList(currentYear.value, currentMonth.value)
    schedules.value = res.rows || []
  } catch (error) {
    console.error('获取排班列表失败:', error)
  } finally {
    loading.value = false
  }
}

watch(() => [currentYear.value, currentMonth.value], fetchSchedules)

onMounted(() => {
  const today = new Date().toISOString().split('T')[0]
  selectedDate.value = today
  fetchSchedules()
})
</script>

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

.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;
}

.month-arrow {
  width: 32px;
  height: 32px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(164, 216, 152, 0.2);
}

.month-arrow-hover {
  opacity: 0.75;
}

.month-arrow-icon {
  font-size: 16px;
  color: #368f6f;
}

.month-title {
  margin: 0 10px;
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
}

.today-btn {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 999px;
  background-color: rgba(164, 216, 152, 0.2);
}

.today-icon {
  font-size: 14px;
  color: #368f6f;
}

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

.week-label {
  font-size: 12px;
  color: #9ca3af;
}

.date-cell {
  flex: 1;
  height: 44px;
  margin: 0 2px;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.date-other {
  opacity: 0.3;
}

.date-today {
  border: 1px solid #368f6f;
}

.date-selected {
  background: linear-gradient(135deg, #368f6f 0%, #4ba98a 100%);
  box-shadow: 0 8px 18px -8px rgba(54, 143, 111, 0.8);
}

.date-num {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.date-num-today {
  color: #368f6f;
  font-weight: 700;
}

.date-num-selected {
  color: #ffffff;
  font-weight: 700;
}

.schedule-dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-top: 3px;
  background-color: #368f6f;
}

.schedule-dot-on {
  background-color: #ffffff;
}

.section-head {
  display: flex;
  align-items: center;
  padding: 16px 16px 12px;
}

.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;
}

.add-btn {
  display: flex;
  align-items: center;
  padding: 5px 12px;
  border-radius: 999px;
  background: linear-gradient(135deg, #368f6f 0%, #4ba98a 100%);
}

.add-icon {
  font-size: 13px;
  color: #ffffff;
}

.add-text {
  font-size: 12px;
  font-weight: 600;
  color: #ffffff;
}

.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;
}

.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;
}

.status-tag {
  padding: 2px 10px;
  border-radius: 999px;
  font-size: 11px;
  font-weight: 600;
}

.status-tag-green {
  color: #368f6f;
  background-color: rgba(164, 216, 152, 0.24);
}

.status-tag-blue {
  color: #2563eb;
  background-color: rgba(37, 99, 235, 0.1);
}

.status-tag-red {
  color: #ef4444;
  background-color: rgba(239, 68, 68, 0.1);
}

.status-tag-gray {
  color: #6b7280;
  background-color: #f3f4f6;
}

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