<template>
  <view class="content-container" v-if="isVisible && isInitialized">
    <view class="slot-container">
      <view class="slot-icon">
        <image
          src="https://image.zfunbox.cn/static/image/lucky/icon.png"
          mode="widthFix"
          style="height: 90rpx; width: 249rpx"
        ></image>
      </view>
      <view class="slot-view">
        <!-- 老虎机组件 -->
        <SlotMachine
          ref="myLucky"
          :width="windowWidth"
          height="160rpx"
          :blocks="blocks"
          :slots="slots"
          :prizes="prizes"
          :defaultConfig="defaultConfig"
          @start="startCallBack"
          @end="endCallBack"
        >
        </SlotMachine>
      </view>
    </view>
  </view>
</template>

<script>
// 导入老虎机组件
import SlotMachine from "@/components/@lucky-canvas/uni/slot-machine";

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    // 生成一个 0 到 i 之间的随机整数
    const j = Math.floor(Math.random() * (i + 1));
    // 交换 array[i] 和 array[j]
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

export default {
  components: { SlotMachine },
  props: {
    // 移除prizeList props
  },
  data() {
    return {
      isVisible: false, // 控制组件显示/隐藏
      isInitialized: false, // 控制是否已初始化
      windowWidth: "0px",
      blocks: [],
      slots: [],
      prizes: [],
      prizeList: [], // 移到data中
      defaultConfig: {
        mode: "horizontal", // 水平模式
        rowSpacing: "10px", // 行间距
        colSpacing: "10px", // 列间距
        accelerationTime: 1500,
      },
      luckyMessage: "恭喜您获得奖品",
      luckyPrize: null,
      currentPrizeIndex: -1,
    };
  },
  computed: {
    // 计算抽奖项尺寸
    lotteryItemSize() {
      let height = uni.upx2px(220);
      let width = uni.upx2px(170);
      return [width, height];
    },
  },
  methods: {
    // 初始化老虎机组件
    init(prizeList) {
      // 设置奖品列表
      if (prizeList && Array.isArray(prizeList) && prizeList.length > 0) {
        this.prizeList = prizeList;
      } else {
        this.prizeList = this.getDefaultPrizes();
      }

      let windowWidth = uni.getSystemInfoSync().windowWidth;
      let t = this.prizeList;

      let prizes = [];
      for (let i = 0; i < t.length; i++) {
        prizes.push({
          imgs: [
            {
              src: t[i].imgurl,
              width: "152.78rpx",
              height: "152.78rpx",
            },
          ],
          background: "#ffffff",
          data: t[i], // 将原始数据保存到prize中，方便后续使用
        });
      }
      const arr = Array.from({ length: t.length }, (_, i) => i);
      let slots = [
        { order: shuffle([...arr]), speed: 20 }, // 第一列速度
      ];

      this.windowWidth = windowWidth + "px";
      this.slots = slots;
      this.prizes = prizes;

      // 标记为已初始化
      this.isInitialized = true;

      return this; // 返回this以支持链式调用
    },

    // 显示老虎机组件
    show() {
      if (!this.isInitialized) {
        console.error("老虎机尚未初始化，请先调用init方法");
        return this;
      }
      this.isVisible = true;
      return this;
    },

    // 隐藏老虎机组件
    hide() {
      this.isVisible = false;
      return this;
    },

    // 获取默认奖品列表
    getDefaultPrizes() {
      return [
        {
          id: 1128,
          title: "兹琪露娜提亚斯",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/2986e27e673ef675e02771cdebd9b822.jpg",
          price: "350.00",
          real_pro: "0.02000",
          goods_type: 1,
          doubling: 1,
          is_lingzhu: 0,
        },
        {
          id: 1129,
          title: "月岗恋钟",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/2c5ed2097716db6bef01da718bc3c091.jpg",
          price: "132.00",
          real_pro: "0.02000",
          goods_type: 1,
          doubling: 3,
          is_lingzhu: 0,
        },
        {
          id: 1130,
          title: "BANDAI万代拼装模型 1/100 MG 机动战士高达 倒A 逆A-15岁以上",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/e35da49b4976f156f2f98dec002274a5.png",
          price: "305.00",
          real_pro: "0.03000",
          goods_type: 1,
          doubling: 1,
          is_lingzhu: 0,
        },
        {
          id: 1131,
          title: "BANDAI 万代拼装模型 MG 主天使-15岁以上",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/77302c6f1ea9ea6a8516cc1208174aee.png",
          price: "289.00",
          real_pro: "0.03000",
          goods_type: 1,
          doubling: 1,
          is_lingzhu: 0,
        },
        {
          id: 1132,
          title: "BANDAI万代 HG00 09 1/144 座天使高达一型-15岁以上",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/55e816c93b5e4103a30682c586816b11.jpg",
          price: "114.00",
          real_pro: "0.50000",
          goods_type: 1,
          doubling: 3,
          is_lingzhu: 0,
        },
        {
          id: 1133,
          title: "BANDAI万代拼装模型 HGUC 130 机动战士高达 杰斯塔-15岁以上",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/aeb6bfb8b4aa8a29796b242e4f5d56d9.png",
          price: "113.00",
          real_pro: "1.50000",
          goods_type: 1,
          doubling: 1,
          is_lingzhu: 0,
        },
        {
          id: 1134,
          title: "BANDAI万代拼装模型HG26 1/144 凯列班高达 异灵高达-15岁以上",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/329e3a7e21772a63cea03d31f948345d.png",
          price: "112.00",
          real_pro: "1.00000",
          goods_type: 1,
          doubling: 2,
          is_lingzhu: 0,
        },
        {
          id: 1135,
          title: "梦幻",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/d2c7e48515d393084000595074209042.jpg",
          price: "41.00",
          real_pro: "2.50000",
          goods_type: 1,
          doubling: 2,
          is_lingzhu: 0,
        },
        {
          id: 1136,
          title: "谜拟丘",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/6031827bc455cbf86ff778d74ddffbd3.jpg",
          price: "38.00",
          real_pro: "1.50000",
          goods_type: 1,
          doubling: 1,
          is_lingzhu: 0,
        },
        {
          id: 1137,
          title: "小提琴模型1个",
          imgurl:
            "https://image.zfunbox.cn/topic/20250515/22846dea5a933ab314998afc51abb7bb.jpg",
          price: "13.80",
          real_pro: "92.90000",
          goods_type: 1,
          doubling: 1,
          is_lingzhu: 0,
        },
      ];
    },

    // 老虎机开始回调
    startCallBack() {
      console.log("开始抽奖");
      this.$emit("start");
    },

    // 抽奖结束回调
    endCallBack(prize) {
      // 奖品详情
      console.log("抽奖结束", prize);

      try {
        // 准备中奖信息
        const prizeData =
          this.prizes[this.currentPrizeIndex]?.data || this.prizes[0]?.data;

        if (!prizeData) {
          console.error("无法获取奖品数据");
          return;
        }

        // 获取所有中奖奖品
        let allPrizes = [];

        // 检查prize是否是数组，如果是则使用map，否则只使用当前prize
        if (Array.isArray(prize)) {
          allPrizes = prize
            .map((item) => {
              const index = typeof item.index === "number" ? item.index : 0;
              return this.prizes[index]?.data || this.prizes[0]?.data;
            })
            .filter((item) => !!item);
        } else if (prize && typeof prize.index === "number") {
          // 如果prize是单个对象
          const index = prize.index;
          const itemData = this.prizes[index]?.data;
          if (itemData) {
            allPrizes.push(itemData);
          }
        } else {
          // 都不符合则使用当前索引的奖品
          allPrizes.push(prizeData);
        }

        // 发送中奖信息到父组件
        this.$emit("end", {
          prize: prize,
          prizeData: prizeData, // 主要奖品数据
          allPrizes: allPrizes, // 所有中奖奖品数据
          message: `恭喜您获得 ${prizeData.title}`,
          prizeInfo: {
            name: prizeData.title,
            image: prizeData.imgurl,
            description: `价值：${prizeData.price} 元`,
            data: prizeData,
          },
        });

        // 延迟隐藏组件
        setTimeout(() => {
          this.hide();
        }, 2000);
      } catch (error) {
        console.error("处理抽奖结果时出错:", error);
        this.hide();
      }
    },

    // 开始抽奖方法
    startDraw(callback) {
      // 检查是否已初始化
      if (!this.isInitialized) {
        console.error("老虎机尚未初始化，请先调用init方法");
        return this;
      }

      // 不再自动初始化，需要先手动调用init
      this.show();

      setTimeout(() => {
        // 确保DOM已渲染完成后再调用play方法
        this.$nextTick(() => {
          // 检查组件是否已初始化
          if (this.$refs.myLucky) {
            // 开始旋转
            this.$refs.myLucky.play();
            if (this.bgmCtx && this.bgmCtx.slotBgm) {
              this.bgmCtx.slotBgm.play();
            }

            if (typeof callback === "function") {
              callback();
            }
          } else {
            console.error("老虎机组件未初始化");
          }
        });
      }, 100);

      return this; // 返回this以支持链式调用
    },

    // 停止抽奖并指定中奖索引
    stopDraw(prizeIndices) {
      // 检查是否已初始化
      if (!this.isInitialized) {
        console.error("老虎机尚未初始化，请先调用init方法");
        return this;
      }

      if (!this.$refs.myLucky) {
        console.error("老虎机组件未初始化");
        return this;
      }

      // 如果没有传入奖品索引数组或传入的不是数组
      if (
        !prizeIndices ||
        !Array.isArray(prizeIndices) ||
        prizeIndices.length === 0
      ) {
        // 生成5个随机索引
        const randomIndices = [];
        for (let i = 0; i < 5; i++) {
          randomIndices.push(Math.floor(Math.random() * this.prizes.length));
        }
        this.currentPrizeIndex = randomIndices[0]; // 使用第一个作为主要中奖索引
        this.$refs.myLucky.stop(randomIndices);
        return this;
      }

      // 如果传入的数组长度不够5个，补足到5个
      let indices = [...prizeIndices];
      while (indices.length < 5) {
        indices.push(indices[indices.length - 1] || 0);
      }

      // 确保所有索引都在有效范围内
      indices = indices.map((index) => {
        if (index < 0 || index >= this.prizes.length) {
          return Math.floor(Math.random() * this.prizes.length);
        }
        return index;
      });

      // 记录第一个索引作为主要中奖索引
      this.currentPrizeIndex = indices[0];

      // 调用stop方法停止旋转
      this.$refs.myLucky.stop(indices[0]);

      return this;
    },

    // 强制结束抽奖
    forceEndDraw() {
      if (!this.isInitialized) {
        console.error("老虎机尚未初始化，请先调用init方法");
        return this;
      }

      this.hide();
      return this; // 返回this以支持链式调用
    },

    // 重置组件状态
    reset() {
      this.isInitialized = false;
      this.isVisible = false;
      this.slots = [];
      this.prizes = [];
      this.prizeList = [];
      this.currentPrizeIndex = -1;
      return this;
    },
  },
  mounted() {
    // 不再自动初始化
  },
};
</script>

<style lang="scss" scoped>
// 内容容器样式
.content-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  background-image: url($imgurl + "common/slot_bg.webp");
  background-size: cover;
  background-position: center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
}

// 老虎机容器样式
.slot-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.slot-icon {
  padding-bottom: 25rpx;
}
// 老虎机视图样式
.slot-view {
  background: url("https://image.zfunbox.cn/static/image/lucky/di_5.png")
    no-repeat;
  background-size: 100% 100%;
  width: 100%;
  padding-top: 80rpx;
  padding-bottom: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

// 抽奖项样式
.item-lottry {
  height: 152.78rpx;
  width: 152.78rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30rpx;
  border-radius: 16rpx;
  color: black;
  box-sizing: border-box;
  background-color: rgba(255, 255, 255, 1);
}
</style>
