<template>
  <div class="match-container acce-render">
    <div class="match-component" :class="data.is_hl ? (data.ranksBackground ? 'away-bg' : 'home-bg') : ''" v-if="isExistence"
      @click="gotoDetail('Game', { league: data.yiqiu_competition_id, yiqiuid: data.id })">
      <div class="match-top">
        <div class="match-top-l">
          <span class="match-competition">{{ teamName(data, 'competition') }}</span>
          <span v-if="data.sporttery_number && isJz" class="match-time">{{ sportteryNumber(data) }}</span>
          <span class="match-time">{{ matchTime(data) }}<span style="opacity: 0;">{{ data.id }}</span></span>
        </div>
        <div class="match-top-c">
          <span class="match-status" v-if="[2, 4].includes(data.status)">
            {{ showStatusTime }}<i class="flicker" v-if="showStatusTime != ''">'</i>
          </span>
          <span class="match-status" v-else>{{ showStatus(data) }}</span>
        </div>
        <div class="match-top-r">
          <span v-if="data.info_count > 0" @click.stop="gotoDetail('GameInfo', { yiqiuid: data.id })">情报</span>
          <span v-if="data.host_formation || data.guest_formation" @click.stop="gotoDetail('GameLineup', { yiqiuid: data.id })">阵容</span>
          <span v-if="data.experts_count > 0" @click.stop="gotoDetail('GameExperts', { yiqiuid: data.id })">爆料{{ data.experts_count }}</span>
          <span v-show="data.hot_count > 0"><svg-icon iconName="renshu"></svg-icon>{{ data.hot_count }}</span>
        </div>
      </div>
      <div class="match-center">
        <div class="match-center-l1" @click.stop="collect(data.id)" v-show="[1, 2, 3, 4, 5, 6, 7].includes(data.status)">
          <span class="match-collect">
            <svg-icon iconName="weiguanzhu" :style="{ color: store.state.attention_id_list.includes(data.id) ? '#da2323' : '#dddddd' }"></svg-icon>
          </span>
        </div>
        <div class="match-center-l2">
          <span class="red" v-if="data.red_card[0] > 0">{{ data.red_card[0] }}</span>
          <span class="yellow" v-if="data.yellow_card[0] > 0">{{ data.yellow_card[0] }}</span>
          <span class="rank" v-if="data.host_rank">[{{ data.host_rank.match(/\d+$/)?.[0] }}]</span>
          <span class="host-team">{{ teamName(data, 'host') }}</span>
        </div>
        <div class="match-center-c">
          <span class="match-score" v-if="[2, 3, 4, 5, 6, 7, 8].includes(data.status)"> {{ data.score[0] }}<i>-</i>{{ data.score[1] }}</span>
          <span class="match-vs" v-else>VS</span>
        </div>
        <div class="match-center-r1">
          <span class="away-team">{{ teamName(data, 'away') }}</span>
          <span class="rank" v-if="data.away_rank">[{{ data.away_rank.match(/\d+$/)?.[0] }}]</span>
          <span class="yellow" v-if="data.yellow_card[1] > 0">{{ data.yellow_card[1] }}</span>
          <span class="red" v-if="data.red_card[1] > 0">{{ data.red_card[1] }}</span>
        </div>
        <div class="match-center-r2" @click.stop="guankan" v-show="[1, 2, 3, 4, 5, 6, 7].includes(data.status)">
          <span class="match-live" style="display: none;">
            <svg-icon iconName="guankan"></svg-icon>
          </span>
        </div>
      </div>
      <div class="match-bottom">
        <div class="match-bottom-l"></div>
        <div class="match-bottom-c">
          <span class="match-corner">{{ showHC(data) }}</span>
        </div>
        <div class="match-bottom-r">
          <span class="match-more-btn" @click.stop="showOtherDate" v-if="otherData">
            {{ isShow ? '收起' : '展开' }}
            <svg-icon :iconName="isShow ? 'zhankai' : 'shouqi'" :className="isShow ? 'zhankai' : 'shouqi'"></svg-icon>
          </span>
        </div>
      </div>
      <template v-if="otherData">
        <div class="match-more" v-show="isShow">
          <div class="model-box">
            <div class="model-text">
              <span>{{ (otherData[25]?.home || 0) + '%' }}</span>
              <span>控球率</span>
              <span>{{ (otherData[25]?.away || 0) + '%' }}</span>
            </div>
            <div class="model-line">
              <template v-if="otherData[25]">
                <span :style="{ width: getLineWidth(otherData, 25) }"></span>
                <span :style="{ width: otherData[25].away > 0 ? '100%' : 0 }"></span>
              </template>
            </div>
          </div>
          <div class="model-boxs">
            <div class="model-box">
              <div class="model-text">
                <span>{{ otherData[24]?.home || 0 }}</span>
                <span>危险进攻</span>
                <span>{{ otherData[24]?.away || 0 }}</span>
              </div>
              <div class="model-line">
                <template v-if="otherData[24]">
                  <span :style="{ width: getLineWidth(otherData, 24) }"></span>
                  <span :style="{ width: otherData[24].away > 0 ? '100%' : 0 }"></span>
                </template>
              </div>
            </div>
            <div class="model-box">
              <div class="model-text">
                <span>{{ (otherData[21]?.home || 0) + (otherData[22]?.home || 0) }}</span>
                <span>射门次数</span>
                <span>{{ (otherData[21]?.away || 0) + (otherData[22]?.away || 0) }}</span>
              </div>
              <div class="model-line">
                <template v-if="otherData[21] || otherData[22]">
                  <span :style="{ width: getLineWidth(otherData, 21, 22) }"></span>
                  <span :style="{ width: (otherData[21].away > 0 || otherData[22].away > 0) ? '100%' : 0 }"></span>
                </template>
              </div>
            </div>
          </div>
          <div class="model-boxs">
            <div class="model-box">
              <div class="model-text">
                <span>{{ otherData[23]?.home || 0 }}</span>
                <span>进攻次数</span>
                <span>{{ otherData[23]?.away || 0 }}</span>
              </div>
              <div class="model-line">
                <template v-if="otherData[23]">
                  <span :style="{ width: getLineWidth(otherData, 23) }"></span>
                  <span :style="{ width: otherData[23].away > 0 ? '100%' : 0 }"></span>
                </template>
              </div>
            </div>
            <div class="model-box">
              <div class="model-text">
                <span>{{ otherData[21]?.home || 0 }}</span>
                <span>射正次数</span>
                <span>{{ otherData[21]?.away || 0 }}</span>
              </div>
              <div class="model-line">
                <template v-if="otherData[21]">
                  <span :style="{ width: getLineWidth(otherData, 21) }"></span>
                  <span :style="{ width: otherData[21].away > 0 ? '100%' : 0 }"></span>
                </template>
              </div>
            </div>
          </div>
        </div>
      </template>
      <div class="match-note" v-if="note != ''">
        <span>{{ note }}</span>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, defineProps, toRef, computed, onMounted, defineEmits, getCurrentInstance } from 'vue';
import router from '@/router';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import moment from 'moment';
import { default as _ } from 'lodash';
import { getWeek } from '@/until/index';
import { nm_status } from '@/common/js/nm_config';
import * as live_api from '@/api/live_api';

const route = useRoute();
const store: any = useStore();
const status: any = nm_status;
const emit = defineEmits(['domHeight', 'showMore']);
const sendDomHeight = ((domHeight: any) => {
  emit('domHeight', data.value.id, domHeight);
});

const props: any = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => { return {}; }
  },
  note: {
    type: String,
    required: false,
    default: () => { return ""; },
  },
  otherData: {
    type: Array,
    required: false,
    default: () => { return []; }
  },
  isShow: {
    type: Boolean,
    required: false,
    default: () => { return false; }
  },
  isJz: {
    type: Boolean,
    required: false,
    default: () => { return false; }
  }
});
const data: any = toRef(props, 'data');
const isShow: any = toRef(props, 'isShow');
const moreDate: any = toRef(props, 'otherData');
const isExistence = computed(() => {
  return Object.keys(data.value).length > 0 ? true : false;
});
const note: any = computed(() => {
  if (!isExistence.value) return null;
  let props_note = toRef(props, 'note');
  if (props_note.value != '') return props_note.value;
  let textArr = [];
  let is_score_all = JSON.stringify(data.value.score_all) != '[0,0]' && !(data.value.score_all[0] == data.value.score[0] && data.value.score_all[1] == data.value.score[1]);
  let is_score_point = JSON.stringify(data.value.score_point) != '[0,0]' && (data.value.score_point[0] > data.value.score[0] || data.value.score_point[1] > data.value.score[1]);
  if ([5, 6, 7].includes(data.value.status) || is_score_all || is_score_point) {
    // >= 加时赛 => score
    textArr.push(`90分钟[${data.value.score[0]}-${data.value.score[1]}]`);
    // >= 点球决战 => score_all
    if ([7, 8].includes(data.value.status) || is_score_point) {
      textArr.push(`120分钟[${data.value.score_all[0]}-${data.value.score_all[1]}]`);
    }
    // 已完场 => score_point + win
    if (data.value.status == 8) {
      textArr.push(`点球[${data.value.score_point[0]}-${data.value.score_point[1]}]`);
      let winName = null;
      if (is_score_point) {
        winName = data.value.score_point[0] > data.value.score_point[1] ? teamName(data.value, 'host') :
          (data.value.score_point[0] < data.value.score_point[1] ? teamName(data.value, 'away') : null);
      } else if (is_score_all) {
        winName = data.value.score_all[0] > data.value.score_all[1] ? teamName(data.value, 'host') :
          (data.value.score_all[0] < data.value.score_all[1] ? teamName(data.value, 'away') : null);
      }
      if (winName) textArr.push(`${winName}胜出`);
    }
  }
  return textArr.join(',');
});
const otherData: any = computed(() => {
  if (!isExistence.value) return null;
  if (moreDate.value.length < 1) return null;
  else return _.keyBy(moreDate.value, 'type');
});

// 显示处理
const competitionColor = ref('#' + (data.value.competition_color || '000000'));
const teamName = (data: any, type: string) => {
  return data[`${type}_short_name`] ? data[`${type}_short_name`] : data[`${type}_name`] ? data[`${type}_name`] : '';
};
const sportteryNumber = (data: any) => {
  return getWeek(data.sporttery_issue_name) + data.sporttery_number;
};
const matchTime = (data: any) => {
  let time = _.clone(data.match_time).split(' ')[1]?.split(':') || null;
  return time ? time[0] + ':' + time[1] : '00:00';
};
const arrToStr = (arr: any, join: string) => {
  return arr[0] + join + arr[1];
};
const showStatus = (data: any) => {
  let passTime = moment(data.match_time).add(3, "hours");
  let isPass = passTime < moment(store.state.server_time);
  if (isPass && data.status < 8) { // 异常不显示状态
    if (data.value) {
      console.log('异常', data.value.id, data.value.status);
      (window as any).repairSingle(store, data.value.id);
    }
    return '';
  } else {
    let text = '';
    switch (data.status) {
      case 1:
        text = '';
        break;
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        text = status[data.status];
        break;
      case 8:
        text = '完';
        break;
      // 异常
      case 0:
      case 9:
      case 10:
      case 11:
      case 12:
      case 13:
        text = status[data.status];
        break;
    }
    return text;
  }
};
const showStatusTime = computed(() => {
  let passTime = moment(data.value.match_time).add(3, "hours");
  let isPass = passTime < moment(store.state.server_time);
  if (data.value.status < 8 && isPass) { // 异常不显示状态
    // console.log('异常', data.value.id, data.value.status);
    (window as any).repairSingle(store, data.value.id);
    return '';
  }
  let contrastTime: any = store.state.nm_live_message[data.value.id]?.score[4] ?
    moment(store.state.nm_live_message[data.value.id]?.score[4] * 1000) : '';
  if (contrastTime == '') return status[data.value.status];
  let startTime = moment(contrastTime).valueOf();
  let abs: any = moment(store.state.server_time).diff(startTime, 'minutes') + 1;
  if (abs < 1) {
    // console.log('异常', data.value.id, data.value.status);
    (window as any).repairSingle(store, data.value.id);
    return '';
  }
  if (data.value.status == 2 && abs > 45) {
    abs = '45+';
    if (abs >= 60) {
      // console.log('异常', data.value.id, data.value.status);
      (window as any).repairSingle(store, data.value.id);
    }
  } else if (data.value.status == 4) {
    abs += 45;
    if (abs > 90) abs = '90+';
    if (abs >= 105) {
      // console.log('异常', data.value.id, data.value.status);
      (window as any).repairSingle(store, data.value.id);
    }
  }
  return abs;
});
const showHC = (data: any) => {
  let text = [];
  if (data.half && [3, 4, 5, 6, 7, 8].includes(data.status)) {
    text.push('半: ' + arrToStr(data.half, '-'));
  }
  if (data.corner_kicks && JSON.stringify(data.corner_kicks) != '[0,0]') {
    text.push('角: ' + arrToStr(data.corner_kicks, '-'));
  }
  return text.join('  ');
};
const getLineWidth = (data: any, type1: number, type2: any = null) => {
  let width: any = 0, obj: any = null;
  switch (type1) {
    case 25:
      width = data[type1].home;
      break;
    case 24:
    case 23:
      obj = data[type1];
      width = obj.home / (obj.home + obj.away) * 100;
      break;
    case 22:
    case 21:
      if (type2) {
        let total = data[type1].home + data[type1].away + data[type2].home + data[type2].away;
        let home = data[type1].home + data[type2].home;
        width = home / total * 100;
      } else {
        obj = data[type1];
        width = obj.home / (obj.home + obj.away) * 100;
      }
      break;
    default:
      width = 0;
      break;
  }
  return width + '%';
};
const showOtherDate = () => {
  emit('showMore', data.value.id);
  if (!instance) return;
  const { proxy } = instance;
  let domHeight = proxy?.$el.offsetHeight || 0;
  sendDomHeight(domHeight);
};

// 跳转
const gotoDetail = async (name: any, params: any) => {
  store.commit('updateLivePath', route.path);
  // preload detail
  store.commit('updateNmGameMessageCache', props.data);
  return router.push({ name: name, params: params });
};
// 收藏
const collect = async (id: any) => {
  if (Object.keys(store.state.userInfo).length < 1) return location.href = `/login?return_url=${location.href}`;
  let is_attention = store.state.attention_id_list.includes(id) ? 0 : 1;
  let res = await live_api.nm_match_set_attention(id, is_attention);
  if (res?.data?.data?.nm_match_set_attention.Error == "") {
    let matchListAttention = _.clone(store.state.match_list_attention) || {};
    let match_date: any = moment(store.state.server_time).format('YYYY-MM-DD');
    if (!matchListAttention[match_date]) matchListAttention[match_date] = [];
    if (is_attention == 1) {
      matchListAttention[match_date].push(data.value);
    } else {
      matchListAttention[match_date].forEach((item: any, index: number) => {
        if (item.id == id) matchListAttention[match_date].splice(index, 1);
      });
    }
    store.commit('updateMatchListAttention', matchListAttention);
  }
};
// 直播
const guankan = () => { console.log('直播'); };

const instance = getCurrentInstance();
onMounted(() => {
  if (instance) {
    const { proxy } = instance;
    let domHeight = proxy?.$el.offsetHeight || 0;
    sendDomHeight(domHeight);
  } else {
    console.error('无法获取组件实例');
  }
  // console.log('Match ========== onMounted', JSON.stringify(props.data))
});
</script>

<style lang="scss" scoped>
.match-container {
  min-height: 98px;

  .match-component {
    display: block;
    background: #ffffff;

    .match-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 6px 6px 0 6px;
      font-size: 12px;
      line-height: 20px;

      .match-top-l {
        width: 40%;
        text-align: left;

        span {
          margin-right: 4px;
        }

        :last-child {
          margin-right: 0;
        }

        .match-competition {
          color: v-bind(competitionColor);
        }

        .match-time {
          color: #868686;
        }
      }

      .match-top-c {
        width: 20%;
        text-align: center;

        .match-status {
          color: #da2323;
        }
      }

      .match-top-r {
        width: 40%;
        text-align: right;
        color: #da2323;

        span {
          margin-right: 4px;
          line-height: 20px;
        }

        :last-child {
          color: #a3a3a3;
          margin-right: 0;

          .svg-icon {
            width: 12px;
            height: 12px;
            margin-top: -3px;
          }
        }
      }
    }

    .match-center {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 5px 6px;
      font-size: 14px;
      line-height: 18px;
      height: 46px;

      .match-center-l1 {
        cursor: pointer;
        width: 8%;

        .match-collect {
          color: #e8e8e8;
          font-size: 12px;

          .guanzhu {
            color: #da2323 !important;
          }
        }
      }

      .match-center-l2 {
        width: 36%;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        span {
          margin-left: 2px;
        }

        :first-child {
          margin-left: 0;
        }

        .host-team {
          color: #101010;
          font-weight: bold;
        }

        .red {
          padding: 0 2px;
          color: #ffffff;
          font-size: 12px;
          line-height: 14px;
          border-radius: 2px;
          background: #da2323;
        }

        .yellow {
          padding: 0 2px;
          color: #ffffff;
          font-size: 12px;
          line-height: 14px;
          border-radius: 2px;
          background: #ffcd00;
        }

        .rank {
          color: #a3a3a3;
          font-size: 12px;
          line-height: 14px;
          white-space: nowrap;
        }
      }

      .match-center-c {
        width: 12%;

        .match-score {
          color: #da2323;
          font-size: 16px;
          font-weight: bold;

          i {
            margin: 0 2px;
            font-style: normal;
          }
        }

        .match-vs {
          color: #a3a3a3;
          font-weight: 500;
        }
      }

      .match-center-r1 {
        width: 36%;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        span {
          margin-right: 2px;
        }

        :last-child {
          margin-right: 0;
        }

        .away-team {
          color: #101010;
          font-weight: bold;
        }

        .red {
          padding: 0 2px;
          color: #ffffff;
          font-size: 12px;
          line-height: 14px;
          border-radius: 2px;
          background: #ff4242;
        }

        .yellow {
          padding: 0 2px;
          color: #ffffff;
          font-size: 12px;
          line-height: 14px;
          border-radius: 2px;
          background: #ffd432;
        }

        .rank {
          color: #a3a3a3;
          font-size: 12px;
          line-height: 14px;
          white-space: nowrap;
        }
      }

      .match-center-r2 {
        cursor: pointer;
        width: 8%;

        .match-live {
          color: #ff4242;
          font-size: 12px;
        }
      }
    }

    .match-bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 6px 6px 6px;
      font-size: 12px;
      line-height: 20px;

      .match-bottom-l {
        width: 20%;
        text-align: left;
      }

      .match-bottom-c {
        width: 40%;
        text-align: center;

        .match-corner {
          color: #a3a3a3;
        }
      }

      .match-bottom-r {
        width: 20%;
        text-align: right;

        .match-more-btn {
          cursor: pointer;
          color: #2482ff;

          .shouqi {
            width: 10px;
            height: 10px;
            margin-bottom: 1px;
          }

          .zhankai {
            width: 10px;
            height: 10px;
            margin-bottom: 1px;
          }
        }
      }
    }

    .match-note {
      color: #FF1818;
      font-size: 12px;
      line-height: 25px;
      background: #FFF7F7;
    }

    .match-more {
      padding: 0 6px 6px 6px;

      .model-boxs {
        display: flex;
        justify-content: space-between;
        align-items: center;

        div.model-box {
          position: relative;
          width: 49%;
        }
      }

      .model-box {
        width: 100%;

        .model-text {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: #777777;
          font-size: 12px;
          line-height: 26px;

          span:nth-child(2) {
            color: #333333;
          }
        }

        .model-line {
          position: relative;
          width: 100%;
          height: 6px;
          border-radius: 4px;
          background: #dddddd;

          span {
            position: absolute;
            top: 0;
            bottom: 0;
            border-radius: 4px;
          }

          span:first-child {
            z-index: 2;
            left: 0;
            background: #267FF5;
          }

          span:last-child {
            z-index: 1;
            left: 0;
            right: 0;
            background: #F61616;
          }
        }
      }
    }
  }

  .home-bg {
    background: linear-gradient(90deg, #FFBCBC 0%, #FFFFFF 60%) !important;
  }

  .away-bg {
    background: linear-gradient(90deg, #FFFFFF 40%, #FFBCBC 100%) !important;
  }
}

@keyframes flicker {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

.flicker {
  animation: flicker 1s infinite;
}
</style>