<script setup>
import { Tooltip } from 'ant-design-vue';
import { ref, computed } from 'vue';
import dayjs from 'dayjs';

import MatchCard from './match_card.vue';

const props = defineProps({
  serial: {
    type: Number,
  },
  id: {
    type: Number,
    required: true
  },
  mk: {
    type: Number,
    required: true
  },
  rel: {
    type: Object,
    required: true
  },
  solutions: {
    type: Array,
    required: true
  },
  selected: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['toggle']);

const selectedIndex = ref(0);

const PS_IOR_KEYS = [
  ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
  ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
  ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
  ['-3', 'ior_rh_35', 'ior_wmh_3', 'ior_rac_25'],
  // ['-4', 'ior_rh_45', 'ior_wmh_4', 'ior_rac_35'],
  // ['-5', 'ior_rh_55', 'ior_wmh_5', 'ior_rac_45'],
  ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  ['+3', 'ior_rah_25', 'ior_wmc_3', 'ior_rc_35'],
  // ['+4', 'ior_rah_35', 'ior_wmc_4', 'ior_rc_45'],
  // ['+5', 'ior_rah_45', 'ior_wmc_5', 'ior_rc_55'],
  ['ou_05', 'ior_ouc_05', '-', 'ior_ouh_05'],
  ['ou_15', 'ior_ouc_15', '-', 'ior_ouh_15'],
  ['ou_25', 'ior_ouc_25', '-', 'ior_ouh_25'],
  ['ou_35', 'ior_ouc_35', '-', 'ior_ouh_35'],
  ['ot_1', '-', 'ior_ot_1', '-'],
  ['ot_2', '-', 'ior_ot_2', '-'],
  ['ot_3', '-', 'ior_ot_3', '-'],
  ['ot_4', '-', 'ior_ot_4', '-'],
  ['ot_5', '-', 'ior_ot_5', '-'],
  // ['ot_6', '-', 'ior_ot_6', '-'],
  // ['ot_7', '-', 'ior_ot_7', '-'],
];

const fixFloat = (number, x = 2) => {
  return parseFloat(number.toFixed(x));
}

const IOR_ORDER = {
  'm': 0,
  '0': 1,
  '-': 2,
  '+': 3,
  'ou': 4,
  'wm': 5,
  'ot': 6,
}

const getIorPrefix = (ior) => {
  const iorParts = ior.split('_');
  if (iorParts.length === 1) {
    return iorParts[0][0];
  }
  return iorParts[0];
}

const parseRatio = (ratioString) => {
  return parseFloat(`${ratioString[0]}.${ratioString.slice(1)}`);
}

const parseIorKey = (iorKey) => {
  const iorKeyMatch = iorKey.match(/^ior_(r|ou|m|wm|ot|os)(a?)(h|c|n)?(_([\d-]+))?$/);
  if (!iorKeyMatch) {
    console.log('no iorKeyMatch', iorKey);
    return null;
  }
  const [, type, accept, side, , ratioString] = iorKeyMatch;
  let ratio = 0;
  if (type === 'ot' || type === 'os') {
    ratio = ratioString;
  }
  else if (ratioString) {
    ratio = parseRatio(ratioString) * (accept ? 1 : -1);
  }
  return { type, side, ratio };
}

const formatPsEvents = (events) => {
  return PS_IOR_KEYS.map(([label, ...keys]) => {
    const labelParts = label.split('_');
    const labelType = labelParts[0];
    if (labelType === 'ou') {
      const labelRatio = parseRatio(labelParts[1]);
      label = `ou_${labelRatio}`;
    }
    const match = keys.map(key => ({
      key,
      value: events[key]?.v ?? 0,
      origin: events[key]?.r,
      source: events[key]?.s,
      qualified: events[key]?.q ?? 1,
      returnRate: events[key]?.rt,
    }));
    return {
      label,
      match
    };
  })
  // .filter(item => item.match.every(entry => entry.value !== 0))
  .map(({label, match}) => [label, ...match]);
}

const formatEvents = (events) => {
  const eventsMap = {};
  Object.keys(events).forEach(key => {
    const { type, side, ratio } = parseIorKey(key) ?? {};
    if (!type) {
      return;
    }
    let ratioKey, index;
    if (type === 'r') {
      if (side === 'h') {
        ratioKey = ratio;
        index = 0;
      }
      else if (side === 'c') {
        ratioKey = -ratio;
        index = 2;
      }
    }
    else if (type === 'm') {
      ratioKey = 'm';
      if (side == 'h') {
        index = 0;
      }
      else if (side == 'c') {
        index = 2;
      }
      else {
        index = 1;
      }
    }
    else if (type === 'wm') {
      ratioKey = `wm_${Math.abs(ratio)}`;
      if (side === 'h') {
        index = 0;
      }
      else if (side === 'c') {
        index = 2;
      }
    }
    else if (type === 'ou') {
      ratioKey = `ou_${Math.abs(ratio)}`;
      if (side === 'c') {
        index = 0;
      }
      else if (side === 'h') {
        index = 2;
      }
    }
    else if (type === 'ot') {
      ratioKey = `ot_${ratio}`;
      index = 1;
    }
    if (typeof (ratioKey) == 'number') {
      if (ratioKey > 0) {
        ratioKey = `+${ratioKey}`;
      }
      else {
        ratioKey = `${ratioKey}`;
      }
    }

    if (!ratioKey) {
      return;
    }

    if (!eventsMap[ratioKey]) {
      eventsMap[ratioKey] = new Array(3).fill(undefined);
    }

    const value = events[key]?.v ?? 0;
    const origin = events[key]?.r;
    const qualified = events[key]?.q ?? 1;
    eventsMap[ratioKey][index] = { key, value, origin, qualified };
  });

  return Object.keys(eventsMap).sort((a, b) => {
    const aPrefix = getIorPrefix(a);
    const bPrefix = getIorPrefix(b);
    if (aPrefix !== bPrefix) {
      return IOR_ORDER[aPrefix] - IOR_ORDER[bPrefix];
    }
    return a.localeCompare(b);
  }).map(key => {
    return [key, ...eventsMap[key]];
  });
}

const toggleSolution = () => {
  const id = props.id;
  const sid = currentSolution.value.sid;
  emit('toggle', { id, sid });
};

const switchSolution = (index) => {
  if (index == selectedIndex.value) {
    return;
  }
  selectedIndex.value = index;
  if (!props.selected) {
    return;
  }
  toggleSolution();
};

const currentIndex = computed(() => {
  const index = selectedIndex.value;
  if (props.solutions[index]) {
    return index;
  }
  return 0;
});

const currentSolution = computed(() => {
  return props.solutions[currentIndex.value];
});

const currentRelation = computed(() => {
  const cpr = currentSolution.value.cpr;
  const rel = props.rel;
  const { ps: { eventId, leagueName, timestamp, stage, retime, score } } = rel;
  const dateTime = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
  const relation = { id: eventId, leagueName, timestamp, dateTime, stage, retime, score };
  Object.keys(rel).forEach(platform => {
    const { eventId, teamHomeName, teamAwayName, events, special } = rel[platform] ?? {};
    if (!relation.rel) {
      relation.rel = {};
    }
    const mergedEvents = { ...events, ...special };
    const formattedEvents = platform === 'ps' ? formatPsEvents(mergedEvents) : formatEvents(mergedEvents);
    // const formattedEvents = formatEvents(mergedEvents);
    relation.rel[platform] = {
      eventId: eventId ?? 0,
      teamHomeName: teamHomeName ?? '主队',
      teamAwayName: teamAwayName ?? '客队',
      events: formattedEvents ?? []
    };
  });
  cpr.forEach(item => {
    const { k, p } = item;
    if (!relation.rel[p]['selected']) {
      relation.rel[p]['selected'] = [];
    }
    relation.rel[p]['selected'].push(k);
  });
  const iorGroups = props.solutions.map(solution => {
    const { group } = solution;
    const idx = group.indexOf('_');
    return group.slice(idx + 1);
  });
  relation.iorGroups = [...new Set(iorGroups)];
  return relation;
});

const isHalf = computed(() => {
  return currentRelation.value.id < 0;
});

const ps = computed(() => {
  return currentRelation.value.rel.ps;
});

const hg = computed(() => {
  return currentRelation.value.rel.hg;
});

const ob = computed(() => {
  return currentRelation.value.rel.ob;
});

// const im = computed(() => {
//   return currentRelation.value.rel.im;
// });

</script>

<template>
<div class="solution-item" :class="{ 'selected': selected }">
  <div class="solution-header" @click.self="toggleSolution">
    <div class="serial-number" v-if="serial">{{ serial }}.</div>
    <div class="stage" v-if="currentRelation.stage">[{{ currentRelation.stage }}{{ currentRelation.retime ? ` ${currentRelation.retime}` : '' }}]</div>
    <div class="score" v-if="currentRelation.stage">[{{ currentRelation.score }}]</div>
    <div class="league-name">{{ currentRelation.leagueName }}</div>
    <div class="period-half" v-if="isHalf">[上半场]</div>
    <div class="date-time">{{ currentRelation.dateTime }}</div>
    <div class="switch-btns" v-if="solutions.length">
      <Tooltip v-for="({sol}, index) in solutions" :key="index"
      class="switch-btn-item"
      :class="{ 'selected': index === currentIndex }"
      @click.stop="switchSolution(index)">
        <template #title>
          {{sol.win_profit_rate}}% ({{sol.cross_type}})
        </template>
        {{ sol.win_average_rate }}
      </Tooltip>
    </div>
  </div>
  <div class="solution-content">
    <MatchCard platform="ps" :eventId="ps.eventId" :teamHomeName="ps.teamHomeName"
    :teamAwayName="ps.teamAwayName" :events="ps.events ?? []"
    :selected="ps.selected ?? []" :iorGroups="currentRelation.iorGroups" />

    <MatchCard platform="ob" :eventId="ob.eventId" :teamHomeName="ob.teamHomeName"
      :teamAwayName="ob.teamAwayName" :events="ob.events ?? []"
      :selected="ob.selected ?? []" />

    <MatchCard platform="hg" :eventId="hg.eventId" :teamHomeName="hg.teamHomeName"
      :teamAwayName="hg.teamAwayName" :events="hg.events ?? []"
      :selected="hg.selected ?? []" />

    <!-- <MatchCard platform="im" :eventId="im.eventId" :teamHomeName="im.teamHomeName"
      :teamAwayName="im.teamAwayName" :events="im.events ?? []"
      :selected="im.selected ?? []" /> -->

    <!-- <div class="solution-profit" @click="toggleSolution()">
      <p>{{ currentSolution.sol.win_average_rate }}%</p>
      <p>{{ currentSolution.sol.win_profit_rate }}%</p>
      <p>{{ currentSolution.sol.cross_type }}</p>
    </div> -->
  </div>
</div>
</template>

<style lang="scss" scoped>
.solution-item {
  display: flex;
  flex-direction: column;
  border-radius: 10px;
  background-color: hsl(var(--card));

  &.selected {
    background-color: hsl(var(--primary) / 0.15);
  }

  &:not(:last-child) {
    margin-bottom: 20px;
  }
}

.solution-header {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 15px;
  border-bottom: 1px solid hsl(var(--border));
  .serial-number {
    margin-right: 5px;
    font-size: 16px;
    font-weight: 400;
    color: hsl(var(--foreground) / 0.7);
  }
  .score, .stage {
    text-align: center;
    font-size: 16px;
    font-weight: 400;
  }
  .score {
    color: hsl(var(--primary));
  }
  .stage {
    color: hsl(var(--destructive));
  }
  .league-name {
    margin-right: 10px;
    font-size: 16px;
    font-weight: 400;
  }
  .period-half {
    margin-right: 10px;
    color: hsl(var(--primary));
  }
  .date-time {
    text-align: right;
    font-size: 14px;
    color: hsl(var(--foreground) / 0.7);
  }
}

.switch-btns {
  display: flex;
  align-items: center;
  margin-left: auto;
  :deep(.switch-btn-item) {
    display: block;
    height: 20px;
    line-height: 20px;
    padding: 0 5px;
    border-radius: 4px;
    cursor: pointer;
    &:hover {
      color: hsl(var(--primary));
    }
    &.selected {
      color: hsl(var(--primary-foreground));
      background-color: hsl(var(--primary));
      cursor: default;
    }
    &:not(:last-child) {
      margin-right: 5px;
    }
  }
}

.solution-content {
  display: flex;
  .match-card {
    flex: 1;
  }
  .match-card:not(:last-child) {
    border-right: 1px solid hsl(var(--border));
  }
}

/*
.solution-profit {
  display: flex;
  flex-direction: column;
  width: 80px;
  align-items: center;
  justify-content: center;
}
  */

</style>