<template>
	<el-dialog v-model="visible" title="添加工时" width="400px">
		<el-form :model="form" label-width="70px">
			<el-form-item label="日期" required>
				<el-date-picker v-model="form.logDate" value-format="YYYY-MM-DD" style="width: 100%" />
			</el-form-item>
			<el-form-item label="工时" required>
				<el-input-number v-model="form.hours" :min="0.5" :step="0.5" :max="24" />
				<span style="margin-left: 8px">小时</span>
			</el-form-item>
			<el-form-item label="内容">
				<el-input v-model="form.description" type="textarea" :rows="2" />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import { useCool } from '/@/cool';
import { ElMessage } from 'element-plus';

const props = defineProps<{
	modelValue: boolean;
	taskId: number;
}>();

const emit = defineEmits<{
	(e: 'update:modelValue', v: boolean): void;
	(e: 'saved'): void;
}>();

const { service } = useCool();

const visible = computed({
	get: () => props.modelValue,
	set: (v) => emit('update:modelValue', v),
});
const saving = ref(false);
const form = reactive({
	logDate: '',
	hours: 1,
	description: '',
});

async function handleSave() {
	if (!form.logDate) { ElMessage.warning('请选择日期'); return; }
	saving.value = true;
	try {
		await service.project.time_log.add({
			taskId: props.taskId,
			logDate: form.logDate,
			hours: form.hours,
			description: form.description,
			userName: '当前用户',
		});
		ElMessage.success('工时已记录');
		emit('saved');
		visible.value = false;
		form.logDate = '';
		form.hours = 1;
		form.description = '';
	} finally {
		saving.value = false;
	}
}
</script>
