<template>
  <div>
    <div class="page-header">
      <h1>工作日设置</h1>
      <p>按年份设定每月工作日天数，用于计算研发工时上限</p>
    </div>

    <div class="content-card">
      <div class="card-title">
        <div class="filter-bar" style="margin-bottom: 0">
          <el-select v-model="selectedYear" @change="loadWorkdays" style="width: 120px">
            <el-option v-for="y in years" :key="y" :label="`${y}年`" :value="y" />
          </el-select>
        </div>
        <el-button type="primary" :loading="saving" @click="handleSave">保存设置</el-button>
      </div>

      <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; margin-top: 8px;">
        <div v-for="(item, idx) in workdays" :key="idx"
          class="stat-card" :class="['purple', 'green', 'blue', 'orange'][idx % 4]">
          <div class="label">{{ item.month }}月</div>
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-input-number v-model="item.days" :min="0" :max="31" size="default"
              style="width: 120px" />
            <span class="unit">天</span>
          </div>
          <div style="margin-top: 6px; font-size: 12px; color: var(--text-muted);">
            工时上限: {{ item.days * 8 }} 小时
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { adminApi } from '../../api'

const currentYear = new Date().getFullYear()
const years = Array.from({ length: 5 }, (_, i) => currentYear - 2 + i)
const selectedYear = ref(currentYear)
const saving = ref(false)

const workdays = ref(
  Array.from({ length: 12 }, (_, i) => ({ month: i + 1, days: 22 }))
)

async function loadWorkdays() {
  try {
    const res = await adminApi.getWorkdays(selectedYear.value)
    if (res.data.length > 0) {
      workdays.value = Array.from({ length: 12 }, (_, i) => {
        const found = res.data.find(w => w.month === i + 1)
        return { month: i + 1, days: found ? found.days : 22 }
      })
    }
  } catch (e) {}
}

async function handleSave() {
  saving.value = true
  try {
    await adminApi.setWorkdays({
      year: selectedYear.value,
      months: workdays.value.map(w => ({ month: w.month, days: w.days }))
    })
    ElMessage.success('保存成功')
  } finally { saving.value = false }
}

onMounted(loadWorkdays)
</script>
