
<inquiry>
    <style scoped>
    </style>

    <!--　日別表示　-->
    <div id="ipat_history_list" class="ipat_history_list">
        <div class="Reference_Status">
            <!-- 収支あり -->
            <virtual if={ !is_show_result_button && bet_list && Object.keys(bet_list).length >= 1 } >
                <div if={ race_status == '0' }>
                    <dl>
                        <dt class="Reference_StatusTotal">投票合計</dt>
                        <dd>{ number_format(total_bet_money) }円</dd>
                    </dl>
                </div>
                <div if={ race_status == '1' }>
                    <dl class="BalanceData cracker">
                        <dt>投票合計</dt>
                        <dd><span class="strong">{ number_format(total_bet_money) }円</span></dd>
                    </dl>
                    <dl class="{ edit_money_class(total_payback) }">
                        <dt class="Reference_StatusTotal">払戻金</dt>
                        <dd class="TotalAmount"><span class="strong">{ number_format(total_payback) }円</span></dd>
                    </dl>
                    <dl class="{ edit_money_class(total_profit) } totalArea">
                        <dt class="Reference_StatusTotal">収支合計</dt>
                        <dd class="TotalAmount"><span class="strong">{ number_format(total_profit) }円</span></dd>
                    </dl>
                    <!-- モック追加 -->
                    <dl class="BalanceData" if={total_refund > 0}>
                        <dt>(マネー返還</dt>
                        <dd>{ number_format(total_refund) }円)</dd>
                    </dl>
                    <!-- モック追加 -->
                </div>
            </virtual>
            <!-- 収支なし -->
            <virtual if={ bet_list && Object.keys(bet_list).length <= 0 } >
                <div class="data_empty" if={ cur_race.race_status < '50' }>
                    <p>投票した買い目がありません</p>
                    <a if={ args.is_v2_appli == '0' } href="{ args.keirin_url }/bet/editor.html?date={ race_date }&race_id={ race_id }">投票する</a>
                    <a if={ args.is_v2_appli == '1' } href="ndapp://open_vote_sheet_modal">投票する</a>
                </div>
                <div class="data_empty" if={ !is_show_result_button && cur_race.race_status >= '50' }>
                    <p>このレースは終了しました</p>
                    <a if={ args.is_v2_appli == '0' } href="{ args.keirin_url }/bet/editor.html">投票できるレースを探す</a>
                    <a if={ args.is_v2_appli == '1' } href="ndapp://open_vote_sheet_modal">投票できるレースを探す</a>
                </div>
            </virtual>
            <div class="data_empty" if={bet_list && Object.keys(bet_list).length >= 1 && is_show_result_button  && cur_race.race_status >= '50' }>
                <img src="{args.cdn_keirin_url}/common/img/icon/icon_race_result_confirmed.png" alt="レースが確定しました" width="63" height="63">
                <p>レースが確定しました</p>
                <a href="" id="show_result" onclick={ show_race_result.bind(this) }>結果を表示する</a>
                <span>※投票したレース結果を常に表示する場合は、<a href="{ args.keirin_url }regist/race_result_setting.html" class="textLink">「レース結果設定」</a>を変更してください。</span>
            </div>

        </div>

        <virtual  if={Object.keys(bet_list).length >= 1} each={ type in bet_type }>
            <div class="Balance_List" if={ !is_show_result_button && bet_list[race_id][type] != undefined } each={ bet_parent, key in bet_list[race_id][type] }>
                <div class="Balance_ListToggle">
                    <ul>
                        <virtual each={ bet, k in bet_parent.houshiki_list }>
                            <li if={ bet.houshiki != 0 } each={ val, key in bet.bet_item } class="{ (val.is_hit == 1) ? 'Payout01' : '' }  Balance_ListToggleItem {shikibetu_class[val.shikibetu]}">
                                <div class="ListToggleItem_01">
                                    <span class="{shikibetu_class[val.shikibetu]} label">{val.name1}</span>
                                    <span class="Result01" if={ val.payback_flag == 0 && val.is_hit == 1 }>的</span>
                                    <!-- モック追加 -->
                                    <span class="Result02" if={ val.payback_flag == 2 }>特</span>
                                    <!-- モック追加 -->
                                    <span class="{ (val.is_hit == 1) ? 'PayoutBetName' : '' }" if={val.shikibetu != 1}>{ edit_bet_name(val) }{ val.is_multi ? '&nbsp;マルチ': '' }{ val.combination.length > 0 ? '&nbsp;'+val.combination.length+'組': '' }</span><!--{ houshiki[val.shikibetu + val.houshiki] }-->
                                    <!-- モック追加 -->
                                    <span class="Return" if={val.refund > 0}>返還</span>
                                    <!-- モック追加 -->
                                    <span class="typeTag keirin" if={type == 'nk_bet_list'}>netkeirin</span><span class="typeTag tipstar" if={type == 'ts_bet_list'}>TIPSTAR</span>
                                    <span class="list_toggle">開く</span>
                                </div>
                                <div class="ListSub">
                                    <div class="ListToggleItem_03 Result_toggleInner">
                                        <div class="BetTable">
                                            <div id="select_kumiawase" class="kaime_view FormationType">
                                                <div class="LabelWrap" if={ val.kaime1 }>
                                                    <div class="LabelArrow" if={ val.houshiki != 2 }> <span>{ edit_arrow_label(val.shikibetu, val.houshiki, '1') } </span> </div>
                                                    <div class="Num">
                                                        <div class="Shaban_InBox" each={ syaban, idx in val.kaime1.split('-') }><span class="Wakuban Waku{ (val.shikibetu == 3 || val.shikibetu == 4) ? '1' : syaban }">{syaban}</span></div>
                                                    </div>
                                                </div>
                                                <div class="LabelWrap" if={ val.kaime2 }>
                                                    <div class="LabelArrow" if={ val.houshiki != 2 }> <span>{ edit_arrow_label(val.shikibetu, val.houshiki, '2') } </span> </div>
                                                    <div class="Num">
                                                        <div class="Shaban_InBox" each={ syaban, idx in val.kaime2.split('-') }><span class="Wakuban Waku{ (val.shikibetu == 3 || val.shikibetu == 4) ? '1' : syaban }">{syaban}</span></div>
                                                    </div>
                                                </div>
                                                <div class="LabelWrap" if={ val.kaime3 }>
                                                    <div class="LabelArrow" if={ val.houshiki != 2 }> <span>{ edit_arrow_label(val.shikibetu, val.houshiki, '3') }</span> </div>
                                                    <div class="Num">
                                                        <div class="Shaban_InBox" each={ syaban, idx in val.kaime3.split('-') }><span class="Wakuban Waku{ (val.shikibetu == 3 || val.shikibetu == 4) ? '1' : syaban }">{syaban}</span></div>
                                                    </div>
                                                </div>
                                                <span if={ val.combination.length > 1 } class="OddsData01">
                                                    { edit_sort_odds(val, 'min') <= '0.0' && edit_sort_odds(val, 'max') <= '0.0' ? '' : edit_sort_odds(val, 'min') == edit_sort_odds(val, 'max') ? edit_sort_odds(val, 'max') + '倍' : edit_sort_odds(val, 'min') + '倍 ～ ' + edit_sort_odds(val, 'max') + '倍' }
                                                </span>
                                                <span if={ val.combination.length <= 1 } class="OddsData01">{ edit_odds(val) > '0.0' ? edit_odds(val) + '倍' : '' }</span>
                                            </div>
                                        </div>
                                        <div class="ListToggleItem_03_total">
                                            <dl class="{ edit_money_class(val.payback) }">
                                                <dt>{ val.combination.length  }点<span>計</span>{ number_format(val.total_bet_money) }円</dt>
                                                <dd if={ race_status == '1' }>{ number_format(val.payback) }円</dd>
                                                <virtual if={ race_status == '0'}>
                                                    <!--dd if={ val.combination.length == 1 }>
                                                        <span class="Profit">
                                                        { number_format( edit_assumed_payback(edit_odds(val, val.combination[0]), val.bet_money) ) }円
                                                            <span class="{ edit_payment_diff( edit_assumed_payback(edit_odds(val, val.combination[0]), val.bet_money), val.total_bet_money) }">
                                                                { number_format( edit_assumed_payback(edit_odds(val, val.combination[0]), val.bet_money) - val.total_bet_money) }円
                                                            </span>
                                                        </span>
                                                    </dd-->
                                                    <dd if={ val.combination.length >= 2 }>
                                                        {number_format(Math.round(edit_sort_odds(val, 'min') * val.bet_money)) }円 ～ { number_format( Math.round(edit_sort_odds(val, 'max') * val.bet_money)) }円
                                                        <span class="Profit">( <span class="{ edit_payment_diff( edit_sort_odds(val, 'min') * val.bet_money, total_bet_money ) }">{ number_format( Math.round(edit_sort_odds(val, 'min') * val.bet_money) - total_bet_money ) }円</span> ～ <span class="{ edit_payment_diff( edit_sort_odds(val, 'max') * val.bet_money, total_bet_money ) }">{ number_format( Math.round(edit_sort_odds(val, 'max') * val.bet_money) - total_bet_money )}円</span> )</span>
                                                    </dd>
                                                </virtual>
                                            </dl>
                                        </div><!-- /.ListToggleItem_03_total -->
                                    </div>
                                
                                    <div class="Develop_ToggleWrap Result_toggleInner">
                                        <a href="javascript:void(0)" class="develop_toggle">展開する<span></span></a>
                                        <div class="develop_wrap Result_toggleInner">
                                            <div class="ListToggleItem_02_develop { (val.hit_combination && val.hit_combination[kaime]) ? 'BalanceData' : '' }" each={ kaime, idx in val.combination }>
                                                <div>
                                                    <ul class="Arrow01">
                                                        <li each={ syaban, key in kaime.split('-') }><span class="UmaBan Waku{ (val.shikibetu == 3 || val.shikibetu == 4) ? '1' : syaban.replace(/^0/, '') } { edit_kaime_class(val.shikibetu) }">{ syaban.replace(/^0/, '') }</span><!--svg class="Icon_Shirushi01 Icon_Honmei"><use xlink:href="/common/img/icon/icon_shirushi.svg#icon-honmei"></use></svg--></li>
                                                        <!--li><span class="UmaBan Waku4">4</span><svg class="Icon_Shirushi01 Icon_Taikou"><use xlink:href="/common/img/icon/icon_shirushi.svg#icon-taikou"></use></svg></li>
                                                        <li><span class="UmaBan Waku1">1</span><svg class="Icon_Shirushi01 Icon_Kurosan"><use xlink:href="/common/img/icon/icon_shirushi.svg#icon-kurosan"></use></svg></li-->
                                                    </ul>
                                                    <span class="OddsData01">{ edit_odds(val, kaime) > '0.0' ? edit_odds(val, kaime) + '倍' : '' }</span>
                                                </div>
                                                <dl>
                                                    <dt if={ !val.refund_combination }>{ val.bet_money }円</dt>
                                                    <dt if={ val.refund_combination }>{ val.bet_money }円</dt>
                                                    <virtual if={ race_status == '0' }>
                                                        <dd >{ number_format( edit_assumed_payback(edit_odds(val, kaime), val.bet_money) ) }円</dd>
                                                        <span class="Profit">( <span class="{ edit_payment_diff( edit_assumed_payback(edit_odds(val, kaime), val.bet_money), total_bet_money) }">{ number_format( edit_assumed_payback(edit_odds(val, kaime), val.bet_money) - total_bet_money) }円</span> )</span>
                                                        <dd if={ val.refund_combination && val.refund_combination[kaime] }>
                                                            <span class="{henkan_label[1].class}">{henkan_label[1].label}</span>
                                                        </dd>
                                                    </virtual>
                                                    <virtual if={ race_status == '1' }>
                                                        <!--dd if={ (!val.hit_combination || !val.hit_combination[kaime]) && !val.refund_combination[kaime] }>0円</dd-->
                                                        <!--dd if={ val.hit_combination && val.hit_combination[kaime] && !val.refund_combination[kaime] }>{ number_format(val.hit_combination[kaime] * (val.bet_money / 100) ) }円</dd-->
                                                        <dd if={ (!val.hit_combination || !val.hit_combination[kaime]) && !val.refund_combination[kaime] }>0円</dd>
                                                        <dd if={ val.hit_combination && val.hit_combination[kaime] && !val.refund_combination[kaime] }>{ number_format(val.hit_combination[kaime] * (val.bet_money / 100) ) }円</dd>
                                                        <dd if={ val.refund_combination && val.refund_combination[kaime] }>
                                                            <span class="{henkan_label[1].class}">{henkan_label[1].label}</span>
                                                        </dd>
                                                    </virtual>
                                                </dl>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </li>
                            <li if={ bet.houshiki == 0 } class="{ check_bet_item(bet.bet_item, 'is_hit', '1') ? 'Payout01' : '' } Balance_ListToggleItem normal {shikibetu_class[bet_parent.shikibetu]}">
                                <div class="ListToggleItem_01">
                                    <span class="{shikibetu_class[bet_parent.shikibetu]} label">{shikibetu_name[bet_parent.shikibetu]}</span>
                                    <span class="Result01" if={ check_bet_item(bet.bet_item, 'payback_flag', '0') && check_bet_item(bet.bet_item, 'is_hit', '1') }>的</span>
                                    <!-- モック追加 -->
                                    <span class="Result02" if={ check_bet_item(bet.bet_item, 'payback_flag', '2') }>特</span>
                                    <!-- モック追加 -->
                                    <span class="{ check_bet_item(bet.bet_item, 'is_hit', '1') ? 'PayoutBetName' : '' }" >通常 { bet.bet_item.length > 0 ? '&nbsp;'+bet.bet_item.length+'組': '' }</span>
                                    <!-- モック追加 -->
                                    <span class="Return" if={check_bet_item_includesOverZero(bet.bet_item, 'refund')}>返還</span>
                                    <!-- モック追加 -->
                                    <span class="typeTag keirin" if={ type == 'nk_bet_list'}>netkeirin</span><span class="typeTag tipstar" if={ type == 'ts_bet_list'}>TIPSTAR</span>
                                    <span class="list_toggle">開く</span>
                                </div>
                                <div class="ListSub" each={ val, key in bet.bet_item }>
                                    <div class="ListToggleItem_02 { val.is_hit == 1 ? 'BalanceData' : '' }">
                                        <div>
                                            <ul class="Arrow01">
                                                <li if={ val.kaime1 }><span class="UmaBan Waku{ (val.shikibetu == 3 || val.shikibetu == 4) ? '1' : val.kaime1 } { edit_kaime_class(val.shikibetu) }">{ val.kaime1 }</span></li>
                                                <li if={ val.kaime2 }><span class="UmaBan Waku{ (val.shikibetu == 3 || val.shikibetu == 4) ? '1' : val.kaime2 } { edit_kaime_class(val.shikibetu) }">{ val.kaime2 }</span></li>
                                                <li if={ val.kaime3 }><span class="UmaBan Waku{ (val.shikibetu == 3 || val.shikibetu == 4) ? '1' : val.kaime3 } { edit_kaime_class(val.shikibetu) }">{ val.kaime3 }</span></li>
                                            </ul>
                                            <span class="OddsData01">{ edit_odds(val) > '0.0' ? edit_odds(val) + '倍' : '' }</span>
                                        </div>
                                        <dl>
                                            <dt>{ number_format(val.bet_money) }円</dt>
                                            <!--dt if={ val.refund_combination }>{ number_format(bet_calc(val)) }円</dt-->
                                            <!-- 確定後 -->
                                            <dd if={ race_status == '1' && val.refund == 0 }>{ number_format(val.payback) }円</dd>
                                            <dd if={ race_status == '1' && val.refund != 0 }>
                                                <span class="{henkan_label[1].class}">{henkan_label[1].label}</span>
                                            </dd>
                                            <!-- 確定前 -->
                                            <virtual  if={ race_status == '0' }>
                                                <dd if={ val.refund == 0 }>{ number_format( edit_assumed_payback(edit_odds(val), val.bet_money) ) }円</dd>
                                                <span if={ val.refund == 0 } class="Profit">( <span class="{ edit_payment_diff( edit_assumed_payback(edit_odds(val), val.bet_money), total_bet_money) }">{ number_format( edit_assumed_payback(edit_odds(val), val.bet_money) - total_bet_money) }円</span> )</span>
                                                <dd if={ val.refund != 0 }>
                                                    <span class="{henkan_label[1].class}">{henkan_label[1].label}</span>
                                                </dd>
                                            </virtual>
                                        </dl>
                                    </div>
                                </div>
                            </li>
                        </virtual>
                    </ul>
                </div><!-- /.Balance_ListToggle -->
            </div><!-- /.Balance_List -->
        </virtual>
        <ul class="typetag_info" if={ bet_list && Object.keys(bet_list).length >= 1 }>
            <li><span class="netkeirin"></span>:netkeirinで投票</li>
            <li><span class="tipstar"></span>:TIPSTARで投票</li>
        </ul>
    </div><!-- /#ipat_history_list -->
    <!--　日別表示　-->

    <virtual if={bet_complete}>
		<div class="CenterModal commonRegister AfterVote" style="display: block;">
			<div class="CenterModal-bg modal-close">
			</div>
			<div class="CenterModalContent">
			  <div class="contentInter">
				<div class="logo">
					<img src="{args.cdn_keirin_url}/common/img/netkeirinlogo_illustver.svg" alt="netkeirin">
				</div>
				<p class="head">投票を受け付けました<br><span style="font-size: 16px;">My収支データ登録完了</span></p>
				<p class="attention"><img src="{args.cdn_keirin_url}/common/img/race/check.svg" width="60" alt=""></p>

				<!-- レースメニュー -->
				<!-- race_bottom_menu2を読み込んでください↓ -->

				<div class="TodayRace_Slide" style="display: block;">
					<div class="Title_Sec">
						<h2>発走直前レース</h2>
						<div class="Title_BtnMore">
							<a href="{args.keirin_url}/race/race_list/?rf=toplive">競輪一覧</a>
						</div>
					</div>
					<!-- /.Title_Sec -->
					<div id="TodayRace_Live" class="TodayRace_SlideBox"></div>
					<!-- /.TodayRace_SlideBox -->
				</div>
			  </div>
			  <div class="CloseBtn modal-close">
				<span>閉じる</span>
			  </div>
			</div>
		</div>
    </virtual>

    <script>

    number_format(num){
        num = Math.floor(num);
        return num.toString().replace(/(\d+?)(?=(?:\d{3})+$)/g, function(x) {
            return x + ',';
        });
    }

    edit_save_date(create_datetime){
        if(create_datetime){
            var tmp_date = create_datetime.split(' ');
            return tmp_date[1].substr(0, 5);
        }else{
            return '';
        }
    }

    edit_money_class(money){
        if(money <= 0){
            //console.log('m');
            return '';
        }else{
            return 'BalanceData';
        }
    }

    edit_kaime_class(shikibetu)
    {
        if(4 == shikibetu || 6 == shikibetu || 9 == shikibetu){ // 枠単,2車単,３連単
            // 馬番の間(矢印)
            return 'Kaime_Arrow'
        }else{
            // 馬番の間(ハイフン)
            return 'Hyphen';
        }
    }

    edit_arrow_label(shikibetu, houshiki, chaku)
    {
        var idx = shikibetu + houshiki;
        var ary_idx = parseInt(chaku) - 1;
        if(self.houshiki_attr[idx][ary_idx]){
            return self.houshiki_attr[idx][ary_idx];
        }else if(idx == 11){
            //単勝
            return self.houshiki_attr[idx]['label'][ary_idx];
        }
    }

    edit_bet_name(val){
        var tmp_bet = self.ipat.cvt_bet(val.cart_item_id, 100, []);
        if(tmp_bet.houshiki == 1 && (tmp_bet.shikibetu == 3 || tmp_bet.shikibetu == 4)){
            var comb = val.combination ? val.combination.length : 0;
            return sprintf("%s%s組", tmp_bet.houshiki_name, comb);
        }else{
            return tmp_bet.houshiki_name;
        }
    }

    edit_odds(val, combi_kaime = false){
        var key = '';
        if(combi_kaime){
            key = combi_kaime.replace(/-/g, '');
        }else{
            if(val.kaime1){
                key  = key + sprintf("%02d", val.kaime1);
            }
            if(val.kaime2){
                key  = key + sprintf("%02d", val.kaime2);
            }
            if(val.kaime3){
                key  = key + sprintf("%02d", val.kaime3);
            }
        }
        if(self.odds[val.shikibetu][key] !== undefined && self.odds[val.shikibetu][key][0] != '0.0'){
            return sprintf("%0.1f", self.odds[val.shikibetu][key][0]);
        }else{
            return '0.0';
        }
    }

    edit_sort_odds(val, mode){
        //console.log('edit_sort_odds', val);
        var tmp_odds = [];
        var odds_list = [];
        if(val['combination']){
            for(var i = 0; i < val['combination'].length; i++){
                var tmp_kaime = val['combination'][i].replace(/-/g, '');
                var odds = {};
                if(self.odds[val.shikibetu][tmp_kaime]){
                    if(self.odds[val.shikibetu][tmp_kaime][0] != '0.0'){
                        //odds[tmp_kaime] = self.odds[val.shikibetu][tmp_kaime][0];
                        if(Math.sign(self.odds[val.shikibetu][tmp_kaime][0]) > 0){
                            tmp_odds.push(self.odds[val.shikibetu][tmp_kaime][0]);
                        }
                    }
                }else{
                    //odds[tmp_kaime] = '0.0';
                    //tmp_odds.push('0.0');
                }
                //odds_list.push(odds);
            }
        }
        var odds = '0';
        if(tmp_odds.length > 0){
            if(mode == 'max'){
                odds = tmp_odds.reduce(function(a, b) {
                    return Math.max(a, b);
                });
            }else if(mode == 'min'){
                odds = tmp_odds.reduce(function(a, b) {
                    return Math.min(a, b);
                });
            }
        }
        return sprintf("%0.1f", odds);
    }

    edit_assumed_payback(odds, bet_money){
        return Math.round(odds * parseInt(bet_money));
        //return Math.floor(odds * parseInt(bet_money));
    }

    edit_payment_diff(payback, total){
        //console.log(payback);
        //console.log(total);
        if((payback - total) < 0){
            return 'minus';
        }else{
            return 'plus';
        }
    }

    edit_ary_maxmin(arr, mode){
        if(mode == 'max'){
            var ret = arr.reduce(function(a, b) {
                return Math.max(a, b);
            });
        }else{
            var ret = arr.reduce(function(a, b) {
                return Math.min(a, b);
            });
        }
        return sprintf("%0.1f", ret);
    }

        object_length(obj){
        return Object.entries(obj).length;
    }

    object_length(obj){
        return Object.entries(obj).length;
    }

    refund_calc(refund_combination, kaime){
        var refund = 0;

        if(refund_combination[kaime]){
            refund = refund_combination[kaime];
        }

        return refund;
    }

    bet_calc(val){
        var bet_money = val.bet_money;
        var kaime = '0' + val.kaime1;

        if(val.kaime2){
            kaime = kaime + '-0' + val.kaime2;
        }

        if(val.kaime3){
            kaime = kaime + '-0' + val.kaime3;
        }

        var refund = val.refund_combination[kaime];

        if(!refund){
            kaime = kaime.replace(/-/g, '');
        }

        refund = val.refund_combination[kaime];

        if(refund){
            bet_money = bet_money - refund;
        }

        return bet_money;
    }

    check_bet_item(bet_item, key, value) {
        return bet_item.some(item =>
          Object.prototype.hasOwnProperty.call(item, key) &&
          item[key] === value
        );
    }

    check_bet_item_includesOverZero(bet_item, key) {
      return bet_item.some(item => item[key] > 0);
    }

    "use strict";

    var self = this;
    self.args = self.opts;
    self.debug = true;
    self.param = null;
    self.bet_list = {};
    self.race_date = '';
    self.race_status = '0';
    self.bet_base_list = {};
    self.cur_race = {};
    self.total_bet_money = 0;
    self.total_payback = 0;
    self.total_refund = 0;
    self.total_profit = 0;
    self.bet_complete = false;
    self.key_hit_animation_invalid = 'hit_animation_invalid';
    self.isam_domain = 'race_result_setting';
    self.is_show_result_button = false;
    self.jyo_list = JSON.parse(self.args.jyo_list);
    self.shikibetu = {};
    self.houshiki = {};
    self.bet_type = ['nk_bet_list', 'ts_bet_list'];
    self.shikibetu_class = {
        1: 'Tansho',
        2: 'Fukusho',
        3: 'Wakuren',
        4: 'Wakutan',
        5: 'Umaren',
        7: 'Wide',
        6: 'Umatan',
        8: 'Fuku3',
        9: 'Tan3',
    }
    self.shikibetu_name = {
        1: '単勝',
        2: '複勝',
        3: '2枠複',
        4: '2枠単',
        5: '2車複',
        6: '2車単',
        7: 'ワイド',
        8: '3連複',
        9: '3連単',
    }

    self.kakutei_label = {
        0: {
            pid: 'entry',
            label: '未',
            class: 'miKakutei',
            status_label: '結果確定前'
        },
        1: {
            pid: 'result',
            label: '確',
            class: 'Kakutei',
            status_label: '結果確定'
        }
    }
    self.henkan_label = {
        0: {
            pid: '',
            label: '',
            class: ''
        },
        1: {
            pid: 'henkan',
            label: '返還',
            class: 'Icon_GradeType Icon_GradeType2'
        },
        2: {
            pid: '',
            label: '',
            class: ''
        }
    }
    self.jyo_cd = null;
    self.sort_type = {
        'sort_race' : '',
        'sort_create_time' : '',
        'payback' : '',
    };
    self.houshiki_attr = {
        // 単勝
        '11': {in: [1,0,0], all: [0,0,0], check: [0,0,0], label: ['1着','--','--']}, // 通常
        // 枠複
        '30': ['枠1','枠2','--'], // 通常
        '31': ['枠1','枠2','--'],  // フォーメーション
        '33': ['軸','相手','--'],  // ながし
        // 車連
        '50': ['--','--','--'], // 通常
        '51': ['車1','車2','--'],  // フォーメーション
        '52': ['選択','--','--'], // BOX
        '53': ['軸','相手','--'],  // ながし
        // ワイド
        '70': ['--','--','--'], // 通常
        '71': ['車1','車2','--'],  // フォーメーション
        '72': ['選択','--','--'], // BOX
        '73': ['軸','相手','--'],  // ながし
        // 2車単
        '60': ['1着','2着','--'], // 通常
        '61': ['軸','相手','--'],  // フォーメーション
        '62': ['選択','--','--'], // BOX
        '63': ['1着軸','相手','--'],  // 1着ながし
        '64': ['2着軸','相手','--'],  // 2着ながし
        // 3連複
        '80': ['車1','車2','車3'], // 通常
        '81': ['車1','車2','車3'],   // フォーメーション
        '82': ['選択','--','--'],  // BOX
        '83': ['軸','相手','--'],  // 軸1頭ながし
        '86': ['軸1','軸2','相手'],   // 軸2頭ながし
        // 3連単
        '90': ['1着 ','2着 ','3着'], // 通常
        '91': ['1着 ','2着 ','3着'],   // フォーメーション
        '92': ['選択','--','--'], // BOX
        '93': ['1着軸','相手','--'],  // 1着ながし
        '94': ['2着軸','相手','--'],  // 2着ながし
        '95': ['3着軸','相手','--'],  // 3着ながし
        '96': ['1着軸','2着軸','相手'],   // 1,2着ながし
        '97': ['1着軸','3着軸','相手'],   // 1,3着ながし
        '98': ['2着軸','3着軸','相手'],   // 2,3着ながし
        // 2枠単
        '40': ['1着','2着','--'], // 通常
        '41': ['1着','2着','--'],  // フォーメーション
        '42': ['選択','--','--'], // BOX
        '43': ['1着軸','相手','--'],  // 1着ながし
        '44': ['2着軸','相手','--'],  // 2着ながし
    };
    if (self.debug) console.log('sel.args: %O', self.args);

    self.on('update', function() {
        //	     console.error('self.update()');
    });
    self.on('updated', function() {
        //	     console.error('self.updated()');
    });

    /*
     * 画面初期化(mount)
     */
    self.on('mount', function() {
        if (self.debug)  console.log('mount %s', self.args.tag_name);
        self.args.obs.trigger('tag_mounted', {tag: self.args.tag_name});
    });

    /*
     * 画面表示(parent -> trigger -> render_xxxx)
     */
    self.args.obs.on('render_' + self.args.tag_name, function(p) {
        if (self.debug) console.log('render_%s start p: %O', self.args.tag_name, p);
        self.bet_list = {};
        self.race_date = '';
        self.race_status = '0';
        self.bet_base_list = {};
        self.cur_race = {};
        self.total_bet_money = 0;
        self.total_payback = 0;
        self.total_profit = 0;
        self.ipat = new IpatDataModel();
        self.shikibetu = self.ipat.get_shikibetu();
        self.houshiki = self.ipat.get_houshiki();
        self.race_id = null;
        self.odds = {}; // オッズデータ
        self.show_data(p);
    });


    /*
     * データ取得、編集
     */
    self.show_data = function(p) {
       console.log('aiueo');
       if (self.debug) console.log('self.show_data');
        if(p['race_id']){
            self.race_id = p['race_id'];
        }
        var api = new AplApiRace(self.args.api_url, true, 'json'/*, true*/);
        self.race_date = self.race_id.substr(0,8);
        self.kaisai_mode = 'keirin';
        if(p['race_id'] !== undefined && p['race_id'].substr(8, 2) == '91'){
            self.kaisai_mode = 'pist6';
        }
        // レース一覧を取得
        api.get('AplRace', {'kaisai_date': self.race_date, 'syusai': self.kaisai_mode}, function(ary_race) {
            var jyo_cd = self.race_id.substr(8,2);
            for (var i = 0; i < ary_race.length; i++) {
                if(ary_race[i]['jyo_cd'] == jyo_cd){
                    for (var idx in ary_race[i].list) {
                        var row = ary_race[i].list[idx];
                        if (row['race_id'] == self.race_id) {
                            self.cur_race = row;
                        }
                    }
                }
            }
            self.get_bet_list(function(data){
                if(data){
                    var ipat = new IpatDataModel();
                    self.bet_list = data;
                    for (var race_id in self.bet_list) {
                        if (!self.bet_list.hasOwnProperty(race_id)) continue;
                        var race_bet_items = self.bet_list[race_id];
                        for (var _i = 0; _i < self.bet_type.length; _i++) {
                            var key = self.bet_type[_i];
                            var bets = race_bet_items && race_bet_items[key];
                            if (!Array.isArray(bets) || bets.length === 0) continue;
                            for (var i = 0; i < bets.length; i++) {
                            var val = bets[i];
                            var houshikiList = val && val.houshiki_list;
                            if (!Array.isArray(houshikiList) || houshikiList.length === 0) continue;
                                for (var j = 0; j < houshikiList.length; j++) {
                                    var houshiki = houshikiList[j];
                                    var betItems = houshiki && houshiki.bet_item;
                                    if (!Array.isArray(betItems) || betItems.length === 0) continue;
                                    for (var k = 0; k < betItems.length; k++) {
                                    var bet_item = betItems[k];
                                    var info = ipat.cvt_bet(bet_item.cart_item_id, bet_item.bet_money, []); // TODO
                                    bet_item.is_multi = info.is_multi; // 参照なのでここでOK
                                    }
                                }
                            }
                        }
                    }


                    for(var race_id in self.bet_list){
                        self.total_bet_money += parseInt(self.bet_list[race_id]['bet_total']);
                        self.total_payback += parseInt(self.bet_list[race_id]['payback']);
                        self.total_refund += parseInt(self.bet_list[race_id]['refund']);
                        self.race_status = self.bet_list[race_id]['state'];
                        self.total_profit = self.total_payback + self.total_refund - self.total_bet_money;
                        if(self.bet_list[race_id]['bet_list'] !== undefined && self.bet_list[race_id]['bet_list'].length > 0){
                            for(var i = 0; i < self.bet_list[race_id]['bet_list'].length; i++){
                                var val = self.bet_list[race_id]['bet_list'][i];
                                var info = ipat.cvt_bet(val['cart_item_id'], val['bet_money'], []); // TODO:引数の配列は？
                                self.bet_list[race_id]['bet_list'][i]['is_multi'] = info.is_multi;
                            }
                        }
                    }
                    if(p['mode'] !== undefined && p['mode'] == 'bet_complete' && Object.keys(self.bet_list).length > 0){
                        if(self.args.is_v2_appli == '1'){
                            // ネイティブの買い目を削除
                            location.href = 'ndapp://del_bet_item?race_id='+self.race_id;
                        }
                        self.bet_complete = true;
                    }
                    // オッズ取得
                    api.get('AplRaceOdds', {'race_id': race_id}, function(odds_data) {
                        //if (self.debug) console.log('=============AplRaceOdds=============');
                        //if (self.debug) console.log(odds_data);
                        for (var i = 1; i <= 9; i++) {
                            self.odds[i] = {};
                            if (undefined === odds_data['list_' + i]) {
                                continue;
                            }
                            for(var j = 0; j < odds_data['list_' + i].length; j++) {
                                var oval = odds_data['list_' + i][j];
                                self.odds[i][oval[0]] = [oval[1], oval[2], oval[3]];
                            }
                        }
                        console.log('self.odds: %O', self.odds);
                        console.log('self.cur_race: %O', self.cur_race);
                        console.log('self.bet_list: %O', self.bet_list);
                        console.log('self.total_bet_money: ', self.total_bet_money);
                        if(self.bet_complete){
                            // ajax_race_live_flash.htmlの結果を反映させるためのここでアップデートする
                            self.update();
                            var _data = {};
                            _data.input = 'UTF-8';
                            _data.output = 'json';
                            _data.rf = 'toplive';
                            $.ajax({
                                type: "POST",
                                url: self.args.keirin_url +  '/race/ajax_race_live_flash.html',
                                data: _data,
                                dataType: _data.output,
                                success: function(data){
                                    console.log(data);
                                    if (data !=='') {
                                        $('#TodayRace_Live').parent().css('display', 'block');
                                        $('#TodayRace_Live').html(data);
                                    }
                                    self.update();
                                    self.event_register();
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    console.error('textStatus:',textStatus);
                                }
                            });
                        }else{
                            console.log('self.total_bet_money: ', self.total_bet_money);
                            const hideRaceResults = ShowRaceResult.isHideRaceResults();
                            const isShowContent = ShowRaceResult.checkVisibilityOnLoad(self.race_id);
                            const shouldShowByDefault = isShowContent || !hideRaceResults;
                            console.log('非表示設定:', hideRaceResults, '表示判定:', isShowContent, 'デフォルト表示判定:', shouldShowByDefault);
                            if(!shouldShowByDefault && self.cur_race.race_status >= '50'){
                                self.is_show_result_button = true;
                            }
                            self.update();
                            self.event_register();
                            self.trigger_hit_animation();
                        }
                    });
                }else{
                    console.log('self.cur_race: %O', self.cur_race);
                    console.log('self.bet_list: %O', self.bet_list);
                    console.log('self.total_bet_money: ', self.total_bet_money);
                    self.update();
                    self.event_register();
                }
            });
        });
    }

    self.get_bet_list = function(fn){
        var add_param = {
             'race_id' : self.race_id,
        };
        $.ajax({
            type     : 'GET',
            url: self.args.shushi_api_url,
            data: add_param,
            dataType: 'json',
            success: function( data ){
                fn(data);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                console.error('textStatus: ',textStatus);
                console.error('errorThrown.message: ',errorThrown.message);
            }
        });
    }

    // 的中演出
    self.trigger_hit_animation = function(){

        if(!self.validate_animation()){
            return;
        }

        // 収支の値によって処理を分岐
        const imagesList = [];
        if(self.total_profit <= 0){
            return;
        } else if(self.total_profit >= 100000){
            //// 松（金色）
            for(let i=1; i<9; i++){
                imagesList.push({
                    src: self.args.cdn_keirin_url + '/common/img/shushi/gold_confetti' + i + '.svg',
                });
            }
        } else if(self.total_profit >= 10000){
            //// 竹（銀色）
            for(let i=1; i<10; i++){
                imagesList.push({
                    src: self.args.cdn_keirin_url + '/common/img/shushi/silver_confetti' + i + '.svg',
                });
            }
        } else if(self.total_profit >= 1){
            //// 梅（赤色）
            for(let i=1; i<8; i++){
                imagesList.push({
                    src: self.args.cdn_keirin_url + '/common/img/shushi/red_confetti' + i + '.svg',
                });
            }
        }

        const $cracker = $('.RaceReference .Reference_Status .cracker');
        const rect = $cracker[0].getBoundingClientRect();
        const leftX = (rect.left + rect.width / 2) / window.innerWidth;
        const leftY = (rect.top + rect.height / 2) / window.innerHeight;

        if ($cracker.length > 0) {
            confetti({
                particleCount: 100,
                spread: 100,
                ticks: 100,
                origin: { x: leftX, y: leftY },
                scalar: 1.6,
                shapes: ["image"],
                shapeOptions: {
                    image: imagesList,
                },
            });
        }

    }

    self.validate_animation = function(){
        var show_animation_key = 'show_flg::' + self.race_id.substr(0,8);
        var ndisam = new NDIsam();
        var list = ndisam.list(self.isam_domain);
        console.log('list: %O', list);
        if(list === false){
            // デフォルトは演出設定がON
            return true;
        }
        var race_kaisai_date = self.race_id.substr(0,8);
        // 本日の日付を取得（YYYYMMDD形式）
        const today = new Date();
        const todayStr = today.getFullYear().toString() + (today.getMonth() + 1).toString().padStart(2, '0') + today.getDate().toString().padStart(2, '0');

        // 過去のフラグがあれば削除する
        Object.keys(list).forEach(function(key){
            if(key.startsWith('show_flg::') && key !== show_animation_key){
                ndisam.remove(self.isam_domain, key);
            }
        });

        // 無効設定 or  過去開催なら処理しない
        if (list[self.key_hit_animation_invalid] === '1') {
            return false;
        }
        if(race_kaisai_date !== todayStr){
            return false;
        }
        return true;
    }

    self.show_race_result = function(){
        ShowRaceResult.onContentClick(self.race_id);
    }

    //制作
    self.event_register = function(){
        $('.develop_wrap.Result_toggleInner').hide();
        $(document).off('click','.Balance_ListItem');
        $(document).on('click', '.Balance_ListItem' , function(){
            $(this).parents('.Balance_ListInner').next().stop().slideToggle('fast');
            $(this).find('.list_toggle').toggleClass('toggle_on');
        });
        $(document).off('click','.Balance_ListToggleItem .ListToggleItem_01');
        $(document).on('click', '.Balance_ListToggleItem .ListToggleItem_01' , function () {
            $(this).siblings('.ListSub').slideToggle('fast');
            $(this).find('.list_toggle').toggleClass('toggle_on');
        });
        $(document).off('click','.develop_toggle');
        $(document).on('click', '.develop_toggle', function () {
            $(this).next().stop().slideToggle('fast');
            $(this).toggleClass('toggle_on');
            if($(this).hasClass('toggle_on')){
                $(this).html('展開を閉じる<span></span>');
            } else {
                $(this).html('展開する<span></span>');
            }
            //if ($(this).attr() === '<a href="javascript:void(0)" class="develop_toggle">展開を閉じる<span></span></a>') {
            //    $(this).attr('<a href="javascript:void(0)" class="develop_toggle">展開する<span></span></a>');
            //} else {
            //    $(this).attr('<a href="javascript:void(0)" class="develop_toggle">展開を閉じる<span></span></a>');
            //};
        });
        $('a').on('click', function(){
            var url = $(this).attr('href');
//            console.log(url);
//            location.href = url;
        });

        $(document).on('click', '.amountWrap', function() {
            var hiddenText = $('.amountWrap .jsHiddenText');
            var balance = $('.amountWrap .jsAmountYen');
            var eyeStatus = $('.amountWrap .jsEyeStatus');
            if (hiddenText.is(':hidden')) {
                eyeStatus.addClass('off');
                balance.hide();
                hiddenText.show();
            } else {
                eyeStatus.removeClass('off');
                balance.show();
                hiddenText.hide();
            }
        });

        //投票完了モーダル閉じる
        $('.CenterModal .modal-close').on('click', function() {
            $(this).closest('.CenterModal').fadeOut(300);
            route('?race_id=' + self.race_id);
            false
        });

    }

    </script>

</inquiry>
