<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
    :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="文件地址" prop="fileUrl">

            <el-upload
                :headers="headers"
                :limit="1"
                :action="uploadUrl"
                :file-list="fileList"
                :on-success="handleUploadSuccess"
                :accept="'.pdf'"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <template #tip>
                <div style="margin-top: 8px;">
                  <el-tag>仅支持pdf后缀的文件上传</el-tag>
                </div>
              </template>
            </el-upload>

<!--            <el-upload-->
<!--                :action="uploadUrl"-->
<!--                class="avatar-uploader"-->
<!--                name="file"-->
<!--                :headers="headers"-->
<!--                :data="uploadData"-->
<!--                :file-list="fileList"-->
<!--                :before-upload="beforeUpload"-->
<!--                :http-request="httpRequest"-->
<!--                :limit="1"-->
<!--                :accept="['.jpg,.jpeg,.png,.pdf']"-->
<!--                :on-success="handleUploadSuccess">-->
<!--              <el-button size="small" type="primary">点击上传</el-button>-->
<!--              <template #tip>-->
<!--                <div style="margin-top: 8px;">-->
<!--                  <el-tag>仅支持jpg,jpeg,png,pdf后缀的文件上传</el-tag>-->
<!--                </div>-->
<!--              </template>-->
<!--            </el-upload>-->
          </el-form-item>
        </el-col>

<!--        <el-col :span="12" class="mb20">-->
<!--          <el-form-item label="1 资助政策文件" prop="type">-->
<!--            <el-input v-model="form.type" placeholder="请输入1 资助政策文件"/>-->
<!--          </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="RecruitPolicyFileDialog">
// ========== 1. 导入语句 ==========
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/recruit/recruitPolicyFile';
import {Plus} from "@element-plus/icons-vue";
import {reactive, ref} from "vue";
import axios from "axios";
import { Session } from '/@/utils/storage'
const fileList = ref<any[]>([])

// ========== 2. 组件定义 ==========
// 定义组件事件
const emit = defineEmits(['refresh']);

// ========== 3. 响应式数据定义 ==========
// 基础响应式变量
const dataFormRef = ref(); // 表单引用
const visible = ref(false); // 弹窗显示状态
const loading = ref(false); // 加载状态
const baseUrl = import.meta.env.VITE_API_URL

// 表单数据对象
const form = reactive({
  id: '', // 主键
  fileUrl: '', // 文件地址
  title: '', // 标题
  type: '', // 1 资助政策文件
});

const uploadUrl = baseUrl + '/recruit/file/uploadPdf'
// 请求头
const headers = computed(() => {
  return {
    "Authorization": 'Bearer ' + Session.getToken()
  }
})
const uploadData = reactive({})
const fileReader = ref<FileReader | null>(null)



// 上传前验证
const beforeUpload = (file: File) => {
  const isLt5M = file.size < 10 * 1024 * 1024
  if (!isLt5M) {
    useMessage().error('文件大小不能超过10M')
    return false
  }
  return true
}
// 通用上传成功回调（单文件 - avatar模式）
const handleUploadSuccess = (res:any) => {
  const fileUrl = res.fileUrl
  form['fileUrl'] = fileUrl
}
// ========== 4. 字典数据处理 ==========

// ========== 5. 表单校验规则 ==========
const dataRules = ref({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  fileUrl: [
    { required: true, message: '请上传文件', trigger: 'blur' },
  ]
});

// ========== 6. 方法定义 ==========
// 获取详情数据
const getRecruitPolicyFileData = async (id: string) => {
  try {
    loading.value = true;
    const { data } = await getObj({ id: id });
    // 直接将第一条数据赋值给表单
    Object.assign(form, data[0]);
  } catch (error) {
    useMessage().error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 打开弹窗方法
const openDialog = (id: string) => {
  visible.value = true;
  form.id = '';

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取RecruitPolicyFile信息
  if (id) {
    form.id = id;
    getRecruitPolicyFileData(id);
  }
};

// 提交表单方法
const onSubmit = async () => {
  loading.value = true; // 防止重复提交
  
  // 表单校验
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) {
    loading.value = false;
    return false;
  }

  try {
    // 根据是否有ID判断是新增还是修改
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh'); // 通知父组件刷新列表
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};
// 初始化 FileReader
onMounted(() => {
  if (!window.FileReader) {
    useMessage().error('您的浏览器不支持 FileReader API!')
  } else {
    fileReader.value = new FileReader()
  }
})
// ========== 7. 对外暴露 ==========
// 暴露方法给父组件
defineExpose({
  openDialog
});
</script>

<style lang="scss" scoped>
//.avatar-uploader {
//  :deep(.el-upload) {
//    border: 1px dashed var(--el-border-color);
//    border-radius: 6px;
//    cursor: pointer;
//    position: relative;
//    overflow: hidden;
//    transition: var(--el-transition-duration-fast);
//    width: 148px;
//    height: 148px;
//    &:hover {
//      border-color: var(--el-color-primary);
//    }
//  }
//}
//
//.avatar-uploader-icon {
//  font-size: 28px;
//  color: #8c939d;
//  width: 148px;
//  height: 148px;
//  line-height: 148px;
//  text-align: center;
//}

.avatar-wrapper {
  width: 148px;
  height: 148px;
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
    object-fit: cover;
    cursor: pointer;
  }
}
</style>