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

      <!-- 全屏/缩小图标（默认显示"缩小"图标） -->
      <van-icon
        v-if="qmFlag && !qmFlags"
        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';

// 声明自定义事件
const emit = defineEmits(['resetQMFlag']);

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

// 核心状态：【修改1】初始值设为true（默认全屏）
const isFullscreen = ref(true);
const signatureContainer = ref(null);
const signature = ref('');
const signatureKey = ref(1);
const signatureWidth = ref('100%');
// 【修改2】初始高度设为全屏高度（适配默认全屏）
const signatureHeight = ref('calc(100vh - 20px)');
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;
  }

  const toast = showLoadingToast({ message: '正在处理签名...', forbidClick: true });

  try {
    await exitFullscreenImmediately();
    const rotatedBase64 = await rotateImageCounterClockwise(data.image);
    const file = dataURLtoFile(rotatedBase64, `${signaturePrefix}${Date.now()}.png`);
    await uploadFile({ file, fileName: file.name });
    showSuccessToast('签名上传成功');
    signature.value = '';
    emit('resetQMFlag')
  } catch (error) {
    showFailToast(error.message || '签名上传失败，请重试');
    console.error('提交错误：', error);
  } finally {
    
    toast.close();
  }
};

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

// 图片旋转（无修改）
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;
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.rotate(-Math.PI / 2);
      ctx.drawImage(img, -img.width / 2, -img.height / 2);
      resolve(canvas.toDataURL('image/png', 1.0));
    };
    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`;
};

// 生命周期：【修改3】添加自动进入全屏逻辑（DOM挂载后执行）
onMounted(() => {
  getTableData();
  // 绑定全屏/窗口事件监听
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);
  window.addEventListener('resize', handleResize);

  // 自动进入全屏（需等待DOM渲染完成）
  nextTick(async () => {
    const container = signatureContainer.value;
    if (!container) return;

    try {
      // 清除已有全屏状态（避免冲突）
      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();

      // 强制更新签名组件，确保尺寸适配
      signatureKey.value += 1;
    } catch (error) {
      // 自动全屏失败时降级（提示用户手动操作）
      // showFailToast('自动全屏失败，请点击右上角"扩大"图标手动进入全屏');
      // console.error('自动全屏错误：', error);
      // 重置为非全屏状态，避免界面异常
      isFullscreen.value = false;
      signatureHeight.value = '400px';
    }
  });
});

// 组件卸载时清理（无修改）
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%;
}

/* 全屏模式样式：确保按钮区域可见 */
.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;
  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;
}

/* 按钮文字旋转90°（逆时针） */
.signature-wrapper.fullscreen-mode :deep(.van-signature__footer .van-button__text) {
  transform: rotate(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;
}
</style>