<template>
  <uni-popup ref="popup" type="center" borderRadius="12px 12px 0 0" @change="changePopup">
    <view class="popup-inner">
      <view v-show="!fileCount" class="title">请扫码上传附件</view>
      <view v-show="!fileCount" class="img-box">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <uni-load-more status="loading" :icon-size="24" :content-text="loadingText" />
        </view>
        <canvas canvas-id="qrcode" id="qrcode" />
      </view>
      <view class="tips" v-if="!loading">
        已上传
        <span class="num">{{ fileCount }}</span>
        个文件
      </view>
      <view v-show="!fileCount" class="tips" v-if="!loading">请使用手机扫描二维码上传文件</view>
      <view v-show="fileCount" class="file-list">
        <view v-for="(file, index) in fileList" class="file-item">
          <image
            class="file-icon"
            @click="preViewImage(file)"
            v-if="isImage(file.fileSuffix)"
            :src="file.fileUrl"
            mode="scaleToFill"
          ></image>
          <FileIcon v-else class="file-icon" :type="file.fileSuffix"></FileIcon>
          <view class="right">
            <view class="file-name">{{ file.originalName }}</view>
            <FileText :type="file.fileSuffix"></FileText>
          </view>
          <view class="remove-btn" @click="delFile(file, index)">×</view>
        </view>
      </view>
      <view v-show="fileCount" class="confirm-btn btn-feel" @click="handleConfirm">确认</view>
      <view class="close-btn" @click="close"></view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, inject, onUnmounted, watch, computed } from 'vue';
import FileIcon from './fileIcon.vue';
import FileText from './fileText.vue';
import uQRCode from '@/static/js/qrcode';
import config from '@/config';
import { onShow, onHide } from '@dcloudio/uni-app';
import { UUID } from '../../../lib/uuid-min';
const props = defineProps({
  sessionId: {
    type: [Number, String],
    default: '',
  },
  leaveFileCount: {
    type: [Number, String],
    default: 2,
  },
});

const emit = defineEmits(['onSend', 'onClose']);
const { $api } = inject('globalFunction');

const popup = ref(null);
const loading = ref(false);
const pollingTimer = ref(null);
const isPolling = ref(false);
const isVisible = ref(false);
const uuid = ref(null);
const fileList = ref([]);
const deleting = ref(false);

const fileCount = computed(() => {
  return fileList.value.length ?? 0;
});

// 计算加载文本
const loadingText = computed(() => ({
  contentdown: '二维码生成中',
  contentrefresh: '二维码生成中',
}));

onUnmounted(() => {
  stopPolling();
  clearResources();
});

function isImage(type) {
  if (!type || typeof type !== 'string') return false;
  const imageTypes = [
    'jpg',
    'jpeg',
    'png',
    'gif',
    'bmp',
    'webp',
    'svg',
    'tiff',
    'tif',
    'ico',
    'apng',
    'avif',
    'heic',
    'heif',
    'jfif',
  ];
  const lowerType = type.toLowerCase();

  return imageTypes.some((item) => lowerType.includes(item));
}
function preViewImage(file) {
  if (file.fileUrl) {
    uni.previewImage({
      urls: [file.fileUrl],
    });
  } else {
    $api.msg('文件地址丢失');
  }
}
async function delFile(file, idx) {
  deleting.value = true;
  try {
    await $api.createRequest(`/app/kiosk/remove?sessionId=${uuid.value}&ids=${file.id}`, {}, 'post', true);
  } catch (error) {
    $api.msg(error);
  } finally {
    deleting.value = false;
  }
  fileList.value.splice(idx, 1);
  if(fileList.value.length == 0){
    open()
  }
}

function open() {
  uuid.value = UUID.generate();
  resetState();
  isVisible.value = true;
  popup.value.open();
  initQrCode();
}

function close() {
  isVisible.value = false;
  stopPolling();
  popup.value.close();
  resetState();
}

function changePopup(e) {
  if (e.show) {
  } else {
    stopPolling();
    emit('onClose');
  }
}

function handleConfirm() {
  emit('onSend', fileList.value);
  close();
}

// 重置所有状态
function resetState() {
  fileList.value = [];
  loading.value = false;
  stopPolling();
}

async function initQrCode() {
  try {
    loading.value = true;
    // 清除之前的二维码
    clearCanvas();
    await makeQrcode();
    // 二维码生成成功后开始轮询
    if (isVisible.value) {
      startPolling();
    }
  } catch (error) {
    console.error('生成二维码失败:', error);
    uni.showToast({
      title: '生成二维码失败，请重试',
      icon: 'none',
    });
    close();
  } finally {
    loading.value = false;
  }
}

function makeQrcode() {
  const protocol = window.location.protocol;
  const host = window.location.host;
  const isLocal = host.includes('localhost') || host.includes('127.0.0.1');
  // const pathPrefix = isLocal ? '' : '/rgpp-api/all-in-one';
  let pathPrefix = '';
  if (host.includes('localhost') || host.includes('127.0.0.1')) {
    pathPrefix = '';
  } else if (host.includes('qd.zhaopinzao8dian.com')) {
    // 外网测试环境
    pathPrefix = '/app';
  } else if (host.includes('fw.rc.qingdao.gov.cn')) {
    // 青岛政务网环境
    pathPrefix = '/rgpp-api/all-in-one';
  } else {
    pathPrefix = '';
  }
  const htmlPath = `${protocol}//${host}${pathPrefix}/static/upload.html?sessionId=${uuid.value}&uploadApi=${config.baseUrl}/app/kiosk/upload&fileCount=${props.leaveFileCount}`;

  // const htmlPath = `${window.location.host}/static/upload.html?sessionId=${uuid.value}&uploadApi=${
  //   config.baseUrl + '/app/kiosk/upload'
  // }`;
  //   const htmlPath = `${window.location.host}/static/upload.html?sessionId=${props.sessionId}&uploadApi=${
  //     config.baseUrl + '/app/kiosk/upload'
  //   }`;
  console.log(htmlPath);
  console.log('剩余可上传文件数量:', props.leaveFileCount);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      uQRCode.make({
        canvasId: 'qrcode',
        text: htmlPath,
        size: uni.upx2px(300),
        margin: 0,
        backgroundColor: '#ffffff',
        foregroundColor: '#1677ff',
        fileType: 'png',
        correctLevel: uQRCode.defaults.correctLevel,
      });
      resolve();
    }, 100);
  });
}

// 清除画布
function clearCanvas() {
  const ctx = uni.createCanvasContext('qrcode');
  ctx.clearRect(0, 0, uni.upx2px(300), uni.upx2px(300));
  ctx.draw();
}

function startPolling() {
  if (isPolling.value) return;

  isPolling.value = true;
  console.log('开始轮询');

  // 轮询检查上传状态
  const poll = async () => {
    if (!isPolling.value || !isVisible.value || deleting.value) return;
    const { data } = await $api.createRequest('/app/kiosk/list', { sessionId: uuid.value });
    // const { data } = await $api.createRequest('/app/kiosk/list',{sessionId:props.sessionId});
    if (data && data.length) {
      fileList.value = data;
    }
    if (isPolling.value && isVisible.value) {
      pollingTimer.value = setTimeout(poll, 2000); // 每2秒轮询一次
    }
  };
  poll();
}

function stopPolling() {
  isPolling.value = false;
  if (pollingTimer.value) {
    clearTimeout(pollingTimer.value);
    pollingTimer.value = null;
  }
  console.log('停止轮询');
}

function clearResources() {
  stopPolling();
  clearCanvas();
}

defineExpose({ open, close });
</script>

<style lang="scss" scoped>
.popup-inner {
  padding: 40rpx 30rpx 50rpx;
  width: 520rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  border-radius: 20rpx;
  background: linear-gradient(135deg, #fafafa 0%, #f0f7ff 100%);
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
}

.title {
  font-size: 32rpx;
  color: #1a1a1a;
  margin-bottom: 30rpx;
  font-weight: 600;
  text-align: center;
  position: relative;
  padding-bottom: 16rpx;

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 4rpx;
    background: linear-gradient(90deg, #4191fe 0%, #256bfa 100%);
    border-radius: 2rpx;
  }
}

.img-box {
  margin: 0 auto 30rpx;
  width: 300rpx;
  height: 300rpx;
  background: linear-gradient(145deg, #ffffff 0%, #f8faff 100%);
  border-radius: 16rpx;
  overflow: hidden;
  position: relative;
  box-shadow: 0 8rpx 32rpx rgba(65, 145, 254, 0.2);
  padding: 20rpx;
  border: 2rpx solid rgba(65, 145, 254, 0.1);

  canvas {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
    transition: all 0.3s ease;
    animation: canvasFadeIn 0.5s ease;
  }
}

@keyframes canvasFadeIn {
  0% {
    opacity: 0;
    transform: scale(0.95);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: translateY(20rpx);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.file-list {
  margin-top: 30rpx;
  width: 470rpx;
  max-height: 60vh;
  overflow-x: hidden;
  overflow-y: auto;
  padding-right: 10rpx;

  .file-item {
    width: 100%;
    padding: 25rpx;
    padding-right: 15rpx;
    box-sizing: border-box;
    border: 1px solid #bbc5d1;
    display: flex;
    align-items: center;
    animation: fadeIn 0.5s ease;
    background: linear-gradient(135deg, #ffffff 0%, #f0f8ff 100%);
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 6rpx;
      height: 100%;
      background: linear-gradient(180deg, #4191fe 0%, #256bfa 100%);
      border-radius: 3rpx 0 0 3rpx;
    }

    &:hover {
      transform: translateY(-2rpx);
      box-shadow: 0 8rpx 24rpx rgba(65, 145, 254, 0.15);
    }

    .file-icon {
      width: 80rpx;
      height: 80rpx;
      margin-right: 20rpx;
      border-radius: 12rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
      transition: transform 0.3s ease;

      &:active {
        transform: scale(0.95);
      }
    }

    .right {
      flex: 1;
      overflow: hidden;
      min-width: 0;

      .file-name {
        font-size: 30rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: 500;
        color: #1a1a1a;
        margin-bottom: 8rpx;
        transition: color 0.3s ease;
      }

      .file-size {
        font-size: 24rpx;
        color: #838383;
      }
    }

    .remove-btn {
      background: none;
      border: none;
      color: #ff6b6b;
      font-size: 52rpx;
      cursor: pointer;
      margin-left: 20rpx;
      flex-shrink: 0;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      transition: all 0.3s ease;
      margin-top: -15rpx;

      &:active {
        background-color: rgba(255, 107, 107, 0.1);
        transform: scale(0.9);
      }
    }
  }
}

.confirm-btn {
  font-weight: 500;
  font-size: 32rpx;
  color: #ffffff;
  text-align: center;
  width: 350rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(135deg, #4191fe 0%, #256bfa 100%);
  border-radius: 16rpx;
  margin-top: 30rpx;
  transition: all 0.3s ease;
  box-shadow: 0 8rpx 24rpx rgba(37, 107, 250, 0.3);
  position: relative;
  overflow: hidden;

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.6s ease;
  }

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 16rpx rgba(37, 107, 250, 0.4);

    &::after {
      left: 100%;
    }
  }
}

.loading-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(145deg, #ffffff 0%, #f8faff 100%);
  border-radius: 16rpx;
}

.tips {
  font-size: 26rpx;
  color: #666;
  text-align: center;
  line-height: 1.6;
  padding: 0 20rpx;
  margin-top: 10rpx;
  animation: fadeIn 0.5s ease;

  .num {
    color: #4191fe;
    font-size: 28rpx;
    font-weight: 600;
    margin: 0 8rpx;
    position: relative;
  }
}

.close-btn {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #ffffff 0%, #f8faff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  z-index: 10;

  &:active {
    transform: scale(0.9) rotate(90deg);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
  }

  &::before,
  &::after {
    content: '';
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 24rpx;
    height: 2rpx;
    background: #5a5a68;
    border-radius: 1rpx;
    transition: all 0.3s ease;
  }

  &::before {
    transform: translate(-50%, -50%) rotate(45deg);
  }

  &::after {
    transform: translate(-50%, -50%) rotate(-45deg);
  }
}
</style>
