<template>
  <main class="safety-platform-container__main">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig">
      <template #fileUrl>
        <!-- <UploadFiles label="上传文件" :maxCount="1" :file-list="ruleFormData.attachmentUrl" :disabled="isViewMode"
          :allow-all-file-types="true" @uploadSuccess="handleUploadSuccess" /> -->
          <UploadFiles
            v-if="!isViewMode"
            label="上传文件"
            :maxCount="1"
            :file-list="ruleFormData.attachmentUrl"
            :disabled="isViewMode"
            :allow-all-file-types="true"
            @uploadSuccess="(list: FileItem[]) => handleUploadSuccess(list)"
          />
          <div class="file-list" v-else>
            <div class="file-item" v-for="file in ruleFormData.attachmentUrl" :key="file.fileId">
              <span class="file-item--name">{{ file.fileName }}</span>
              <div class="file-item--footer">
                <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                  >预览</el-button
                >
                <!-- <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                  >下载</el-button
                > -->
              </div>
            </div>
          </div>
      </template>
      <template #imageFileUrl>
        <el-upload
          :key="approvalUploadKey"
          ref="approvalUploadRef"
          v-model:file-list="approvalImageFileList"
          :auto-upload="false"
          list-type="picture-card"
          :limit="1"
          :disabled="isViewMode"
          :on-change="handleApprovalImageChange"
          :on-exceed="handleApprovalImageExceed"
          :on-preview="handleApprovalPictureCardPreview"
          :on-remove="handleApprovalImageRemove"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }"> 
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.fileUrl" alt="" />
              <span class="el-upload-list__item-actions" v-if="!isViewMode">
                <span class="el-upload-list__item-preview" @click="handleApprovalPictureCardPreview(file)">
                  <el-icon><ZoomIn /></el-icon>
                </span>
                <span class="el-upload-list__item-delete" @click.stop="handleApprovalDeleteClick()">
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </template>
      <template #content>
        <div class="editor-container">
          <Toolbar style="border-bottom: 1px solid #dcdfe6" :editor="editorRef" />
          <Editor style="height: 400px; overflow-y: auto" v-model="ruleFormData.description" mode="default"
            :defaultConfig="editorConfig" @on-created="handleEditorCreated" @on-change="handleEditorChange" />
        </div>
      </template>
      <template #status>
        <el-radio-group v-model="ruleFormData.status" :disabled="isViewMode"> 
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="2">禁用</el-radio>
        </el-radio-group>
      </template>
    </BasicForm>
    <PreviewOnline ref="previewOnlineRef" />
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isCreateMode ? '提交' : '保存' }}
    </el-button>
  </footer>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, shallowRef, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage , ElIcon, genFileId, type UploadProps, type UploadUserFile, type UploadRawFile, type UploadInstance } from 'element-plus';
import BasicForm from '@/components/BasicForm.vue';
import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { useFormConfigHook } from '@/hooks/useFormConfigHook';
import { ACADEMY_FILE_FORM_CONFIG, ACADEMY_FILE_FORM_DATA, ACADEMY_FILE_FORM_RULES } from '../configs/form';
import {
  queryAccidentCaseDetail,
  saveAccidentCase,
  updateAccidentCase,
  type newAccidentCases,
} from '@/api/safety-culture';
import type { FileItem } from '@/components/UploadFiles/types';
import { formatAttachmentList } from '@/components/UploadFiles/utils';
import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';
const router = useRouter();
const route = useRoute();
const approvalUploadKey = ref(0);
const operate = computed(() => (route.query.operate as string) || 'safety-culture-material-create');
const currentId = computed(() => Number(route.query.id));
const approvalImageFileList = ref<UploadUserFile[]>([]);
const isCreateMode = computed(() => operate.value === 'safety-culture-material-create');
const isEditMode = computed(() => operate.value === 'safety-culture-material-edit');
const isViewMode = computed(() => operate.value === 'safety-culture-material-view');
const approvalUploadRef = ref<UploadInstance>();
const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
import { Plus, Delete, ZoomIn } from '@element-plus/icons-vue';

const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData, beforeRouteLeave } =
  useFormConfigHook(ACADEMY_FILE_FORM_CONFIG, ACADEMY_FILE_FORM_DATA, ACADEMY_FILE_FORM_RULES);

const viewFormConfig = ref(
  ACADEMY_FILE_FORM_CONFIG.map((item) => ({
    ...item,
    componentProps: {
      ...item.componentProps,
      disabled: true,
    },
  })),
);

const computedFormConfig = computed(() => {
  if (isViewMode.value) {
    return viewFormConfig.value;
  }
  return ruleFormConfig.value;
});

const basicFormRef = ref<InstanceType<typeof BasicForm>>();

const editorRef = shallowRef();
const editorConfig = computed(() => ({
  placeholder: '请输入文档内容',
  MENU_CONF: {},
}));

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

const handleEditorChange = () => {
};


const handleUploadSuccess = (files) => {
  ruleFormData.attachmentUrl = files;
};



// 将逗号分隔的URL字符串转换为FileItem数组
const convertFileUrlToFileItems = (fileUrl: string): FileItem[] => {
  if (!fileUrl || !fileUrl.trim()) {
    return [];
  }
  
  // 按逗号分割URL
  const urls = fileUrl.split(',').map(url => url.trim()).filter(url => url);
  
  return urls.map((url, index) => {
    // 从URL中提取文件名
    const urlParts = url.split('/');
    const fileName = urlParts[urlParts.length - 1] || `附件${index + 1}`;
    
    // 根据文件扩展名判断文件类型
    const extension = fileName.split('.').pop()?.toLowerCase() || '';
    let fileType = 'pdf';
    if (extension === 'doc' || extension === 'docx') {
      fileType = 'word';
    } else if (extension === 'xls' || extension === 'xlsx') {
      fileType = 'excel';
    } else if (extension === 'ppt' || extension === 'pptx') {
      fileType = 'ppt';
    }
    
    return {
      fileId: Date.now() + index,
      fileName,
      fileType,
      fileSize: '0',
      fileUrl: url,
    };
  });
};

const handleValidate = async () => {
  if (!basicFormRef.value) return;
  const res = await basicFormRef.value.validateForm();
  return res;
};

const getDetail = async () => {
  if (!currentId.value) return;
  try {
    const res = await queryAccidentCaseDetail(currentId.value);
    if (res) {
      ruleFormData.caseName = res.caseName || '';
      ruleFormData.categoryName = res.categoryName || '';
      ruleFormData.status = res.status ?? 1;
      ruleFormData.description = res.description || '';
      ruleFormData.attachmentUrl = JSON.parse(res.attachmentUrl || res.fileUrl || '');
      approvalImageFileList.value = JSON.parse(res.imageUrl || '[]');
      ruleFormData.imageUrl = res.imageUrl || '';
    }
    cloneRuleFormData();
  } catch (e) {
    console.error('获取事故案例详情失败:', e);
    ElMessage.error('获取详情失败');
  }
};

const handleSubmit = async () => {
  const res = await handleValidate();
  if (!res) return;

  if (!ruleFormData.attachmentUrl || ruleFormData.attachmentUrl.length === 0) {
    ElMessage.warning('请上传文件');
    return;
  }

  console.log('ruleFormData', ruleFormData);

  try {
    const uploadedFileList = await formatAttachmentList(ruleFormData.attachmentUrl);

    const basePayload: newAccidentCases = {
      caseName: ruleFormData.caseName,
      categoryName: ruleFormData.categoryName,
      description: ruleFormData.description,
      attachmentUrl:JSON.stringify(uploadedFileList),
      status: ruleFormData.status,
      imageUrl: JSON.stringify(approvalImageFileList.value),
    };
    if (isCreateMode.value) {
      await saveAccidentCase(basePayload);
      ElMessage.success('创建成功');
    } else if (isEditMode.value && currentId.value) {
      await updateAccidentCase({
        id: currentId.value,
        ...basePayload,
      });
      ElMessage.success('保存成功');
    }

    router.back();
  } catch (e) {
    console.error('保存事故案例失败:', e);
    ElMessage.error('保存失败，请重试');
  }
};

const previewOnline = (url: string | undefined, type) => {
  if (url) {
    previewOnlineRef.value?.open(url, type);
  }
};

const handleApprovalImageChange = (uploadFile: UploadUserFile) => {
  if (!uploadFile.raw) return;

  uploadFileApi({
    file: uploadFile.raw,
    bizType: UPLOAD_BIZ_TYPE['DICTIONARY'],
    fileName: uploadFile.raw.name,
  })
    .then((res) => {
      ruleFormData.imageUrl = [res.url];
      approvalImageFileList.value = [
        {
          fileName: uploadFile.name || res.url.split('/').pop() || 'image',
          fileUrl: res.url,
          fileId: res.uid
        },
      ];
    })
    .catch(() => {
      ElMessage.error('图片上传失败，请重试');
    });
};


const handleApprovalImageExceed: UploadProps['onExceed'] = (files) => {
  const uploadInstance = approvalUploadRef.value;
  if (!uploadInstance) return;

  uploadInstance.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  uploadInstance.handleStart(file);
};

const handleApprovalPictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  // dialogImageUrl.value = uploadFile.url || '';
  // dialogVisible.value = true;
};

const resetApprovalImageUpload = () => {
  approvalUploadRef.value?.clearFiles();
  ruleFormData.imageUrl = [];
  approvalImageFileList.value = [];
  approvalUploadKey.value += 1;
};

const handleApprovalDeleteClick = () => {
  resetApprovalImageUpload();
};

const handleApprovalImageRemove: UploadProps['onRemove'] = () => {
  resetApprovalImageUpload();
};

onMounted(() => {
  cloneRuleFormData();
  // beforeRouteLeave();
  if (isEditMode.value || isViewMode.value) {
    getDetail();
  }
});

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style scoped lang="scss">
@use '@/styles/page-details-layout.scss' as *;

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

.content-display {
  min-height: 200px;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.file-display {
  .file-link {
    color: #409eff;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.no-file {
  color: rgba(0, 0, 0, 0.65);
}

.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;
  }
}
</style>

<style lang="scss">
.w-e-full-screen-container {
  inset: 0 !important;
  z-index: 3000 !important;
}

.w-e-full-screen-container .w-e-text-container {
  height: calc(100vh - 42px) !important;
}
</style>
