<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-date-picker v-model="selectedDate" type="date" placeholder="选择日期"
            value-format="YYYY-MM-DD" size="default" :disabled-date="disabledDate" @change="loadTimesheets" />
          <el-tag type="info" effect="dark" round size="large" style="margin-left: 8px;">
            当日已填: {{ dayTotal }} / 8 小时
          </el-tag>
        </div>
        <el-button type="primary" @click="showAddDialog" :disabled="dayTotal >= 8">+ 添加工时</el-button>
      </div>

      <el-table :data="records" stripe v-loading="loading">
        <el-table-column prop="client_name" label="客户/项目" min-width="150" />
        <el-table-column prop="service_type" label="售前/售后" width="100">
          <template #default="{ row }">
            <el-tag :type="row.service_type === '售后' ? 'warning' : 'success'" size="small">{{ row.service_type || '售前' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="project_type" label="子项目" width="120" />
        <el-table-column prop="hours" label="工时(h)" width="80" />
        <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="140">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Progress bar -->
      <div style="margin-top: 16px;">
        <el-progress :percentage="(dayTotal / 8) * 100" :color="dayTotal > 8 ? '#ef4444' : '#6366f1'"
          :stroke-width="10" :format="() => `${dayTotal}/8h`" />
      </div>
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog v-model="dialogVisible" :title="editingId ? '编辑工时' : '添加工时'" width="460px" destroy-on-close>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="项目" prop="client_id" v-if="!editingId">
          <el-select v-model="form.client_id" placeholder="选择客户/项目" style="width: 100%" filterable>
            <el-option v-for="c in clients" :key="c.id" :label="`${c.name} (${c.sales_name})`" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="service_type">
          <el-radio-group v-model="form.service_type">
            <el-radio value="售前">售前</el-radio>
            <el-radio value="售后">售后</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="子项目" prop="project_type">
          <el-select v-model="form.project_type" style="width: 100%" filterable
            :disabled="!projectTypeOptions.length && !form.project_type"
            :placeholder="projectTypeOptions.length ? '请选择子项目' : '该项目未配置子项目'">
            <el-option v-for="pt in projectTypeOptions" :key="pt" :label="pt" :value="pt" />
          </el-select>
        </el-form-item>
        <el-form-item label="工时" prop="hours">
          <el-input-number v-model="form.hours" :min="0.5" :max="8" :step="0.5" :precision="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="工作内容说明（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { rdApi } from '../../api'

const route = useRoute()
const today = new Date().toISOString().split('T')[0]
const selectedDate = ref(route.query.date || today)
const records = ref([])
const dayTotal = ref(0)
const clients = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const saving = ref(false)
const editingId = ref(null)
const formRef = ref(null)

const form = reactive({ client_id: '', hours: 1, remark: '', service_type: '售前', project_type: '' })
const rules = {
  client_id: [{ required: true, message: '请选择项目', trigger: 'change' }],
  hours: [{ required: true, message: '请输入工时', trigger: 'blur' }],
  project_type: [{ required: true, message: '请输入项目类型', trigger: 'blur' }]
}

const disabledDate = (time) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const minDate = new Date(today)
  minDate.setDate(today.getDate() - 40)
  return time.getTime() < minDate.getTime() || time.getTime() > today.getTime()
}

async function loadTimesheets() {
  loading.value = true
  try {
    const res = await rdApi.getTimesheets({ date: selectedDate.value })
    records.value = res.data.records
    dayTotal.value = res.data.day_total
  } finally { loading.value = false }
}

async function loadClients() {
  const res = await rdApi.getClients()
  clients.value = res.data
}

// Compute project type options from selected client's service_types
const projectTypeOptions = computed(() => {
  if (!form.client_id) return []
  const found = clients.value.find(c => c.id === form.client_id)
  return found?.service_types || []
})

// When client changes, reset project_type if it's no longer valid
watch(() => form.client_id, () => {
  if (!projectTypeOptions.value.includes(form.project_type)) {
    form.project_type = projectTypeOptions.value[0] || ''
  }
})

function showAddDialog() {
  editingId.value = null
  form.client_id = ''
  form.hours = 1
  form.remark = ''
  form.service_type = '售前'
  form.project_type = ''
  dialogVisible.value = true
}

function showEditDialog(row) {
  editingId.value = row.id
  form.client_id = row.client_id
  form.hours = row.hours
  form.remark = row.remark || ''
  form.service_type = row.service_type || '售前'
  form.project_type = row.project_type || ''
  dialogVisible.value = true
}

async function handleSave() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  saving.value = true
  try {
    if (editingId.value) {
      await rdApi.updateTimesheet(editingId.value, { 
        hours: form.hours, 
        remark: form.remark,
        service_type: form.service_type,
        project_type: form.project_type
      })
      ElMessage.success('更新成功')
    } else {
      await rdApi.createTimesheet({
        client_id: form.client_id,
        work_date: selectedDate.value,
        hours: form.hours,
        remark: form.remark,
        service_type: form.service_type,
        project_type: form.project_type
      })
      ElMessage.success('提交成功')
    }
    dialogVisible.value = false
    loadTimesheets()
  } finally { saving.value = false }
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除该工时记录吗？', '确认', { type: 'warning' })
  await rdApi.deleteTimesheet(row.id)
  ElMessage.success('删除成功')
  loadTimesheets()
}

onMounted(() => {
  loadTimesheets()
  loadClients()
})
</script>
