<!-- src/pages/base/message/detail.vue -->
<template>
  <view class="message-detail-page" :class="{ 'readonly-mode': isReadOnly }">
    <!-- 提交遮罩层 -->
    <view v-if="isSubmitting" class="submit-overlay">
      <view class="submit-loading">
        <view class="loading-spinner"></view>
        <text class="loading-text">提交中...</text>
      </view>
    </view>
    
    <view v-if="isLoading" class="loading-indicator">加载中...</view>
    <view v-else class="detail-content">
      <view class="detail-header">
        <view class="title-tag-row">
          <text class="detail-title">{{ rw.rwmc }}</text>
        </view>
        <view v-if="isReadOnly" class="readonly-tip">
          <text class="tip-text">📖 只读模式 - 查看已提交的内容</text>
        </view>
        <view class="detail-meta">
          <text>{{ rw.rwkstime }}</text>
          <!--          <text>{{ messageDetail.timeAgo }}</text>-->
        </view>
      </view>
      <view class="detail-body">
        <BasicForm :schema="schema" v-model="formData" :disabled="isReadOnly">
        </BasicForm>
      </view>
      <view v-if="!isReadOnly" class="detail-footer">
        <button class="action-button" @click="saveRwZx" :disabled="isSubmitting">
          {{ isSubmitting ? '提交中...' : '提交' }}
        </button>
      </view>
    </view>
    <!--    <view v-else class="empty-state">消息详情未找到</view>-->
  </view>
</template>

<script lang="ts" setup>
import {ref, reactive} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import {rwFindInfoByRwId, rwflFindRwlxsByRwId, rwzxExecutedInfoByRwIdAndJsApi, rwzxSaveApi} from "@/api/base/server";
import {useForm} from "@/components/BasicForm/hooks/useForm";
import {navigateBack, showToast} from "@/utils/uniapp";
import {useUserStore} from "@/store/modules/user";
import { ImageVideoUpload, type FileItem, COMPRESS_PRESETS } from "@/components/ImageVideoUpload";
import { attachmentUpload } from "@/api/system/upload";

interface MessageDetail {
  id: string; // Assuming an ID is passed or can be derived
  title: string;
  desc: string;
  date: string;
  timeAgo: string;
  tagText: string;
  tagType: string;
  // Add other fields as necessary
}

const formData: any = ref({})
const messageId = ref<string>('');
const jsId = ref<string>(''); // 教师ID
const executionId = ref<string>(''); // 执行ID
const isReadOnly = ref<boolean>(false); // 只读模式
const isSubmitting = ref<boolean>(false); // 提交状态
const submitTimer = ref<any>(null); // 防抖定时器

const messageDetail = ref<MessageDetail | null>({
  id: 'todo1',
  title: '教务通知 (待办)',
  desc: '学校召开期初教学准备会议暨首次教学工作例会. 会议强调了新学期的教学重点和要求，请各位老师认真准备。',
  date: '2025-02-17',
  timeAgo: '8 mins 前',
  tagText: '通知',
  tagType: 'notice',
  likes: 6,
  comments: 12
});
const isLoading = ref(false);
const rwflx: any = ref([])
const rw = ref<any>({})
const schema = ref<FormsSchema[]>([])
const {getUser} = useUserStore()

async function saveRwZx() {
  // 防抖处理
  if (isSubmitting.value) {
    console.log('正在提交中，请勿重复点击');
    return;
  }
  
  // 清除之前的定时器
  if (submitTimer.value) {
    clearTimeout(submitTimer.value);
  }
  
  // 设置防抖延迟
  submitTimer.value = setTimeout(async () => {
    await performSubmit();
  }, 300);
}

async function performSubmit() {
  if (isSubmitting.value) {
    return;
  }
  
  isSubmitting.value = true;
  
  try {
    const result = [];
    for (let i = 0; i < rwflx.value.length; i++) {
    const fieldId = rwflx.value[i].id;
    let fieldValue = formData.value[fieldId];
    
    // 处理上传类型的任务
    let fileNames = '';
    if (rwflx.value[i].rwfl == "sctp" || rwflx.value[i].rwfl == "scsp" || rwflx.value[i].rwfl == "scwd") {
      // 收集上传文件的URL和文件名
      const fileUrls = [];
      const names = [];
      
      if (rwflx.value[i].rwfl == "sctp") {
        // 图片上传
        const images = formData.value[`${fieldId}_imageList`] || [];
        images.forEach((img: any) => {
          if (img.url) {
            fileUrls.push(img.url);
            names.push(img.name || img.url.split('/').pop() || 'image.jpg');
          }
        });
      } else if (rwflx.value[i].rwfl == "scsp") {
        // 视频上传
        const videos = formData.value[`${fieldId}_videoList`] || [];
        videos.forEach((video: any) => {
          if (video.url) {
            fileUrls.push(video.url);
            names.push(video.name || video.url.split('/').pop() || 'video.mp4');
          }
        });
      } else if (rwflx.value[i].rwfl == "scwd") {
        // 文档上传
        const files = formData.value[`${fieldId}_fileList`] || [];
        files.forEach((file: any) => {
          if (file.url) {
            fileUrls.push(file.url);
            names.push(file.name || file.url.split('/').pop() || 'document');
          }
        });
      }
      
      fieldValue = fileUrls.join(',');
      fileNames = names.join(',');
    }
    
    
    // 验证必填项 - 针对上传类型使用不同的判断方式
    if (rwflx.value[i].rwbs) {
      let isEmpty = false;
      
      if (rwflx.value[i].rwfl == "sctp" || rwflx.value[i].rwfl == "scsp" || rwflx.value[i].rwfl == "scwd") {
        // 上传类型的验证：检查是否有上传的文件
        if (rwflx.value[i].rwfl == "sctp") {
          const images = formData.value[`${fieldId}_imageList`] || [];
          isEmpty = images.length === 0;
        } else if (rwflx.value[i].rwfl == "scsp") {
          const videos = formData.value[`${fieldId}_videoList`] || [];
          isEmpty = videos.length === 0;
        } else if (rwflx.value[i].rwfl == "scwd") {
          const files = formData.value[`${fieldId}_fileList`] || [];
          isEmpty = files.length === 0;
        }
      } else {
        // 非上传类型的验证：检查字段值是否为空
        isEmpty = !fieldValue || fieldValue == "";
      }
      
      if (isEmpty) {
        showToast("请填写必填项!")
        isSubmitting.value = false;
        return;
      }
    }
    // 查找对应的执行记录ID
    const existingRecord = rwzxqds.value.find(item => item.rwlxId === fieldId);
    const recordId = existingRecord ? existingRecord.id : undefined;
    
    result.push({
      id: recordId, // 如果有现有记录则保留ID，否则为undefined（新增）
      rwlxId: fieldId,
      rwzxqdtx: fieldValue,
      wjmc: fileNames || undefined, // 文件名，只有上传类型才有
    })
  }
  await rwzxSaveApi({
    id: executionId.value, // 执行记录ID，如果有的话就是更新，没有就是新增
    rwId: rw.value.id, // 任务ID
    rwzxfzr: jsId.value || getUser.id, // 执行人（教师ID）
    mobile: getUser.mobile, // 手机号
    rwzxqdDtos: result // 执行清单
  })
  showToast("操作成功!");
  
  // 延迟一下再跳转，让用户看到成功提示
  setTimeout(() => {
    // 直接跳转到课程详情页面
    uni.redirectTo({
      url: `/pages/view/routine/yishiyice/detail?kcjbId=${rw.value.rwlyId}&kcmc=${encodeURIComponent(rw.value.rwmc)}`,
      success: () => {
        console.log('跳转到课程详情页面成功');
      },
      fail: (error) => {
        console.error('跳转到课程详情页面失败:', error);
        // 如果跳转失败，回退到上一页
        uni.navigateBack({ delta: 1 });
      }
    });
  }, 1500);
  
  } catch (error) {
    console.error('提交失败:', error);
    showToast("提交失败，请重试");
  } finally {
    isSubmitting.value = false;
  }
}

const rwzxqds = ref<any[]>([])
onLoad(async (options: any) => {
  console.log('页面加载参数:', options);
  
  let taskId = '';
  
  // 从全局存储中获取参数数据
  const storedParams = uni.getStorageSync('taskSubmitData');
  
  if (storedParams) {
    try {
      taskId = storedParams.id;
      jsId.value = storedParams.jsId || '';
      executionId.value = storedParams.executionId || '';
      isReadOnly.value = storedParams.isReadOnly || false;
      console.log('从全局存储解析参数成功:', { taskId, jsId: jsId.value, executionId: executionId.value, isReadOnly: isReadOnly.value });
      
      // 清除存储的参数数据
      uni.removeStorageSync('taskSubmitData');
    } catch (error) {
      console.error('解析全局存储参数失败:', error);
      taskId = options.id || '';
    }
  } else {
    // 兼容原有的URL参数方式（向后兼容）
    if (options && options.params) {
      try {
        const params = JSON.parse(decodeURIComponent(options.params));
        taskId = params.id;
        jsId.value = params.jsId || '';
        executionId.value = params.executionId || '';
        isReadOnly.value = params.isReadOnly || false;
        console.log('解析URL参数成功:', { taskId, jsId: jsId.value, executionId: executionId.value, isReadOnly: isReadOnly.value });
      } catch (error) {
        console.error('解析URL参数失败:', error);
        taskId = options.id || '';
      }
    } else if (options && options.id) {
      taskId = options.id;
    }
  }
  
  if (taskId) {
    const {result} = await rwFindInfoByRwId({
      rwId: taskId
    });
    rwflx.value = result.rwlxes;
    rw.value = result;
    for (let i = 0; i < rwflx.value.length; i++) {
      // 处理上传类型的任务
      if (rwflx.value[i].rwfl == "sctp" || rwflx.value[i].rwfl == "scsp" || rwflx.value[i].rwfl == "scwd") {
        // 初始化表单数据
        const fieldId = rwflx.value[i].id;
        if (rwflx.value[i].rwfl == "sctp") {
          formData.value[`${fieldId}_imageList`] = [];
        } else if (rwflx.value[i].rwfl == "scsp") {
          formData.value[`${fieldId}_videoList`] = [];
        } else if (rwflx.value[i].rwfl == "scwd") {
          formData.value[`${fieldId}_fileList`] = [];
        }
        // 根据任务类型配置上传组件
        let componentConfig = {};
        
        if (rwflx.value[i].rwfl == "sctp") {
          // 上传图片
          componentConfig = {
            component: "ImageVideoUpload",
            componentProps: {
              enableImage: true,
              enableVideo: false,
              enableFile: false,
              maxImageCount: 30,
              uploadApi: attachmentUpload,
              compressConfig: COMPRESS_PRESETS.medium,
              imageList: formData.value[`${fieldId}_imageList`] || []
            }
          };
        } else if (rwflx.value[i].rwfl == "scsp") {
          // 上传视频
          componentConfig = {
            component: "ImageVideoUpload",
            componentProps: {
              enableImage: false,
              enableVideo: true,
              enableFile: false,
              maxVideoCount: 30,
              uploadApi: attachmentUpload,
              compressConfig: COMPRESS_PRESETS.medium,
              videoList: formData.value[`${fieldId}_videoList`] || []
            }
          };
        } else if (rwflx.value[i].rwfl == "scwd") {
          // 上传文档
          componentConfig = {
            component: "ImageVideoUpload",
            componentProps: {
              enableImage: false,
              enableVideo: false,
              enableFile: true,
              maxFileCount: 30,
              allowedFileTypes: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'mp3', 'wav', 'zip', 'rar'],
              uploadApi: attachmentUpload,
              compressConfig: COMPRESS_PRESETS.medium,
              fileList: formData.value[`${fieldId}_fileList`] || []
            }
          };
        }
        
        // 对于上传类型，使用特殊的字段名
        const schemaField = rwflx.value[i].rwfl === "sctp" ? `${rwflx.value[i].id}_imageList` :
                           rwflx.value[i].rwfl === "scsp" ? `${rwflx.value[i].id}_videoList` :
                           rwflx.value[i].rwfl === "scwd" ? `${rwflx.value[i].id}_fileList` :
                           `${rwflx.value[i].id}`;
        
        schema.value.push({
          field: schemaField,
          label: `${rwflx.value[i].rwbt}`,
          required: rwflx.value[i].rwbs && !isReadOnly.value, // 只读模式下不要求必填
          itemProps: {
            labelPosition: "top",
          },
          ...componentConfig,
          componentProps: {
            ...componentConfig.componentProps,
            disabled: isReadOnly.value // 禁用上传组件
          }
        })
      } else if (rwflx.value[i].rwfl == "text") {
        schema.value.push({
          field: `${rwflx.value[i].id}`,
          label: `${rwflx.value[i].rwbt}`,
          component: "BasicInput",
          required: rwflx.value[i].rwbs && !isReadOnly.value, // 只读模式下不要求必填
          itemProps: {
            labelPosition: "top",
          },
          componentProps: {
            type: "textarea",
            placeholder: isReadOnly.value ? "" : "请输入内容",
            disabled: isReadOnly.value // 禁用文本输入
          },
        })
      } else if (rwflx.value[i].rwfl == "dxsx" || rwflx.value[i].rwfl == "dxxz") {
        let options = rwflx.value[i].remark.split("；");
        let range = [];
        for (let j = 0; j < options.length; j++) {
          range.push({
            name: options[j]
          });
        }
        schema.value.push({
          field: `${rwflx.value[i].id}`,
          label: `${rwflx.value[i].rwbt}`,
          component: "BasicPicker",
          required: rwflx.value[i].rwbs && !isReadOnly.value, // 只读模式下不要求必填
          itemProps: {
            labelPosition: "top",
          },
          componentProps: {
            range: range,
            rangeKey: "name",
            savaKey: "name",
            disabled: isReadOnly.value // 禁用选择器
          },
        })
      }
    }
    
    
    const res = await rwzxExecutedInfoByRwIdAndJsApi({
      rwId: taskId,
      jsId: jsId.value || getUser.id // 使用传入的jsId，如果没有则使用当前用户ID
    });
    if (res && res.result && res.result.length) {
      rwzxqds.value = res.result;
      const showData = {};
      
      for (let i = 0; i < rwzxqds.value.length; i++) {
        const record = rwzxqds.value[i];
        const rwlxId = record.rwlxId;
        const rwzxqdtx = record.rwzxqdtx;
        
        // 查找对应的任务类型
        const taskType = rwflx.value.find(item => item.id === rwlxId);
        
        if (taskType) {
          if (taskType.rwfl === "sctp") {
            // 图片上传类型 - 解析URL和文件名并创建图片对象
            if (rwzxqdtx) {
              const urls = rwzxqdtx.split(',').filter(Boolean);
              const names = record.wjmc ? record.wjmc.split(',').filter(Boolean) : [];
              const images = urls.map((url, index) => ({
                url: url.trim(),
                name: names[index] || url.split('/').pop() || 'image.jpg',
                tempPath: undefined
              }));
              showData[`${rwlxId}_imageList`] = images;
            }
          } else if (taskType.rwfl === "scsp") {
            // 视频上传类型
            if (rwzxqdtx) {
              const urls = rwzxqdtx.split(',').filter(Boolean);
              const names = record.wjmc ? record.wjmc.split(',').filter(Boolean) : [];
              const videos = urls.map((url, index) => ({
                url: url.trim(),
                name: names[index] || url.split('/').pop() || 'video.mp4',
                tempPath: undefined
              }));
              showData[`${rwlxId}_videoList`] = videos;
            }
          } else if (taskType.rwfl === "scwd") {
            // 文档上传类型
            if (rwzxqdtx) {
              const urls = rwzxqdtx.split(',').filter(Boolean);
              const names = record.wjmc ? record.wjmc.split(',').filter(Boolean) : [];
              const files = urls.map((url, index) => ({
                url: url.trim(),
                name: names[index] || url.split('/').pop() || 'document',
                tempPath: undefined,
                type: 'document',
                extension: url.split('.').pop() || ''
              }));
              showData[`${rwlxId}_fileList`] = files;
            }
          } else {
            // 文本等其他类型
            showData[rwlxId] = rwzxqdtx;
          }
        }
      }
      
      // 合并已保存的数据，而不是完全覆盖
      formData.value = { ...formData.value, ...showData };
      
      // 更新 schema 中上传组件的初始值
      for (let i = 0; i < schema.value.length; i++) {
        const schemaItem = schema.value[i];
        if (schemaItem.component === "ImageVideoUpload" && schemaItem.field) {
          const fieldName = schemaItem.field;
          
          if (fieldName.includes('_imageList') && formData.value[fieldName]) {
            schemaItem.componentProps.imageList = formData.value[fieldName];
          } else if (fieldName.includes('_videoList') && formData.value[fieldName]) {
            schemaItem.componentProps.videoList = formData.value[fieldName];
          } else if (fieldName.includes('_fileList') && formData.value[fieldName]) {
            schemaItem.componentProps.fileList = formData.value[fieldName];
          }
        }
      }
      
      // 调试：输出回显数据
      console.log('数据回显 - showData:', showData);
      console.log('数据回显 - formData.value:', formData.value);
      console.log('更新后的 schema:', schema.value);
      
      // 调试：输出文件名处理情况
      console.log('文件名处理 - rwzxqds.value:', rwzxqds.value);
    }
  } else {
    console.error('Message ID/Data is missing!');
    uni.showToast({title: '加载失败，缺少信息', icon: 'none'});
  }
});
</script>

<style scoped lang="scss">
.message-detail-page {
  background-color: #f4f5f7;
  min-height: 100vh;
  padding: 15px;
  box-sizing: border-box;
}

.loading-indicator,
.empty-state {
  text-align: center;
  color: #999;
  padding: 40px 15px;
  font-size: 14px;
}

.detail-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.detail-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
  margin-bottom: 20px;

  .title-tag-row {
    display: flex;
    justify-content: space-between;
    align-items: flex-start; // Align items to the top
    margin-bottom: 10px;
  }

  .detail-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    flex: 1; // Allow title to take available space
    margin-right: 10px; // Space between title and tag
    line-height: 1.4;
    text-align: center; // 居中显示
  }

  .tag { // Reuse tag styles from index page if possible, or define here
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: bold;
    color: #ffffff;
    white-space: nowrap;
    flex-shrink: 0; // Prevent tag from shrinking

    &.notice {
      background-color: #447ade;
    }

    &.task {
      background-color: #19be6b;
    }

    &.approval {
      background-color: #ff9f0a;
    }

    &.submit {
      background-color: #8e8e93;
    }
  }


  .readonly-tip {
    margin: 8px 0;
    padding: 8px 12px;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    border-radius: 4px;
    
    .tip-text {
      font-size: 12px;
      color: #1890ff;
    }
  }

  .detail-meta {
    font-size: 12px;
    color: #999;

    text {
      margin-right: 15px;
    }
  }
}

.detail-body {
  margin-bottom: 40px;

  .detail-desc {
    font-size: 15px;
    color: #555;
    line-height: 1.7;
    word-break: break-word;
  }
}

.detail-footer {
  // text-align: center; // Removed center alignment
  // Add margin if needed, e.g., margin-top: 20px;
}

// Style for the action button
.action-button {
  width: 100%; // Make button full width
  height: 44px; // Standard button height
  line-height: 44px; // Match height for vertical centering
  font-size: 16px; // Slightly larger font
  font-weight: 500; // Medium weight
  border-radius: 8px; // Consistent border radius
  margin-top: 20px; // Add space above the button
  background-color: #1890ff; // 蓝色背景
  color: #ffffff; // 白色文字
  border: none; // 移除边框
  
  &:active:not(:disabled) {
    background-color: #1976d2; // 点击时的深蓝色
  }
  
  &:disabled {
    background-color: #d9d9d9;
    color: #999;
    cursor: not-allowed;
    opacity: 0.6;
  }
}

// 为输入框添加基本边框（参考原生 textFiled 样式）
:deep(.uni-input),
:deep(.uni-textarea) {
  width: 100% !important;
  min-height: 35px !important;
  font-size: 13px !important;
  border: 1px #CCCCCC solid !important;
  border-radius: 3px !important;
  padding: 8px 12px !important;
  box-sizing: border-box !important;
}

// 为 BasicForm 组件内的输入框添加边框
:deep(.basic-form) {
  .uni-input,
  .uni-textarea {
    width: 100% !important;
    min-height: 35px !important;
    font-size: 13px !important;
    border: 1px #CCCCCC solid !important;
    border-radius: 3px !important;
    padding: 8px 12px !important;
    box-sizing: border-box !important;
  }
}

// 尝试直接选择 input 和 textarea 标签
:deep(input),
:deep(textarea) {
  width: 100% !important;
  min-height: 35px !important;
  font-size: 13px !important;
  border: 1px #CCCCCC solid !important;
  border-radius: 3px !important;
  padding: 8px 12px !important;
  box-sizing: border-box !important;
}

// 只读模式样式
.readonly-mode {
  :deep(input),
  :deep(textarea),
  :deep(.uni-input),
  :deep(.uni-textarea) {
    background-color: #f5f5f5 !important;
    color: #666 !important;
    cursor: not-allowed !important;
  }
  
  :deep(.upload-container),
  :deep(.picker-container) {
    opacity: 0.6;
    pointer-events: none;
  }
}

// 提交遮罩层样式
.submit-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.submit-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

</style>
