<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="标题" prop="title">
            <el-input 
              v-model="form.title" 
              placeholder="请输入标题" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="内容" prop="content">
            <Editor
              v-model:get-html="form.content"
              height="400"
              placeholder="请输入内容" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="作者" prop="author">
            <el-input 
              v-model="form.author" 
              placeholder="请输入作者" 
              clearable />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="WeekPlanDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/stuwork/weekPlan'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import Editor from '/@/components/Editor/index.vue'

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const schoolYearList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  schoolYear: '',
  schoolTerm: '',
  title: '',
  content: '',
  author: ''
});

// 定义校验规则
const dataRules = ref({
  schoolYear: [
    { required: false, message: '学年不能为空', trigger: 'blur' }
  ],
  schoolTerm: [
    { required: false, message: '学期不能为空', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '内容不能为空', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '作者不能为空', trigger: 'blur' }
  ]
})

// 打开弹窗
const openDialog = async (id?: string) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: '',
    schoolYear: '',
    schoolTerm: '',
    title: '',
    content: '',
    author: ''
  })

  // 确保学年列表已加载
  if (schoolYearList.value.length === 0) {
    await getSchoolYearList()
  }
  
  // 如果是新增，设置学年为列表中的第一条数据，学期默认为1
  if (!id) {
    // 设置学年为列表中的第一条数据
    if (schoolYearList.value.length > 0) {
      form.schoolYear = schoolYearList.value[0].year
    }
    // 设置学期默认为1
    form.schoolTerm = '1'
  } else {
    // 编辑时，如果没有学年，也设置默认值
    if (!form.schoolYear && schoolYearList.value.length > 0) {
      form.schoolYear = schoolYearList.value[0].year
    }
    // 编辑时，如果没有学期，设置默认为1
    if (!form.schoolTerm) {
      form.schoolTerm = '1'
    }
  }

  // 重置表单验证
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取详情
  if (id) {
    form.id = id
    getWeekPlanData(id)
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || '操作失败');
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const getWeekPlanData = (id: string) => {
  loading.value = true
  getObj({ id: id }).then((res: any) => {
    if (res.data) {
      // 处理返回数据，可能是对象或数组
      const data = Array.isArray(res.data) ? res.data[0] : res.data
      if (data) {
        Object.assign(form, {
          id: data.id || '',
          schoolYear: data.schoolYear || '',
          schoolTerm: data.schoolTerm || '',
          title: data.title || '',
          content: data.content || '',
          author: data.author || ''
        })
      }
    }
  }).catch((err: any) => {
    console.error('获取详情失败', err)
    useMessage().error('获取详情失败')
  }).finally(() => {
    loading.value = false
  })
}

// 获取学年列表
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data) {
      schoolYearList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取学年列表失败', err)
    schoolYearList.value = []
  }
}

// 初始化
onMounted(() => {
  getSchoolYearList()
})

// 暴露变量
defineExpose({
  openDialog
});
</script>
