<template>
  <div class="app-container">
    <el-card class="container">
      <template #header>
        <div class="card-header">
          <span>新增报表</span>
        </div>
      </template>
      <el-form :model="form"
        :rules="rules"
        ref="reportRef"
        label-width="140px">
        <!-- 报表所属部门 -->
        <el-form-item label="报表所属部门"
          prop="categoryName">
          <el-select v-model="form.categoryName"
            placeholder="选择报表所属部门">
            <el-option v-for="item in deptList"
              :key="item.value"
              :label="item.title"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="报表名字"
          prop="name">
          <el-input v-model="form.name"
            placeholder="请输入报表名字" />
        </el-form-item>
        <!-- 超链接输入 -->
        <el-form-item label="超链接"
          prop="previewUrl">
          <el-input v-model="form.previewUrl"
            placeholder="请输入超链接地址" />
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary"
            @click="handleSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { enterOtherReportAPI, getReportFolderListAPI } from '@/api'
const { proxy } = getCurrentInstance();

// 表单数据
const form = ref({
  categoryName: '',
  name: '',
  previewUrl: '',
})

// 表单验证规则
const rules = ref({
  categoryName: [
    { required: true, message: '请选择报表所属部门', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入报表名字', trigger: 'blur' }
  ],
  previewUrl: [
    { required: true, message: '请输入超链接地址', trigger: 'blur' },
    // 判断必须是个完成的链接
    {
      validator: (rule, value, callback) => {
        if (!/^https?:\/\//.test(value)) {
          callback(new Error('请输入正确的超链接地址'))
        } else {
          callback()
        }
      }
    }
  ]
})

// 提交处理
const handleSubmit = async () => {
  // 调用表单验证方法
  proxy.$refs["reportRef"].validate(async valid => {
    if (valid) {
      // 表单验证通过，进行提交操作
      await enterOtherReportAPI(form.value)
      ElMessage.success('提交成功')
      // 清空表单
      form.value = {
        id: '',
        name: '',
        previewUrl: '',
      }
      proxy.$refs["reportRef"].resetFields()
    }
  })
}

// 获取积木报表文件夹分组一级
const deptList = ref([])
const getDeptList = async () => {
  const res = await getReportFolderListAPI()
  deptList.value = res.result
}
getDeptList()
</script>