<template>
  <div style="padding: 5px;flex: 1; position: relative;">
    <!-- 签名容器 -->
    <div
      ref="signatureContainer"
      class="signature-wrapper"
      :class="{ 'fullscreen-mode': isFullscreen }"
    >
      <!-- 签名组件：强制保留按钮区域 -->
      <van-signature
        v-if="qmFlag"
        :key="signatureKey"
        v-model="signature"
        :width="signatureWidth"
        :height="signatureHeight"
        pen-color="#000000"
        background-color="#ffffff"
        :line-width="3"
        :show-export="true"
        @submit="handleSubmit"
        @clear="handleClear"
      />
<!--      :style="{-->
<!--      '&#45;&#45;van-signature-content-width': '100%',-->
<!--      '&#45;&#45;van-signature-content-height': 'calc(100% - 60px)',-->
<!--      border: isFullscreen ? '1px dashed #ccc' : '1px solid #eee'-->
<!--      }"-->
      <!-- 全屏/缩小图标 -->
      <van-icon
        v-if="qmFlag"
        class="fullscreen-icon"
        :name="isFullscreen ? 'shrink' : 'expand'"
        color="#409EFF"
        size="28"
        @click="toggleFullscreen"
      />
    </div>

    <!-- 文件上传区域：全屏时隐藏 -->
    <br v-if="!isFullscreen" />
    <div v-if="!isFullscreen">
      <van-uploader
        :disabled="true"
        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="true"
        :before-delete="onDelete"
      />
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted, getCurrentInstance, watch, onUnmounted, nextTick } from 'vue';
import { showFailToast, showSuccessToast, showConfirmDialog, showLoadingToast } from 'vant';
import { Icon } from 'vant';
import { atob } from 'js-base64';

// 声明自定义事件（事件名与父组件绑定的@jsdiafj一致）
const emit = defineEmits(['resetQMFlag','updateModel']);


// 基础实例与props
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 },
  isFile: { type: Boolean, default: () => false },
  qmFlag: { type: Boolean, default: () => true }
});

// 核心状态
const isFullscreen = ref(false);
const signatureContainer = ref(null);
const signature = ref('');
const signatureKey = ref(1);
const signatureWidth = ref('100%');
const signatureHeight = ref('400px'); // 非全屏高度（含按钮区域）
const signaturePrefix = 'signature_';

// 业务变量
const tableData = ref([]);
const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId')
});
const fileListTemp = ref([]);
const bucket = ref(import.meta.env.VITE_BUCKET);
const showDialogVisible = ref(false);
const deleteInfo = ref();

// 全屏切换逻辑
const toggleFullscreen = async () => {
  const container = signatureContainer.value;
  if (!container) return;

  try {
    if (!isFullscreen.value) {
      // 进入全屏
      if (document.fullscreenElement) await document.exitFullscreen();
      if (container.requestFullscreen) await container.requestFullscreen();
      else if (container.webkitRequestFullscreen) await container.webkitRequestFullscreen();
      else if (container.msRequestFullscreen) await container.msRequestFullscreen();

      // 同步尺寸（预留按钮高度）
      await nextTick();
      signatureHeight.value = `calc(100vh - 20px)`; // 全屏总高度（含按钮）
      signatureKey.value += 1;
    } else {
      // 退出全屏
      if (document.fullscreenElement) await document.exitFullscreen();
      await nextTick();
      signatureHeight.value = '400px';
      signatureKey.value += 1;
    }
  } catch (error) {
    showFailToast(`全屏失败：${error.message}`);
    console.error('全屏错误：', error);
  }
};

// 退出全屏的独立方法
const exitFullscreenImmediately = async () => {
  if (isFullscreen.value) {
    try {
      if (document.fullscreenElement) await document.exitFullscreen();
      await nextTick();
      signatureHeight.value = '400px';
      signatureKey.value += 1;
      isFullscreen.value = false; // 强制更新状态
    } catch (error) {
      console.error('立即退出全屏失败：', error);
    }
  }
};

// 全屏状态变化监听
const handleFullscreenChange = async () => {
  const newState = !!document.fullscreenElement;
  isFullscreen.value = newState;
  await nextTick();
  if (newState) {
    signatureHeight.value = `calc(100vh - 20px)`;
  } else {
    signatureHeight.value = '400px';
  }
  signatureKey.value += 1;
};

// 窗口尺寸变化监听
const handleResize = async () => {
  if (isFullscreen.value) {
    await nextTick();
    signatureHeight.value = `calc(100vh - 20px)`;
    signatureKey.value += 1;
  }
};

// 签名提交（确认按钮逻辑）- 先退出全屏再处理请求
const handleSubmit = async (data) => {
  if (!data.image) {
    showFailToast('请先完成签名');
    return;
  }

  // 1. 显示加载提示
  const toast = showLoadingToast({ message: '正在处理签名...', forbidClick: true });

  try {
    //原逻辑
    // const rotatedBase64 = await rotateImageCounterClockwise(data.image);
    const rotatedBase64 = isFullscreen.value
      ? await rotateImageCounterClockwise(data.image) // 全屏：旋转
      : data.image; // 非全屏：不旋转，直接用原始图片
    // 2. 立即退出全屏
    await exitFullscreenImmediately();

    // 3. 处理签名数据并上传
    // 修改前：const file = dataURLtoFile(rotatedBase64, `${signaturePrefix}${Date.now()}.png`);
    // 修改后：使用.jpg扩展名
    const file = dataURLtoFile(rotatedBase64, `${signaturePrefix}${Date.now()}.jpg`);
    // console.log('上传文件：AAAAAAAAAAAAA', rotatedBase64);

    // 4. 执行上传请求
    await uploadFile({ file, fileName: file.name });

    // 5. 上传成功提示
    showSuccessToast('签名上传成功');
    signature.value = '';
  } catch (error) {
    // 6. 上传失败提示
    showFailToast(error.message || '签名上传失败，请重试');
    console.error('提交错误：', error);
  } finally {
    // 7. 关闭加载提示
    emit('resetQMFlag')
    emit('updateModel');
    toast.close();
  }
};

// 清空按钮逻辑
const handleClear = () => {
  signature.value = '';
};

//添加位置水印
const watermarkConfig = {
  text: JSON.parse(localStorage.getItem("realLocation")), // 文字水印内容
  textFont: "16px PingFang SC", // 文字水印字体
  textColor: "rgba(102, 102, 102, 0.5)", // 文字水印颜色（半透明）
  timeFont: "14px PingFang SC", // 时间水印字体
  timeColor: "rgba(153, 153, 153, 0.4)", // 时间水印颜色（更淡）
  marginBottom: 30, // 水印区域距离图片底部的距离
  textTimeGap: 8, // 文字水印与时间水印的垂直间距
};

// 图片旋转
const rotateImageCounterClockwise = (base64) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = img.height;
      canvas.height = img.width;

      // 添加clearRect，保持背景透明
      /*
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      */
      // 设置白色背景
      ctx.fillStyle = '#FFFFFF';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.rotate(-Math.PI / 2);
      ctx.drawImage(img, -img.width / 2, -img.height / 2);
      // 旋转后恢复画布状态（关键：否则水印会跟着旋转）
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      // --------------------------
      // 新增：步骤3：绘制文字水印（在时间水印上方）
      // --------------------------
      ctx.font = watermarkConfig.textFont;
      ctx.fillStyle = watermarkConfig.textColor;
      ctx.textAlign = 'center'; // 文字水平居中
      // 计算文字水印Y坐标：图片高度 - 底部间距 - 时间水印高度 - 文字与时间间距
      const timeText = new Date().toLocaleString(); // 获取当前时间
      const textWidth = ctx.measureText(watermarkConfig.text).width;
      const timeWidth = ctx.measureText(timeText).width;
      // 文字水印Y坐标：确保在时间水印上方
      const textY = canvas.height - watermarkConfig.marginBottom - 20 - watermarkConfig.textTimeGap;
      ctx.fillText(watermarkConfig.text, canvas.width / 2, textY);
      // --------------------------
      // 新增：步骤4：绘制时间水印（在文字水印正下方）
      // --------------------------
      ctx.font = watermarkConfig.timeFont;
      ctx.fillStyle = watermarkConfig.timeColor;
      ctx.textAlign = 'center'; // 时间水平居中
      // 时间水印Y坐标：文字水印Y坐标 + 文字高度（约20px） + 间距
      const timeY = textY + 20 + watermarkConfig.textTimeGap;
      ctx.fillText(timeText, canvas.width / 2, timeY);
      // 步骤5：生成带水印的JPG图片
      // 修改前：resolve(canvas.toDataURL('image/png', 1.0));
      // 修改后：输出JPG格式，质量0.95
      resolve(canvas.toDataURL('image/jpeg', 0.95));
    };
    img.onerror = (error) => reject(new Error(`图片加载失败：${error.message}`));
    img.src = base64;
  });
};

// Base64转File
const dataURLtoFile = (dataurl, filename) => {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) u8arr[n] = bstr.charCodeAt(n);
  return new File([u8arr], filename, { type: mime });
};

// 文件列表查询
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.forEach(item => {
        fileListTemp.value.push({
          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);
    }
  });
};

// 文件上传
const uploadFile = (file) => {
  return new Promise((resolve, reject) => {
    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', file.file);
    formData.append('fileName', file.file.name);
    proxy.$axios.post('framework/Common/uploadFileS3', formData, 'multipart/form-data')
      .then(res => {
        getTableData();
        resolve();
      })
      .catch(err => {
        reject(err);
      });
  });
};

// 文件删除
const handleDelete = (row) => {
  showDialogVisible.value = true;
  deleteInfo.value = row;
};

const onDelete = (file) => {
  return showConfirmDialog({
    title: '删除确认',
    message: '确定删除该文件吗？'
  }).then(() => {
    return proxy.$axios.post('framework/Common/removeFile', { id: file.id })
      .then(res => {
        if (res.data.code === 0) {
          showSuccessToast('删除成功');
          getTableData();
          return true;
        } else {
          showFailToast('删除失败：' + res.data.msg);
          return false;
        }
      });
  }).catch(() => 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`;
};

// 生命周期
onMounted(() => {
  getTableData();
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
  window.removeEventListener('resize', handleResize);
  if (document.fullscreenElement) document.exitFullscreen().catch(() => {
  });
});

// Props变化监听
watch(props, (newVal, oldVal) => {
  if (newVal.fId !== oldVal.fId || Object.values(newVal).some((v, i) => v !== Object.values(oldVal)[i])) {
    getTableData();
  }
});
</script>


<style scoped>
/* 签名容器基础样式 */
.signature-wrapper {
  position: relative;
  border-radius: 6px;
  overflow: hidden;
  width: 100%;
  height: 30vh;
}

/* 全屏模式样式：确保按钮区域可见 */
.signature-wrapper.fullscreen-mode {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999;
  background-color: #F8F8F8;
  padding: 15px;
  box-sizing: border-box;
}

/* 全屏图标样式 */
.fullscreen-icon {
  position: absolute;
  right: 20px;
  top: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  z-index: 10;
}

/* 核心：强制保留按钮区域并优化布局 */
:deep(.van-signature) {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  flex-direction: column;
}

/* ########## 关键修改：全屏模式按钮布局（居左+垂直排列） ########## */
.signature-wrapper.fullscreen-mode :deep(.van-signature__footer) {
  display: flex !important;
  flex-direction: column; /* 按钮垂直排列 */
  position: absolute; /* 固定到左侧 */
  left: 15px; /* 距左侧距离 */
  top: 50%; /* 垂直居中第一步 */
  transform: translateY(-50%); /* 垂直居中第二步（抵消自身高度） */
  margin: 0; /* 清除原有margin */
  padding: 10px 0; /* 垂直内边距 */
  gap: 20px; /* 按钮上下间距 */
  background-color: transparent; /* 取消背景色，避免遮挡 */
  border-top: none; /* 取消上边框 */
}

/* ########## 关键修改：全屏模式按钮样式（适配文字旋转） ########## */
.signature-wrapper.fullscreen-mode :deep(.van-signature__footer .van-button) {
  width: 40px; /* 按钮宽度（窄） */
  height: 120px; /* 按钮高度（长，适配旋转文字） */
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0; /* 清除原有水平padding */
}

/* ########## 关键修改：按钮文字旋转90°（逆时针） ########## */
.signature-wrapper.fullscreen-mode :deep(.van-signature__footer .van-button__text) {
  transform: rotate(90deg); /* 逆时针旋转90°（顺时针用90deg） */
  white-space: nowrap; /* 文字不换行 */
  font-size: 14px; /* 文字大小微调 */
}

/* ########## 关键修改：签名画布留空（避免遮挡） ########## */
:deep(.van-signature__content) {
  flex: 1; /* 填满剩余空间 */
  width: 100% !important;
  min-height: 0 !important;
  padding-left: 60px; /* 给左侧按钮留空间（大于按钮宽度+间距） */
}

/* 全局样式 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  color: #333;
  line-height: 1.6;
  min-height: 100vh;
}

:deep(.van-signature__content) {
  padding: 0;
}
</style>