<script setup>
import { ref, onMounted, computed } from "vue";
import ScreenHint from "./ScreenHint.vue";
import BowData from "./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,
  },
  trainingType: {
    type: String,
    default: "",
  },
  difficultyLevel: {
    type: Number,
    default: 0,
  },
  hasNextDifficulty: {
    type: Boolean,
    default: false,
  },
  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");
}

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 hasResultValue = (...keys) =>
  keys.some((key) => {
    const value = props.result[key];
    return value !== undefined && value !== null && value !== "";
  });

const readResultNumber = (keys, fallback = 0) => {
  for (const key of keys) {
    const value = props.result[key];
    if (value === undefined || value === null || value === "") continue;
    const numberValue = Number(value);
    if (Number.isFinite(numberValue)) return numberValue;
  }
  return fallback;
};

const beforeExp = computed(() =>
  readResultNumber(["beforeExp", "before_exp"])
);

const currentExp = computed(() => {
  const userScores = Number(user.value.scores);
  return readResultNumber(
    ["currentExp", "current_exp", "score"],
    Number.isFinite(userScores) ? userScores : 0
  );
});

// 新版练习结算返回练习前后累计经验，本局经验由两者相减得到。
const gainedExp = computed(() => {
  if (
    hasResultValue("beforeExp", "before_exp") &&
    hasResultValue("currentExp", "current_exp")
  ) {
    return Math.max(0, currentExp.value - beforeExp.value);
  }
  return Math.max(0, readResultNumber(["exp", "experience"]));
});

const beforeLevel = computed(() => {
  const currentUserLevel = Number(user.value.lvl);
  return readResultNumber(
    ["beforeLevel", "before_level"],
    Number.isFinite(currentUserLevel) ? currentUserLevel : 0
  );
});

const userLevel = computed(() => {
  const fallbackLevel = Number(user.value.lvl ?? user.value.rankLvl ?? 1);
  const level = readResultNumber(
    ["level", "lvl"],
    Number.isFinite(fallbackLevel) ? fallbackLevel : 1
  );
  return Math.max(1, Math.trunc(level));
});

const resultDifficultyLevel = computed(() => {
  const level = Number(props.difficultyLevel);
  return Number.isInteger(level) && level > 0 ? level : "--";
});

const upgradeExp = computed(() =>
  Math.max(
    0,
    readResultNumber(
      ["upgradeExp", "upgrade_exp", "nextExp", "upgradeScore"],
      100
    )
  )
);

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

onMounted(() => {
  if (userLevel.value > beforeLevel.value) {
    showUpgrade.value = true;
  }
});

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

const formatDuration = (value) => {
  const valueNumber = Number(value);
  const seconds = Number.isFinite(valueNumber)
    ? Math.max(0, Math.round(valueNumber))
    : 0;
  const minutes = Math.floor(seconds / 60);
  const rest = seconds % 60;
  return minutes ? `${minutes}分${rest}秒` : `${rest}秒`;
};

const formatMetricNumber = (value) => {
  const valueNumber = Number(value);
  if (!Number.isFinite(valueNumber)) return "0";
  return String(Number(valueNumber.toFixed(2)));
};

const readMetricNumber = (keys, fallback = 0) => {
  const value = findValue(...keys);
  const valueNumber = Number(value);
  return Number.isFinite(valueNumber) ? valueNumber : fallback;
};

const resultTrainingType = computed(
  () => props.result.trainingType || props.trainingType || "precision"
);

const metricConfigs = {
  base: [
    {
      label: "平均环数",
      valueKeys: ["averageRing", "average_ring"],
      unit: "环",
      deltaKeys: ["deltaAverageRing", "delta_average_ring"],
      deltaUnit: "环",
    },
    {
      label: "稳定性",
      valueKeys: ["stability"],
      unit: "",
      deltaKeys: ["deltaStability", "delta_stability"],
      deltaUnit: "",
    },
  ],
  rhythm: [
    {
      label: "最高连击次数",
      valueKeys: ["maxCombo", "max_combo"],
      unit: "连",
      deltaKeys: ["deltaMaxCombo", "delta_max_combo"],
      deltaUnit: "连",
    },
    {
      label: "共命中环数",
      valueKeys: ["currentRings", "current_rings"],
      unit: "环",
      deltaKeys: ["deltaTotalRings", "delta_total_rings"],
      deltaUnit: "环",
    },
  ],
  endurance: [
    {
      label: "完成箭数",
      valueKeys: ["totalArrows", "total_arrows"],
      unit: "支",
      deltaKeys: ["deltaTotalArrows", "delta_total_arrows"],
      deltaUnit: "支",
    },
    {
      label: "命中环数",
      valueKeys: ["currentRings", "current_rings"],
      unit: "环",
      deltaKeys: ["deltaTotalRings", "delta_total_rings"],
      deltaUnit: "环",
    },
  ],
  precision: [
    {
      label: "共命中目标",
      valueKeys: ["totalHits", "total_hits"],
      fallback: () => 0,
      unit: "次",
      deltaKeys: [
        "deltaTotalHits",
        "delta_total_hits",
        "hitCompare",
        "hitDiff",
        "hitDelta",
      ],
      deltaUnit: "次",
    },
    {
      label: "用时",
      valueKeys: ["duration", "usedTime", "shootTime", "time"],
      unit: "",
      deltaKeys: [
        "deltaDuration",
        "delta_duration",
        "timeCompare",
        "timeDiff",
        "durationDiff",
      ],
      deltaUnit: "",
      duration: true,
    },
  ],
};

const resultRows = computed(() => {
  const configs = metricConfigs[resultTrainingType.value] || metricConfigs.precision;
  return configs.map((config) => {
    const fallback = config.fallback ? config.fallback() : 0;
    const value = readMetricNumber(config.valueKeys, fallback);
    const delta = readMetricNumber(config.deltaKeys);
    const formatter = config.duration ? formatDuration : formatMetricNumber;

    return {
      ...config,
      valueText: formatter(value),
      delta,
      deltaText: formatter(Math.abs(delta)),
    };
  });
});

const advancesDifficulty = computed(() => props.hasNextDifficulty);
const primaryText = computed(() =>
  advancesDifficulty.value ? "下一难度" : "再来一次"
);

const handlePrimary = () => {
  if (advancesDifficulty.value) {
    closePanel();
    return;
  }
  retryPractice();
};

const calories = computed(
  () => formatMetricNumber(readMetricNumber(["calories", "calorie", "kcal"]))
);
</script>

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

    <view class="result-panel">
      <view class="line-top"></view>
      <view class="line-bottom"></view>
      <view class="stats">
        <view v-for="row in resultRows" :key="row.label" class="stat-row">
          <image class="stat-bg" src="https://static.shelingxingqiu.com/shootmini/static/training-difficulty-design/result-c-bg.png" mode="scaleToFill" />
          <view class="stat-cell">
            <text class="stat-label">{{ row.label }}</text>
            <view class="stat-value">
              <text>{{ row.valueText }}</text>
              <text v-if="row.unit" class="stat-unit">{{ row.unit }}</text>
            </view>
          </view>
          <view class="stat-divider"></view>
          <view class="stat-cell stat-cell--compare">
            <text class="stat-label">对比上次</text>
            <view v-if="row.delta !== 0" class="stat-value">
              <text>{{ row.delta > 0 ? "+" : "-" }}{{ row.deltaText }}</text>
              <text v-if="row.deltaUnit" class="stat-unit">{{ row.deltaUnit }}</text>
              <image class="trend-icon" :class="{ 'trend-icon--down': row.delta < 0 }"
                src="https://static.shelingxingqiu.com/shootmini/static/training-difficulty-design/result-up.png" mode="widthFix" />
            </view>
            <view v-else class="stat-value">--</view>
          </view>
        </view>
         <view class="stat-row">
          <image class="stat-bg" src="https://static.shelingxingqiu.com/shootmini/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="https://static.shelingxingqiu.com/shootmini/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="https://static.shelingxingqiu.com/shootmini/static/training-difficulty-design/result-icon-1.png" mode="widthFix" />
            <text>查看靶纸</text>
          </view>
          <view class="action-item" @click="() => (showComment = true)">
            <image class="action-icon" src="https://static.shelingxingqiu.com/shootmini/static/training-difficulty-design/result-icon-2.png" mode="widthFix" />
            <text>教练点评</text>
          </view>
          <view class="action-item" @click="onClickShare">
            <image class="action-icon" src="https://static.shelingxingqiu.com/shootmini/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.{{ userLevel }}</text>
          <view class="progress-track">
            <view class="progress-fill" :style="{ width: `${expPercent}%` }"></view>
          </view>
          <text class="progress-text">{{ currentExp }} / {{ upgradeExp }}</text>
        </view>
      </view>

      <view class="footer-actions">
        <view class="result-btn result-btn--muted" @click="closePanel">
          <text>完成</text>
        </view>
        <view class="result-btn result-btn--primary" @click="handlePrimary">
          <text>{{ primaryText }}</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="userLevel" />
  </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>
