<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="categoryCode">
        <el-select 
          v-model="form.categoryCode" 
          placeholder="请选择类别" 
          clearable
          filterable
          style="width: 100%">
          <el-option
            v-for="item in categoryList"
            :key="item.categoryCode"
            :label="item.categoryName"
            :value="item.categoryCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面" prop="bookImg">
        <upload-img 
          v-model="form.bookImg"
          :width="'150px'"
          :height="'200px'"
          upload-file-url="/admin/sys-file/upload" />
      </el-form-item>
      <el-form-item label="书名" prop="bookName">
        <el-input 
          v-model="form.bookName" 
          placeholder="请输入书名" 
          clearable
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="作者" prop="bookAuthor">
        <el-input 
          v-model="form.bookAuthor" 
          placeholder="请输入作者" 
          clearable
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="链接" prop="webUrl">
        <el-input 
          v-model="form.webUrl" 
          placeholder="请输入链接，例如：https://www.example.com" 
          clearable
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input 
          v-model="form.remarks" 
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          maxlength="250"
          show-word-limit
          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="OnlineBooksFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/onlinebooks'
import request from '/@/utils/request'
import UploadImg from '/@/components/Upload/Image.vue'

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 categoryList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  deptCode: '',
  categoryCode: '',
  bookImg: '',
  bookName: '',
  bookAuthor: '',
  webUrl: '',
  remarks: ''
})

// URL验证函数
const validateUrl = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('链接不能为空'))
    return
  }
  const urlPattern = /^(https?:\/\/)?([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,}(:\d+)?(\/[^\s]*)?$/i
  if (urlPattern.test(value)) {
    callback()
  } else {
    callback(new Error('请输入合法的网址，例如：https://www.baidu.com'))
  }
}

// 定义校验规则
const dataRules = {
  deptCode: [
    { required: true, message: '请选择学院', trigger: 'change' }
  ],
  categoryCode: [
    { required: true, message: '请选择类别', trigger: 'change' }
  ],
  bookName: [
    { required: true, message: '请输入书名', trigger: 'blur' }
  ],
  bookAuthor: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  webUrl: [
    { validator: validateUrl, trigger: 'blur' }
  ],
  remarks: [
    { max: 250, message: '备注不能超过250个字符', trigger: 'blur' }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.deptCode = ''
    form.categoryCode = ''
    form.bookImg = ''
    form.bookName = ''
    form.bookAuthor = ''
    form.webUrl = ''
    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.categoryCode = res.data.categoryCode || ''
            form.bookImg = res.data.bookImg || ''
            form.bookName = res.data.bookName || ''
            form.bookAuthor = res.data.bookAuthor || ''
            form.webUrl = res.data.webUrl || ''
            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,
        categoryCode: form.categoryCode,
        bookImg: form.bookImg,
        bookName: form.bookName,
        bookAuthor: form.bookAuthor,
        webUrl: form.webUrl,
        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 getCategoryList = async () => {
  try {
    const res = await request({
      url: '/stuwork/onlinebookscategory/list',
      method: 'get'
    })
    if (res.data) {
      categoryList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    categoryList.value = []
  }
}

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

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

