<template>
  <van-pull-refresh
    v-model="loading"
    class="game-analysis-nm-content custom-font-text"
    @refresh="onRefresh"
  >
    <template #loosing>
      <div class="refresh-txt">
        <svg-icon
          className="icon"
          iconName="loading"
          :class="{ 'is-spinning': loading }"
        ></svg-icon>
        <span>释放即可刷新</span>
      </div>
    </template>

    <template #loading>
      <div class="refresh-txt">
        <svg-icon
          className="icon"
          iconName="loading"
          :class="{ 'is-spinning': loading }"
        ></svg-icon>
        <span>加载中……</span>
      </div>
    </template>

    <template #success>
      <div class="refresh-txt">
        <svg-icon
          className="icon"
          iconName="loading"
          :class="{ 'is-spinning': loading }"
        ></svg-icon>
        <span>刷新成功</span>
      </div>
    </template>
    <!--支持率 -->
    <article class="article-wrapper" v-if="odds_eu">
      <approval-rating :game-info="game_info" :voteInfo="toupiao" />
    </article>
    <div class="analysis_content">
      <!--两队评分-->
      <section>
        <team-evaluate
          :game-info="game_info"
          :history-data="game_detail?.history"
        />
      </section>

      <!--进球分布-->
      <section class="goal-distribution">
        <goal-distribution
          v-if="showScoreDistribution"
          :goal-period="goal_period"
          :score-distribution="scoreDistribution"
          :game-info="game_info"
          :game-detail="game_detail"
        />
      </section>

      <!--积分排名-->
      <section v-if="showPointsRank" class="points-ranking">
        <div class="section-haeder">
          <div class="section-title">积分排名</div>

          <div class="tools-box">
            <div class="select-capsule">
              <div :class="['select-item', pointType == 'all' && 'active']" @click="pointType = 'all'">全部</div>
              <div :class="['select-item', pointType == 'home' && 'active']" @click="pointType = 'home'">主场</div>
              <div :class="['select-item', pointType == 'away' && 'active']" @click="pointType = 'away'">客场</div>
            </div>

            <Button
              class="rank-btn"
              icon="arrow"
              plain
              color="#4f96fa"
              round
              size="small"
              icon-position="right"
              @click="toPointsRanking"
              >全部排名</Button
            >
          </div>
        </div>

        <div class="section-body">
          <div class="table-row header">
            <div class="table-col">排名</div>
            <div class="table-col">赛事({{ game_detail.competition_name }})</div>
            <div class="table-col">已赛</div>
            <div class="table-col">胜/平/负</div>
            <div class="table-col">进/失</div>
            <div class="table-col">积分</div>
          </div>
          <div class="table-row host">
            <div class="table-col">
              {{ pointsRankInfo?.home?.[`${points_prefix}position`] }}
            </div>
            <div class="table-col">{{ game_info?.host_name }}</div>
            <div class="table-col">{{ pointsRankInfo?.home?.[`${points_prefix}total`] }}</div>
            <div class="table-col">
              {{ pointsRankInfo?.home?.[`${points_prefix}won`] }}/{{
                pointsRankInfo?.home?.[`${points_prefix}draw`]
              }}/{{ pointsRankInfo?.home?.[`${points_prefix}loss`] }}
            </div>
            <div class="table-col">
              {{ pointsRankInfo?.home?.[`${points_prefix}goals`] }}/{{
                pointsRankInfo?.home?.[`${points_prefix}goals_against`]
              }}
            </div>
            <div class="table-col">{{ pointsRankInfo?.home?.[`${points_prefix}points`] }}</div>
          </div>
          <div class="table-row guest">
            <div class="table-col">
              {{ pointsRankInfo?.away?.[`${points_prefix}position`] }}
            </div>
            <div class="table-col">{{ game_info?.away_name }}</div>
            <div class="table-col">{{ pointsRankInfo?.away?.[`${points_prefix}total`] }}</div>
            <div class="table-col">
              {{ pointsRankInfo?.away?.[`${points_prefix}won`] }}/{{
                pointsRankInfo?.away?.[`${points_prefix}draw`]
              }}/{{ pointsRankInfo?.away?.[`${points_prefix}loss`] }}
            </div>
            <div class="table-col">
              {{ pointsRankInfo?.away?.[`${points_prefix}goals`] }}/{{
                pointsRankInfo?.away?.[`${points_prefix}goals_against`]
              }}
            </div>
            <div class="table-col">{{ pointsRankInfo?.away?.[`${points_prefix}points`] }}</div>
          </div>
        </div>
      </section>

      <!--历史交锋-->
      <GameAnalysisTable
        v-if="game_detail?.history?.vs?.length"
        title="历史交锋"
        :filterInfo="filterInfo"
        :game-info="game_info"
        :tableData="game_detail.history.vs"
        :team-info="{
          team_id: game_info?.home_team_id,
          team_name: game_info?.host_name,
          team_logo: game_info?.host_photo,
        }"
      />

      <!--主队近期战绩-->
      <GameAnalysisTable
        v-if="game_detail?.history?.home?.length"
        title="主队近期战绩"
        tableType="home"
        :filterInfo="filterInfo"
        :game-info="game_info"
        :tableData="game_detail.history.home"
        :team-info="{
          team_id: game_info?.home_team_id,
          team_name: game_info?.host_name,
          team_logo: game_info?.host_photo,
        }"
      />

      <!--客队近期战绩-->
      <GameAnalysisTable
        v-if="game_detail?.history?.away?.length"
        title="客队近期战绩"
        tableType="guest"
        :filterInfo="filterInfo"
        :game-info="game_info"
        :tableData="game_detail.history.away"
        :team-info="{
          team_id: game_info?.away_team_id,
          team_name: game_info?.away_name,
          team_logo: game_info?.away_photo,
        }"
      />

      <!--数据PK-->
      <section>
        <div class="tool-wrapper">
          <div class="duel-away">
            <div class="button-box">
              <div
                :class="[
                  'same-btn',
                  state.competitionType === 'host_guest' && 'active',
                ]"
                @click="changeCompetitionType('host_guest')"
              >
                同主客
              </div>
              <div
                :class="[
                  'same-btn',
                  state.competitionType === 'season' && 'active',
                ]"
                @click="changeCompetitionType('season')"
              >
                同赛事
              </div>
            </div>
            <div class="select-capsule">
              <div
                :class="['select-item', state.competitionNum == 6 && 'active']"
                @click="state.competitionNum = 6"
              >
                6场
              </div>
              <div
                :class="['select-item', state.competitionNum == 10 && 'active']"
                @click="state.competitionNum = 10"
              >
                10场
              </div>
              <div
                :class="['select-item', state.competitionNum == 20 && 'active']"
                @click="state.competitionNum = 20"
              >
                20场
              </div>
            </div>
          </div>
        </div>
        <div class="match_team">
          <div class="match_team_container">
            <div
              class="team_logo"
              :style="`background-image: url(${game_info?.host_photo});`"
            ></div>
            <div class="text-info">
              <p class="team_name">{{ game_info?.host_name }}</p>
            </div>
          </div>
          <div class="content-title">
            数据<span style="color: #ff6858">P</span>K
          </div>
          <div class="match_team_container">
            <div class="text-info">
              <p class="team_name">{{ game_info?.away_name }}</p>
            </div>
            <div
              class="team_logo mat-left"
              :style="`background-image: url(${game_info?.away_photo});`"
            ></div>
          </div>
        </div>

        <div class="stats-box">
          <div class="stats-item top">
            <div class="content-wrapper">
              <span class="value">近 {{ state.competitionNum }} 场</span>
              <span class="title">场次</span>
              <span class="value">近 {{ state.competitionNum }} 场</span>
            </div>
            <div class="bar-wrapper">
              <progress-bar
                color="#fc5056"
                grayLevelColor="#5294f5"
                :inner-radius="false"
                :value="50"
                :max="100"
              />
            </div>
          </div>

          <div v-for="item in state.pk_data" :key="item" class="stats-item">
            <div class="content-wrapper">
              <span class="value">{{ item.left_value }}{{ item.unit }}</span>
              <span class="value">{{ item.right_value }}{{ item.unit }}</span>
            </div>
            <div class="bar-wrapper">
              <div class="bar">
                <progress-bar
                  color="#fc5056"
                  direction="right"
                  :value="item.left_value"
                  :max="item.max || state.home_pk_total"
                />
              </div>
              <div class="title">{{ item.label }}</div>
              <div class="bar">
                <progress-bar
                  color="#5294f5"
                  direction="left"
                  :value="item.right_value"
                  :max="item.max || state.home_pk_total"
                />
              </div>
            </div>
          </div>
        </div>
      </section>

      <!--未来赛事-->
      <section v-if="game_detail?.future">
        <div class="match-future" v-if="game_detail.future.home">
          <div class="analysis-title">
            <div class="title-left">未来赛事</div>
            <div class="title-right">
              {{ game_info?.host_name }}
              <img
                :src="game_info?.host_photo"
                :onerror="getTeamErrorLogo(game_detail.nm_home_team_logo)"
                class="lazyLoad isLoaded"
              />
            </div>
          </div>

          <div class="game-table">
            <div class="game-table-row header">
              <div class="game-table-col">赛事/日期</div>
              <div class="game-table-col">主队</div>
              <div class="game-table-col">客队</div>
              <div class="game-table-col">相隔</div>
            </div>
            <template v-for="(item, index) in game_detail.future.home" :key="index">
              <div v-if="index < 5" class="game-table-row">
                <div class="game-table-col">
                  <span>{{ item.competition_name }}</span>
                  <span>{{ formatDate(item.match_time * 1000) }}</span>
                </div>
                <div :style="{color: item.home_team_id == game_detail.home_team_id ? '#000' : ''}" class="game-table-col">{{ getTeamName(item, true) || "—--—" }}</div>
                <div :style="{color: item.away_team_id == game_detail.home_team_id ? '#000' : ''}" class="game-table-col">
                  <span class="vs-flag">VS</span>
                  {{ getTeamName(item, false) || "—--—" }}
                </div>
                <div class="game-table-col day_col">{{ formatDay(item.match_time * 1000) }}天</div>
              </div>
            </template>
          </div>
        </div>

        <div class="match-future" v-if="game_detail.future.away">
          <div class="analysis-title">
            <div class="title-left"></div>
            <div class="title-right">
              {{ game_info?.away_name }}
              <img
                :src="game_info?.away_photo"
                :onerror="getTeamErrorLogo(game_detail.nm_away_team_logo)"
                class="lazyLoad isLoaded"
              />
            </div>
          </div>
          <div class="game-table">
            <div class="game-table-row header">
              <div class="game-table-col">赛事/日期</div>
              <div class="game-table-col">主队</div>
              <div class="game-table-col">客队</div>
              <div class="game-table-col">相隔</div>
            </div>
            <template v-for="(item, index) in game_detail.future.away" :key="index">
              <div v-if="index < 5" class="game-table-row">
                <div class="game-table-col">
                  <span>{{ item.competition_name }}</span>
                  <span>{{ formatDate(item.match_time * 1000) }}</span>
                </div>
                <div :style="{color: item.home_team_id == game_detail.away_team_id ? '#000' : ''}" class="game-table-col">{{ getTeamName(item, true) || "—--—" }}</div>
                <div :style="{color: item.away_team_id == game_detail.away_team_id ? '#000' : ''}" class="game-table-col">
                  <span class="vs-flag">VS</span>
                  {{ getTeamName(item, false) || "—--—" }}
                </div>
                <div class="game-table-col day_col">{{ formatDay(item.match_time * 1000) }}天</div>
              </div>
            </template>
          </div>
        </div>
      </section>
    </div>

    <noData v-if="no_data" nodata_message="暂无分析数据！"></noData>
  </van-pull-refresh>
</template>

<script lang="ts" name="GameAnalysisNm">
import {
  ref,
  reactive,
  defineComponent,
  computed,
  onBeforeMount,
  onMounted,
  onUnmounted,
  onActivated,
  onDeactivated,
  watch,
  watchEffect,
} from "vue";
import * as nm_match_api from "@/api/nm_match_api";
import * as game_api from "@/api/game_api";
// import * as user_api from "@/api/user_api";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { default as moment } from "moment";
import { Button } from "vant";
// import { get_localstorage, set_localstorage } from "@/common/js/utils";
import { usePointsRanking } from "@/hooks/Integral/use-points-ranking";

import noData from "@/components/NoData.vue";
import ProgressBar from "@/components/ProgressBar.vue";
import GameAnalysisTable from "./component/GameAnalysisTable.vue";
import ApprovalRating from "./component/approval-rating.vue";
import GoalDistribution from "./component/goal-distribution.vue";
import TeamEvaluate from "./component/team-evaluate.vue";

import { getTeamErrorLogo } from "@/until/index";

interface ScoreDistributionInter {
  home: { value: number; class: string[] }[];
  home_total_score: number;
  guest: { value: number; class: string[] }[];
  guest_total_score: number;
}

const result_option = [
  {
    result: "胜",
    color: "#FF3333",
  },
  {
    result: "平",
    color: "#1F78FF",
  },
  {
    result: "负",
    color: "#00C423",
  },
];

const odds_option = [
  {
    result: "赢",
    color: "#FF3333",
  },
  {
    result: "走",
    color: "#1F78FF",
  },
  {
    result: "输",
    color: "#00C423",
  },
];

//盘路
// const plateDic: any = {
//   '8.75': '受八球半/九', '8.5': '受八球半', '8.25': '受八/八球半', '8': '受八球',
//   '7.75': '受七球半/八', '7.5': '受七球半', '7.25': '受七/七球半', '7': '受七球',
//   '6.75': '受六球半/七', '6.5': '受六球半', '6.25': '受六/六球半', '6': '受六球',
//   '5.75': '受五球半/六', '5.5': '受五球半', '5.25': '受五/五球半', '5': '受五球',
//   '4.75': '受四球半/五', '4.5': '受四球半', '4.25': '受四/四球半', '4': '受四球',
//   '3.75': '受三球半/四', '3.5': '受三球半', '3.25': '受三/三球半', '3': '受三球',
//   '2.75': '受两球半/三', '2.5': '受两球半', '2.25': '受两/两球半', '2': '受两球',
//   '1.75': '受球半/两球', '1.5': '受球半', '1.25': '受一/球半', '1': '受一球',
//   '0.75': '受半/一', '0.5': '受半球', '0.25': '受平/半',
//   '0': '平手', '-0.25': '平/半', '-0.5': '半球', '-0.75': '半/一',
//   '-1': '一球', '-1.25': '一/球半', '-1.5': '球半', '-1.75': '球半/两球',
//   '-2': '两球', '-2.25': '两/两球半', '-2.5': '两球半', '-2.75': '两球半/三',
//   '-3': '三球', '-3.25': '三/三球半', '-3.5': '三球半', '-3.75': '三球半/四',
//   '-4': '四球', '-4.25': '四/四球半', '-4.5': '四球半', '-4.75': '四球半/五',
//   '-5': '五球', '-5.25': '五/五球半', '-5.5': '五球半', '-5.75': '五球半/六',
//   '-6': '六球', '-6.25': '六/六球半', '-6.5': '六球半', '-6.75': '六球半/七',
//   '-7': '七球', '-7.25': '七/七球半', '-7.5': '七球半', '-7.75': '七球半/八',
//   '-8': '八球', '-8.25': '八/八球半', '-8.5': '八球半', '-8.75': '八球半/九',
// };

//盘路数字
const plateDic: any = {
  "8.75": "-8.5/9",
  "8.5": "-8.5",
  "8.25": "-8/8.5",
  "8": "-8",
  "7.75": "-7.5/8",
  "7.5": "-7.5",
  "7.25": "-7/7.5",
  "7": "-7",
  "6.75": "-6.5/7",
  "6.5": "-6.5",
  "6.25": "-6/6.5",
  "6": "-6",
  "5.75": "-5.5/6",
  "5.5": "-5.5",
  "5.25": "-5/5.5",
  "5": "-5",
  "4.75": "-4.5/5",
  "4.5": "-4.5",
  "4.25": "-4/4.5",
  "4": "-4",
  "3.75": "-3.5/4",
  "3.5": "-3.5",
  "3.25": "-3/3.5",
  "3": "-3",
  "2.75": "-2.5/3",
  "2.5": "-2.5",
  "2.25": "-2/2.5",
  "2": "-2",
  "1.75": "-1.5/2",
  "1.5": "-1.5",
  "1.25": "-1/1.5",
  "1": "-1",
  "0.75": "-0.5/1",
  "0.5": "-0.5",
  "0.25": "-0/0.5",
  "0": "0",
  "-0.25": "0/0.5",
  "-0.5": "0.5",
  "-0.75": "0.5/1",
  "-1": "1",
  "-1.25": "1/1.5",
  "-1.5": "1.5",
  "-1.75": "1.5/2",
  "-2": "2",
  "-2.25": "2/2.5",
  "-2.5": "2.5",
  "-2.75": "2.5/3",
  "-3": "3",
  "-3.25": "3/3.5",
  "-3.5": "3.5",
  "-3.75": "3.5/4",
  "-4": "4",
  "-4.25": "4/4.5",
  "-4.5": "4.5",
  "-4.75": "4.5/5",
  "-5": "5",
  "-5.25": "5/5.5",
  "-5.5": "5.5",
  "-5.75": "5.5/6",
  "-6": "6",
  "-6.25": "6/6.5",
  "-6.5": "6.5",
  "-6.75": "6.5/7",
  "-7": "7",
  "-7.25": "7/7.5",
  "-7.5": "7.5",
  "-7.75": "7.5/8",
  "-8": "8",
  "-8.25": "8/8.5",
  "-8.5": "8.5",
  "-8.75": "8.5/9",
};

export default defineComponent({
  name: "GameAnalysisNm",
  components: {
    noData,
    GameAnalysisTable,
    Button,
    ProgressBar,

    ApprovalRating,
    GoalDistribution,
    TeamEvaluate,
  },
  props: {
    gameInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    gameDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props: any) {
    const route = useRoute();
    const router = useRouter();

	const store: any = useStore();
    const game_info: any = ref({ ...props.gameInfo });
    const game_detail: any = ref({ ...props.gameDetail });
    // const userInfo: any = computed(() => store.state.userInfo);

    const { pointsRankInfo, load_points_info } = usePointsRanking();

    const game_id = ref<string>();
    const no_data = ref(false);
    const loading = ref(false);
    const filterInfo = ref<any>({});
    const pointType = ref('all')
    const showScoreDistribution = ref<boolean>(true);

    const state: any = ref({
      scoreType: "Total",
      bg_color_box: ["background-color:#fafafa", "background-color:#fff"],

      jfdb_key: "Total",
      sqjf_key: "Total",
      round_key: "Total",

      competitionNum: 6,
      competitionType: "",
      home_pk_total: 100,
      guest_pk_total: 100,
      pk_data: [
        {
          label: "赢",
          left_value: 50,
          right_value: 50,
          unit: "场",
        },
        {
          label: "赢率",
          left_value: 50,
          right_value: 50,
          max: 100,
          unit: "%",
        },
        {
          label: "和",
          left_value: 50,
          right_value: 50,
          unit: "场",
        },
        {
          label: "输",
          left_value: 50,
          right_value: 50,
          unit: "场",
        },
        {
          label: "大球",
          left_value: 50,
          right_value: 50,
          unit: "场",
        },
        {
          label: "大球率",
          left_value: 50,
          right_value: 50,
          max: 100,
          unit: "%",
        },
        {
          label: "小球",
          left_value: 50,
          right_value: 50,
          unit: "场",
        },
        {
          label: "小球率",
          left_value: 50,
          right_value: 50,
          max: 100,
          unit: "%",
        },
      ],
    });
    const odds_eu: any = ref(null);
    const toupiao: any = ref({
      is_show: false,
      win_num: 0,
      draw_num: 0,
      lose_num: 0,
    });

    const scoreDistribution = reactive<ScoreDistributionInter>({
      home: [],
      home_total_score: 0,
      guest: [],
      guest_total_score: 0,
    });

    const goal_period = reactive([
      { start: "30", end: "45" },
      { start: "0", end: "15" },
      { start: "75", end: "90" },
    ]);

    const getTeamName = (teamInfo: any, isHome: boolean) => {
      const prefixed = isHome ? "home" : "away";
      const info = game_info.value;
      if (teamInfo[`${prefixed}_team_id`] === info.home_team_id) {
        return info.host_name;
      } else if (teamInfo[`${prefixed}_team_id`] === info.away_team_id) {
        return info.away_name;
      } else {
        return teamInfo[`${prefixed}_team_name`];
      }
    };

    const handleTeamData = (source: any[]) => {
      return source?.map((item: any) => {
        // 半场结果
        let half_result_info = {
          home: result_option[0],
          guest: result_option[2],
        };
        if (item?.home_scores?.[1] > item?.away_scores?.[1]) {
          half_result_info = {
            home: result_option[0],
            guest: result_option[2],
          };
        } else if (item?.home_scores?.[1] == item?.away_scores?.[1]) {
          half_result_info = {
            home: result_option[1],
            guest: result_option[1],
          };
        } else {
          half_result_info = {
            home: result_option[2],
            guest: result_option[0],
          };
        }
        // 半场结果
        let result_info = {
          home: result_option[0],
          guest: result_option[2],
        };
        if (item?.home_scores?.[0] > item?.away_scores?.[0]) {
          result_info = {
            home: result_option[0],
            guest: result_option[2],
          };
        } else if (item?.home_scores?.[0] == item?.away_scores?.[0]) {
          result_info = {
            home: result_option[1],
            guest: result_option[1],
          };
        } else {
          result_info = {
            home: result_option[2],
            guest: result_option[0],
          };
        }

        let odds_info = {
          home: odds_option[0],
          guest: odds_option[2],
        };
        let the_odds_data = item?.odds?.[0]?.split(",") || [];
        let odds_data = item.odds[2]?.split(",") || [];
        let handicap_txt = getOddsBet(-the_odds_data[1]);
        if (
          item.home_scores[0] - parseFloat(the_odds_data?.[1]) >
          item.away_scores[0]
        ) {
          odds_info = {
            home: odds_option[0],
            guest: odds_option[2],
          };
        } else if (
          item.home_scores[0] - parseFloat(the_odds_data?.[1]) ==
          item.away_scores[0]
        ) {
          odds_info = {
            home: odds_option[1],
            guest: odds_option[1],
          };
        } else {
          odds_info = {
            home: odds_option[2],
            guest: odds_option[0],
          };
        }
        // 大，走，小球
        let goal_info = {
          value: "小",
          color: "#00C423"
        }
        if (
          item?.home_scores[0] * 1 + 1 * item?.away_scores[0] >
          odds_data?.[1]
        ) {
          goal_info = {
            value: "大",
            color: "#FF3333"
          }
        } else if (
          item?.home_scores[0] * 1 + 1 * item?.away_scores[0] <
          odds_data?.[1]
        ) {
          goal_info = {
            value: "小",
            color: "#00C423"
          }
        } else {
          goal_info = {
            value: "走",
            color: "#1F78FF"
          }
        }

        return {
          ...item,
          odds_data,
          odds_info,
          result_info,
          the_odds_data,
          handicap_txt,
          goal_info,
          half_result_info,
        };
      });
    };

    const init_data = async () => {
      try {
        let yiqiu_id =
          game_info?.value?.id ||
          route?.query?.yiqiuid ||
          route?.params?.yiqiuid;
        game_id.value = yiqiu_id;
        if (!game_detail.value) {
          let nm_result = await nm_match_api.nm_match_detail({
            yiqiu_id: yiqiu_id,
          });
          game_detail.value = nm_result;
          // console.log('game_detail --------- ', JSON.stringify(game_detail.value))
          if (game_detail.value) {
            no_data.value = false;
          }
        }
        if (!game_info.value?.sportsdt_game_id) {
          const yiqiuid =
            game_info?.value?.id || route.query.yiqiuid || route.params.yiqiuid;
          const gameid = route.query.gameid;
          const infoid = route.query.infoid;
          let temp = await game_api.get_soccer_game_info({
            yiqiu_id: yiqiuid,
            game_id: gameid,
            info_id: infoid,
          });
          game_info.value = temp;
        }
        data_processing();

        await load_points_info(game_id.value as string);
        const timer = setTimeout(() => {
          handleScoreItemData();
          clearTimeout(timer);
        }, 0);
      } catch (error) {
        no_data.value = false;
      }
    };

    const sortArrayDesToOriginalIndices = (arr: number[]): number[] => {
      // 如果数组为空，返回空数组
      if (arr.length === 0) {
        return [];
      }

      // 创建一个包含元素及其原始下标的数组
      const indexedArray = arr.map((value, index) => ({ value, index }));

      // 按照元素的值从大到小排序
      indexedArray.sort((a, b) => b.value - a.value);

      // 提取排序后的原始下标
      const originalIndices = indexedArray.map((item) => item.index);

      return originalIndices;
    };

    const handleScoreItemData = () => {
      showScoreDistribution.value = true;
      const homeList =
        game_detail.value.goal_distribution?.home?.all?.scored?.map(
          (item: any) => item[0]
        ) || [];
      const guestList =
        game_detail.value.goal_distribution?.away?.all?.scored?.map(
          (item: any) => item[0]
        ) || [];
      if (!homeList.length || !guestList.length)
        return (showScoreDistribution.value = false);
      const composeList = homeList.map(
        (item: any, index: number) => item + guestList[index]
      );
      const composeIndexList = sortArrayDesToOriginalIndices(composeList).slice(
        0,
        3
      );
      const goal_period_options = ["0", "15", "30", "45", "60", "75", "90"];
      composeIndexList.forEach((ind: number, index: number) => {
        goal_period[index] = {
          start: goal_period_options[ind],
          end: goal_period_options[ind + 1],
        }; //`${goal_period_options[ind]}~${goal_period_options[ind + 1]}`;
      });

      const home_total_score = homeList.reduce((acc: number, num: number) => {
        acc += num;
        return acc;
      }, 0);

      const guest_total_score = guestList.reduce((acc: number, num: number) => {
        acc += num;
        return acc;
      }, 0);

      const homeIndexList = sortArrayDesToOriginalIndices(homeList).slice(0, 2);
      const guestndexList = sortArrayDesToOriginalIndices(guestList).slice(
        0,
        2
      );
      const hostData = [];
      const guestData = [];
      for (let i = 0; i < 6; i++) {
        let hostClass = ["dis-table-col"];
        let guestClass = ["dis-table-col"];

        if (homeIndexList.includes(i)) {
          hostClass.push("top_two");
        }

        if (guestndexList.includes(i)) {
          guestClass.push("top_two");
        }

        if (composeIndexList[0] == i) {
          hostClass.push("first");
          guestClass.push("first");
        } else if (composeIndexList.includes(i)) {
          hostClass.push("super");
          guestClass.push("super");
        }

        hostData[i] = {
          value: homeList[i],
          class: hostClass,
        };
        guestData[i] = {
          value: guestList[i],
          class: guestClass,
        };
      }

      scoreDistribution.home = hostData as any;
      scoreDistribution.guest = guestData as any;
      scoreDistribution.home_total_score = home_total_score;
      scoreDistribution.guest_total_score = guest_total_score;
    };

    const changeNmState = (status: any) => {
      if (status == 0 || status == 17) {
        status = 1;
      } else if (status == 1 || status == 2 || status == 3) {
        status = status + 1;
      } else if (status == 4 || status == 10 || status == 12) {
        status = 8;
      } else if (status == 7 || status == 8 || status == 9) {
        status = 5;
      } else if (status == 13 || status == 14 || status == 15) {
        status = status - 4;
      } else if (status == 6) {
        status = 12;
      } else if (status == 15) {
        status = 13;
      } else if (status == null) {
        status = 1;
      }
      return status;
    };

    const formatGameInfo = (game: any) => {
      game.competition_short_name =
        game?.competition?.short_name || game?.competition?.name;
      game.host_photo = game?.host_team?.logo;
      game.away_photo = game?.away_team?.logo;
      game.host_name = game?.host_team?.short_name || game?.host_team?.name;
      game.away_name = game?.away_team?.short_name || game?.away_team?.name;
      if (game?.handicap) {
        let bar_left = 50 - (game?.handicap / 0.5) * 10;
        game.home_rate = bar_left;
        game.away_rate = 100 - bar_left;
      }
      game.nm_status = changeNmState(game?.status); //转换为nm的比赛状态
      game_info.value = game;
	  store.commit("updateNmGameMessageCache", game);
    };

    function data_processing() {
      if (game_detail.value?.history) {
        game_detail.value.history.vs = handleTeamData(game_detail.value.history?.vs);
        game_detail.value.history.home = handleTeamData(
          game_detail.value.history?.home
        );
        game_detail.value.history.away = handleTeamData(
          game_detail.value.history?.away
        );
      }

      // 额外处理
      filterInfo.value = {
        host_guest: [
          game_detail.value?.home_team_id,
          game_detail.value?.away_team_id,
        ],
        competition_id: game_detail.value?.competition_id,
      };

      if (game_info.value) {
        game_info.value.competition_id = game_detail.value?.competition_id;
        game_info.value.home_team_id = game_detail.value?.home_team_id;
        game_info.value.away_team_id = game_detail.value?.away_team_id;
      }
    }

    const refresh_data = async () => {
      let yiqiu_id =
        game_info?.value?.id || route?.query?.yiqiuid || route?.params?.yiqiuid;
      const gameid = route.query?.gameid;
      const infoid = route.query?.infoid;
      game_id.value = yiqiu_id;
      let result = await game_api.get_soccer_game_info_and_nm_match_detail({
        yiqiu_id: yiqiu_id,
        game_id: gameid,
        info_id: infoid,
      });
      let soccer_game_info = result?.get_soccer_game_info;
      formatGameInfo(soccer_game_info);
      game_detail.value = result?.nm_match_detail;
      data_processing();
      loading.value = false;
    };

    const disableRightClick = function(event: Event) {
      event.preventDefault(); // 阻止事件默认行为
    };

    onBeforeMount(() => {
      init_data();
    });

    onMounted(async () => {
      // init_data();
      document.addEventListener('contextmenu', disableRightClick);
      // console.log('onMounted ============= Nm', props.gameInfo, JSON.stringify(props.gameDetail))
    });
    onUnmounted(() => {
      document.removeEventListener('contextmenu', disableRightClick);
    })
    onActivated(() => {
      document.addEventListener('contextmenu', disableRightClick);
    })
    onDeactivated(() => {
      document.removeEventListener('contextmenu', disableRightClick);
    })

    // watch(
    //   () => route.query.yiqiuid || route.params.yiqiuid,
    //   (newVal: any) => {
    //     if (newVal && newVal != game_info.value.id) {
    //       init_data();
    //     }
    //   }
    // );
    watch(() => props.gameInfo, (newValue) => {
      formatGameInfo({...props.gameInfo});
      if (newValue.id != game_id.value) {
        init_data();
        game_id.value = newValue.id;
      }
      data_processing();
    }, {deep: true})

    watch(() => props.gameDetail, (newValue) => {
      game_detail.value = {...props.gameDetail}
      data_processing();
    }, {deep: true})

    const onRefresh = () => {
      refresh_data();
      // setTimeout(() => {
      //   init_data();
      //   loading.value = false;
      // }, 200);
    };

    const formatDate = computed(() => {
      return (date: any) => {
        return moment(date).format("YY/MM/DD");
      };
    });

    const points_prefix = computed(() => {
      if (pointType.value === 'home') {
        return 'home_'
      } else if (pointType.value === 'away') {
        return 'away_'
      }
      return ''
    })

    const showPointsRank = computed(() => {
      const { home, away } = pointsRankInfo.value ?? {};
      if (home && away) {
        const checkFileds = [
          "total",
          "won",
          "draw",
          "loss",
          "goals",
          "goals_against",
          "points",
        ];
        for (let i = 0; i < checkFileds.length; i++) {
          const key = checkFileds[i];
          if (
            (!home[key] && typeof home[key] !== "number") ||
            (!away[key] && typeof away[key] !== "number")
          )
            return false;
        }
        return true;
      } else {
        return false;
      }
    });

    const formatDay = function (e: any) {
      let date: any = new Date();
      var timestamp = Date.parse(date);
      var num = e - timestamp;
      return Math.floor(num / 1000 / 60 / 60 / 24) == 0
        ? "今"
        : Math.floor(num / 1000 / 60 / 60 / 24);
    };

    const getOddsBet = (handicap: any) => {
      var handicapName = plateDic[handicap] || "";
      return handicapName;
    };

    const changeCompetitionType = (competitionType: string) => {
      if (state.value.competitionType !== competitionType) {
        state.value.competitionType = competitionType;
      } else {
        state.value.competitionType = "";
      }
    };

    const toPointsRanking = () => {
      router.push({
        path: `/integral`,
        query: {
          yiqiuid: game_id.value,
          comid: filterInfo.value.competition_id,
        },
      });
    };

    const handlePKAnalyze = (team_id: string, source: any[]): number[] => {
      if (!team_id || !source.length) return [0, 0, 0, 0, 0, 0, 0, 0];
      let win = 0;
      let flat = 0;
      let lose = 0;
      let big = 0;
      let small = 0;
      let count = 0;
      source?.map((item) => {
        if (
          item.home_team_id === team_id &&
          item.home_scores?.[0] - parseFloat(item.the_odds_data?.[1]) >
            item.away_scores?.[0]
        ) {
          win++;
        } else if (
          item.away_team_id === team_id &&
          item.home_scores?.[0] - parseFloat(item.the_odds_data?.[1]) <
            item.away_scores?.[0]
        ) {
          win++;
        } else if (
          [item.away_team_id, item.home_team_id].includes(team_id) &&
          item.home_scores?.[0] - parseFloat(item.the_odds_data?.[1]) ==
            item.away_scores?.[0]
        ) {
          flat++;
        } else if (
          item.home_team_id === team_id &&
          item.home_scores?.[0] - parseFloat(item.the_odds_data?.[1]) <
            item.away_scores?.[0]
        ) {
          lose++;
        } else if (
          item.away_team_id === team_id &&
          item.home_scores?.[0] - parseFloat(item.the_odds_data?.[1]) >
            item.away_scores?.[0]
        ) {
          lose++;
        }

        if (
          [item.away_team_id, item.home_team_id].includes(team_id) &&
          1 * item.home_scores?.[0] + item.away_scores?.[0] * 1 >
            parseFloat(item?.odds_data?.[1])
        ) {
          big++;
        } else if (
          [item.away_team_id, item.home_team_id].includes(team_id) &&
          1 * item.home_scores?.[0] + item.away_scores?.[0] * 1 <
            parseFloat(item?.odds_data?.[1])
        ) {
          small++;
        }
        [item.away_team_id, item.home_team_id].includes(team_id) && count++;
      });
      const winPercentage = win && (win / count) * 100;
      const bigPercentage = big && (big / count) * 100;
      const smallPercentage = small && (small / count) * 100;
      return [
        win,
        winPercentage,
        flat,
        lose,
        big,
        bigPercentage,
        small,
        smallPercentage,
        count,
      ].map((item) => Math.round(item));
    };

    watchEffect(
      () => {
        let info = filterInfo.value as any;
        let homeList: any[] = game_detail.value?.history?.home || [];
        let guestList: any[] = game_detail.value?.history?.away || [];
        if (state.value.competitionType) {
          if (state.value.competitionType === "season") {
            homeList = homeList.filter(
              (item) => item.competition_id == info.competition_id
            );
            guestList = guestList.filter(
              (item) => item.competition_id == info.competition_id
            );
          } else if (state.value.competitionType === "host_guest") {
            homeList = homeList.filter(
              (item) => info.host_guest[0] == item.home_team_id
            );
            guestList = guestList.filter(
              (item) => info.host_guest[1] == item.away_team_id
            );
          }
        }
        const useHomeDatas = homeList.slice(0, state.value.competitionNum);
        const useGuestDatas = guestList.slice(0, state.value.competitionNum);
        const homeResult = handlePKAnalyze(
          game_info.value.home_team_id,
          useHomeDatas
        );
        const guestResult = handlePKAnalyze(
          game_info.value.away_team_id,
          useGuestDatas
        );
        state.value.home_pk_total = homeResult[homeResult.length - 1];
        state.value.guest_pk_total = guestResult[guestResult.length - 1];
        state.value.pk_data.forEach((item: any, index: number) => {
          item.left_value = homeResult[index];
          item.right_value = guestResult[index];
        });
      },
      { flush: "post" }
    );

    return {
      game_info,
      game_detail,
      loading,
      toupiao,
      filterInfo,
      pointType,
      points_prefix,
      showPointsRank,
      pointsRankInfo,

      onRefresh,
      // toupiaoClick,
      toPointsRanking,
      no_data,
      state,
      odds_eu,
      goal_period,
      scoreDistribution,
      showScoreDistribution,

      getTeamErrorLogo,
      formatDate,
      formatDay,
      getTeamName,
      changeCompetitionType,
    };
  },
});
</script>

<style lang="scss">
@use '@/common/style/common' as *;

@font-face {
  font-family: 'MyCustomFont';
  src: url('../../../assets/DIN-Alternate-Bold.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

.custom-font-text {
  font-family: 'MyCustomFont', sans-serif;
}

body {
  background-color: #fff;
}

.game-analysis-nm-content {
  min-width: 350px;
}

.article-wrapper {
  display: none; // 功能暂时隐藏
}

.analysis_content {
  background-color: #fff;
  section {
    border-bottom: #f5f5f5 10px solid;
  }
  .match_team {
    width: 100%;
    padding: 10px;
    display: -webkit-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    -ms-flex-align: center;

    .match_team_container {
      display: flex;
      .team_logo {
        width: 26px;
        height: 26px;
        background-repeat: no-repeat;
        background-size: contain;
        background-position: 50%;
      }
      .team_name {
        align-items: flex-start;
        margin: 0 10px;
        font-size: 16px;
        color: #000;
      }
    }
    .content-title {
      font-size: 16px;
      font-weight: 700;
    }
  }

  /* 胶囊组件 */
  .select-capsule {
    display: flex;
    height: 30px;
    border-radius: 25px;
    overflow: hidden;
    margin: 0 4px;
    padding: 3px;
    background-color: #f7f7f7;

    .select-item {
      width: 50px;
      height: 100%;
      color: #b3b3b3;
      text-align: center;
      border-radius: 12px;
      line-height: 24px;
      font-size: 12px;
      cursor: pointer;
    }

    .active {
      color: #267bfb !important;
      background-color: #fff !important;
    }
  }

  .active {
    color: #267bfb;
    background-color: #e8f0fa;
  }

  /* 历史交锋 */
  .analysis-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    font-size: 14px;
    .title-left {
      font-size: 16px;
      font-weight: 500;
    }
    .title-right {
      display: flex;
      font-weight: 500;
      img {
        width: 20px;
      }
    }
  }

  .text-content {
    text-align: justify;
    word-break: break-all;
  }
}

.highlight-text {
  text-wrap: wrap;
  color: #000000;
  font-weight: 700;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
}

/* 积分排名 */
.points-ranking {
  width: 100%;
  text-align: center;
  padding-bottom: 20px;

  .section-haeder {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    justify-content: space-between;

    .tools-box {
      flex: 1;
      margin-left: 18px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .section-body {
    width: 100%;
    padding: 0 15px;
    font-size: 12px;
  }

  .table-row {
    width: 100%;
    min-height: 35px;
    display: flex;

    .table-col {
      flex: 1;
      min-width: 35px;
      border-left: 1px solid #ffffff;

      display: flex;
      align-items: center;
      justify-content: center;
    }

    .table-col:nth-child(2) {
      flex: 2.5;
      padding-left: 10px;
      text-align: left;
      min-width: 128px;
      border: none;
      justify-content: flex-start;
    }
    .table-col:nth-child(3) {
      flex: 1.2;
      min-width: 40px;
    }
    .table-col:nth-child(4) {
      flex: 1.2;
      min-width: 60px;
    }

    .table-col:nth-child(5) {
      flex: 1.2;
      min-width: 50px;
    }

    &.header {
      color: #b3b3b3;
    }
  }

  .table-row.host .table-col {
    background-color: #FFF3DB;
  }

  .table-row.guest .table-col {
    background-color: #ffffff;
  }

  .table-row:not(.header) .table-col:last-child {
    color: #FF2121;
  }
}

.rank-btn {
  border-color: #f2f2f2 !important;

  .van-button__content {
    padding-left: 4px;
  }
}

/* PK */
.duel-away {
  padding: 10px;
  font-size: 12px;
  text-align: center;
  display: flex;
  justify-content: space-between;
  color: #999999;

  .same-btn {
    margin: 0 4px;
    width: 64px;
    height: 32px;
    line-height: 32px;
    border-radius: 25px;
    cursor: pointer;
    border: 1px solid #f2f2f2;
  }

  .button-box {
    display: flex;
  }

  .select-capsule {
    justify-self: flex-end;
  }
}

.stats-box {
  padding: 12px;
  font-size: 12px;

  .title {
    width: 88px;
    text-align: center;
    font-weight: 700;
  }

  .top {
    padding: 4px 0;

    .bar-wrapper {
      padding: 4px 0;
    }
  }

  .content-wrapper {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .bar-wrapper {
    padding-bottom: 4px;
    display: flex;

    .bar {
      flex: 1;
      display: flex;
      align-items: center;
    }
  }
}

.match-future div {
  height: 100%;
}

.game-table {
  position: relative;
  text-align: center;
  overflow: auto;
  color: #777777;
  border-top: 1px solid #E5E9EE;

  .game-table-row {
    display: flex;

    .game-table-col {
        display: flex;
        align-items: center;
        align-content: center;
        justify-content: center;

        flex-wrap: wrap;
        font-size: 12px;
        border-bottom: 1px solid #E5E9EE;

        &:nth-child(1) {
          width: 78px;
          border-right: 1px solid #E5E9EE;
        }

        &:nth-child(2) {
          flex: 1.2;
          padding: 0 12px;
        }

        &:nth-child(3) {
          flex: 1.2;
          padding: 0 12px;
        }

        &:nth-child(4) {
          flex: 1;
          border-left: 1px solid #E5E9EE;
        }
    }
  }

  .game-table-row.header {
    font-size: 12px;
    .game-table-col {
      height: 32px;
      line-height: 32px;
    }
  }

  .game-table-row:not(.header) {

    .vs-flag {
      position: absolute;
      left: -8px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 12px;
      color: #AAAAAA;
    }

    .game-table-col {
      position: relative;
      min-height: 52px;
      height: 100%;

      &:nth-child(1) {
        flex-direction: column;
      }

      &:nth-child(2) {
        padding: 8px 12px;
      }

      &:nth-child(3) {
        padding: 8px 12px;
      }
    }

    &:nth-child(even) {
      background-color: #FAFAFA;
    }
  }

  .day_col {
    color: #000;
    font-size: 12px;
  }
}
</style>
