<script lang="ts" setup>
  import { saveTrainingInformation, updateTrainingInformation, queryEducationTrainingPlanCourseDetail } from '@/api/production-education-training-plan-dept';
  import { ref, reactive, onMounted, watch, shallowRef, computed, nextTick } from 'vue';
  import { UploadFilled, Plus, Delete, Download, ZoomIn } from '@element-plus/icons-vue';
  import { TRAINING_FORM_RULES } from '../configs/form';
  import { queryUserGroupPage } from '@/api/system/person-group';
  import type { FileItem } from '@/components/UploadFiles/types';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  // @ts-ignore: missing type declarations for CSS side-effect import
  import '@wangeditor/editor/dist/css/style.css';
  import { ElMessage, UploadRawFile } from 'element-plus';
  import { unformatAttachment, formatAttachmentList } from '@/components/UploadFiles/utils';
  import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';

  import { debounce } from 'lodash-es';
  const props = defineProps({
    state: {
      type: String,
      default: 'add', // add: 新增, edit: 编辑
    },
    visible: {
      type: Boolean,
      default: false,
    },
    currentId: {
      type: [String, Number],
      default: null,
    },
  });
  
  const isViewMode = computed(() => props.state === 'view');
  const isEditMode = computed(() => props.state === 'edit');
  const isCreateMode = computed(() => props.state === 'add');

  const emit = defineEmits(['update:visible', 'refreshList', 'saveSuccess']);
  const formRef = ref();
  const rules = ref(TRAINING_FORM_RULES);
 
  const form = reactive({
    courseType: '',
    courseName: '',
    trainingMethod: '',
    trainingTeacher: '',
    planNumOfParticipants: '',
    groupOfParticipants: [],
    startDate: '',
    endDate: '',
    courseIntroduction: '',
    courseContent: [] as FileItem[],
    isSign: 0,
    courseImg: [] as FileItem[],
  });
  const fileList = ref<FileItem[]>([]);
  const fileInfo = ref<any>(null);

  const categoryOptions = ref([
    { label: '入院三级安全教育', value: 1 },
    { label: '安全生产继续教育', value: 2 },
    { label: '特种作业培训考核', value: 3 },
    { label: '特种作业复训考核', value: 4 },
  ]);

   // 上传文件
 const formatAttachment = async (data: any) => {
    if (!data) return data;
    const uuid = Math.random().toString(36).substring(2, 9);
    const timestamp = Date.now().toString();
    const random = Math.random().toString(36).substring(2, 4);
    const fileName = data.name;
    const res = await uploadFileApi({
        bizType: UPLOAD_BIZ_TYPE.ATTACHMENT,
        fileName: `${uuid}-${timestamp}-${random}`,
        file: data,
    });
    const fileType = data.fileType;
    const fileSize = data.fileSize;
    const fileId = data.fileId;
    const fileUrl = res.url;
    return {
        fileName,
        fileType,
        fileSize,
        fileUrl,
        fileId,
    };
};
const openState = ref(false)
  // 打开抽屉时的事件
  const openDrawerFn = async () => {
    await nextTick();
    if ((props.state === 'edit' || props.state === 'view') && props.currentId) {
      // 编辑/查看模式，加载现有详情数据
      // 这里可以调用接口获取当前培训课程的信息，并填充到 form 中
      await queryEducationTrainingPlanCourseDetail(props.currentId).then((res) => {
        console.log(res, '课程详情',);
        Object.assign(form, {
            courseType: res.courseType,
            courseName: res.courseName,
            trainingMethod: res.trainingMethod,
            trainingTeacher: res.trainingTeacher,
            planNumOfParticipants: res.planNumOfParticipants,
            startDate: res.startDate ? new Date(res.startDate) : '',
            endDate: res.endDate ? new Date(res.endDate) : '',
            courseIntroduction: res.courseIntroduction,
            isSign: res.isSign,
        }); 
        form.groupOfParticipants = res.groupOfParticipants ? res.groupOfParticipants.split(',').map(Number) : [];
        // 编辑和查看时 没有回显
        if(res.courseImg){
            form.courseImg = [JSON.parse(res.courseImg)]
        }
        if(res.courseContent){
            // handleFileExceed(JSON.parse(res.courseContent))
            // fileList.value =  JSON.parse(res.courseContent) || [];
            form.courseContent = res.courseContent
        }
      });
    } else if (props.state === 'add') {
        // 新增模式，重置表单
        fileList.value = [];
        Object.assign(form, {
          courseType: '',
          courseName: '',
          trainingMethod: '',
          trainingTeacher: '',
          planNumOfParticipants: '',
          groupOfParticipants: [],
          startDate: '',
          endDate: '',
          courseIntroduction: '',
          courseContent: [] as FileItem[],
          isSign: 0,
          courseImg: [] as FileItem[],
        });
        courseContentUpload.value?.clearFiles();
        courseImgRef.value?.clearFiles();
    }
  };
  


  // 富文本编辑器
  const editorRef = shallowRef();
  const editorConfig = computed(() => ({
    placeholder: '请输入培训课程简述',
    MENU_CONF: {},
  }));

  const handleEditorChange = () => {
    // 编辑器内容变化时的处理
  };
  const handleEditorCreated = (editor: any) => {
    editorRef.value = editor;
  };

  //  上传图片
  const handleImageUploadChange = async (uploadFile: any, uploadFiles: any) => {
    form.courseImg = uploadFiles;
    if(uploadFile.raw){
        let res = await formatAttachment(uploadFile.raw)
        console.log(res, '图片上传')
        if(res){
            ElMessage.success('上传成功')
        }
    }
  };
  // 替换图片
  const courseImgRef = ref();
  const handleImageExceed = (files) => {
    courseImgRef.value!.clearFiles(); 
    const file = files[0] as UploadRawFile;
    console.log(file)
    if (!validateImage(file)) {
      return;
    }
    courseImgRef.value!.handleStart(file); 
  };
// 图片预览
  const dialogVisible = ref(false);
  const dialogImageUrl = ref('');
  const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
  };

// 图片格式校验
  const validateImage = (file) => {
    const validMIME = [
      'image/jpeg',
      'image/png',
      'image/gif',
      'image/bmp',
      'image/webp',
      'image/svg+xml',
      'image/tiff',
      'image/heic',
      'image/heif',
      'image/avif',
    ];

    if (!validMIME.includes(file.type)) {
      ElMessage.error('仅支持图片文件（JPEG/PNG/GIF/BMP/WEBP/SVG/TIFF/HEIC/AVIF等）');
      return false;
    }

    if (!validMIME.includes(file.type)) {
      ElMessage.error('仅支持JPG/PNG格式图片');
      return false; // 阻止上传
    }

    // 可选：添加文件大小限制
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
      ElMessage.error('图片大小不能超过5MB');
      return false;
    }

    return true; // 验证通过
  };

  // 验证文件类型
    const allowedTypes = [
      'application/rar',
      'application/zip',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/pdf',
      'video/mp4',
    ];

  const beforeUpload = (file) => {
    const isAllowedType = allowedTypes.includes(file.type);
    const isLt20M = file.size / 1024 / 1024 < 20;

    if (!isAllowedType) {
      ElMessage.error('上传文件格式不正确!');
    }
    if (!isLt20M) {
      ElMessage.error('上传文件大小不能超过20MB!');
    }

    return isAllowedType && isLt20M;
  };
  // 文件选择更新
  const courseContentUpload = ref();
  const handleFileExceed = (files) => {
    courseContentUpload.value!.clearFiles(); // 清空文件列表
    const file = files[0] as UploadRawFile;
    if (!beforeUpload(file)) {
      return;
    }
    courseContentUpload.value!.handleStart(file); // 手动触发上传
  };


  // 课程内容文件上传
  const handleFileChange = async (file, fileList) => {
    

    if (!allowedTypes.includes(file.raw.type)) {
      ElMessage.error('不支持的文件格式');
      return;
    }

    if (file.raw.size > 20 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过20MB');
      return;
    }
    
    if(file.raw){
        let res = await formatAttachment(file.raw)
        console.log(res, '文件上传')
        if(res){
            ElMessage.success('上传成功')
        }
    }
    // 直接替换为新文件
    fileList.value = [file.raw]; 
    form.courseContent = file; // 更新表单数据
  };

  // 提交保存/编辑
  const handleValidate = async () => {
    if (!formRef.value) return;
    try {
        await formRef.value.validate();
        return true;
    } catch {
        return false;
    }
  };
  const handleSave = debounce(async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      const basePayload = {
        ...form,
        petpiId: props.currentId,
        courseImg: form.courseImg[0],
      };
      console.log('提交的表单数据：', basePayload);
      
      if (isCreateMode.value) {
        // 新增,创建接口
        await saveTrainingInformation(basePayload);
        ElMessage.success('创建成功');

      } else if (isEditMode.value && props.currentId) {
        // 编辑,更新接口
        await updateTrainingInformation({
          id: props.currentId,
          ...basePayload,
        });
        ElMessage.success('保存成功');

      }
      emit('saveSuccess');
    } catch (e) {
      ElMessage.error('保存失败，请重试');
      emit('update:visible', false);
    }
  }, 1000);

  const groupList = ref<any>([]);
  // 获取级联部门分组数据
  const loadGroupTreeData = async () => {
    queryUserGroupPage({
      pageNumber: 1,
      pageSize: 500,
    }).then((res) => {
      groupList.value = res.records;
    });
  };
  onMounted(() => {
    loadGroupTreeData();
  });
</script>

<template>
  <div class="training-course">
    <el-drawer
      :model-value="props.visible"
      @update:model-value="$emit('update:visible', $event)"
      direction="rtl"
      size="45%"
      @opened="openDrawerFn"
      :title="state === 'add' ? '新增培训课程': state === 'edit' ? '编辑培训课程' : '查看培训课程'"
      @close="$emit('update:visible', false)"
    >
      <el-form label-position="right" label-width="150px" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="课程所属类别：" prop="courseType">
          <el-select v-model="form.courseType" placeholder="请选择课程所属类别，单选" clearable :disabled="isViewMode">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="培训课程名称：" prop="courseName">
          <el-input v-model="form.courseName" placeholder="输入课程名称" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="培训方式：" prop="trainingMethod">
          <el-input v-model="form.trainingMethod" placeholder="输入培训方式" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="培训课程讲师：" prop="trainingTeacher">
          <el-input v-model="form.trainingTeacher" placeholder="输入培训课程讲师" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="计划参与人数：" prop="planNumOfParticipants">
          <el-input v-model.number="form.planNumOfParticipants" placeholder="输入计划参与人数" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="参与人员分组：" prop="groupOfParticipants">
          <el-select
            v-model="form.groupOfParticipants"
            multiple
            filterable
            placeholder="请选择培训责任部门责任人所在分组，多选"
            clearable
            :disabled="isViewMode"
          >
            <el-option v-for="group in groupList" :key="group.id" :label="group.name" :value="group.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="培训开始日期：" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            style="width: 100%"
            type="date"
            placeholder="选择计划开始日期"
            :disabled="isViewMode"
          />
        </el-form-item>

        <el-form-item label="培训结束日期：" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            style="width: 100%"
            type="date"
            placeholder="选择计划结束日期"
            :disabled="isViewMode"
          />
        </el-form-item>

        <el-form-item label="培训课程简述：" prop="courseIntroduction">
          <div class="editor-container">
            <Toolbar style="border-bottom: 1px solid #dcdfe6" :editor="editorRef" />
            <Editor
              style="height: 400px; overflow-y: auto"
              v-model="form.courseIntroduction"
              mode="disabled"
              :disabled="isViewMode"
              :defaultConfig="editorConfig"
              @on-created="handleEditorCreated"
              @on-change="handleEditorChange"
            />
          </div>
        </el-form-item>

        <el-form-item label="课程内容：" prop="courseContent">
          <el-upload
            action=""
            ref="courseContentUpload"
            :auto-upload="false"
            :disabled="isViewMode"
            :on-change="handleFileChange"
            accept=".rar, .zip, .doc, .docx, .pdf, .mp4"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleFileExceed"
          >
            <el-button type="default" :disabled="isViewMode">
              <el-icon style="margin-right: 6px">
                <UploadFilled />
              </el-icon>
              选择附件
            </el-button>
            <template #tip>
              <div class="el-upload__tip"> 支持格式：.rar .zip .doc .docx .pdf .mp4，单个文件不能超过20MB </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="是否需要签名：" prop="isSign">
          <el-radio-group v-model="form.isSign" :disabled="isViewMode">
            <el-radio label="是" :value="1"></el-radio>
            <el-radio label="否" :value="0"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="课程图片：" prop="courseImg">
          <el-upload
            class="image-uploader"
            ref="courseImgRef"
            action="#"
            :file-list="form.courseImg"
            :disabled="isViewMode"
            :auto-upload="false"
            :limit="1"
            accept="image/*"
            :on-change="handleImageUploadChange"
            :on-exceed="handleImageExceed"
            :before-upload="validateImage"
            list-type="picture-card"
          >
            <el-icon>
              <Plus />
            </el-icon>

            <template #tip>
              <div class="el-upload__tip"> 支持格式：.jpg .png .jpeg，单个文件不能超过300k，设置一个默认图片。</div>
            </template>
            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail courseImg" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon><zoom-in /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;" />
          </el-dialog>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="$emit('update:visible', false)">取消</el-button>
          <el-button type="primary" @click="handleSave" v-if="!isViewMode">
            {{ isEditMode ? '保存' : '新增' }}
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
  .image-uploader {
    :deep(.el-upload--picture-card) {
      width: 80px !important;
      height: 80px !important;
      line-height: 80px;
    }

    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 80px !important;
      height: 80px !important;
    }
  }

  .editor-container {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    z-index: 1000;

    :deep(.w-e-text-placeholder) {
      font-style: normal;
    }
  }

  .el-upload__tip {
    line-height: 1.5;
  }

  .file-info {
    margin-top: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
  :deep(.el-upload-list__item) {
    // margin: 10px 0;
    border-radius: 8px;
    border: 1px solid #e1e1e1;
    background-color: #f9fafb;
  }
  :deep(.el-upload-list__item .el-icon--close) {
    display: inline-block !important;
    opacity: 1 !important;
  }
  .courseImg {
    width: 78px;
    height: 78px;
    object-fit: cover;
    border-radius: 4px;
  }
  pre {
    white-space: pre-wrap;
  }
</style>
