<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="120px" 
      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%"
              :disabled="!!form.id">
              <el-option
                v-for="item in schoolYearList"
                :key="item.year"
                :label="item.year"
                :value="item.year">
              </el-option>
            </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%"
              :disabled="!!form.id">
              <el-option
                v-for="item in schoolTermList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="发生时间" prop="operatTime">
            <el-date-picker
              v-model="form.operatTime"
              type="date"
              placeholder="选择发生时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="类型" prop="type">
            <el-select 
              v-model="form.type" 
              placeholder="请选择类型" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="金额" prop="money">
            <el-input-number
              v-model="form.money"
              :min="0"
              :precision="2"
              placeholder="请输入金额"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="经办人" prop="operator">
            <el-input 
              v-model="form.operator" 
              placeholder="请输入经办人" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="用途" prop="purpose">
            <el-input 
              v-model="form.purpose" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入用途"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="附件" prop="attachment">
            <upload-file
              v-model="form.attachment"
              :limit="5"
              :fileSize="10"
              type="simple" />
          </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="ClassFeeLogFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/classfeelog'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import { getDicts } from '/@/api/admin/dict'
import UploadFile from '/@/components/Upload/index.vue'

const emit = defineEmits(['refresh'])

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

// 提交表单数据
const form = reactive({
  id: '',
  schoolYear: '',
  schoolTerm: '',
  classCode: '',
  operatTime: '',
  type: '',
  money: 0,
  operator: '',
  purpose: '',
  attachment: ''
})

// 定义校验规则
const dataRules = {
  schoolYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  classCode: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  operatTime: [
    { required: true, message: '请选择发生时间', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  money: [
    { required: true, message: '请输入金额', trigger: 'blur' }
  ],
  operator: [
    { required: true, message: '请输入经办人', trigger: 'blur' }
  ],
  purpose: [
    { required: true, message: '请输入用途', trigger: 'blur' }
  ]
  // attachment 非必填，不需要验证规则
}

// 打开弹窗
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.classCode = ''
    form.operatTime = ''
    form.type = ''
    form.money = 0
    form.operator = ''
    form.purpose = ''
    form.attachment = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.schoolYear = row.schoolYear || ''
      form.schoolTerm = row.schoolTerm || ''
      form.classCode = row.classCode || ''
      form.operatTime = row.operatTime || ''
      form.type = row.type || ''
      form.money = row.money || 0
      form.operator = row.operator || ''
      form.purpose = row.purpose || ''
      form.attachment = row.attachment || ''
      
      // 如果需要获取详情
      if (row.id && (!row.purpose || !row.attachment)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.attachment = res.data.attachment || ''
          }
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 提交表单
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,
        classCode: form.classCode,
        operatTime: form.operatTime,
        type: form.type,
        money: form.money,
        operator: form.operator,
        purpose: form.purpose,
        attachment: form.attachment || ''
      }
      
      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) {
      useMessage().error(err.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
    } finally {
      loading.value = false
    }
  })
}

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

// 获取学期字典
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
      }))
    }
  } catch (err) {
    console.error('获取学期字典失败', err)
  }
}

// 获取班级列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data && Array.isArray(res.data)) {
      classList.value = res.data
    }
  } catch (err) {
    console.error('获取班级列表失败', err)
  }
}

// 获取类型字典
const getTypeDict = async () => {
  try {
    const res = await getDicts('class_fee_type')
    if (res.data && Array.isArray(res.data)) {
      typeList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    }
  } catch (err) {
    console.error('获取类型字典失败', err)
  }
}

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

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

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

