<script setup lang="ts">
import { runLogic } from '@af-mobile-client-vue3/services/api/common'
import { mobileUtil } from '@af-mobile-client-vue3/utils/mobileUtil'
import {
  Button as VanButton,
  Popup as VanPopup,
} from 'vant'
import { onUnmounted, ref, watch } from 'vue'

interface PrintItem {
  type?: string
  text?: string
  align?: 'left' | 'center' | 'right'
  isbold?: boolean
  fontsize?: number
  value?: number
  unit?: string
  [key: string]: any
}

const props = defineProps({
  title: {
    type: String,
    default: '电子凭证',
  },
  subTitle: {
    type: String,
    default: '',
  },
  showSaveButton: {
    type: Boolean,
    default: true,
  },
  saveButtonText: {
    type: String,
    default: '打印',
  },
  closeButtonText: {
    type: String,
    default: '完成',
  },
})

const emit = defineEmits(['update:show', 'ok', 'close'])

// 保存原始滚动位置和样式
const scrollPosition = ref(0)
const documentWidth = ref(0)
// 是否显示弹窗
const show = ref(false)
// 打印列表
const printList = ref<PrintItem[]>([])
// 获取祖父组件的方法
// const success = inject('success')

// 锁定滚动
function lockScroll() {
  // 保存当前滚动位置
  scrollPosition.value = window.pageYOffset
  // 保存文档原始宽度以防止滚动条消失导致的页面抖动
  documentWidth.value = document.documentElement.clientWidth
  // 弹窗打开时，给body添加类以禁止滚动
  document.body.classList.add('receipt-modal-open')
  // 设置body的top位置，保持视觉位置不变
  document.body.style.top = `-${scrollPosition.value}px`
  // 保持页面宽度不变，防止滚动条消失导致的布局偏移
  document.body.style.width = `${documentWidth.value}px`
}

// 解除滚动锁定
function unlockScroll() {
  // 弹窗关闭时，移除禁止滚动的类
  document.body.classList.remove('receipt-modal-open')
  // 恢复body样式
  document.body.style.top = ''
  document.body.style.width = ''
  // 恢复滚动位置
  window.scrollTo(0, scrollPosition.value)
}

// 调用Logic组织打印参数
async function printParams(printLogic: string, printId: string, otherParams?: any) {
  try {
    printList.value = await runLogic(printLogic, { id: printId, otherParams })
    console.log('打印参数==', printList.value)
    if (printList.value.length > 0) {
      show.value = true
    }
    else {
      // 没查到数据默认不打印
      close()
    }
  }
  catch (error) {
    console.error('Error calling logic:', error)
  }
}

// 打印
function ok() {
  // 实际项目中应添加收据截图保存逻辑
  mobileUtil.execute({
    funcName: 'print',
    param: { data: printList.value },
    callbackFunc: (result) => {
      // emit('ok', { status: true })
      emit('close', { status: true })
    },
  })
}

// 关闭弹窗
function close() {
  show.value = false
  emit('close', { status: true })
  // if (typeof success === 'function') {
  //   success()
  // }
}

// 监听show变化，控制body滚动
watch(() => show.value, (newVal, oldVal) => {
  if (newVal && !oldVal) {
    lockScroll()
  }
  else if (!newVal && oldVal) {
    unlockScroll()
  }
}, { immediate: true })

// 组件卸载时确保移除类和恢复滚动
onUnmounted(() => {
  if (document.body.classList.contains('receipt-modal-open')) {
    unlockScroll()
  }
})

// 暴露组织参数的给父组件调用
defineExpose({ printParams, close })
</script>

<template>
  <VanPopup
    :show="show"

    :close-on-click-overlay="false"
    position="center"
    round lock-scroll
    class="receipt-modal"
    :style="{ width: '90%', maxWidth: '375px' }"
  >
    <div class="receipt-modal-container">
      <div class="receipt-modal-header">
        <div class="receipt-modal-title-container">
          <div class="receipt-modal-title">
            {{ props.title }}
          </div>
          <div v-if="subTitle" class="receipt-modal-subtitle">
            {{ props.subTitle }}
          </div>
        </div>
      </div>
      <div class="receipt-modal-content">
        <template v-for="(item, index) in printList" :key="index">
          <div
            v-if="item?.text !== undefined"
            class="print-list-item"
            :style="{
              'text-align': item.align || undefined,
              'font-weight': item.isbold ? 'bold' : undefined,
              'font-size': item.fontsize ? `${item.fontsize * 7}px` : undefined,
              'color': '#6b7280',
            }"
          >
            {{ item.text }}
          </div>
        </template>
      </div>
      <div class="receipt-modal-footer">
        <VanButton
          v-if="showSaveButton"
          class="save-button"
          type="primary"
          @click="ok"
        >
          {{ saveButtonText }}
        </VanButton>
        <VanButton class="close-button" @click="close">
          {{ closeButtonText }}
        </VanButton>
      </div>
    </div>
  </VanPopup>
</template>

<style lang="less">
/* 全局样式，不使用scoped */
body.receipt-modal-open {
  overflow: hidden !important;
  position: fixed !important;
  width: 100% !important;
  height: 100% !important;
  left: 0 !important;
  /* top设置由JS动态控制 */
}
</style>

<style lang="less" scoped>
.receipt-modal {
  z-index: 1000;
  border-radius: 8px;
  overflow: hidden;
}

.receipt-modal-container {
  display: flex;
  flex-direction: column;
  max-height: 80vh;
  padding: 16px;
  box-sizing: border-box;
}

.receipt-modal-header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
}

.receipt-modal-title-container {
  text-align: center;
}

.receipt-modal-title {
  font-size: 18px;
  font-weight: bold;
}

.receipt-modal-subtitle {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.receipt-modal-content {
  flex: 1;
  overflow-y: auto;
  max-height: 50vh;
}

.receipt-modal-footer {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  margin-top: 16px;
  padding-bottom: 8px;
  padding-left: 16px;
  padding-right: 16px;
}

.save-button,
.close-button {
  flex: 1;
  height: 36px;
  font-size: 14px;
  max-width: 120px;
}

.print-list-item {
  padding: 8px 0;
  // border-bottom: 1px solid #eee;
}
</style>
