<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :width="600" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="120px" v-loading="loading">
      <el-form-item label="学院" prop="deptCode">
        <el-select 
          v-model="form.deptCode" 
          placeholder="请选择学院" 
          clearable
          filterable
          style="width: 100%">
          <el-option
            v-for="item in deptList"
            :key="item.deptCode"
            :label="item.deptName"
            :value="item.deptCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select 
          v-model="form.userType" 
          placeholder="请选择用户类型" 
          clearable
          style="width: 100%">
          <el-option
            v-for="item in userTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input 
          v-model="form.userName" 
          placeholder="请输入用户名" 
          clearable
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input 
          v-model="form.realName" 
          placeholder="请输入姓名" 
          clearable
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="图书" prop="bookId">
        <el-select 
          v-model="form.bookId" 
          placeholder="请选择图书" 
          clearable
          filterable
          style="width: 100%">
          <el-option
            v-for="item in bookList"
            :key="item.id"
            :label="item.bookName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="浏览时间" prop="readTime">
        <el-date-picker
          v-model="form.readTime"
          type="datetime"
          placeholder="请选择浏览时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input 
          v-model="form.remarks" 
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          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="OnlineBooksBrowsingHistoryFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/onlinebooksbrowsinghistory'
import { getList as getBookList } from '/@/api/stuwork/onlinebooks'
import request from '/@/utils/request'

const emit = defineEmits(['refresh'])

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

// 用户类型列表
const userTypeList = [
  { label: '学生', value: '0' },
  { label: '老师', value: '1' }
]

// 提交表单数据
const form = reactive({
  id: '',
  deptCode: '',
  userType: '',
  userName: '',
  realName: '',
  bookId: '',
  readTime: '',
  remarks: ''
})

// 定义校验规则
const dataRules = {
  deptCode: [
    { required: true, message: '请选择学院', trigger: 'change' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  bookId: [
    { required: true, message: '请选择图书', trigger: 'change' }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.deptCode = ''
    form.userType = ''
    form.userName = ''
    form.realName = ''
    form.bookId = ''
    form.readTime = ''
    form.remarks = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      loading.value = true
      getDetail(row.id)
        .then((res: any) => {
          if (res.data) {
            form.id = res.data.id || row.id
            form.deptCode = res.data.deptCode || ''
            form.userType = res.data.userType || ''
            form.userName = res.data.userName || ''
            form.realName = res.data.realName || ''
            form.bookId = res.data.bookId || ''
            form.readTime = res.data.readTime || ''
            form.remarks = res.data.remarks || ''
          }
        })
        .catch((err: any) => {
          useMessage().error(err.msg || '获取详情失败')
          visible.value = false
        })
        .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: any = {
        deptCode: form.deptCode,
        userType: form.userType,
        userName: form.userName,
        realName: form.realName,
        bookId: form.bookId,
        readTime: form.readTime,
        remarks: form.remarks
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        submitData.id = form.id
        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 getDeptList = async () => {
  try {
    const res = await request({
      url: '/basic/basicdept/getDeptList',
      method: 'get',
      params: { secondFlag: 1 }
    })
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    deptList.value = []
  }
}

// 获取图书列表
const getBookListData = async () => {
  try {
    const res = await getBookList()
    if (res.data) {
      bookList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    bookList.value = []
  }
}

// 初始化
onMounted(() => {
  getDeptList()
  getBookListData()
})

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

