<script lang="ts" setup>
  import { saveTrainingInformation, updateTrainingInformation } from '@/api/production-education-training-plan-dept';
  import { ref, reactive, onMounted, watch, shallowRef, computed } from 'vue';
  import { UploadFilled, Plus } 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 } from 'element-plus';

  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 = ref(props.state === 'view');
  const isEditMode = ref(props.state === 'edit');
  const isCreateMode = ref(props.state === 'add');

  const emit = defineEmits(['update:visible', 'refreshList']);
  const formRef = ref();
  const rules = ref(TRAINING_FORM_RULES);

  const form = reactive({
    courseType: '',
    courseName: '',
    trainingMethod: '',
    trainingTeacher: '',
    planNumOfParticipants: null,
    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 handleValidate = async () => {
    if (!formRef.value) return;
    const res = await formRef.value.validateField();
    return res;
  };
  const handleSave = debounce(async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      const basePayload = {
        ...form,
        // responsibleDeptIds: form.responsibleDeptIds.toString()
      };

      if (isCreateMode.value) {
        // await saveTrainingInformation(basePayload);
        ElMessage.success('创建成功');
      } else if (isEditMode.value && props.currentId) {
        // await updateTrainingInformation({
        //     id: props.currentId,
        //     ...basePayload,
        // });
        ElMessage.success('保存成功');
      }
    } catch (e) {
      ElMessage.error('保存失败，请重试');
    }
    emit('update:visible', false);
  }, 1000);
  // const handleSave = () => {

  //     // 简单验证，可以根据需要添加更多验证逻辑
  //     if (!form.courseName || !form.courseType) {
  //         ElMessage.error('请填写完整信息');
  //         return;
  //     }
  //     emit('refreshList', { ...form }); // 传递表单数据，可以根据实际需求调整
  //     emit('update:visible', false);
  // };
  // 富文本编辑器
  const editorRef = shallowRef();
  const editorConfig = computed(() => ({
    placeholder: '请输入培训课程简述',
    MENU_CONF: {},
  }));

  const beforeUpload = (file) => {
    const isAllowedType = [
      'application/rar',
      'application/zip',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/pdf',
      'video/mp4',
    ].includes(file.type);
    const isLt20M = file.size / 1024 / 1024 < 20;

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

  const handleExceed = () => {
    ElMessage.warning('只能上传一个文件，请先删除当前文件再上传!');
  };

  const handleEditorCreated = (editor: any) => {
    editorRef.value = editor;
  };

  const handleEditorChange = () => {
    // 编辑器内容变化时的处理
  };
  const handleImageUploadSuccess = (response: any, file: any, fileList: any[]) => {};

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

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

    // 验证文件大小
    if (file.raw.size > 20 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过20MB');
      return;
    }
    console.log('选择的文件：', file.raw);
    fileList.value = [file.raw];
    // 生成文件信息JSON
    fileInfo.value = {
      fileName: file.raw.name,
      fileSize: `${(file.raw.size / (1024 * 1024)).toFixed(2)} MB`,
      fileType: file.raw.type,
      lastModified: new Date(file.raw.lastModified).toLocaleString(),
      rawFile: file.raw, // 包含更多原始文件信息
    };
  };

  const handleImageRemove = (file: any, fileList: any[]) => {};

  // 文件上传
  const handleUploadSuccess = (files: FileItem[]) => {
    console.log('上传成功的文件列表：', files);
    form.courseImg = files;
  };

  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
      v-model="props.visible"
      direction="rtl"
      size="45%"
      :title="state === 'add' ? '新增培训课程' : '编辑培训课程'"
      @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
            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="default"
              :defaultConfig="editorConfig"
              @on-created="handleEditorCreated"
              @on-change="handleEditorChange"
            />
          </div>
        </el-form-item>

        <el-form-item label="课程内容：" prop="courseContent">
          <!-- <UploadFiles label="上传文件" :maxCount="1" :file-list="form.courseImg" :disabled="isViewMode"
                        accept=".rar,.zip,.doc,.docx,.pdf,.mp4" desc="支持格式：.rar .zip .doc .docx .pdf .mp4 ，单个文件不能超过20MB"
                        :allow-all-file-types="true" @uploadSuccess="handleUploadSuccess" /> -->

          <!-- <el-upload action="https://jsonplaceholder.typicode.com/posts/" :on-exceed="handleExceed"
                        :before-upload="beforeUpload" :file-list="fileList" :limit="1"
                        accept=".rar, .zip, .doc, .docx, .pdf, .mp4">
                        <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-upload
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".rar, .zip, .doc, .docx, .pdf, .mp4"
            :file-list="fileList"
            :limit="1"
          >
            <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>

          <!-- 显示文件信息 -->
          <div v-if="fileInfo" class="file-info">
            <h3>文件信息：</h3>
            <pre>{{ fileInfo }}</pre>
          </div>
        </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"
            action="/api/admin/minio/uploadFile"
            :file-list="form.courseContent"
            :disabled="isViewMode"
            :limit="5"
            :on-success="handleImageUploadSuccess"
            :on-remove="handleImageRemove"
            list-type="picture-card"
          >
            <el-icon>
              <Plus />
            </el-icon>

            <template #tip>
              <div class="el-upload__tip"> 支持格式：.jpg .png .jpeg，单个文件不能超过300k，设置一个默认图片。 </div>
            </template>
          </el-upload>
        </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;
  }

  pre {
    white-space: pre-wrap;
  }
</style>
