<script lang="ts" name="GameAnalysisTable">
import {
  reactive,
  defineComponent,
  computed,
  onMounted,
  watch,
  toRefs,
  markRaw,
} from "vue";
import { default as _ } from "lodash";
import { default as moment } from "moment";
import { Button, Checkbox, CheckboxGroup } from "vant";
import noData from "@/components/NoData.vue";
import CustomSelect from "@/components/CustomSelect.vue";

import ic_xuanzhong from "@/assets/images/ic_xuanzhong.png";
import ic_weixuanzhong from "@/assets/images/ic_weixuanzhong.png";

interface StateInter {
  winSum: number;
  loseSum: number;
  competitionNum: number;
  winningPercentage: number;
  bigPercentage: number;
  win_or_draw: number[];
  competitionType: string;
  showCols: string[];
  selectChecked: string;
  bg_color_box: string[];
}

export default defineComponent({
  name: "GameAnalysisTable",
  components: { noData, CustomSelect, Button, Checkbox, CheckboxGroup },
  props: {
    title: {
      type: String,
      default: "历史交锋",
    },
    teamInfo: {
      type: Object,
      default: () => ({}),
    },
    tableType: {
      type: String,
      default: "history"
    },
    gameInfo: {
      type: Object,
      default: () => ({})
    },
    tableData: {
      type: Array<any>,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    // $const
    const selectOtpions = markRaw([
      {
        label: "BET365",
        value: "BET365",
      },
      // {
      //   label: "澳*",
      //   value: "1",
      // },
      // {
      //   label: "36*",
      //   value: "2",
      // },
      // {
      //   label: "易胜*",
      //   value: "3",
      // },
    ]);
    // $const

    // $data
    const state = reactive<StateInter>({
      winSum: 0,
      loseSum: 0,
      competitionNum: 10,
      competitionType: '',
      winningPercentage: 0,
      bigPercentage: 0,
      win_or_draw: [0, 0 , 0],
      showCols: ["victory_or_defeat", "subdactylia"],
      selectChecked: "BET365",
      bg_color_box: ["background-color:#fafafa", "background-color:#fff"],
    });
    // $data

    // $computed
    const showList = computed(() => {
      let list = props.tableData;
      let info = props.gameInfo;
      if (!!state.competitionType) {
        if (state.competitionType === 'season') {
          list = list.filter(item => item.competition_id === info.competition_id)
        } else if (state.competitionType === 'host_guest') {
          list = list.filter(item => {
            if (props.tableType === 'home') {
              return info.home_team_id === item?.home_team_id
            } else if (props.tableType === 'guest') {
              return info.away_team_id === item?.away_team_id
            } else {
              return info.away_team_id === item?.away_team_id && info.home_team_id  === item?.home_team_id
            }
        });
        }
      }
      return list.slice(0, state.competitionNum);
    })

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

    // $watch
    watch(
      () => state.showCols,
      (val, oldVal) => {
        state.showCols.length > 2 && state.showCols.shift();
        !val.length && (state.showCols = oldVal);
      },
      { deep: true }
    );

    watch(
      showList,
      () => {
        statistics_data();
      },
      { deep: true }
    );
    // $watch

    // $methods
    const statistics_data = () => {
      let win = 0;
      let lose = 0;
      let bigSum = 0;
      let winningSum = 0;
      const win_or_draw = [0, 0 ,0];
      const list = showList.value;

      list?.forEach((item: any) => {
        if (item?.home_team_id === props?.teamInfo?.team_id) {
          win += item?.home_scores[0] * 1;
          lose += item?.away_scores[0] * 1;

          if (item?.home_scores?.[0] > item?.away_scores?.[0]) {
            win_or_draw[0] += 1;
          } else if (item?.home_scores?.[0] == item?.away_scores?.[0]) {
            win_or_draw[1] += 1;
          } else {
            win_or_draw[2] += 1;
          }

          ((item?.home_scores?.[0] - item?.the_odds_data?.[1]) > item?.away_scores?.[0]) && winningSum++
        } else {
          win += item?.away_scores?.[0] * 1;
          lose += item?.home_scores?.[0] * 1;

          if (item?.home_scores?.[0] > item?.away_scores?.[0]) {
            win_or_draw[2] += 1;
          } else if (item?.home_scores?.[0] == item?.away_scores?.[0]) {
            win_or_draw[1] += 1;
          } else {
            win_or_draw[0] += 1;
          }

          ((item?.home_scores?.[0] - item?.the_odds_data?.[1]) < item?.away_scores?.[0]) && winningSum++
        }
        (item.away_scores?.[0] * 1 + item?.home_scores?.[0] * 1 > item?.odds_data?.[1]) && bigSum++;
      });
      state.winSum = win;
      state.loseSum = lose;
      state.win_or_draw = win_or_draw;
      state.bigPercentage = bigSum && Math.round(bigSum / list.length * 100);
      // 赢率
      state.winningPercentage = winningSum && Math.round(winningSum / list.length * 100);
    };

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

    const getTeamName = (teamInfo: any, isHome: boolean) => {
      const prefixed = isHome ? 'home' : 'away';
       const info = props.gameInfo;
        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 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);
    };

    // is_self 是否以 "统计队" 的视角展示数据
    const getResultType = (data: any, field: 'result_info' | 'half_result_info' | 'odds_info', is_self: boolean = true) => {
      return is_self ? (props.teamInfo?.team_id === data.away_team_id ? data[field]?.guest : data[field]?.home) : data[field]?.home;
    }
    // $methods

    // $life
    onMounted(() => {
      statistics_data();
    });
    // $life

    return {
      selectOtpions,
      ...toRefs(props),
      ...toRefs(state),
      formatDay,
      formatDate,
      showList,
      getResultType,
      getTeamName,
      changeCompetitionType,

      ic_weixuanzhong,
      ic_xuanzhong
    };
  },
});
</script>

<template>
  <section class="game-analysis-table">
    <div v-if="tableType === 'history'" class="analysis-title">
      <div class="title-left">{{ title }}</div>
      <div class="title-right">
        <div class="history-home-away">
          <div class="button-group">
            <div :class="['same-btn', competitionType === 'host_guest' && 'active']" @click="changeCompetitionType('host_guest')">同主客</div>
            <div :class="['same-btn', competitionType === 'season' && 'active']" @click="changeCompetitionType('season')">同赛事</div>
          </div>

          <div class="select-capsule">
            <div :class="['select-item', competitionNum == 10 && 'active']" @click="competitionNum = 10">10场</div>
            <div :class="['select-item', competitionNum == 20 && 'active']" @click="competitionNum = 20">20场</div>
          </div>
        </div>
      </div>
    </div>
    <div class="team-info">
      <div class="info-left">
        <div
          class="info-logo"
          :style="`background-image: url(${ teamInfo.team_logo });`"
        ></div>
        <div class="info-content">
          <div class="title">{{ teamInfo.team_name }}</div>
          <div>
            <span style="color: #fb252e">{{win_or_draw[0]}}胜</span>
            <span style="color: #287cfb">{{win_or_draw[1]}}平</span>
            <span style="color: #1dc22f">{{win_or_draw[2]}}负</span>
          </div>
        </div>
      </div>
      <div class="info-right">
        <div>
          <span>{{ winSum }}</span>
          <p>进球</p>
        </div>
        <div>
          <span>{{ loseSum }}</span>
          <p>失球</p>
        </div>
        <div>
          <span>{{ winningPercentage }}%</span>
          <p>赢率</p>
        </div>
        <div>
          <span>{{ bigPercentage }}%</span>
          <p>大率</p>
        </div>
      </div>
    </div>
    <div v-if="tableType !== 'history'" class="history-home-away p-x-9">
      <div class="button-group">
        <div :class="['same-btn', competitionType === 'host_guest' && 'active']" @click="changeCompetitionType('host_guest')">同主客</div>
        <div :class="['same-btn', competitionType === 'season' && 'active']" @click="changeCompetitionType('season')">同赛事</div>
      </div>

      <div class="select-capsule">
        <div :class="['select-item', competitionNum == 10 && 'active']" @click="competitionNum = 10">10场</div>
        <div :class="['select-item', competitionNum == 20 && 'active']" @click="competitionNum = 20">20场</div>
      </div>
    </div>
    <div class="team-tools">
      <checkbox-group
        v-model="showCols"
        checked-color="#2779fb"
        shape="square"
        direction="horizontal"
        size="small"
      >
        <Checkbox name="victory_or_defeat">胜负
          <template #icon="props">
            <img class="img-icon" :src="props.checked ? ic_xuanzhong : ic_weixuanzhong" />
          </template>
        </Checkbox>
        <Checkbox name="goal">进球
          <template #icon="props">
            <img class="img-icon" :src="props.checked ? ic_xuanzhong : ic_weixuanzhong" />
          </template>
        </Checkbox>
        <Checkbox name="Corner_Kick">角球
          <template #icon="props">
            <img class="img-icon" :src="props.checked ? ic_xuanzhong : ic_weixuanzhong" />
          </template>
        </Checkbox>
        <Checkbox name="subdactylia">亚指
          <template #icon="props">
            <img class="img-icon" :src="props.checked ? ic_xuanzhong : ic_weixuanzhong" />
          </template>
        </Checkbox>
        <Checkbox name="Partial_total">半全
          <template #icon="props">
            <img class="img-icon" :src="props.checked ? ic_xuanzhong : ic_weixuanzhong" />
          </template>
        </Checkbox>
      </checkbox-group>
      <div class="bottom-box">
        <CustomSelect v-model:value="selectChecked" :options="selectOtpions" />
        <div class="button-group">
          <span class="btn active">初</span>
          <span class="btn active">终</span>
        </div>
      </div>
    </div>
    <div class="al-table">
      <!-- table-header -->
      <div class="al-table-row header">
        <div class="al-table-col">赛事</div>
        <div class="al-table-col">主队</div>
        <div class="al-table-col">比分</div>
        <div class="al-table-col">客队</div>
        <!-- <div class="al-table-col">赛果</div> -->
        <div v-if="showCols.includes('victory_or_defeat')" class="al-table-col">
          胜负
        </div>
        <div v-if="showCols.includes('goal')" class="al-table-col">进球</div>
        <div v-if="showCols.includes('Corner_Kick')" class="al-table-col">
          角球
        </div>
        <div v-if="showCols.includes('subdactylia')" class="al-table-col">
          亚指
        </div>
        <div v-if="showCols.includes('Partial_total')" class="al-table-col">
          半全
        </div>
      </div>

      <!-- table-body -->
      <template v-if="tableData.length">
        <div
          v-for="(item, index) in showList"
          :key="index"
          class="al-table-row"
        >
          <!-- 赛事 -->
          <div class="al-table-col flex-center-y">
            <div class="small-txt">{{ item.competition_name }}</div>
            <div class="small-time">{{ formatDate(item.match_time * 1000) }}</div>
          </div>
          <!-- 主队 -->
          <div
            :class="[
              'al-table-col',
              teamInfo.team_id === item?.home_team_id ? 'key-point' : '',
            ]"
          >
            {{ getTeamName(item, true)|| '—--—' }}
          </div>
          <!-- 比分 -->
          <div class="al-table-col flex-center-y">
            <div
              :style="{ backgroundColor: getResultType(item, 'result_info')?.color }"
              class="score-tag"
            >
              {{ item?.home_scores[0] }}-{{ item?.away_scores[0] }}
            </div>
            <span>({{ item?.home_scores[1] }}-{{ item?.away_scores[1] }})</span>
          </div>
          <!-- 客队 -->
          <div
            :class="[
              'al-table-col',
              teamInfo.team_id === item.away_team_id ? 'key-point' : '',
            ]"
          >
            {{ getTeamName(item, false) || '—--—' }}
          </div>
          <!-- 赛果 -->
          <!-- <div :style="{color: item.color}" class="al-table-col flex-center-y">{{item.syzygote}}</div> -->
          <!-- 胜负 -->
          <div
            v-if="showCols.includes('victory_or_defeat')"
            :style="{ color: getResultType(item, 'result_info')?.color }"
            class="al-table-col flex-center-y"
          >
            {{ getResultType(item, 'result_info')?.result }}
          </div>
          <!-- 进球 -->
          <div
            v-if="showCols.includes('goal')"
            :style="{ color: item?.goal_info?.color }"
            class="al-table-col flex-center-y"
          >
          <template v-if="item?.odds_data?.[1]">
            <div>{{ item?.odds_data?.[1] || '-' }}</div>
            <span>{{
              (item?.goal_info?.value)
            }}</span>
          </template>
          <span v-else>—</span>
          </div>
          <!-- 角球 -->
          <div
            v-if="showCols.includes('Corner_Kick')"
            class="al-table-col flex-center-y"
          >
            <div style="color: #000">
              {{ item?.home_scores[4] + item?.away_scores[4] }}
            </div>
            <span>({{ item?.home_scores[4] }}-{{ item?.away_scores[4] }})</span>
          </div>
          <!-- 亚指 -->
          <div
            v-if="showCols.includes('subdactylia')"
            :style="{color: getResultType(item, 'odds_info')?.color}"
            class="al-table-col flex-center-y"
          >
            <!-- <div>{{ item.the_odds_data?.[1] }}</div> -->
             <template v-if="item.handicap_txt && getResultType(item, 'odds_info')?.result">
              <span>{{ item.handicap_txt || '-' }}</span>
              <span>{{ getResultType(item, 'odds_info')?.result }}</span>
             </template>
             <span v-else>—</span>
            
          </div>
          <!-- 半全 -->
          <div
            v-if="showCols.includes('Partial_total')"
            class="al-table-col flex-center-x"
          >
            <span :style="{ color: getResultType(item, 'half_result_info')?.color }">{{
              getResultType(item, 'half_result_info')?.result
            }}</span
            ><span :style="{ color: getResultType(item, 'result_info')?.color }">{{
              getResultType(item, 'result_info')?.result
            }}</span>
          </div>
        </div>
      </template>
      <div v-else style="padding-bottom: 30px">
        <noData nodata_message="暂无数据！"></noData>
      </div>
    </div>
  </section>
</template>

<style lang="scss">
.game-analysis-table {
  background-color: #fff;
  /* 历史交锋 */
  .analysis-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    font-size: 14px;
    border-bottom: #f5f5f5 solid 1px;
    .title-left {
      font-size: 16px;
      font-weight: 500;
    }
    .title-right {
      display: flex;
      img {
        width: 20px;
      }
    }
  }

  .p-x-9 {
    padding: 0 9px;
  }

  .history-home-away {
      font-size: 12px;
      text-align: center;
      display: flex;
      justify-content: space-between;
      color: #999999;

      .button-group {
        display: flex;
        justify-content: space-evenly;
      }

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

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

  .team-info {
    padding: 10px;
    display: flex;
    justify-content: space-between;

    text-align: center;

    .info-left {
      display: flex;
      align-items: center;
      flex-grow: 0;
      text-align: left;
      .info-logo {
        width: 36px;
        height: 36px;
        background-repeat: no-repeat;
        background-size: contain;
        background-position: 50%;
      }

      .title {
        font-size: 14px;
        font-weight: 700;
      }
      .info-content {
        padding-left: 8px;
        font-size: 12px;
      }
    }

    .info-right {
      display: flex;
      align-items: center;
      flex-shrink: 0;

      div {
        padding: 0 10px;
      }

      span {
        font-size: 16px;
        font-weight: 600;
        color: #FF2121;
      }

      p {
        font-size: 12px;
        color: #b3b3b3;
      }
    }
  }

  .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;
      cursor: pointer;
    }

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

  .img-icon{
    width: 16px;
    height: 16px;
  }

  .team-tools {
    padding: 10px;
    position: relative;

    .van-checkbox__label {
      font-size: 14px;
      margin-left: 4px !important;
    }

    .van-checkbox__icon {
      display: flex;
      align-items: center;
    }

    .van-checkbox-group--horizontal {
      justify-content: space-evenly;
    }

    --van-checkbox-label-color: #999999;

    .van-checkbox__icon--checked + .van-checkbox__label {
      --van-checkbox-label-color: #333333;
    }

    .bottom-box {
      padding: 10px 2px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      display: none; // 功能暂时隐藏
    }

    .button-group {
      color: #ababab;
      position: relative;

      .btn {
        margin: 0 4px;
        padding: 4px 20px;
        border-radius: 4px;
        background-color: #f5f5f5;
      }

      .active {
        color: #fd7779;
      }
    }
  }

  .al-table {
    position: relative;
    overflow: auto;
    text-align: center;
    color: #999999;
    font-size: 12px;
    border-top: 1px solid #eaeaea;

    .score-tag {
      color: #ffffff;
      width: 40px;
      height: 20px;
      line-height: 20px;
      border-radius: 10px;
      background-color: red;
    }

    .al-table-row {
      display: flex;

      .al-table-col {
        flex: 1;
        padding: 8px 0;
        min-width: 36px;
        text-align: center;
        border-bottom: 1px solid #eaeaea;
        border-right: 1px solid #eaeaea;

        &:nth-child(1) {
          width: 58px;
          min-width: 58px;
        }
        &:nth-child(2) {
          border: none;
          min-width: 74px;
          border-bottom: 1px solid #eaeaea;
        }
        &:nth-child(3) {
          border: none;
          min-width: 50px;
          border-bottom: 1px solid #eaeaea;
        }
        &:nth-child(4) {
          min-width: 74px;
        }
      }
    }

    .small-txt {
      font-size: 12px;
    }

    .small-time {
      font-size: 10px;
    }

    .key-point {
      color: #000000;
      font-weight: 600;
    }

    .al-table-row:not(.header) {
      display: flex;

      .al-table-col:nth-child(2) {
        padding: 7.5px 0;
        text-align: right;
      }
      .al-table-col:nth-child(3) {
        padding: 4px 0;
      }
      .al-table-col:nth-child(4) {
        padding: 7.5px 0;
        text-align: left;
      }
    }
  }
}

.flex-center-x {
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: center;
}

.flex-center-y {
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: center;
  justify-content: center;
}
</style>
