<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible" 
    :width="800" 
    :close-on-click-modal="false" 
    draggable>
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="学年" prop="schoolYear">
            <el-select
              v-model="form.schoolYear"
              placeholder="请选择学年"
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in schoolYearList"
                :key="item.year"
                :label="item.year"
                :value="item.year" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="学期" prop="schoolTerm">
            <el-select
              v-model="form.schoolTerm"
              placeholder="请选择学期"
              clearable
              style="width: 100%">
              <el-option
                v-for="item in schoolTermList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入标题"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="作者" prop="author">
            <el-input
              v-model="form.author"
              placeholder="请输入作者"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="内容" prop="content">
            <Editor
              v-model:getHtml="form.content"
              :height="'400'"
              placeholder="请输入内容" />
          </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="MoralPlanFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/moralplan'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import { getDicts } from '/@/api/admin/dict'
import Editor from '/@/components/Editor/index.vue'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const operType = ref('add') // add 或 edit
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])

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

// 定义校验规则
const dataRules = {
  schoolYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.schoolYear = ''
    form.schoolTerm = ''
    form.title = ''
    form.content = ''
    form.author = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.schoolYear = row.schoolYear || ''
      form.schoolTerm = row.schoolTerm || ''
      form.title = row.title || ''
      form.content = row.content || ''
      form.author = row.author || ''
      
      // 如果需要获取详情
      if (row.id && !row.content) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.schoolYear = res.data.schoolYear || form.schoolYear
            form.schoolTerm = res.data.schoolTerm || form.schoolTerm
            form.title = res.data.title || ''
            form.content = res.data.content || ''
            form.author = res.data.author || ''
          }
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 学年列表（班级管理-学年接口）
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    schoolYearList.value = res?.data && Array.isArray(res.data) ? res.data : []
  } catch (err) {
    schoolYearList.value = []
  }
}

// 学期字典（系统通用）
const getSchoolTermDict = async () => {
  try {
    const res = await getDicts('school_term')
    if (res?.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data.map((item: any) => ({
        label: item.label ?? item.dictLabel ?? item.name,
        value: item.value ?? item.dictValue ?? item.code
      }))
    } else {
      schoolTermList.value = []
    }
  } catch (err) {
    schoolTermList.value = []
  }
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      const submitData = {
        schoolYear: form.schoolYear,
        schoolTerm: form.schoolTerm,
        title: form.title,
        content: form.content,
        author: form.author
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        await editObj({
          id: form.id,
          ...submitData
        })
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      if (!err?._messageShown) {
        useMessage().error(err?.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
      }
    } finally {
      loading.value = false
    }
  })
}

// 初始化：加载学年、学期
onMounted(() => {
  getSchoolYearList()
  getSchoolTermDict()
})

// 暴露方法
defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
.mb20 {
  margin-bottom: 20px;
}
</style>
