<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="600px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      v-loading="loading">
      <el-form-item label="留宿类型" prop="liveType">
        <el-select 
          v-model="form.liveType" 
          placeholder="请选择留宿类型" 
          clearable
          style="width: 100%">
          <el-option
            v-for="item in liveTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="留宿日期" prop="liveDates">
        <el-date-picker
          v-model="form.liveDates"
          type="dates"
          placeholder="选择留宿日期（可多选）"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%" />
      </el-form-item>
    </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="DormLiveApplyFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/dormliveapply'
import { getDicts } from '/@/api/admin/dict'

const emit = defineEmits(['refresh'])

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

// 提交表单数据
const form = reactive({
  id: '',
  liveType: '',
  liveDates: [] as string[]
})

// 定义校验规则
const dataRules = {
  liveType: [
    { required: true, message: '请选择留宿类型', trigger: 'change' }
  ],
  liveDates: [
    { required: true, message: '请选择留宿日期', trigger: 'change', type: 'array', min: 1 }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.liveType = ''
    form.liveDates = []
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.liveType = row.liveType || ''
      
      // 获取详情以获取liveDates
      if (row.id) {
        getDetailData(row.id)
      }
    }
  })
}

// 获取详情
const getDetailData = async (id: string) => {
  try {
    loading.value = true
    const res = await getDetail(id)
    if (res.data && res.data.records && res.data.records.length > 0) {
      const detail = res.data.records[0]
      form.liveType = detail.liveType || ''
      // 处理留宿日期，可能是字符串或数组
      if (detail.liveDates) {
        if (Array.isArray(detail.liveDates)) {
          form.liveDates = detail.liveDates
        } else if (typeof detail.liveDates === 'string') {
          // 如果是逗号分隔的字符串，转换为数组
          form.liveDates = detail.liveDates.split(',').filter((d: string) => d.trim())
        }
      } else if (detail.liveDate) {
        // 如果只有单个日期，转换为数组
        form.liveDates = [detail.liveDate]
      }
    }
  } catch (err) {
  } finally {
    loading.value = false
  }
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    if (!form.liveDates || form.liveDates.length === 0) {
      useMessage().error('请至少选择一个留宿日期')
      return
    }
    
    loading.value = true
    try {
      const submitData: any = {
        liveType: form.liveType,
        liveDates: form.liveDates
      }
      
      // 编辑时需要包含id
      if (operType.value === 'edit') {
        submitData.id = form.id
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        await editObj(submitData)
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
    } finally {
      loading.value = false
    }
  })
}

// 获取留宿类型字典
const getLiveTypeDict = async () => {
  try {
    const res = await getDicts('live_type')
    if (res.data) {
      liveTypeList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    liveTypeList.value = []
  }
}

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

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

