<template>
  <div style="padding: 5px;flex: 1">
    <div>
      <van-uploader
        :disabled="readonly"
        v-model="fileListTemp"
        accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.wps,.et,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/*"
        :after-read="uploadFile"
        upload-icon="plus"
        :show-upload="plusIcon"
        :before-delete="onDelete"
      />
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted, getCurrentInstance, watch } from 'vue'
import { showFailToast, showSuccessToast, showConfirmDialog } from 'vant';
const { proxy } = getCurrentInstance()

// 组件属性定义
const props = defineProps({
  fId: { type: String, default: () => '' },
  value1: { type: String, default: () => null },
  value2: { type: String, default: () => null },
  value3: { type: String, default: () => null },
  value4: { type: String, default: () => null },
  value5: { type: String, default: () => null },
  selectButton: { type: Boolean, default: () => true },
  deleteButton: { type: Boolean, default: () => true },
  readonly: { type: Boolean, default: () => false },
  plusIcon:{type:Boolean, default: () => true},
  isFile: { type: Boolean, default: () => false }
})

// 初始化加载文件列表
onMounted(() => { getTableData() })

// 状态管理
const tableData = ref([])
const fileListTemp = ref([])
const bucket = ref(import.meta.env.VITE_BUCKET)

// 获取文件列表
const getTableData = () => {
  const url = 'framework/Common/queryFileWithValues'
  const param = { fId: props.fId, value1: props.value1, value2: props.value2, value3: props.value3, value4: props.value4, value5: props.value5 }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code === 0) {
      tableData.value = response.data.data
      fileListTemp.value = tableData.value.map(item => ({
        id: item.id,
        url: `${import.meta.env.VITE_BASE_API}framework/Common/downloadFileS3?bucket=${bucket.value}&id=${item.id}&fullfilename=${Date.now()}${item.fileName}`
      }))
    } else {
      showFailToast(`获取文件列表失败！${response.data.msg}`)
    }
  }).catch(error => {
    showFailToast(`网络错误：${error.message}`)
  })
}

// 监听属性变化
watch(
  [() => props.fId, () => props.value1, () => props.value2, () => props.value3, () => props.value4, () => props.value5],
  (newVals, oldVals) => {
    if (newVals.some((val, i) => val !== oldVals[i])) getTableData()
  }
)

// 时间格式化
const getCurrentTime = () => {
  const date = new Date();
  const padZero = (num) => num.toString().padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth()+1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
};

// 文本自动换行函数
const wrapText = (ctx, text, maxWidth, font) => {
  ctx.font = font;
  const words = text.split('');
  const lines = [];
  let currentLine = '';
  let currentWidth = 0;

  words.forEach(word => {
    const testLine = currentLine + word;
    const testWidth = ctx.measureText(testLine).width;

    if (testWidth > maxWidth && currentLine !== '') {
      lines.push(currentLine);
      currentLine = word;
      currentWidth = ctx.measureText(word).width;
    } else {
      currentLine = testLine;
      currentWidth = testWidth;
    }
  });

  if (currentLine !== '') {
    lines.push(currentLine);
  }

  return lines;
};

// 水印配置
const watermarkConfig = {
  title: "现场拍照",
  titleFont: "bold 48px PingFang SC",
  contentFont: "40px PingFang SC",
  coordinateFont: "32px PingFang SC",
  titleBgColor: "rgba(252, 211, 77, 0.45)", // 浅透明警示黄（标题背景，比红色稍透）
  contentBgColor: "rgba(252, 211, 77, 0.35)",// 更浅的警示黄（内容背景，不遮挡工人）
  titleColor: "#333",                    // 深灰色文字（黄色背景配深色文字更柔和，不刺眼）
  contentColor: "#333",                  // 深灰色文字（避免白色文字在黄色上反光感）
  coordinateColor: "rgba(51, 51, 51, 0.9)",  // 半透明深灰（坐标系文字低调）
  padding: 40,
  margin: 30,
  lineHeight: 64,
  borderRadius: 16,
  shadowColor: "rgba(0, 0, 0, 0.25)",
  widthRatio: 0.35,
  maxHeightRatio: 0.7
};

// 加水印函数（完整版，包含天气信息）
const addWatermark = (file) => {
  return new Promise((resolve, reject) => {
    if (!file.type.startsWith('image/')) {
      resolve(file);
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.width;
        canvas.height = img.height;

        // 先画原图
        ctx.drawImage(img, 0, 0);

        // 从localStorage获取所有需要的值
        const locationText = JSON.parse(localStorage.getItem('realLocation')) || '';
        const longitude = JSON.parse(localStorage.getItem('longitude')) || '';  // 经度
        const latitude = JSON.parse(localStorage.getItem('latitude')) || '';    // 纬度
        const elevation = JSON.parse(localStorage.getItem('elevation')) || '';  // 海拔
        const timeText = getCurrentTime();

        // 获取天气信息 - 通过JSON.parse解析
        let weatherInfo = {};
        try {
          weatherInfo = JSON.parse(localStorage.getItem('weatherInfo')) || {};
        } catch (e) {
          console.warn('天气信息解析失败:', e);
          weatherInfo = {};
        }

        // 水印内容 - 按顺序：经纬度 → 天气 → 海拔 → 位置 → 时间 → 坐标系
        const watermarkItems = [];

        // 6. 坐标系信息(坐标系放在最上面)
        watermarkItems.push({
          label: '坐标系：',
          text: 'WGS84坐标系',
          font: watermarkConfig.coordinateFont,
          color: watermarkConfig.coordinateColor
        });

        // 1. 经纬度信息（分两行显示，放在最上面）
        if (longitude) {
          watermarkItems.push({
            label: '经度：',
            text: longitude,
            font: watermarkConfig.contentFont,
            color: watermarkConfig.contentColor
          });
        }
        if (latitude) {
          watermarkItems.push({
            label: '纬度：',
            text: latitude,
            font: watermarkConfig.contentFont,
            color: watermarkConfig.contentColor
          });
        }

        // 2. 天气信息（放在经纬度下方，海拔上方）
        if (weatherInfo.weather || weatherInfo.temperature) {
          const weatherText = [];
          if (weatherInfo.weather) weatherText.push(weatherInfo.weather);
          if (weatherInfo.temperature) weatherText.push(weatherInfo.temperature);

          watermarkItems.push({
            label: '天气：',
            text: weatherText.join('，'),
            font: watermarkConfig.contentFont,
            color: watermarkConfig.contentColor
          });
        }

        // 3. 海拔高度信息（放在天气下方）
        if (elevation) {
          watermarkItems.push({
            label: '海拔：',
            text: elevation + ' 米',
            font: watermarkConfig.contentFont,
            color: watermarkConfig.contentColor
          });
        }

        // 4. 位置信息（放在海拔下面）
        if (locationText) {
          watermarkItems.push({
            label: '位置：',
            text: locationText,
            font: watermarkConfig.contentFont,
            color: watermarkConfig.contentColor
          });
        }

        // 5. 时间信息
        watermarkItems.push({
          label: '时间：',
          text: timeText,
          font: watermarkConfig.contentFont,
          color: watermarkConfig.contentColor
        });

        // 计算水印宽度
        const watermarkWidth = canvas.width * watermarkConfig.widthRatio;
        const maxContentWidth = watermarkWidth - watermarkConfig.padding * 2;

        // 计算所有换行后的文本行
        const allWrappedLines = [];

        watermarkItems.forEach(item => {
          // 计算标签宽度
          ctx.font = item.font;
          const labelWidth = ctx.measureText(item.label).width;
          const availableTextWidth = maxContentWidth - labelWidth;

          // 如果文本加上标签超过宽度，需要换行
          if (availableTextWidth > 0) {
            const wrappedTextLines = wrapText(ctx, item.text, availableTextWidth, item.font);

            if (wrappedTextLines.length > 0) {
              // 第一行包含标签
              allWrappedLines.push({
                text: item.label + wrappedTextLines[0],
                font: item.font,
                color: item.color,
                hasLabel: true
              });

              // 后续行不包含标签，需要缩进
              for (let i = 1; i < wrappedTextLines.length; i++) {
                // 创建缩进空格
                const indentSpaces = ' '.repeat(Math.ceil(labelWidth / ctx.measureText(' ').width));
                allWrappedLines.push({
                  text: indentSpaces + wrappedTextLines[i],
                  font: item.font,
                  color: item.color,
                  hasLabel: false
                });
              }
            }
          } else {
            // 如果标签宽度都超过了最大宽度，单独显示标签
            allWrappedLines.push({
              text: item.label,
              font: item.font,
              color: item.color,
              hasLabel: true
            });

            // 文本单独显示，可能需要换行
            const wrappedTextLines = wrapText(ctx, item.text, maxContentWidth, item.font);
            wrappedTextLines.forEach(line => {
              allWrappedLines.push({
                text: line,
                font: item.font,
                color: item.color,
                hasLabel: false
              });
            });
          }
        });

        // 计算水印高度
        const maxHeight = canvas.height * watermarkConfig.maxHeightRatio;
        const totalContentHeight = allWrappedLines.length * watermarkConfig.lineHeight;
        const watermarkHeight = Math.min(
          watermarkConfig.lineHeight + watermarkConfig.padding * 3 + totalContentHeight,
          maxHeight
        );

        // 水印位置：左下角
        const x = watermarkConfig.margin;
        const y = canvas.height - watermarkHeight - watermarkConfig.margin;

        // 绘制标题背景
        const titleHeight = watermarkConfig.lineHeight + watermarkConfig.padding;
        ctx.fillStyle = watermarkConfig.titleBgColor;
        ctx.beginPath();
        ctx.roundRect(x, y, watermarkWidth, titleHeight, [watermarkConfig.borderRadius, watermarkConfig.borderRadius, 0, 0]);
        ctx.fill();

        // 绘制标题文字
        ctx.font = watermarkConfig.titleFont;
        ctx.fillStyle = watermarkConfig.titleColor;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(watermarkConfig.title, x + watermarkWidth / 2, y + titleHeight / 2);

        // 绘制内容背景
        const contentHeight = watermarkHeight - titleHeight;
        ctx.fillStyle = watermarkConfig.contentBgColor;
        ctx.beginPath();
        ctx.roundRect(x, y + titleHeight, watermarkWidth, contentHeight, [0, 0, watermarkConfig.borderRadius, watermarkConfig.borderRadius]);
        ctx.fill();

        // 绘制所有文本行
        allWrappedLines.forEach((line, index) => {
          const lineY = y + titleHeight + watermarkConfig.padding + watermarkConfig.lineHeight * (index + 0.5);

          ctx.font = line.font;
          ctx.fillStyle = line.color;
          ctx.textAlign = 'left';
          ctx.textBaseline = 'middle';

          ctx.fillText(line.text, x + watermarkConfig.padding, lineY);
        });

        // 转为File返回
        canvas.toBlob((blob) => {
          // 开发环境预览（3秒后消失）
          if (process.env.NODE_ENV === 'development') {
            try {
              const tempUrl = URL.createObjectURL(blob);
              const preview = document.createElement('img');
              preview.style.cssText = 'position:fixed;top:20px;right:20px;max-width:400px;border:2px solid #409EFF;border-radius:4px;z-index:9999';
              preview.src = tempUrl;
              document.body.appendChild(preview);
              setTimeout(() => {
                document.body.removeChild(preview);
                URL.revokeObjectURL(tempUrl);
              }, 3000);
            } catch (err) {
              console.warn('水印预览失败：', err);
            }
          }
          resolve(new File([blob], file.name, { type: file.type, lastModified: Date.now() }));
        }, file.type);
      };
      img.onerror = (err) => reject(new Error(`图片加载失败：${err.message}`));
      img.src = e.target.result;
    };
    reader.onerror = (err) => reject(new Error(`文件读取失败：${err.message}`));
    reader.readAsDataURL(file);
  });
};

// 上传文件
const uploadFile = async (file) => {
  try {
    let processedFile = file.file;
    if (file.file.type.startsWith('image/')) {
      processedFile = await addWatermark(file.file);
    }

    const formData = new FormData();
    formData.append('fId', props.fId);
    formData.append('bucket', bucket.value);
    formData.append('value1', props.value1);
    formData.append('value2', props.value2);
    formData.append('value3', props.value3);
    formData.append('value4', props.value4);
    formData.append('value5', props.value5);
    formData.append('file', processedFile);
    formData.append('fileName', processedFile.name);

    proxy.$axios.post('framework/Common/uploadFileS3', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
      .then(res => {
        if (res.data.code === 0) {
          showSuccessToast('上传成功');
          getTableData();
        } else {
          showFailToast(`上传失败: ${res.data.msg}`);
        }
      }).catch(err => {
      showFailToast(`上传请求失败: ${err.data?.msg || err.message}`);
    });
  } catch (error) {
    showFailToast(`文件处理失败: ${error.message}`);
  }
}

// 删除文件
const onDelete = (file) => {
  return new Promise((resolve) => {
    showConfirmDialog({ title: '删除文件', message: '确定删除该文件吗?' })
      .then(() => {
        proxy.$axios.post('framework/Common/removeFile', { id: file.id })
          .then(res => {
            if (res.data.code === 0) {
              showSuccessToast('删除成功!');
              getTableData();
              resolve(true);
            } else {
              showFailToast(`删除失败: ${res.data.msg}`);
              resolve(false);
            }
          }).catch(err => {
          showFailToast(`删除请求失败: ${err.message}`);
          resolve(false);
        });
      }).catch(() => {
      resolve(false);
    });
  })
}

// 工具函数（保留原逻辑）
const getFileIconClass = (fileType) => {
  if (fileType === 'pdf') return 'pdf-icon';
  if (['image', 'jpg', 'png', 'gif'].includes(fileType)) return 'image-icon';
  if (['doc', 'docx'].includes(fileType)) return 'doc-icon';
  if (['xls', 'xlsx'].includes(fileType)) return 'excel-icon';
  if (fileType === 'txt') return 'text-icon';
  return 'other-icon';
}
const getFileIcon = (fileType) => {
  if (fileType === 'pdf') return 'description';
  if (['image', 'jpg', 'png', 'gif'].includes(fileType)) return 'photo-o';
  if (['doc', 'docx'].includes(fileType)) return 'notes-o';
  if (['xls', 'xlsx'].includes(fileType)) return 'chart-trending-o';
  if (fileType === 'txt') return 'document';
  return 'description';
}
const convertBytesToSize = (bytes) => {
  const kb = 1024;
  const mb = kb * 1024;
  if (bytes < kb) return `${bytes} B`;
  if (bytes < mb) return `${(bytes / kb).toFixed(2)} KB`;
  return `${(bytes / mb).toFixed(2)} MB`;
}

// 暴露方法
defineExpose({ getTableData })
</script>

<style scoped>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.table-row {
  background: white;
  border-radius: 8px;
  margin-bottom: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: transform 0.2s, box-shadow 0.2s;
  align-items: center;
}

.table-row:hover {
  transform: translateX(5px);
  box-shadow: 0 5px 15px rgba(25, 137, 250, 0.15);
}

.file-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-start;
}
</style>