
<shushi_navi>
    <style scoped>
    </style>

    <div class="RaceInfo_Local_Menu Tab01 mysyuushi">
        <ul class="Tab_Col3">
            <li class="{ (mode == 'daily') ? 'Active' : '' }"><a href="javascript:void(0);" onclick={ change_page.bind(this, 'daily', null, cur_jyo_cd, type) }>日別</a></li>
            <li class="{ (mode == 'monthly') ? 'Active' : '' }"><a href="javascript:void(0);" onclick={ change_page.bind(this, 'monthly', null, cur_jyo_cd, type) }>月別</a></li>
            <li class="{ (mode == 'year') ? 'Active' : '' }"><a href="javascript:void(0);" onclick={ change_page.bind(this, 'year', null, cur_jyo_cd, type) }>年別</a></li>
        </ul>
    </div><!-- /.Tab01 -->
    <div class="RaceInfo_Place_Wrap">
        <div class="RaceInfo_Place">
            <p class="RaceInfo_Place_label">{ type_list[type] }</p>
            <select name="vote_list" id="vote_list">
                <option riot-value="{ key }" each={ val, key in type_list } selected={ type == key ? 'selected' : '' } >{ val }</option>
            </select>
            </div>
        </div>
        <!-- <div class="RaceInfo_Place">
            <p class="RaceInfo_Place_label">{ jyo_list[cur_jyo_cd] ? jyo_list[cur_jyo_cd] : '全場' }</p>
            <select name="jyo_list" id="jyo_list"> -->
                <!--option disabled selected value>競輪場選択</option-->
                <!-- <option value="{ jyo_cd }" each={ val, jyo_cd in bet_jyo_list } selected={ cur_jyo_cd == jyo_cd ? 'selected' : ''}>{ jyo_list[jyo_cd] }</option> -->
            <!-- </select> -->

        <!-- </div> -->
        <!-- /.RaceInfo_Place -->
    </div>
    <!--div class="Result_Total" if={ total_money[cur_date] }-->
    <div class="Result_Total">
        <div class="Result_Total_DayWrap">
            <div class="Result_Total_DayPrev" if={ prev }>
                <a href="javascript:void(0);" onclick={ change_page.bind(this, mode, prev, cur_jyo_cd, type) }>前へ</a>
            </div>
            <div class="Result_Total_Date">
                <p if={ cur_date }>{edit_cur_date(cur_date)}{edit_week(cur_date)}</p>
            </div>
            <div class="Result_Total_DayNext" if={ next }>
                <a href="javascript:void(0);" onclick={ change_page.bind(this, mode, next, cur_jyo_cd, type) }>次へ</a>
            </div>
        </div><!-- /.Result_Total_DayWrap -->
        <div class="Result_Total_PriceWrap" if={ total_money[cur_date] }>
            <dl class="{ edit_money_class(total_money[cur_date].total_diff) }">
                <dt>収支合計</dt>
                <dd class="price_total { edit_money_class(total_money[cur_date].total_diff) }" if={ total_money[cur_date] }>{number_format(total_money[cur_date].total_diff)}<span>円</span></dd>
                <dd class="price_total" if={ !total_money[cur_date] }>0<span>円</span></dd>
            </dl>
            <div class="Result_Total_PriceDetail">
                <dl>
                    <dt>購入</dt>
                    <dd class="price_detail" if={ total_money[cur_date] }>{number_format(total_money[cur_date].total_bet_money)}<span>円</span></dd>
                    <dd class="price_detail" if={ !total_money[cur_date] }>0<span>円</span></dd>
                </dl>
                <dl>
                    <dt>払戻</dt>
                    <dd class="price_detail" if={ total_money[cur_date] }>{number_format(total_money[cur_date].total_pay)}<span>円</span></dd>
                    <dd class="price_detail" if={ !total_money[cur_date] }>0<span>円</span></dd>
                    <!-- モック追加 -->
                    <!--dd class="price_return" if={ total_refund > 0 } >(返還 {number_format(total_refund)}円)</dd-->
                    <!-- モック追加 -->
                </dl>
            </div>
        </div><!-- /.Result_Total_PriceWrap -->
    </div><!-- /.Result_Total -->

    <!--　モーダル表示用テキスト　-->
    <!--a href="javascript:void(0)" class="modal_button">モーダル表示用テキスト</a-->
    <div class="ResultModal">
        <div class="ResultModal_bg ModalClose"></div>
        <div class="ResultModalInner">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160.118 24.497"><defs><style>.cls-1{fill:#3c3938;}.cls-2{fill:#e03d3d;}</style></defs><path id="パス_3900" data-name="パス 3900" class="cls-1" d="M78.032,11.608h4.116l.762-2.846H78.794l1.37-5.092H76.72L75.351,8.762H72.736l-.762,2.846h2.615l-2.279,8.5a3.074,3.074,0,0,0,.221,2.7,2.852,2.852,0,0,0,2.431.929h3.147l.794-2.965h-1.86q-.869,0-1.088-.3t.014-1.168Z"/><path id="パス_3901" data-name="パス 3901" class="cls-1" d="M50.34,8.763H40.814L36.8,23.737h3.533l3.29-12.279h4.933a1.123,1.123,0,0,1,1.109,1.516L46.783,23.737h3.534l2.944-10.985A2.958,2.958,0,0,0,50.34,8.763Z"/><path id="パス_3902" data-name="パス 3902" class="cls-1" d="M66.809,8.763H60.756v.01A5.147,5.147,0,0,0,56.3,12.424L54.22,20.2a2.616,2.616,0,0,0,2.527,3.53h8.237L65.717,21H59.044a1.116,1.116,0,0,1-1.1-1.5l.329-1.458L68.59,16.687l1.143-3.935a2.958,2.958,0,0,0-2.924-3.989Zm-.673,4.211-.491,1.487L59,15.3l.689-2.342A2.145,2.145,0,0,1,61.248,11.5h4.115a1.12,1.12,0,0,1,.809,1.363A1.045,1.045,0,0,1,66.136,12.974Z"/><path id="パス_3903" data-name="パス 3903" class="cls-2" d="M99.959,8.7H95.868L87.25,17.687,91.511,1.971H88.067L82.184,23.738h3.264l4.6-4.754,1.984,4.754H96.2l-3.312-7.665Z"/><path id="パス_3904" data-name="パス 3904" class="cls-2" d="M118.987,8.763l-4.012,14.974h3.441l4.012-14.974Z"/><path id="パス_3905" data-name="パス 3905" class="cls-2" d="M123.791,3.671h-3.444l-.921,3.437h3.449Z"/><path id="パス_3906" data-name="パス 3906" class="cls-2" d="M140.035,8.763l-4.012,14.974h3.444l4.012-14.974Z"/><path id="パス_3907" data-name="パス 3907" class="cls-2" d="M144.839,3.671H141.4l-.921,3.437h3.444Z"/><path id="パス_3908" data-name="パス 3908" class="cls-2" d="M134.268,8.794l-5.5,3.873,1.072-3.873H126.4l-4,14.944h3.444l1.825-6.937L138.5,8.8Z"/><path id="パス_3909" data-name="パス 3909" class="cls-2" d="M157.008,8.763h-9.522l-4.012,14.974h3.757l3.29-12.279h4.709a1.123,1.123,0,0,1,1.11,1.516l-2.884,10.763h3.53l2.944-10.985a2.959,2.959,0,0,0-2.922-3.989Z"/><path id="パス_3910" data-name="パス 3910" class="cls-2" d="M111.678,8.763h-6.053v.01a5.147,5.147,0,0,0-4.452,3.651L99.088,20.2a2.616,2.616,0,0,0,2.527,3.53h8.237L110.585,21h-6.673a1.115,1.115,0,0,1-1.167-1.06,1.1,1.1,0,0,1,.067-.44l.329-1.459,10.317-1.353,1.143-3.935a2.958,2.958,0,0,0-2.923-3.989Zm-.673,4.211-.491,1.487-6.643.843.689-2.342a2.144,2.144,0,0,1,1.554-1.463h4.114a1.12,1.12,0,0,1,.814,1.359.779.779,0,0,1-.036.116Z"/><path id="パス_3911" data-name="パス 3911" class="cls-2" d="M26.578,4.214A4.352,4.352,0,0,0,20.634,2.62h0L16.976,4.729a5.266,5.266,0,1,0-8.33,4.8L2.889,12.852l1.565,2.715L22.2,5.335a1.219,1.219,0,1,1,1.22,2.111l-7.33,4.222a3.79,3.79,0,0,0-.508,6.211l6.042,5.21,2.046-2.373L17.61,15.491l-.039-.033a.656.656,0,0,1-.1-.921.7.7,0,0,1,.182-.156l7.326-4.226a4.351,4.351,0,0,0,1.594-5.944v0ZM11.738,3.141A2.133,2.133,0,1,1,9.605,5.274h0a2.136,2.136,0,0,1,2.132-2.133Z"/><path id="パス_3912" data-name="パス 3912" class="cls-1" d="M9.477,12.672,4.925,15.3a3.174,3.174,0,1,1-.393.227l-.075.044L2.888,12.854a6.331,6.331,0,1,0,6.586-.182Z"/><path id="パス_3913" data-name="パス 3913" class="cls-1" d="M2.911,12.841l.547-.316A6.312,6.312,0,0,0,2.911,12.841Z"/><path id="パス_3914" data-name="パス 3914" class="cls-1" d="M25.594,11.832A6.341,6.341,0,0,0,19.37,17.01l4.1,3.532a3.129,3.129,0,1,1,.134.116l.072.062-2.045,2.373A6.33,6.33,0,1,0,25.6,11.834Z"/><path id="パス_3915" data-name="パス 3915" class="cls-1" d="M21.591,23.063l-.259-.223C21.416,22.914,21.5,22.989,21.591,23.063Z"/></svg>
            <p>My収支データ<br>登録完了</p>
            <div class="ResultModal_RaceInfo">
                <p class="RaceInfo_text01">保存時間&nbsp;{ bet_race_data.create_datetime }</p>
                <p class="RaceInfo_text02">{ bet_race_data.jyo_name } { bet_race_data.race_num }R { bet_race_data.kyuhan }{ bet_race_data.race_name }</p>
                <div class="LinkBtn_03" if={ Object.keys(bet_race_data).length >= 1 }>
                    <a href="{ args.keirin_url }{kaisai_mode}/entry/?race_id={ bet_race_data.race_id }">出走表に戻る</a>
                    <!--a if={ bet_race_data.race_id.substr(8,2) != '91' } href="{ args.keirin_url }race/entry/?race_id={ bet_race_data.race_id }">出走表に戻る</a>
                    <a if={ bet_race_data.race_id.substr(8,2) == '91' } href="{ args.keirin_url }pist6/entry/?race_id={ bet_race_data.race_id }">出走表に戻る</a-->
                </div>
            </div>
            <section class="Contents_Box Top_RaceMenu">
                <div class="Top_RaceMenu_Inner">
                    <ul class="Btn_List_01 Col2 fc">
                        <li>
                            <a href="{ args.keirin_url }{kaisai_mode}/race_list/" title="開催日程">
                                <svg class="Icon_Race01 Icon_Race01_09">
                                    <use xlink:href="{ args.keirin_url }common/img/race/icon/icon_race_sprite01.svg#icon-race_09" /></svg>
                                <span class="Icon_Label">レース一覧</span>
                            </a>
                        </li>
                        <li>
                            <a href="{ args.keirin_url }{kaisai_mode}/{race_movie_url}" title="{race_movie_title}">
                                <svg class="Icon_Race01 Icon_Race01_22">
                                    <use xlink:href="{ args.keirin_url }common/img/race/icon/icon_race_sprite01.svg#icon-race_22" /></svg>
                                <span class="Icon_Label PcFsS">{race_movie_title}</span>
                            </a>
                        </li>
                    </ul>
                </div><!-- /.Top_RaceMenu_Inner -->
            </section>
            <div class="LinkBtn_03 ModalClose">
                <a href="javascript:void(0)">My収支を見る</a>
            </div>
        </div>

    </div><!-- /.ResultModal -->
    <!--　モーダル表示用テキスト　-->

    <script>

    "use strict";

    edit_cur_date(cur_date){
        if(self.mode == 'year'){
            return String(cur_date).substr(0,4) + '年';
        }else if(self.mode == 'monthly'){
            return String(cur_date).substr(0,4) + '年' + String(cur_date).substr(4,2).replace(/^0/, '') + '月';
        }else{
            return String(cur_date).substr(0,4) + '年' + String(cur_date).substr(4,2).replace(/^0/, '') + '月' + String(cur_date).substr(6,2) + '日';
        }
    }

    edit_week(cur_date){
        if(self.mode == 'daily'){
            var week_list = [ "日", "月", "火", "水", "木", "金", "土" ] ;
            var yyyy = String(cur_date).substr(0,4);
            var mm = String(cur_date).substr(4,2);
            var dd = String(cur_date).substr(6,2);
            var date = new Date( yyyy, mm - 1 , dd );
            return sprintf("(%s)", week_list[date.getDay()]);
        }
    }

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

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

    var self = this;
    self.args = self.opts;
    self.debug = true;
    self.param = null;
    self.mode = 'daily';
    self.cur_date = '';
    self.prev = null;
    self.next = null;
    self.total_money = {};
    self.jyo_list = JSON.parse(self.args.jyo_list);
    self.cur_jyo_cd = null;
    self.bet_id = false;
    self.bet_race_data = {};
    self.bet_jyo_list = {1: true};
    self.type_list = ['すべての投票先', 'netkeirin', 'TIPSTAR'];
    self.total_refund = 0;
    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});
    });

    self.args.obs.on('appli_update_bet_summary', async function() {
        console.log('appli_update_bet_summary');
        var now = new Date()
        self.year = now.getFullYear();
        self.month = String(now.getMonth()+1).padStart(2, '0');
        await self.show_data({});
        self.args.obs.trigger('appli_update_bet_summary_complete');
    });
    /*
     * 画面表示(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.mode = 'daily';
        self.prev = null;
        self.next = null;
        self.cur_jyo_cd = null;
        self.bet_id = false;
        //self.total_money = {};
        //self.cur_date = '';
        self.bet_race_data = {};
        self.bet_jyo_list = {1: true};
        self.kaisai_mode = 'race';
        self.total_refund = 0;
        self.race_movie_url = 'race_movie/';
        self.race_movie_title = 'ライブ映像一覧';
        var now = new Date()
        self.year = p.date ? p.date.substr(0,4) : now.getFullYear();
        if(p.date && p.date.substr(4,2)){
            self.month = p.date.substr(4,2);
        }else{
            var month = "0" + String(now.getMonth()+1);
            self.month = month.substr(-2);
        }
        self.show_data(p);
    });

    /*
     * データ取得、編集
     */
    self.show_data = async function(p) {
        if (self.debug) console.log('self.show_data');
        if(p['m']){
            self.mode = p['m'];
        }
        if(p['jyo']){
            self.cur_jyo_cd = p['jyo'];
        }
        if(p['bet_id']){
            self.bet_id = p['bet_id'];
        }
        self.type = '0'; // 0:すべての投票先 1:netkeirin 2:TIPSTAR
        if(p['type'] == '1'){
            self.type = '1';
        }else if(p['type'] == '2'){
            self.type = '2';
        }
        try {
            // netkeirin投票データ取得
            var netkeirinData = self.type != '2' ? await self.get_netkeirin_myshushi_sum_data() : {};
            console.log('netkeirinData: %O', netkeirinData);
            // TIPSTAR連携データ取得
            var myshushiData = self.type != '1' ? await self.get_myshushi_data() : {};
            console.log('myshushiData: %O', myshushiData);

            var myshushi_ary_sum = Object.keys(myshushiData).length > 0 ? myshushiData.ary_sum : {};
            var netkeirin_data_list = Object.keys(netkeirinData).length > 0 ? netkeirinData : {};;
            console.log('myshushi_ary_sum: %O', myshushi_ary_sum);
            console.log('netkeirin_data_list: %O', netkeirin_data_list);
            self.total_money = self.merge_shushi_data(myshushi_ary_sum, netkeirin_data_list, self.mode);
            console.log('self.total_moneyaaaaaaaaaaaaaaa: %O', self.total_money);
            if(Object.keys(self.total_money).length > 0){
                var date_list = Object.keys(self.total_money);
                date_list.sort(function(a,b){
                    if( a < b ) return -1;
                    if( a > b ) return 1;
                    return 0;
                });

                console.log('date_list: %O', date_list);
                self.prev = null;
                self.next = null;
                if(p['date']){
                    self.cur_date = p['date'];
                }else{
                    self.cur_date = Math.max(...date_list);
                }
                console.log('self.cur_date: %O', self.cur_date);
                var idx = date_list.indexOf(String(self.cur_date));
                if(idx === -1){
                    self.cur_date = Math.max(...date_list);
                    idx = date_list.indexOf(String(self.cur_date));
                }
                console.log('idx: %O', idx);
                if(idx >= 0){
                    if(date_list[idx + 1]){
                        console.log('next idx: %O', idx + 1);
                        self.next = date_list[idx + 1];
                    }
                    if(date_list[idx - 1]){
                        console.log('prev idx: %O', idx - 1);
                        self.prev = date_list[idx - 1];
                    }
                }
                // 場別のサマリー取得
                //var netkeirinShushiData = self.type != '2' ? await self.get_netkeirin_myshushi_data() : {};
                //console.log('netkeirinShushiData: %O', netkeirinShushiData);
                //var netkeirin_jyo_sum = self.type != '2' && netkeirinShushiData['jyo_summary'] ? netkeirinShushiData['jyo_summary'] : {};
                //var myshushi_jyo_sum = self.type != '1' ? myshushiData.jyo_sum : {};
                //var jyo_sum = self.merge_jyo_sum_data(myshushi_jyo_sum, netkeirin_jyo_sum);
                //console.log('jyo_sum: %O', jyo_sum);
                //if(Object.keys(jyo_sum).length > 0){
                //    for(var jyo_cd in jyo_sum){
                //        if(jyo_sum[jyo_cd][self.cur_date]){
                //            self.bet_jyo_list[jyo_cd] = true;
                //        }
                //    }
                //}
                //// 返還金額計算
                //self.total_refund = self.calc_refund_money(self.cur_date, netkeirinShushiData['votes'], myshushiData['bet_list']);
            }

            self.jyo_list[1] = '全場';
            console.log('self.total_money: %O', self.total_money);
            console.log('self.bet_jyo_list: %O', self.bet_jyo_list);
            console.log('self.cur_date:', self.cur_date);
            console.log('self.prev:', self.prev);
            console.log('self.next:', self.next);
            self.args.obs.trigger('shushi_navi_complete');
            console.log('self.args.obs.trigger(shushi_navi_complete)');
            self.update();
            self.event_register();
            if(p['bet_id']){
                self.get_user_bet(function(data){
                    if(data['race_id'].substr(8,2) == '91'){
                        self.kaisai_mode = 'pist6';
                        self.race_movie_url = 'live/live_detail.html';
                        self.race_movie_title = 'レースライブ';
                    }
                    //購入が完了したら買い目削除
                    var ndisam = new NDIsam();
                    var key = sprintf("bet_%s", data['race_id']);
                    ndisam.clear(key);
                    self.bet_race_data = data;
                    console.log('self.bet_race_data: %O', self.bet_race_data);
                    if(self.args.is_v2_appli == '1'){
                        // ネイティブの買い目を削除
                        location.href = 'ndapp://del_bet_item?race_id='+data['race_id'];
                    }
                    self.update();
                    $('.ResultModal').fadeIn();
                });
            }
        } catch (error) {
            console.error('Error:', error);
        }

    }

    self.get_myshushi_data = function(){
        return new Promise(function(resolve, reject) {
            var add_param = {
                'compress': self.args.compress,
                'year' : self.year,
                'month' : self.month
            };
            $.ajax({
                    type     : 'GET',
                    url: self.args.api_url,
                    data: add_param,
                    dataType: 'json',
                    timeout: self.args.timeout_sec,
                    success: function( data ){
                        console.log('get http');
                        if(self.args.compress){
                            //ndisam.replace(key, 'shushi', data);
                            var z_stream = ZLIB.inflateInit();
                            var oj = z_stream.inflate( base64decode(data.ret) );
                            data.ret = JSON.parse(oj);
                        }
                        resolve(data.ret);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                        console.error('textStatus: ',textStatus);
                        console.error('errorThrown.message: ',errorThrown.message);
                        reject({});
                    }
                });

/*
            var ndisam = new NDIsam();
            var key = sprintf("%s%s%s_%s", self.args.ls_key_myshushi, self.year, self.month, self.args.sns_user_id);
            var list = ndisam.list(key);
            var date = new Date() ;
            var now = date.getTime() ;
            now = Math.floor( now / 1000 ) ;
            if(list && now <= parseInt(list.shushi.date) + self.args.expire){
                console.log('get storege');
                var z_stream = ZLIB.inflateInit();
                var oj = z_stream.inflate( base64decode(list.shushi.ret) );
                resolve(JSON.parse(oj));
            }else{
                $.ajax({
                    type     : 'GET',
                    url: self.args.api_url,
                    data: add_param,
                    dataType: 'json',
                    timeout: self.args.timeout_sec,
                    success: function( data ){
                        console.log('get http');
                        if(self.args.compress){
                            ndisam.replace(key, 'shushi', data);
                            var z_stream = ZLIB.inflateInit();
                            var oj = z_stream.inflate( base64decode(data.ret) );
                            data.ret = JSON.parse(oj);
                        }
                        resolve(data.ret);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                        console.error('textStatus: ',textStatus);
                        console.error('errorThrown.message: ',errorThrown.message);
                        reject({});
                    }
                });
            }
*/
        });
    }

    self.get_netkeirin_myshushi_sum_data = function(){
        return new Promise(function(resolve, reject) {
            var api_url = sprintf("%s/api/v1/analysis/balances", self.args.betapi_url);
            console.log('betapi_url: %s', api_url);
            $.ajax({
                type     : 'GET',
                url: api_url,
                dataType: 'json',
                timeout: self.args.timeout_sec,
                crossDomain: true, // 認証のためCookie設定
                xhrFields: {
                    withCredentials: true // これを追加
                },
                success: function( result ){
                    resolve(result['data']);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if(XMLHttpRequest.status == 404){
                        resolve({});
                    }
                    console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                    console.error('textStatus: ',textStatus);
                    console.error('errorThrown.message: ',errorThrown.message);
                    resolve({});
                }
            });

/*
            var ndisam = new NDIsam();
            var key = sprintf("%s%s_%s_%s", self.args.ls_key_netkeirin, 'analysis', 'balances', self.args.sns_user_id);
            var list = ndisam.list(key);
            console.log('list: %O', list);
            var date = new Date() ;
            var now = date.getTime() ;
            now = Math.floor( now / 1000 ) ;
            if(list && now <= parseInt(list.shushi.date) + self.args.expire){
                console.log('get storege');
                resolve(list.shushi.data);
            }else{
                $.ajax({
                    type     : 'GET',
                    url: api_url,
                    dataType: 'json',
                    timeout: self.args.timeout_sec,
                    crossDomain: true, // 認証のためCookie設定
                    xhrFields: {
                        withCredentials: true // これを追加
                    },
                    success: function( result ){
                        result['date'] = now;
                        ndisam.replace(key, 'shushi', result);
                        resolve(result['data']);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if(XMLHttpRequest.status == 404){
                            resolve({});
                        }
                        console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                        console.error('textStatus: ',textStatus);
                        console.error('errorThrown.message: ',errorThrown.message);
                        resolve({});
                    }
                });
            }
*/
        });
    }
/*
    self.get_netkeirin_myshushi_data = function(){
        return new Promise(function(resolve, reject) {
            var api_url = sprintf("%s/api/v1/analysis/balances/%s/%s/votes", self.args.betapi_url, self.year, self.month);
            console.log('betapi_url: %s', api_url);
            var ndisam = new NDIsam();
            var key = sprintf("%s%s%s_%s", self.args.ls_key_netkeirin, self.year, self.month, self.args.sns_user_id);
            console.log('key: %s', key);
            var list = ndisam.list(key);
            console.log('list: %O', list);
            var date = new Date() ;
            var now = date.getTime() ;
            now = Math.floor( now / 1000 ) ;
            if(list && now <= parseInt(list.shushi.date) + self.args.expire){
                console.log('get storege');
                resolve(list.shushi.data);
            }else{
                $.ajax({
                    type     : 'GET',
                    url: api_url,
                    dataType: 'json',
                    timeout: self.args.timeout_sec,
                    crossDomain: true, // 認証のためCookie設定
                    xhrFields: {
                        withCredentials: true // これを追加
                    },
                    success: function( result ){
                        result['date'] = now;
                        ndisam.replace(key, 'shushi', result);
                        resolve(result['data']);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if(XMLHttpRequest.status == 404){
                            resolve({});
                        }
                        console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                        console.error('textStatus: ',textStatus);
                        console.error('errorThrown.message: ',errorThrown.message);
                        resolve({});
                    }
                });
            }

        });
    }
*/
    self.get_user_bet = function(fn){
        var add_param = {
            'mode': 'check',
            'bet_id': self.bet_id
        };
        $.ajax({
            type     : 'GET',
            url: self.args.api_bet_url,
            data: add_param,
            dataType: 'json',
            timeout: self.args.timeout_sec,
            success: function( data ){
                if(data.status == 'OK'){
                    fn(data.race_data);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.error('XMLHttpRequest.status: ',XMLHttpRequest.status)
                console.error('textStatus: ',textStatus);
                console.error('errorThrown.message: ',errorThrown.message);
                fn({});
            }
        });
    }

    self.merge_shushi_data = function(myshushi_ary_sum, netkeirin_data_list, mode){
        console.log('myshushi_ary_sum: %O', myshushi_ary_sum);
        console.log('netkeirin_data_list: %O', netkeirin_data_list);
        var merge_data = {};
        if(myshushi_ary_sum[mode]){
            for(var date in myshushi_ary_sum[mode]){
                if(!merge_data[date]){
                    merge_data[date] = {};
                }
                merge_data[date] = myshushi_ary_sum[mode][date];
            }
        }
        if(mode == 'year'){
            mode = 'yearly';
        }
        if(netkeirin_data_list[mode]){
            for(var date in netkeirin_data_list[mode]){
                if(!merge_data[date]){
                    merge_data[date] = {};
                    merge_data[date]['total_bet_money'] = netkeirin_data_list[mode][date]['total_vote_money'];
                    merge_data[date]['total_pay'] = netkeirin_data_list[mode][date]['total_pay'];
                    merge_data[date]['total_diff'] = netkeirin_data_list[mode][date]['total_diff'];
                }else{
                    merge_data[date]['total_bet_money'] += netkeirin_data_list[mode][date]['total_vote_money'];
                    merge_data[date]['total_pay'] += netkeirin_data_list[mode][date]['total_pay'];
                    merge_data[date]['total_diff'] += netkeirin_data_list[mode][date]['total_diff'];
                }
            }
        }
        console.log('merge_data: %O', merge_data);
        return merge_data;
    }

    self.merge_jyo_sum_data = function(myshushi_jyo_sum, netkeirin_jyo_sum){
        var merge_data = {};
        // 場一覧取得
        var tmp_jyo_list = Object.keys(myshushi_jyo_sum);
        var tmp_jyo_list2 = Object.keys(netkeirin_jyo_sum);
        var jyo_list = tmp_jyo_list.concat(tmp_jyo_list2);
        // 重複削除
        jyo_list = [...new Set(jyo_list)];
        for(var jyo_cd of jyo_list){
           if(myshushi_jyo_sum[jyo_cd]){
                for(var date in myshushi_jyo_sum[jyo_cd]){
                    if(!merge_data[jyo_cd]){
                        merge_data[jyo_cd] = {};
                    }
                    if(!merge_data[jyo_cd][date]){
                        merge_data[jyo_cd][date] = {};
                    }
                    merge_data[jyo_cd][date] = myshushi_jyo_sum[jyo_cd][date];
                }
            }
            if(netkeirin_jyo_sum[jyo_cd]){
                for(var date in netkeirin_jyo_sum[jyo_cd]){
                    if(!merge_data[jyo_cd]){
                        merge_data[jyo_cd] = {};
                    }
                    if(!merge_data[jyo_cd][date]){
                        merge_data[jyo_cd][date] = {};
                        merge_data[jyo_cd][date]['total_bet_money'] = netkeirin_jyo_sum[jyo_cd][date]['total_vote_money'];
                        merge_data[jyo_cd][date]['total_pay'] = netkeirin_jyo_sum[jyo_cd][date]['total_pay'];
                        merge_data[jyo_cd][date]['total_diff'] = netkeirin_jyo_sum[jyo_cd][date]['total_diff'];
                    }else{
                        merge_data[jyo_cd][date]['total_bet_money'] += netkeirin_jyo_sum[jyo_cd][date]['total_vote_money'];
                        merge_data[jyo_cd][date]['total_pay'] += netkeirin_jyo_sum[jyo_cd][date]['total_pay'];
                        merge_data[jyo_cd][date]['total_diff'] += netkeirin_jyo_sum[jyo_cd][date]['total_diff'];
                    }
                }
            }
        }
        return merge_data;
    }

    self.get_date_list = function(myshushi_ary_sum, netkeirin_data_list){
        var myshushi_date_list = Object.keys(myshushi_ary_sum);
        var netkeirin_date_list2 = Object.keys(netkeirin_data_list);
        var date_list = myshushi_date_list.concat(netkeirin_date_list2);
        // 重複削除
        date_list = [...new Set(date_list)];
        // 降順ソート
        date_list.sort(function(a,b){
            if( a < b ) return 1;
            if( a > b ) return -1;
            return 0;
        });
        return date_list;
    }

    // 返還金額計算
/*
    self.calc_refund_money = function(date, netkeirinVotes, myShushiBetList){
        console.log('calc_refund_money');
        var total_refund = 0;
        console.log('netkeirinVotes: %O', netkeirinVotes);
        console.log('myShushiBetList: %O', myShushiBetList);
        console.log('date: %O', date);
        // netkeirin投票の返還計算
        if(netkeirinVotes && netkeirinVotes[date]){
            console.log('netkeirinVotes[date]: %O', netkeirinVotes[date]);
            for(var race_id in netkeirinVotes[date]){
                var vote_list = netkeirinVotes[date][race_id]['vote_list'];
                for(var key in vote_list){
                    var vote = vote_list[key];
                    if(vote['status'] == 1 && vote['payback_flag'] == 1){
                        total_refund += vote['refund'];
                    }
                }
            }
        }
        // TIPSTAR投票の返還計算
        if(myShushiBetList && myShushiBetList[date]){
            console.log('myShushiBetList[date]: %O', myShushiBetList[date]);
            for(var race_id in myShushiBetList[date]){
                var bet_list = myShushiBetList[date][race_id]['bet_list'];
                console.log('bet_list: %O', bet_list);
                for(var key in bet_list){
                    var vote = bet_list[key];
                    var refund = vote['refund'] != '0' ? Number(vote['refund']) : 0;
                    if(vote['state'] == '1' && refund > 0){
                        total_refund += refund;
                    }
                }
            }
        }
        console.log('total_refund: %O', total_refund);
        return total_refund;
    }
*/
    //制作
    self.event_register = function(){
        $('#jyo_list').off().on('change', function () {
            var jyo_cd = $(this).val();
            self.change_page(self.mode, self.cur_date, jyo_cd, self.type);
        });
        $('#vote_list').off().on('change', function () {
            var type = $(this).val();
            self.change_page(self.mode, self.cur_date, self.cur_jyo_cd, type);
        });
        $('.modal_button').off().on('click', function () {
            $('.ResultModal').fadeIn();
            return false;
        });
        $('.ModalClose').off().on('click', function () {
            $('.ResultModal').fadeOut();
            self.change_page(self.mode, self.cur_date, self.cur_jyo_cd, self.type);
            return false;
        });

    }

    self.change_page = function( mode, date, jyo_cd, type ){
        console.log(date);
        if(self.debug) console.log('self.change_page mode: %s',mode);
        var base_url = '?m=%s';
        var change_url = sprintf(base_url, mode);
        if(date){
            change_url += '&date=' + date;
        }
        if(jyo_cd){
            change_url += '&jyo=' + jyo_cd;
        }
        if(type){
            change_url += '&type=' + type;
        }
        console.log(change_url);
        route(change_url);
    }

    </script>

</shushi_navi>
