<template>
  <van-popup ref="popupRef" position="bottom" v-model:show="show">
    <div class="rounded-t-[15px] pb-10 bg-[#F5F7FA]">
      <div class="flex items-center justify-between pt-[12px] pb-[12px] relative">
        <div class="flex flex-col items-center flex-1">
          <div class="flex-1 text-[16px] text-[#181B25] text-center">
            {{ t("order.qrcode.title") }}
          </div>
          <div class="flex-1 text-[12px] text-[#666666] text-center mt-[4px]">
            {{ t("order.qrcode.instruction") }}
          </div>
        </div>
        <!-- 关闭按钮 -->
        <van-icon class="top-[14px] right-[12px] absolute" name="cross" size="20" color="#CACFD8"
          @click="handleClose" />
      </div>

      <div class="bg-white rounded-[12px] flex flex-col items-center justify-center p-[12px] mb-[12px] mx-[12px]">
        <div class="flex w-full flex-row items-center justify-between py-[4px]">
          <div>
            <div class="text-[16px] font-medium text-black leading-[24px] truncate">
              {{ selectedVoucher.name }}
            </div>
          </div>

          <div v-if="selectedVoucher" class="flex flex-row">
            <div class="bg-[#F5F7FA] text-[#666666] font-medium px-[4px] rounded-[4px] mr-[4px]">
              {{ t("order.qrcode.total") }}{{ selectedVoucher.count }}{{ selectedVoucher.unit }}
            </div>
            <div class="bg-[#F0F8F3] text-[#0CCD58] text-[12px] p-[4px] rounded-[4px]">
              {{ t("order.qrcode.remaining") }}{{ selectedVoucher.count - selectedVoucher.writeOffCount
              }}{{ selectedVoucher.unit }}{{ t("order.qrcode.available") }}
            </div>
          </div>
        </div>

        <div
          class="flex flex-col w-full items-center justify-center rounded-[8px] border border-ink-200 pt-[16px] pb-[32px] mt-[12px]">
          <div class="flex flex-row justify-between w-full px-[12px]">
            <div class="bg-[#F9FAFB] text-[#0CCD58] text-[14px] px-[12px] leading-[24px] rounded-[12px]">
              {{ t("order.qrcode.voucher") }}{{
                selectedVoucherList.length > 1 ? currentVoucherIndex + 1 : ""
              }}
            </div>
            <div class="text-ink-500 text-[14px] px-[12px] leading-[24px] rounded-[12px]">
              {{ t("order.qrcode.onlyVerify") }}{{
                selectedVoucher.count - selectedVoucher.writeOffCount
              }}{{ t("order.qrcode.unit") }}
            </div>
          </div>

          <div class="flex items-center justify-center mt-[20px] p-[20px] rounded-[12px] border border-[#0CCD58]"
            :style="{ borderColor: selectedVoucher?.color }">
            <Qrcode v-if="showQrcode" :size="props.size" :unit="props.unit" :val="qrcodeVal" :loadMake="true"
              :onval="true" />
          </div>

          <div v-if="false"
            class="mt-[20px] bg-[#f0f8f3] text-[#0CCD58] text-[14px] px-12 leading-[24px] rounded-[12px]">
            {{ selectedVoucher.name }}
          </div>
        </div>

        <div v-if="selectedVoucherList.length > 1"
          class="flex flex-row w-full items-center justify-between mt-[16px] mb-[24px]">
          <div class="actions-btn" @click.stop="upAction">
            <van-icon name="arrow-left" size="16" color="#171717" />
          </div>

          <div class="flex flex-col">
            <div class="flex flex-row justify-center items-center">
              <div class="text-[#0CCD58] text-[16px]">
                {{ currentVoucherIndex + 1 }}
              </div>
              <div class="text-[#02C34E] text-[12px]">
                /{{ selectedVoucherList.length }}
              </div>
            </div>

            <div class="text-[#02C34E] text-[14px]">{{ t("order.qrcode.swipeHint") }}</div>
          </div>

          <div class="w-10 h-10 rounded-full bg-[#f5f5f5] flex items-center justify-center" @click.stop="downAction">
            <van-icon type="right" size="16" color="#171717" />
          </div>
        </div>
        <div v-else class="mb-[24px]"></div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, watch, computed, nextTick, defineProps, defineEmits, defineExpose } from "vue";
import { useI18n } from "vue-i18n";
import Qrcode from "@/components/Qrcode/index.vue";

const { t } = useI18n();

const props = defineProps({
  // 弹窗显示状态
  modelValue: {
    type: Boolean,
    default: false,
  },
  orderData: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  selectedVoucher: {
    type: Object,
    required: false,
    default: null,
  },
  selectedVoucherIndex: {
    type: Number,
    required: false,
    default: 0,
  },
  size: {
    type: Number,
    default: 132,
  },
  unit: {
    type: String,
    default: "px",
  },
});

// Events定义
const emit = defineEmits([
  "close",
  "update:modelValue",
  "update:selectedVoucherIndex",
]);

// 弹窗引用
const popupRef = ref(null);
const show = ref(false)

// 控制二维码渲染
const showQrcode = ref(false);

// 当前选择的凭证索引
const currentVoucherIndex = ref(props.selectedVoucherIndex || 0);

const selectedVoucherList = computed(() => {
  const list = props.orderData?.commodityPackageConfig || [];
  if (!Array.isArray(list)) return [];
  return list.filter((item) => item?.packageStatus === 0);
});

// 二维码内容
const selectedVoucher = computed(() => {
  const list = selectedVoucherList.value || [];
  if (!list.length) return null;
  const idx = Math.min(
    Math.max(Number(currentVoucherIndex.value || 0), 0),
    list.length - 1,
  );
  return list[idx] || null;
});

const qrcodeVal = computed(() => {
  const orderId = props.orderData?.orderId || "";
  const voucherName = selectedVoucher.value?.name || "";
  return orderId ? `${orderId}&${voucherName}` : "";
});

// 方法定义
const open = () => show.value = true;
const close = () => show.value = false;

const handlePopupChange = ({ show }) => {
  // popup 真实打开后再渲染二维码，避免 canvas 尺寸为 0 报错
  if (show) {
    nextTick(() => {
      showQrcode.value = true;
    });
  } else {
    showQrcode.value = false;
  }
};

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      showQrcode.value = false;
      show();
    } else {
      showQrcode.value = false;
      hide();
    }
  },
  { immediate: true },
);

// 同步外部 prop -> 内部 index（初始化/外部变更）
watch(
  () => props.selectedVoucherIndex,
  (newIdx) => {
    const len = selectedVoucherList.value.length;
    let idx = Number(newIdx || 0);
    if (len && idx >= len) idx = 0;
    currentVoucherIndex.value = idx;
  },
  { immediate: true },
);

// 当可用凭证列表变化时，确保 currentVoucherIndex 不越界
watch(
  selectedVoucherList,
  (list) => {
    const len = list.length;
    if (len === 0) {
      if (currentVoucherIndex.value !== 0) {
        currentVoucherIndex.value = 0;
      }
      return;
    }
    if (currentVoucherIndex.value >= len) {
      currentVoucherIndex.value = 0;
    }
  },
  { immediate: true },
);

// 当内部索引变化时，通知父组件（避免无用循环）
watch(
  () => currentVoucherIndex.value,
  (val, oldVal) => {
    if (val !== props.selectedVoucherIndex) {
      emit("update:selectedVoucherIndex", val);
    }
  },
);

const handleClose = () => {
  emit("update:modelValue", false);
  emit("close");
};

const upAction = () => {
  const len = selectedVoucherList.value.length;
  if (!len) return;
  let idx = Number(currentVoucherIndex.value || 0) - 1;
  if (idx < 0) idx = len - 1;
  currentVoucherIndex.value = idx;
};

const downAction = () => {
  const len = selectedVoucherList.value.length;
  if (!len) return;
  let idx = Number(currentVoucherIndex.value || 0) + 1;
  if (idx >= len) idx = 0;
  currentVoucherIndex.value = idx;
};

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