<template>
  <el-dialog :title="isEdit ? '编辑任务' : '新增任务'" v-model="visible" width="600px" @close="onClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" />
      </el-form-item>
      <el-form-item label="里程碑" prop="milestone_id">
        <el-select v-model="form.milestone_id" placeholder="请选择">
          <el-option v-for="m in milestones" :key="m.id" :label="m.name" :value="m.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="assignee_id">
        <el-select v-model="form.assignee_id" placeholder="选择负责人" filterable clearable>
          <el-option v-for="m in assigneeOptions" :key="m.value" :label="m.label" :value="m.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="form.priority" placeholder="请选择">
          <el-option v-for="p in priorities" :key="p" :label="priorityLabel(p)" :value="p" />
        </el-select>
      </el-form-item>
      <el-form-item label="截止日期" prop="due_date">
        <el-date-picker v-model="form.due_date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择">
          <el-option v-for="s in statuses" :key="s" :label="statusLabel(s)" :value="s" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="onSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { createTask, updateTask } from "../api/tasks";
import { useStudyStore } from "../store/study";

interface Props {
  modelValue: boolean;
  task?: Record<string, any>;
  milestones: any[];
  members?: any[];
}

const props = defineProps<Props>();
const emit = defineEmits(["update:modelValue", "success"]);

const formRef = ref<FormInstance>();
const study = useStudyStore();
const visible = computed({
  get: () => props.modelValue,
  set: (v: boolean) => emit("update:modelValue", v),
});

const priorities = ["LOW", "MEDIUM", "HIGH"];
const statuses = ["TODO", "DOING", "DONE", "BLOCKED"];
const priorityLabel = (v: string) => ({ LOW: "低", MEDIUM: "中", HIGH: "高" }[v] || v);
const statusLabel = (v: string) =>
  ({
    TODO: "待处理",
    DOING: "进行中",
    DONE: "已完成",
    BLOCKED: "阻塞",
  }[v] || v);

const form = reactive({
  title: "",
  description: "",
  milestone_id: "",
  assignee_id: "",
  priority: "MEDIUM",
  due_date: "",
  status: "TODO",
});

const rules: FormRules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  priority: [{ required: true, message: "请选择优先级", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

const submitting = ref(false);
const isEdit = computed(() => !!props.task);
const assigneeOptions = computed(() => {
  const seen = new Set<string>();
  return (props.members || [])
    .filter((m: any) => m.is_active !== false)
    .map((m: any) => {
      const user = m.user || {};
      return { value: m.user_id, label: user.display_name || user.username || m.username || "—" };
    })
    .filter((opt) => {
      if (seen.has(opt.value)) return false;
      seen.add(opt.value);
      return true;
    });
});

watch(
  () => props.task,
  (val) => {
    if (val) {
      form.title = val.title || "";
      form.description = val.description || "";
      form.milestone_id = val.milestone_id || "";
      form.assignee_id = val.assignee_id || "";
      form.priority = val.priority || "MEDIUM";
      form.due_date = val.due_date || "";
      form.status = val.status || "TODO";
    } else {
      form.title = "";
      form.description = "";
      form.milestone_id = "";
      form.assignee_id = "";
      form.priority = "MEDIUM";
      form.due_date = "";
      form.status = "TODO";
    }
  },
  { immediate: true }
);

const onClose = () => {
  visible.value = false;
};

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!study.currentStudy) {
      ElMessage.error("未选择项目");
      return;
    }
    submitting.value = true;
    try {
    const payload: Record<string, any> = {};
    Object.entries(form).forEach(([k, v]) => {
      if (v !== "" && v !== null && v !== undefined) {
        payload[k] = v;
      }
    });
      if (isEdit.value && props.task) {
        await updateTask(study.currentStudy.id, props.task.id, payload);
      } else {
        await createTask(study.currentStudy.id, payload);
      }
      ElMessage.success("提交成功");
      emit("success");
      onClose();
    } catch (e: any) {
      ElMessage.error(e?.response?.data?.message || "提交失败");
    } finally {
      submitting.value = false;
    }
  });
};
</script>
