<template>
  <div class="task-create-page">
    <el-page-header @back="$router.back()" content="创建任务" />

    <el-card style="margin-top: 20px; max-width: 800px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="任务标题" required>
          <el-input v-model="form.title" placeholder="请输入任务标题" />
        </el-form-item>
        <el-form-item label="任务内容">
          <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入任务详情" />
        </el-form-item>
        <el-form-item label="指派给" required>
          <el-select v-model="form.assignee_id" placeholder="选择员工" filterable style="width: 100%">
            <el-option v-for="u in subordinates" :key="u.id" :label="u.display_name" :value="u.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-radio-group v-model="form.priority">
            <el-radio-button value="low">低</el-radio-button>
            <el-radio-button value="normal">中</el-radio-button>
            <el-radio-button value="high">高</el-radio-button>
            <el-radio-button value="urgent">紧急</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="截止日期">
          <el-date-picker v-model="form.deadline" type="datetime" placeholder="选择日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="推送企微">
          <el-switch v-model="form.push_to_wecom" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCreate" :loading="submitting">创建任务</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { taskApi, orgApi } from '@/api'

const router = useRouter()
const submitting = ref(false)
const subordinates = ref<any[]>([])

const form = reactive({
  title: '',
  content: '',
  assignee_id: '',
  priority: 'normal',
  deadline: null,
  push_to_wecom: true,
})

onMounted(async () => {
  const res: any = await orgApi.getSubordinates()
  subordinates.value = res || []
})

async function handleCreate() {
  if (!form.title || !form.assignee_id) {
    ElMessage.warning('请填写任务标题并选择员工')
    return
  }
  submitting.value = true
  try {
    await taskApi.createTask(form)
    ElMessage.success('任务已创建')
    router.push('/user/task/list')
  } finally {
    submitting.value = false
  }
}
</script>