<template>
  <div class="data-report-page">
    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <van-icon name="arrow-left" class="nav-back" @click="goBack" />
      <h1 class="nav-title">处罚结果</h1>
      <div class="nav-placeholder"></div>
    </div>

    <div class="page-content">
      <!-- 车辆抓拍 -->
      <div class="section-card">
        <div class="section-header">
          <van-icon name="photograph" class="section-icon" />
          <h3 class="section-title">车辆抓拍</h3>
          <span class="required">*</span>
        </div>
        <div class="image-grid">
          <div v-for="(img, index) in captureImages" :key="index" class="image-item">
            <van-image :src="img" fit="cover" class="grid-img" />
          </div>
          <div v-if="!isViewMode" class="image-item add-btn" @click="handleImageUpload('capture')">
            <van-icon name="photograph" class="add-icon" />
            <span class="add-text">拍照</span>
          </div>
        </div>
      </div>

      <!-- 车辆纸证 -->
      <div class="section-card">
        <div class="section-header">
          <van-icon name="description" class="section-icon" />
          <h3 class="section-title">车辆纸证</h3>
          <span class="required">*</span>
        </div>
        <div class="image-grid">
          <div v-for="(img, index) in documentImages" :key="index" class="image-item">
            <van-image :src="img" fit="cover" class="grid-img" />
          </div>
          <div v-if="!isViewMode" class="image-item add-btn" @click="handleImageUpload('document')">
            <van-icon name="photograph" class="add-icon" />
            <span class="add-text">拍照</span>
          </div>
        </div>
      </div>

      <!-- 现场取证 -->
      <div class="section-card">
        <div class="section-header">
          <van-icon name="photograph" class="section-icon" />
          <h3 class="section-title">现场取证</h3>
          <span class="required">*</span>
        </div>
        <div class="image-grid">
          <div v-for="(img, index) in evidenceImages" :key="index" class="image-item">
            <van-image :src="img" fit="cover" class="grid-img" />
          </div>
          <div v-if="!isViewMode" class="image-item add-btn" @click="handleImageUpload('evidence')">
            <van-icon name="photograph" class="add-icon" />
            <span class="add-text">拍照</span>
          </div>
        </div>
      </div>

      <!-- 执法文书 -->
      <div class="section-card">
        <div class="section-header">
          <van-icon name="description" class="section-icon" />
          <h3 class="section-title">执法文书</h3>
          <span class="required">*</span>
        </div>
        <div class="image-grid">
          <div v-for="(img, index) in lawDocImages" :key="index" class="image-item">
            <van-image :src="img" fit="cover" class="grid-img" />
          </div>
          <div v-if="!isViewMode" class="image-item add-btn" @click="handleImageUpload('lawDoc')">
            <van-icon name="photograph" class="add-icon" />
            <span class="add-text">拍照</span>
          </div>
        </div>
      </div>

      <!-- 签字确认 -->
      <div class="section-card">
        <div class="section-header">
          <van-icon name="records" class="section-icon" />
          <h3 class="section-title">签字确认</h3>
          <span class="required">*</span>
        </div>

        <!-- 当事人签名 -->
        <div class="signature-section">
          <div class="signature-label">当事人签名</div>
          <div class="signature-box" @click="!isViewMode && openSignature('party')">
            <template v-if="partySignature">
              <van-image :src="partySignature" fit="contain" class="signature-img" />
            </template>
            <template v-else>
              <van-icon name="edit" class="signature-icon" />
              <span class="signature-hint">点击签名</span>
            </template>
          </div>
        </div>

        <!-- 执法人员签名 -->
        <div class="signature-section">
          <div class="signature-label">执法人员签名</div>
          <div class="signature-box" @click="!isViewMode && openSignature('officer')">
            <template v-if="officerSignature">
              <van-image :src="officerSignature" fit="contain" class="signature-img" />
            </template>
            <template v-else>
              <van-icon name="edit" class="signature-icon" />
              <span class="signature-hint">点击签名</span>
            </template>
          </div>
        </div>
      </div>

      <!-- 补充描述 -->
      <div class="section-card">
        <div class="section-header">
          <van-icon name="description" class="section-icon" />
          <h3 class="section-title">补充描述</h3>
        </div>
        <van-field
          v-model="description"
          type="textarea"
          rows="4"
          placeholder="请输入补充描述信息..."
          :disabled="isViewMode"
          class="desc-textarea"
        />
      </div>

      <!-- 保存按钮 -->
      <div v-if="!isViewMode" class="save-section">
        <van-button block round type="primary" class="save-btn" @click="handleSave">
          保存
        </van-button>
      </div>
    </div>

    <!-- 签名弹窗 -->
    <van-popup v-model:show="showSignaturePopup" round position="bottom" :style="{ height: '60%' }" class="signature-popup">
      <div class="popup-header">
        <span class="popup-cancel" @click="showSignaturePopup = false">取消</span>
        <span class="popup-title">{{ currentSignatureType === 'party' ? '当事人签名' : '执法人员签名' }}</span>
        <span class="popup-confirm" @click="confirmSignature">确认</span>
      </div>
      <div class="canvas-wrapper">
        <canvas
          ref="signatureCanvas"
          class="signature-canvas"
          @touchstart.prevent="handleTouchStart"
          @touchmove.prevent="handleTouchMove"
          @touchend.prevent="handleTouchEnd"
          @mousedown="handleMouseDown"
          @mousemove="handleMouseMove"
          @mouseup="handleMouseUp"
        ></canvas>
      </div>
      <div class="popup-footer">
        <van-button size="small" round @click="clearSignature">清除</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Toast } from "vant";

const router = useRouter();
const route = useRoute();

// 获取URL参数
const violationId = route.query.id || "1";
const status = route.query.status || "";

// 判断是否为已完成状态的数据查看
const isViewMode = computed(() => status === "completed");

// 已完成数据
const completedData = {
  captureImages: [
    "https://images.unsplash.com/photo-1710939968666-a7447d3c584e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400"
  ],
  documentImages: [
    "https://images.unsplash.com/photo-1563298723-dcfebaa392e3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400",
    "https://images.unsplash.com/photo-1590856029620-0964541d93c2?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400"
  ],
  evidenceImages: [
    "https://images.unsplash.com/photo-1613314188851-2c04697535ab?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400",
    "https://images.unsplash.com/photo-1656644177899-a83d045640e9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400"
  ],
  lawDocImages: [
    "https://images.unsplash.com/photo-1450101499163-c8848c66ca85?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400"
  ],
  description: "已对违章车辆进行处罚，车主已将车辆驶离。现场已拍照取证，违章信息已录入系统。建议加强该区域的巡查力度，防止类似违章行为再次发生。"
};

// 图片数据
const captureImages = ref(isViewMode.value ? completedData.captureImages : []);
const documentImages = ref(isViewMode.value ? completedData.documentImages : []);
const evidenceImages = ref(isViewMode.value ? completedData.evidenceImages : []);
const lawDocImages = ref(isViewMode.value ? completedData.lawDocImages : []);

// 签名数据（存储 base64）
const partySignature = ref(isViewMode.value ? "signed" : "");
const officerSignature = ref(isViewMode.value ? "signed" : "");

// 描述
const description = ref(isViewMode.value ? completedData.description : "");

// 签名弹窗
const showSignaturePopup = ref(false);
const currentSignatureType = ref("party");
const signatureCanvas = ref(null);
let ctx = null;
let isDrawing = false;
let lastX = 0;
let lastY = 0;

// 打开签名弹窗
async function openSignature(type) {
  currentSignatureType.value = type;
  showSignaturePopup.value = true;
  await nextTick();
  initCanvas();
}

// 初始化 canvas
function initCanvas() {
  const canvas = signatureCanvas.value;
  if (!canvas) return;
  ctx = canvas.getContext("2d");
  const dpr = window.devicePixelRatio || 1;
  const rect = canvas.getBoundingClientRect();
  canvas.width = rect.width * dpr;
  canvas.height = rect.height * dpr;
  ctx.scale(dpr, dpr);
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  ctx.lineWidth = 3;
  ctx.strokeStyle = "#333";
}

// 获取触摸/鼠标坐标
function getPos(e) {
  const canvas = signatureCanvas.value;
  const rect = canvas.getBoundingClientRect();
  if (e.touches) {
    return {
      x: e.touches[0].clientX - rect.left,
      y: e.touches[0].clientY - rect.top
    };
  }
  return {
    x: e.clientX - rect.left,
    y: e.clientY - rect.top
  };
}

// 鼠标事件
function handleMouseDown(e) {
  isDrawing = true;
  const pos = getPos(e);
  lastX = pos.x;
  lastY = pos.y;
}
function handleMouseMove(e) {
  if (!isDrawing) return;
  const pos = getPos(e);
  drawLine(pos.x, pos.y);
  lastX = pos.x;
  lastY = pos.y;
}
function handleMouseUp() {
  isDrawing = false;
}

// 触摸事件
function handleTouchStart(e) {
  isDrawing = true;
  const pos = getPos(e);
  lastX = pos.x;
  lastY = pos.y;
}
function handleTouchMove(e) {
  if (!isDrawing) return;
  const pos = getPos(e);
  drawLine(pos.x, pos.y);
  lastX = pos.x;
  lastY = pos.y;
}
function handleTouchEnd() {
  isDrawing = false;
}

// 绑线
function drawLine(x, y) {
  if (!ctx) return;
  ctx.beginPath();
  ctx.moveTo(lastX, lastY);
  ctx.lineTo(x, y);
  ctx.stroke();
}

// 清除签名
function clearSignature() {
  if (!ctx || !signatureCanvas.value) return;
  const canvas = signatureCanvas.value;
  const rect = canvas.getBoundingClientRect();
  ctx.clearRect(0, 0, rect.width, rect.height);
}

// 确认签名
function confirmSignature() {
  if (!signatureCanvas.value) return;
  const dataUrl = signatureCanvas.value.toDataURL("image/png");
  if (currentSignatureType.value === "party") {
    partySignature.value = dataUrl;
  } else {
    officerSignature.value = dataUrl;
  }
  showSignaturePopup.value = false;
}

// 模拟图片上传
function handleImageUpload(type) {
  const mockImage = "https://images.unsplash.com/photo-1449965408869-eaa3f722e40d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400";

  switch (type) {
    case 'capture':
      captureImages.value.push(mockImage);
      break;
    case 'document':
      documentImages.value.push(mockImage);
      break;
    case 'evidence':
      evidenceImages.value.push(mockImage);
      break;
    case 'lawDoc':
      lawDocImages.value.push(mockImage);
      break;
  }
}

// 保存
function handleSave() {
  Toast.success("数据已保存");
  router.back();
}

// 返回
function goBack() {
  router.back();
}
</script>

<style lang="scss" scoped>
.data-report-page {
  min-height: 100vh;
  background: #f1f5f9;
  padding-bottom: 100px;
}

.nav-bar {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-bottom: 1px solid #e5e5e5;
  padding: 12px 16px;

  .nav-back {
    font-size: 24px;
    color: #333;
  }

  .nav-title {
    font-size: 17px;
    font-weight: 600;
    color: #333;
  }

  .nav-placeholder {
    width: 24px;
  }
}

.page-content {
  padding: 16px;
}

.section-card {
  background: white;
  border-radius: 20px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;

  .section-icon {
    font-size: 20px;
    color: #2563eb;
  }

  .section-title {
    font-size: 15px;
    font-weight: 600;
    color: #333;
  }

  .required {
    color: #ef4444;
    font-size: 14px;
  }
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;

  .image-item {
    aspect-ratio: 1;
    border-radius: 12px;
    overflow: hidden;

    &.add-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #f1f5f9;
      cursor: pointer;

      &:active {
        background: #e2e8f0;
      }

      .add-icon {
        font-size: 24px;
        color: #94a3b8;
        margin-bottom: 4px;
      }

      .add-text {
        font-size: 12px;
        color: #94a3b8;
      }
    }

    .grid-img {
      width: 100%;
      height: 100%;
    }
  }
}

.signature-section {
  &:not(:last-child) {
    margin-bottom: 16px;
  }

  .signature-label {
    font-size: 14px;
    color: #64748b;
    margin-bottom: 8px;
  }

  .signature-box {
    height: 140px;
    border: 2px dashed #d1d5db;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f9fafb;
    cursor: pointer;
    overflow: hidden;

    &:active {
      background: #f1f5f9;
    }

    .signature-icon {
      font-size: 24px;
      color: #94a3b8;
      margin-bottom: 6px;
    }

    .signature-hint {
      font-size: 14px;
      color: #94a3b8;
    }

    .signature-img {
      width: 100%;
      height: 100%;
    }
  }
}

.desc-textarea {
  padding: 12px;
  border: 1px solid #e5e5e5;
  border-radius: 12px;
  font-size: 14px;

  :deep(.van-field__control) {
    color: #333;
  }
}

.save-section {
  padding: 0 16px;

  .save-btn {
    height: 48px;
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    border: none;
    border-radius: 16px;
    font-size: 16px;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
  }
}

.signature-popup {
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 16px;
  border-bottom: 1px solid #e5e5e5;
  background: white;

  .popup-cancel {
    font-size: 15px;
    color: #666;
  }

  .popup-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .popup-confirm {
    font-size: 15px;
    color: #2563eb;
    font-weight: 600;
  }
}

.canvas-wrapper {
  flex: 1;
  padding: 16px;
  overflow: hidden;
}

.signature-canvas {
  width: 100%;
  height: 100%;
  background: white;
  border-radius: 12px;
  border: 1px solid #e5e5e5;
  touch-action: none;
  cursor: crosshair;
}

.popup-footer {
  padding: 12px 16px;
  display: flex;
  justify-content: center;
  background: white;
  border-top: 1px solid #e5e5e5;
}
</style>