<template>
  <div class="mobile-approval-container">
    <div class="mobile-header">
      <h3>审批记录</h3>
      <el-button @click="goBack" type="primary" size="small">返回</el-button>
    </div>
    
    <el-tabs v-model="tabActiveName" class="mobile-tabs">
      <el-tab-pane v-loading="loading" label="流程图" name="image" class="mobile-tab-content">
        <div
          ref="imageWrapperRef"
          class="mobile-image-wrapper"
          @wheel="handleMouseWheel"
          @mousedown="handleMouseDown"
          @mousemove="handleMouseMove"
          @mouseup="handleMouseUp"
          @mouseleave="handleMouseLeave"
          @dblclick="resetTransform"
          :style="transformStyle"
        >
          <el-card class="mobile-image-card">
            <el-image :src="imgUrl" class="mobile-scalable-image" fit="contain" />
          </el-card>
        </div>
      </el-tab-pane>
      
      <el-tab-pane v-loading="loading" label="审批信息" name="info" class="mobile-tab-content">
        <div class="mobile-table-container">
          <el-table :data="historyList" border stripe size="small" class="mobile-table">
            <el-table-column type="index" label="序号" align="center" width="50" />
            <el-table-column prop="nodeName" label="任务" align="center" min-width="80" show-overflow-tooltip />
            <el-table-column prop="approveName" label="办理人" align="center" min-width="80" show-overflow-tooltip>
              <template #default="scope">
                <template v-if="scope.row.approveName">
                  <div class="mobile-tags">
                    <el-tag 
                      v-for="(item, index) in scope.row.approveName.split(',')" 
                      :key="index" 
                      type="success" 
                      size="small"
                      class="mobile-tag"
                    >
                      {{ item }}
                    </el-tag>
                  </div>
                </template>
                <template v-else>
                  <el-tag type="success" size="small">无</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="flowStatus" label="状态" width="60" align="center">
              <template #default="scope">
                <dict-tag :options="wf_task_status" :value="scope.row.flowStatus" size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="message" label="意见" align="center" min-width="100" show-overflow-tooltip />
            <el-table-column prop="createTime" label="开始时间" width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="updateTime" label="结束时间" width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="runDuration" label="时长" width="80" align="center" show-overflow-tooltip />
            <el-table-column prop="attachmentList" width="60" label="附件" align="center">
              <template #default="scope">
                <el-popover 
                  v-if="scope.row.attachmentList && scope.row.attachmentList.length > 0" 
                  placement="top" 
                  :width="280" 
                  trigger="click"
                >
                  <template #reference>
                    <el-button type="primary" size="small">附件</el-button>
                  </template>
                  <el-table border :data="scope.row.attachmentList" size="small">
                    <el-table-column prop="originalName" label="文件名" show-overflow-tooltip />
                    <el-table-column prop="name" width="60" align="center" label="操作">
                      <template #default="tool">
                        <el-button type="text" size="small" @click="handleDownload(tool.row.ossId)">下载</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { flowImage } from '@/api/workflow/instance';
import { listByIds } from '@/api/system/oss';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wf_task_status } = toRefs<any>(proxy?.useDict('wf_task_status'));
const route = useRoute();
const router = useRouter();

const loading = ref(false);
const historyList = ref<Array<any>>([]);
const tabActiveName = ref('image');
const imgUrl = ref('');

// 图片缩放相关变量
const imageWrapperRef = ref<HTMLElement | null>(null);
const scale = ref(1);
const maxScale = 3;
const minScale = 0.5;

let isDragging = false;
let startX = 0;
let startY = 0;
let currentTranslateX = 0;
let currentTranslateY = 0;

// 从URL参数获取businessId并初始化
onMounted(() => {
  const businessId = route.query.businessId as string;
  if (businessId) {
    init(businessId);
  } else {
    proxy?.$modal.msgError('缺少业务ID参数');
  }
});

// 初始化查询审批记录
const init = async (businessId: string | number) => {
  loading.value = true;
  tabActiveName.value = 'image';
  historyList.value = [];
  
  try {
    const resp = await flowImage(businessId);
    if (resp.data) {
      historyList.value = resp.data.list;
      imgUrl.value = 'data:image/gif;base64,' + resp.data.image;
      
      if (historyList.value.length > 0) {
        // 处理附件
        for (const item of historyList.value) {
          if (item.ext) {
            const res = await getIds(item.ext);
            item.attachmentList = res.data;
          } else {
            item.attachmentList = [];
          }
        }
      }
    }
  } catch (error) {
    proxy?.$modal.msgError('获取审批记录失败');
  } finally {
    loading.value = false;
  }
};

const getIds = async (ids: string | number) => {
  return await listByIds(ids);
};

const handleDownload = (ossId: string) => {
  proxy?.$download.oss(ossId);
};

const goBack = () => {
  // PDA可以通过JavaScript桥接与原生应用通信
  if ((window as any).PDABridge && (window as any).PDABridge.closeWebView) {
    (window as any).PDABridge.closeWebView();
  } else if (window.parent !== window) {
    window.parent.postMessage({ type: 'CLOSE_WEBVIEW' }, '*');
  } else {
    // 如果是直接在浏览器中打开，则返回上一页
    router.back();
  }
};

// 图片缩放和拖拽相关方法
const handleMouseWheel = (event: WheelEvent) => {
  event.preventDefault();
  let newScale = scale.value - event.deltaY / 1000;
  newScale = Math.max(minScale, Math.min(newScale, maxScale));
  if (newScale !== scale.value) {
    scale.value = newScale;
    resetDragPosition();
  }
};

const handleMouseDown = (event: MouseEvent) => {
  if (scale.value > 1) {
    event.preventDefault();
    isDragging = true;
    startX = event.clientX;
    startY = event.clientY;
  }
};

const handleMouseMove = (event: MouseEvent) => {
  if (!isDragging || !imageWrapperRef.value) return;

  const deltaX = event.clientX - startX;
  const deltaY = event.clientY - startY;
  startX = event.clientX;
  startY = event.clientY;

  currentTranslateX += deltaX;
  currentTranslateY += deltaY;

  const bounds = getBounds();
  if (currentTranslateX > bounds.maxTranslateX) {
    currentTranslateX = bounds.maxTranslateX;
  } else if (currentTranslateX < bounds.minTranslateX) {
    currentTranslateX = bounds.minTranslateX;
  }

  if (currentTranslateY > bounds.maxTranslateY) {
    currentTranslateY = bounds.maxTranslateY;
  } else if (currentTranslateY < bounds.minTranslateY) {
    currentTranslateY = bounds.minTranslateY;
  }

  applyTransform();
};

const handleMouseUp = () => {
  isDragging = false;
};

const handleMouseLeave = () => {
  isDragging = false;
};

const resetTransform = () => {
  scale.value = 1;
  currentTranslateX = 0;
  currentTranslateY = 0;
  applyTransform();
};

const resetDragPosition = () => {
  currentTranslateX = 0;
  currentTranslateY = 0;
  applyTransform();
};

const applyTransform = () => {
  if (imageWrapperRef.value) {
    imageWrapperRef.value.style.transform = `translate(${currentTranslateX}px, ${currentTranslateY}px) scale(${scale.value})`;
  }
};

const getBounds = () => {
  if (!imageWrapperRef.value) return { minTranslateX: 0, maxTranslateX: 0, minTranslateY: 0, maxTranslateY: 0 };

  const imgRect = imageWrapperRef.value.getBoundingClientRect();
  const containerRect = imageWrapperRef.value.parentElement?.getBoundingClientRect() ?? imgRect;

  const minTranslateX = (containerRect.width - imgRect.width * scale.value) / 2;
  const maxTranslateX = -(containerRect.width - imgRect.width * scale.value) / 2;
  const minTranslateY = (containerRect.height - imgRect.height * scale.value) / 2;
  const maxTranslateY = -(containerRect.height - imgRect.height * scale.value) / 2;

  return { minTranslateX, maxTranslateX, minTranslateY, maxTranslateY };
};

const transformStyle = computed(() => ({
  transition: isDragging ? 'none' : 'transform 0.2s ease'
}));
</script>

<style lang="scss" scoped>
.mobile-approval-container {
  width: 100%;
  height: 100vh;
  padding: 10px;
  background-color: #f5f5f5;
  overflow: hidden;
  
  .mobile-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #ddd;
    background-color: white;
    margin-bottom: 10px;
    border-radius: 6px;
    padding: 15px;
    
    h3 {
      margin: 0;
      color: #333;
      font-size: 18px;
    }
  }
  
  .mobile-tabs {
    height: calc(100vh - 80px);
    
    :deep(.el-tabs__header) {
      margin: 0 0 10px 0;
      background-color: white;
      border-radius: 6px;
      padding: 10px;
    }
    
    :deep(.el-tabs__content) {
      height: calc(100% - 50px);
      overflow: hidden;
    }
    
    .mobile-tab-content {
      height: 100%;
      overflow: auto;
    }
  }
  
  .mobile-image-wrapper {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
    user-select: none;
    cursor: grab;
    
    &:active {
      cursor: grabbing;
    }
    
    .mobile-image-card {
      width: 100%;
      height: 100%;
      border: none;
      
      :deep(.el-card__body) {
        padding: 10px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    
    .mobile-scalable-image {
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
    }
  }
  
  .mobile-table-container {
    background-color: white;
    border-radius: 6px;
    padding: 10px;
    height: 100%;
    overflow: auto;
    
    .mobile-table {
      font-size: 12px;
      
      :deep(.el-table__header th) {
        background-color: #f8f9fa;
        font-size: 12px;
        padding: 8px 0;
      }
      
      :deep(.el-table__body td) {
        padding: 6px 0;
      }
      
      .mobile-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 2px;
        
        .mobile-tag {
          font-size: 10px;
          padding: 2px 4px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .mobile-approval-container {
    padding: 5px;
    
    .mobile-header {
      padding: 8px 10px;
      margin-bottom: 5px;
      
      h3 {
        font-size: 16px;
      }
    }
    
    .mobile-tabs {
      height: calc(100vh - 65px);
      
      :deep(.el-tabs__header) {
        padding: 5px;
        margin-bottom: 5px;
      }
    }
    
    .mobile-table-container {
      padding: 5px;
      
      .mobile-table {
        font-size: 10px;
        
        :deep(.el-table__header th) {
          font-size: 10px;
          padding: 6px 0;
        }
        
        :deep(.el-table__body td) {
          padding: 4px 0;
        }
      }
    }
  }
}
</style> 