<script setup>
import { ref, onMounted, computed } from "vue";
import ScreenHint from "@/components/ScreenHint.vue";
import BowData from "@/components/BowData.vue";
import UserUpgrade from "@/components/UserUpgrade.vue";
import { directionAdjusts } from "@/constants";
import useStore from "@/store";
import { storeToRefs } from "pinia";

const store = useStore();
const { user } = storeToRefs(store);

const props = defineProps({
  onClose: {
    type: Function,
    default: () => { },
  },
  onRetry: {
    type: Function,
    default: () => { },
  },
  total: {
    type: Number,
    default: 0,
  },
  rowCount: {
    type: Number,
    default: 0,
  },
  result: {
    type: Object,
    default: () => ({}),
  },
  tipSrc: {
    type: String,
    default: "",
  },
});

const showPanel = ref(true);
const showComment = ref(false);
const showBowData = ref(false);
const showUpgrade = ref(false);

const closePanel = () => {
  showPanel.value = false;
  setTimeout(() => {
    props.onClose();
  }, 300);
};

const retryPractice = () => {
  showPanel.value = false;
  setTimeout(() => {
    props.onRetry();
  }, 300);
};

function onClickShare() {
  uni.$emit("share-image");
}

onMounted(() => {
  if (props.result.lvl > user.value.lvl) {
    showUpgrade.value = true;
  }
});

const details = computed(() => props.result.details || []);

const arrows = computed(() => {
  const data = new Array(props.total).fill(null);
  details.value.forEach((arrow, index) => {
    data[index] = arrow;
  });
  return data;
});

const validArrows = computed(() => arrows.value.filter((a) => !!a?.ring).length);
const totalRing = computed(() =>
  details.value.reduce((last, next) => last + (Number(next.ring) || 0), 0)
);

const gainedExp = computed(
  () => props.result.exp || props.result.experience || validArrows.value
);

const currentLevel = computed(
  () => props.result.lvl || user.value.lvl || user.value.rankLvl || 1
);

const currentExp = computed(
  () => props.result.currentExp || props.result.score || user.value.scores || 0
);

const nextExp = computed(
  () => props.result.nextExp || props.result.upgradeScore || 100
);

const expPercent = computed(() => {
  if (!nextExp.value) return 0;
  return Math.min(100, Math.max(0, (currentExp.value / nextExp.value) * 100));
});

const findValue = (...keys) => {
  const item = keys.find((key) => props.result[key] !== undefined);
  return item ? props.result[item] : undefined;
};

const formatDuration = (value) => {
  const seconds = Number(value || 0);
  if (!seconds) return "--";
  const minutes = Math.floor(seconds / 60);
  const rest = seconds % 60;
  return minutes ? `${minutes}分${rest}秒` : `${rest}秒`;
};

const usedTime = computed(() =>
  findValue("duration", "usedTime", "shootTime", "time")
);

const hitCompare = computed(
  () => Number(findValue("hitCompare", "hitDiff", "hitDelta") || 0)
);

const timeCompare = computed(
  () => Number(findValue("timeCompare", "timeDiff", "durationDiff") || 0)
);

const calories = computed(
  () => Number(findValue("calories", "calorie", "kcal") || 0)
);
</script>

<template>
  <view :class="['result-mask', showPanel ? 'result-mask--show' : 'result-mask--hide']">
    <image class="hero-glow" src="/static/training-difficulty-design/result-bg.png" mode="widthFix" />
    <view class="result-title">
      <image class="result-title-bg" src="/static/training-difficulty-design/result-t-bg.png" mode="widthFix" />
      <view class="result-title-text">Lv{{ currentLevel }}</view>
    </view>

    <view class="result-panel">
      <view class="line-top"></view>
      <view class="line-bottom"></view>
      <view class="stats">
        <view class="stat-row">
          <image class="stat-bg" src="/static/training-difficulty-design/result-c-bg.png" mode="scaleToFill" />
          <view class="stat-cell">
            <text class="stat-label">共命中目标</text>
            <view class="stat-value">
              <text>{{ validArrows }}</text>
              <text class="stat-unit">次</text>
            </view>
          </view>
          <view class="stat-divider"></view>
          <view class="stat-cell stat-cell--compare">
            <text class="stat-label">对比上次</text>
            <view class="stat-value">
              <text>{{ Math.abs(hitCompare) }}</text>
              <text class="stat-unit">次</text>
              <image class="trend-icon" :class="{ 'trend-icon--down': hitCompare < 0 }"
                src="/static/training-difficulty-design/result-up.png" mode="widthFix" />
            </view>
          </view>
        </view>

        <view class="stat-row">
          <image class="stat-bg" src="/static/training-difficulty-design/result-c-bg.png" mode="scaleToFill" />
          <view class="stat-cell">
            <text class="stat-label">用时</text>
            <view class="stat-value">
              <text>{{ formatDuration(usedTime) }}</text>
            </view>
          </view>
          <view class="stat-divider"></view>
          <view class="stat-cell stat-cell--compare">
            <text class="stat-label">对比上次</text>
            <view class="stat-value">
              <text>{{ formatDuration(Math.abs(timeCompare)) }}</text>
              <image class="trend-icon" :class="{ 'trend-icon--down': timeCompare <= 0 }"
                src="/static/training-difficulty-design/result-up.png" mode="widthFix" />
            </view>
          </view>
        </view>
         <view class="stat-row">
          <image class="stat-bg" src="/static/training-difficulty-design/result-c-bg.png" mode="scaleToFill" />
          <view class="stat-cell">
            <text class="stat-label">消耗卡路里</text>
            <view class="stat-value">
              <text>{{ calories }}卡</text>
            </view>
          </view>
          <text class="stat-equal">≈</text>
          <!-- <view class="stat-divider"></view> -->
          <view class="stat-cell stat-cell--compare">
            <view class="stat-value">
              <image v-for="index in 3" :key="index" class="rice-icon"
                  src="/static/training-difficulty-design/result-rice.png" mode="widthFix" />
            </view>
          </view>
        </view>

     
        <view class="actions">
          <view class="action-item" @click="() => (showBowData = true)">
            <image class="action-icon" src="/static/training-difficulty-design/result-icon-1.png" mode="widthFix" />
            <text>查看靶纸</text>
          </view>
          <view v-if="validArrows === total" class="action-item" @click="() => (showComment = true)">
            <image class="action-icon" src="/static/training-difficulty-design/result-icon-2.png" mode="widthFix" />
            <text>教练点评</text>
          </view>
          <view v-if="validArrows === total" class="action-item" @click="onClickShare">
            <image class="action-icon" src="/static/training-difficulty-design/result-icon-3.png" mode="widthFix" />
            <text>分享成绩</text>
          </view>
        </view>
      </view>
    </view>
    <view class="oper-box">
      <view class="exp-area">
        <text class="exp-gain">+{{ gainedExp }}经验</text>
        <view class="level-progress">
          <text class="level-text">LV.{{ currentLevel }}</text>
          <view class="progress-track">
            <view class="progress-fill" :style="{ width: `${expPercent}%` }"></view>
          </view>
          <text class="progress-text">{{ currentExp }} / {{ nextExp }}</text>
        </view>
      </view>

      <view class="footer-actions">
        <view class="result-btn result-btn--muted" @click="closePanel">
          <text>{{ validArrows === total ? "完成" : "返回" }}</text>
        </view>
        <view class="result-btn result-btn--primary" @click="retryPractice">
          <text>再来一次</text>
        </view>
      </view>
    </view>

    <ScreenHint :show="showComment" :onClose="() => (showComment = false)" mode="tall">
      <view class="coach-comment">
        <text>
          您本次练习取得了<text class="gold-text">{{ totalRing }}</text>环的成绩，所有箭支上靶后的平均点间距离为<text class="gold-text">{{
            Number((result.average_distance || 0).toFixed(2))
            }}</text>，{{
              result.spreadEvaluation === "Dispersed"
                ? "还需要持续改进哦~"
                : "成绩优秀。"
            }}
        </text>
        <view>
          <image src="https://static.shelingxingqiu.com/attachment/2025-11-26/deihtj15xjwcz3c1tx.png" mode="widthFix" />
          <text class="coach-suggestion">
            针对您本次的练习，{{
              result.spreadEvaluation === "Dispersed"
                ? "我们建议您充分练习推弓、靠位以及撒放动作一致性。"
                : totalRing >= 100
                  ? "我们建议您继续保持即可。"
                  : `我们建议您将设备的瞄准器${directionAdjusts[result.adjustmentHint]
                  }调整。`
            }}
          </text>
        </view>
      </view>
    </ScreenHint>
    <BowData :total="arrows.length" :arrows="result.details" :show="showBowData"
      :onClose="() => (showBowData = false)" />
    <UserUpgrade :show="showUpgrade" :onClose="() => (showUpgrade = false)" :lvl="result.lvl" />
  </view>
</template>

<style scoped lang="scss">
.result-mask {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  background:
    linear-gradient(180deg,
      rgba(24, 22, 17, 0.38) 0%,
      rgba(24, 22, 17, 0.56) 28%,
      rgba(17, 17, 25, 0.92) 58%),
    rgba(0, 0, 0, 0.72);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.result-mask--show {
  opacity: 1;
}

.result-mask--hide {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.hero-glow {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

.result-title {
  position: relative;
  width: 100%;
  height: 264rpx;
  z-index: 2;
}

.result-title-bg {
  width: 100%;
  height: 264rpx;
  display: block;
}

.result-title-text {
  width: 100%;
  font-size: 28rpx;
  color: #FBFCE6;
  font-weight: 600;
  line-height: 40rpx;
  text-align: center;
  position: absolute;
  top: 116rpx;
  left: 0;
}

.result-panel {
  width: 100vw;
  height: 634rpx;
  padding: 144rpx 80rpx 0 80rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(0, 0, 0, 0.8);
  z-index: 1;
  margin-top: -100rpx;
  position: relative;
}

.stats {
  width: 100%;
  margin-top: 34rpx;
}

.line-top {
  background: linear-gradient(45deg, rgba(205, 183, 122, 0) 0%, #CDB77A 49.92%, rgba(205, 183, 122, 0) 100%);
  width: 100%;
  height: 4rpx;
  opacity: 0.9;
  position: absolute;
  top: 2rpx;
  left: 0;
}

.line-bottom {
  background: linear-gradient(45deg, rgba(205, 183, 122, 0) 0%, #CDB77A 49.92%, rgba(205, 183, 122, 0) 100%);
  width: 100%;
  height: 4rpx;
  opacity: 0.9;
  position: absolute;
  bottom: 2rpx;
  left: 0;
}

.stat-row {
  width: 100%;
  height: 62rpx;
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 52rpx;
  // border: 2rpx solid rgba(209, 184, 125, 0.72);
  // border-radius: 14rpx;
  transform: skewX(-12deg);
  box-sizing: border-box;
}

.stat-cell {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transform: skewX(12deg);
}

.stat-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 582rpx;
  height: 62rpx;
}

.stat-cell--compare {
  padding-left: 8rpx;
  box-sizing: border-box;
}

.stat-label {
  position: absolute;
  top: -30rpx;
  color: rgba(255, 255, 255, 0.7);
  font-size: 20rpx;
  line-height: 1;
}

.stat-value {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 120rpx;
  color: #F3E0B9;
  font-size: 32rpx;
  line-height: 1;
  font-weight: 700;
  font-style: italic;
}

.stat-unit {
  margin-left: 4rpx;
  font-size: 24rpx;
}

.stat-divider {
  width: 2rpx;
  height: 34rpx;
  background: rgba(197, 160, 92, 0.64);
  transform: skewX(12deg);
}

.stat-equal{
  width: 30rpx;
  height: 40rpx;
  color: #F3E0B9;
  font-size: 30rpx;
  margin-left: 10rpx;
}

.trend-icon {
  width: 28rpx;
  height: 42rpx;
  margin-left: 16rpx;
}

.trend-icon--down {
  transform: rotate(180deg);
}

.stat-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 582rpx;
  height: 62rpx;
}

.rice-list {
  width: 160rpx;
  display: flex;
  align-items: center;
}

.rice-icon {
  width: 36rpx;
  height: 34rpx;
  margin-right: 14rpx;
}

.oper-box {
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 598rpx;
}

.actions {
  width: 350rpx;
  display: flex;
  justify-content: space-between;
  margin: 0 auto;
  margin-top: 38rpx;
}

.action-item {
  width: 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action-icon {
  width: 70rpx;
  height: 68rpx;
}

.action-item>text {
  margin-top: 4rpx;
  color: #FAE6BC;
  font-size: 20rpx;
  line-height: 1;
  white-space: nowrap;
}

.exp-area {
  width: 100%;
  margin-top: auto;
  padding-top: 122rpx;
}

.exp-gain {
  display: block;
  margin-bottom: 14rpx;
  color: #f6e3b2;
  font-size: 22rpx;
  line-height: 1;
  text-align: center;
}

.level-progress {
  display: flex;
  align-items: center;
  width: 100%;
}

.level-text,
.progress-text {
  color: rgba(255, 255, 255, 0.86);
  font-size: 24rpx;
  line-height: 1;
}

.level-text {
  min-width: 60rpx;
}

.progress-text {
  min-width: 72rpx;
  text-align: right;
}

.progress-track {
  flex: 1;
  height: 10rpx;
  margin: 0 14rpx;
  border-radius: 999rpx;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.26);
}

.progress-fill {
  height: 100%;
  border-radius: 999rpx;
  background: linear-gradient(90deg, #ff940f 0%, #ffbb33 58%, #fff0a7 100%);
}

.footer-actions {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 70rpx;
}

.result-btn {
  width: 234rpx;
  height: 72rpx;
  border-radius: 999rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 18rpx;
}

.result-btn>text {
  font-size: 28rpx;
  line-height: 1;
  font-weight: 700;
}

.result-btn--muted {
  color: #ffffff;
  background: rgba(255, 255, 255, 0.2);
}

.result-btn--primary {
  background: #FED847;
  color: #151515;
}

.gold-text {
  color: #fed847;
}

.coach-comment {
  display: flex;
  flex-direction: column;
  font-size: 14px;
}

.coach-comment>view {
  display: flex;
}

.coach-comment>view>image {
  width: 420rpx;
  height: 420rpx;
  margin-right: 20rpx;
}

.coach-suggestion {
  margin-top: 12px;
}
</style>
