<template>
  <uni-popup ref="answerPopup" type="bottom" :maskClick="false" :safe-area="true">
    <view class="answer-popup-container">
      <view class="answer-popup">
        <!-- 关闭按钮 -->
        <view class="close-btn" @tap="handleClose">
          <image :src="`${$baseUrl}homepage/Q3Res/canEatCloseBtn.png`" mode="aspectFit"></image>
        </view>

        <!-- 结果标题和图标 -->
        <view class="result-header">
          <text class="result-title">{{ isCorrect ? '你太棒了，回答正确！' : '快来补课吧，回答错误哦!' }}</text>
          <view class="result-icon">
            <image class="correct" v-if="isCorrect" :src="`${$baseUrl}homepage/Q3Res/eat_goodIcon.png`"
              mode="aspectFit"></image>
            <image class="incorrect" v-else :src="`${$baseUrl}homepage/Q3Res/eat_cryIcon.png`" mode="aspectFit"></image>
          </view>
        </view>

        <!-- 奖励信息 -->
        <view v-if="rewardInfo && isCorrect" class="reward-info">
          已获得{{ rewardInfo }}
        </view>
        <!-- 错误状态下也保留相同高度的空间 -->
        <view v-else class="empty-reward-space"></view>

        <!-- 选项分布 -->
        <view class="option-distribution">
          <view class="option-bar" v-for="(option, index) in displayOptionDistribution" :key="index">
            <text class="option-text">{{ option.label }}: {{ option.percentage }}</text>
          </view>
        </view>

        <!-- 题目和答案 -->
        <view class="question-answer-section">
          <text class="question-text">{{ question }}</text>
          <text class="answer-text">答案：{{ correctAnswer }}</text>
        </view>

        <!-- 解析内容 -->
        <view class="analysis-section">
          <text class="analysis-title">解析</text>
          <text class="analysis-content">{{ analysis }}</text>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import md from '../md';

export default {
  name: 'CanEatAnswerPopup',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isCorrect: {
      type: Boolean,
      default: false
    },
    rewardInfo: {
      type: String,
      default: ''
    },
    question: {
      type: String,
      default: ''
    },
    correctAnswer: {
      type: String,
      default: ''
    },
    analysis: {
      type: String,
      default: ''
    },
    allResult: {
      type: String,
      default: '25|25|25|25'
    },
    fallResult: {
      type: String,
      default: ''
    },
    optionDistribution: {
      type: Array,
      default: () => [
        { label: '能吃', percentage: '25%', color: '#B27C1E' },
        { label: '少吃', percentage: '25%', color: '#B27C1E' },
        { label: '慎吃', percentage: '25%', color: '#B27C1E' },
        { label: '禁吃', percentage: '25%', color: '#B27C1E' }
      ]
    }
  },
  computed: {
    // 根据fallResult或allResult字符串生成显示用的选项分布数据
    displayOptionDistribution() {
      const labels = ['能吃', '少吃', '慎吃', '禁吃'];

      // 确保所有数据都被正确记录
      console.log('AllResult数据:', this.allResult, '类型:', typeof this.allResult);
      console.log('FallResult数据:', this.fallResult, '类型:', typeof this.fallResult);

      // 首先检查fallResult
      if (this.fallResult && this.fallResult !== null && this.fallResult.trim() !== '' && this.fallResult.includes('|')) {
        try {
          const percentages = this.fallResult.split('|');
          console.log('使用fallResult生成分布:', percentages);
          return percentages.map((percent, index) => ({
            label: labels[index] || '',
            percentage: `${percent}%`
          }));
        } catch (error) {
          console.error('处理fallResult时出错:', error);
        }
      }

      // 然后检查allResult，使用更宽松的判断条件
      if (this.allResult && this.allResult !== null && typeof this.allResult === 'string') {
        // 即使不包含|符号，也尝试处理
        let percentages;
        if (this.allResult.includes('|')) {
          percentages = this.allResult.split('|');
        } else {
          // 尝试作为单个百分比处理
          percentages = [this.allResult, '0', '0', '0'];
        }
        console.log('使用allResult生成分布:', percentages);
        return percentages.map((percent, index) => ({
          label: labels[index] || '',
          percentage: `${percent}%`
        }));
      }

      // 最后使用默认的optionDistribution
      console.log('使用默认optionDistribution');
      return this.optionDistribution;
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.openPopup();
        } else {
          this.closePopup();
        }
      },
      immediate: true
    }
  },
  methods: {
    openPopup() {
      // 禁止背景页面滚动（小程序原生方式）
      wx.setPageStyle({
        style: {
          overflow: 'hidden'
        }
      });
      this.$refs.answerPopup.open();

      // 添加曝光埋点
      this.$nextTick(() => {
        md.sensorPopLogTake({
          xcxPopExposure: "true",
          toolName: "能不能吃",
          popName: "解析弹窗"
        });
      });
    },
    closePopup() {
      // 恢复背景页面滚动（小程序原生方式）
      wx.setPageStyle({
        style: {
          overflow: 'auto'
        }
      });
      if (this.$refs.answerPopup) {
        this.$refs.answerPopup.close();
      }
    },
    handleClose() {
      this.$emit('close');
    }
  }
}
</script>

<style scoped>
.answer-popup-container {
  width: 750rpx;
  position: relative;
  margin: 0 auto;
  bottom: -80rpx;
  overflow: visible;
}

.answer-popup {
  /* width: 100%;
  height: 100%; */
  background: #FFF9EB;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx 40rpx 60rpx 40rpx;
  position: relative;
  /* box-sizing: border-box; */
  overflow: visible;
  display: flex;
  flex-direction: column;
}

.close-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn image {
  width: 100%;
  height: 100%;
}

.result-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 60rpx;
}

.result-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #B27C1E;
  margin-right: 20rpx;
  flex: 1;
  line-height: 1.4;
}


.result-icon .correct {
  width: 164rpx;
  height: 164rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  top: -20rpx;

  left: -170rpx;
}

.result-icon .incorrect {
  width: 164rpx;
  height: 164rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  top: 0rpx;
  left: -120rpx;
}

.result-icon image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.reward-info {
  text-align: left;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.option-distribution {
  display: flex;
  gap: 3rpx;
  margin-bottom: 30rpx;
  align-items: center;
  width: 100%;
}

.option-bar {
  flex: 1;
  padding: 10rpx 15rpx;
  color: #fff;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  text-align: center;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

/* 从左到右4种颜色 - 反转顺序 */
.option-bar:nth-child(1) {
  border-radius: 50rpx 20rpx 50rpx 50rpx;
  background: #D3A458;
}

.option-bar:nth-child(2) {
  border-radius: 20rpx 10rpx 20rpx 10rpx;
  background: #B27C1E;
}

.option-bar:nth-child(3) {
  border-radius: 20rpx 10rpx 20rpx 10rpx;
  background: #8D5C05;
}

.option-bar:nth-child(4) {
  border-radius: 20rpx 50rpx 50rpx 20rpx;
  background: #644104;
}

/* 第一个选项只有右斜切 */
.option-bar:first-child {
  clip-path: polygon(0 0, 100% 0, 90% 100%, 0% 100%);
}

/* 中间的选项左右都有斜切 */
.option-bar:not(:first-child):not(:last-child) {
  clip-path: polygon(10% 0, 100% 0, 90% 100%, 0% 100%);
  margin-left: -12rpx;
}

/* 最后一个选项只有左斜切 */
.option-bar:last-child {
  clip-path: polygon(10% 0, 100% 0, 100% 100%, 0% 100%);
  margin-left: -12rpx;
}

.question-answer-section {
  background: #FFFFFF;
  /* height: 164rpx; */
  padding: 40rpx;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  overflow-y: auto;
}

.question-text {
  font-size: 28rpx;
  color: #333;
  display: block;
  font-weight: bolder;
  margin-bottom: 15rpx;
  line-height: 1.6;
}

.answer-text {
  font-size: 28rpx;
  color: #D3A358;
  display: block;
  /* font-weight: bold; */
}

.analysis-section {
  background: #FFFFFF;
  max-height: 446rpx;
  padding: 40rpx;
  border-radius: 36rpx;
  margin-bottom: 40rpx;
  overflow-y: auto;
}

.analysis-title {
  font-size: 30rpx;
  font-weight: bolder;
  color: #000;
  display: block;
  margin-bottom: 15rpx;
}

.analysis-content {
  font-size: 28rpx;
  color: #999999;
  line-height: 1.8;
  white-space: pre-wrap;
}

/* .confirm-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  background: #D3A358;
  color: #fff;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: bold;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
} */

.empty-reward-space {
  height: 40rpx;
  margin-bottom: 30rpx;
}
</style>