<script setup lang="ts">
import {computed, onMounted, onUnmounted, ref} from 'vue';
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import {useRoute, useRouter} from "vue-router";

const router = useRouter();

const route = useRoute()
const taskId = route.params.taskId ? Number(route.params.taskId) : null;
const buttonName = route.meta.buttonText;


const taskName = ref('');
const taskDescription = ref('');
const materialURL = ref('');
const priority = ref({
  urgency: 0,
  importance: 0,
  contentDifficulty: 0,
  futureValue: 0,
  subjectivePriority: 0,
});

const priorityOptions = [0, 1, 2, 3, 4, 5];

const createTask = () => {
  console.log('创建任务', {
    taskName: taskName.value,
    taskDescription: taskDescription.value,
    priority: priority.value,
  });

  request.post("/tasks", {
    taskName: taskName.value,
    taskDescription: taskDescription.value,
    materialURL: materialURL.value,
    ...priority.value
  }).then(result => {
    if (result.code == 200) {
      ElMessage.success("创建任务成功，任务id：" + result.message)
      router.back()
    } else {
      ElMessage.error("任务创建失败，错误原因：" + result.message)
    }
  })
};

const loadTask = () => {
  console.info("开始加载任务信息")
  if (taskId !== null) {
    request.get(`/tasks/${taskId}`, {}).then(result => {
      if (result.code === 200) {
        const data = result.data;
        taskName.value = data.taskName;
        taskDescription.value = data.taskDescription;
        materialURL.value = data.materialURL || data.materialUrl || "";
        priority.value = {
          urgency: data.urgency,
          importance: data.importance,
          contentDifficulty: data.contentDifficulty,
          futureValue: data.futureValue,
          subjectivePriority: data.subjectivePriority,
        };
      } else {
        ElMessage.error(`任务加载失败：${result.message}`);
      }
    });
  }
};

const updateTask = () => {
  console.log('更新任务', {
    taskName: taskName.value,
    taskDescription: taskDescription.value,
    priority: priority.value,
  });

  request.put("/tasks/" + taskId, {
    id: taskId,
    taskName: taskName.value,
    taskDescription: taskDescription.value,
    materialURL: materialURL.value,
    ...priority.value
  }).then(result => {
    if (result.code == 200) {
      ElMessage.success("更新任务成功" + result.message)
      router.back()
    } else {
      ElMessage.error("任务更新失败，错误原因：" + result.message)
    }
  })
};

const cancelTask = () => {
  ElMessage.success("已取消创建")
  router.back()
};


const submitTask = () => {
  switch (route.name) {
    case 'add-task':
      createTask();
      break;
    case 'update-task':
      updateTask();
      break;
    default:
      ElMessage.error('未知操作类型');
  }
}

const screenWidth = ref(window.innerWidth);

const updateWidth = () => {
  screenWidth.value = window.innerWidth;
};


onMounted(() => {
  window.addEventListener('resize', updateWidth)
  if (route.meta.action === 'update' && taskId !== null) {
    loadTask();
  }
});
onUnmounted(() => window.removeEventListener('resize', updateWidth));

const columnSpan = computed(() => {
  return screenWidth.value <= 768 ? 20 : 8;
});
</script>

<template>
  <el-form label-width="100px">
    <el-form-item label="任务名:">
      <el-input v-model="taskName" placeholder="请输入任务名"></el-input>
    </el-form-item>

    <el-form-item label="任务描述:">
      <el-input
          v-model="taskDescription"
          type="textarea"
          placeholder="请输入任务描述"
          rows="6"
      ></el-input>
    </el-form-item>

    <el-form-item label="材料地址:">
      <el-input v-model="materialURL" placeholder="请输入学习材料URL"></el-input>
    </el-form-item>

    <el-form-item label="优先级:">
      <el-row :gutter="10">
        <el-col :span="columnSpan">
          <el-form-item label="急迫性">
            <el-select v-model="priority.urgency">
              <el-option
                  v-for="item in priorityOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="columnSpan">
          <el-form-item label="重要性">
            <el-select v-model="priority.importance">
              <el-option
                  v-for="item in priorityOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="columnSpan">
          <el-form-item label="内容难度">
            <el-select v-model="priority.contentDifficulty">
              <el-option
                  v-for="item in priorityOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="columnSpan">
          <el-form-item label="未来价值">
            <el-select v-model="priority.futureValue">
              <el-option
                  v-for="item in priorityOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="columnSpan">
          <el-form-item label="主观优先级">
            <el-select v-model="priority.subjectivePriority">
              <el-option
                  v-for="item in priorityOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitTask">{{ buttonName }}</el-button>
      <el-button @click="cancelTask">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.el-form-item {
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }
}
</style>
