<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="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="author">
            <el-input 
              v-model="form.author" 
              placeholder="请输入作者" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="标题" prop="title">
            <el-input 
              v-model="form.title" 
              placeholder="请输入标题" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="网址" prop="website">
            <el-input 
              v-model="form.website" 
              placeholder="请输入网址，例如：https://www.example.com" 
              clearable
              style="width: 100%" />
          </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="ClassPublicityFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/classpublicity'
import { getClassListByRole } from '/@/api/basic/basicclass'

const emit = defineEmits(['refresh'])

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

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

// 定义校验规则
const dataRules = {
  classCode: [
    { required: true, message: '请选择班号', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  website: [
    { required: true, message: '请输入网址', trigger: 'blur' },
    { 
      pattern: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/, 
      message: '请输入正确的网址格式', 
      trigger: 'blur' 
    }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.classCode = ''
    form.author = ''
    form.title = ''
    form.website = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.classCode = row.classCode || ''
      form.author = row.author || ''
      form.title = row.title || ''
      form.website = row.website || ''
      
      // 如果需要获取详情
      if (row.id && (!row.title || !row.website)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.website = res.data.website || ''
          }
        }).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 = {
        classCode: form.classCode,
        author: form.author,
        title: form.title,
        website: form.website
      }
      
      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 getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data && Array.isArray(res.data)) {
      classList.value = res.data
    }
  } catch (err) {
  }
}

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

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

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

