<order-history-s>
    <link rel="stylesheet" href="css/S11.css">
    <link rel="stylesheet" href="css/common.css" type="text/css" />
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://rawgit.com/jquery/jquery-ui/master/ui/i18n/datepicker-ja.js"></script>
    <div class="main">
      <div class="content">
        <div class="page-title">
          <h2>受注履歴</h2>
        </div>
        <div class="form-wrapper">
          <table>
            <tr>
              <td>
                <input type="text" placeholder="yyyy/mm/dd" class="order_start_date datepicker" > ~ <input type="text" class="order_end_date datepicker1" placeholder="yyyy/mm/dd">
              </td>
              <td>
                <button class="search-btn reset-btn"><i class="fa fa-search"></i>発注日で絞り込む</button>
              </td>
            </tr>
          </table>
        </div>
        <div class="btn-wrapper">
          <progress id="progress" value="0" style="display:none;"></progress>
        </div>
        <div class="top-wrapper">
          <div class="filters" style="width:55%">
            <div class="select-box w-100">
              <select id="status_select" class="w-100" onchange="{changeStatusSelect}">
                <option value="0" selected>ステータスで絞り込む</option>
                <option value="4,12">受注</option>
                <option value="5">キャンセル依頼</option>
                <option value="6">キャンセル済</option>
                <option value="7">受注確定</option>
                <option value="8">返品依頼</option>
                <option value="9">返品了承済</option>
                <option value="15">注文確認中</option>
                <option value="16">注文確認（回答済み）</option>
                <option value="30">出荷確定</option>
                <option value="31">受入検収済</option>
              </select>
            </div>
            <div class="select-box" style="width: 100%; height: 31px;">
              <div class="div-wraper-autocompleter"><input style="width:95%;" type="text" id="customer_co_cd_select" placeholder="顧客で絞り込む"></div>
            </div>
            <div class="select-box" style="width:80%;">
              <select id="customer_dep_cd_select" class="w-100" onchange="{changeCusDepCdSelect}" disabled>
                <option value="" selected>顧客部署で絞り込む</option>
                <option each="{item in list_dep}" value="{item.kyoten_code}">{item.kyoten_name}</option>
              </select>
            </div>
          </div>
          <div class="check-box">
            <div style="margin-right: 5px">
              <span>チェックした注文を</span>
            </div>
            <div style="margin-right: 5px">
              <select id="check_cart">
                <option data-status="0" data-st="1" value="4,12,15,16" selected="selected">受注確定する</option>
                <option data-status="0" data-st="0" value="4,12">注文確認する</option>
                <option data-status="0" data-st="2" value="7">出荷確定する</option>
                <option data-status="0" data-st="0" value="5">キャンセル承認する</option>
                <option data-status="0" data-st="0" value="8">返品承認する</option>
                <option data-status="1" data-st="0" value="7">受注に戻す</option>
                <option data-st="0" value="1">CSV出力する</option>
              </select>
            </div>
            <div>
              <button onclick="{postCart}">実行</button>
            </div>
          </div>
        </div>
        <div class="table-wrapper">
          <table class="blue-table">
            <thead>
              <tr>
                <th>
                  <div>注文管理番号</div>
                  <div>見積管理番号</div>
                </th>
                <th style="width:82px">
                  <div>ご注文日</div>
                  <div>最終更新日</div>
                </th>
                <th>製品情報</th>
                <th>
                  <div>お客様</div>
                  <div>希望納期</div>
                  <!-- <div>コード</div> -->
                </th>
                <th style="width:50px">
                  <div>注文<br>数量</div>
                  <div>納入<br>数量</div>
                </th>
                <th style="width:82px">
                  <div>納入価格</div>
                  <div>納入金額</div>
                </th>
                <th style="width:82px">
                  <div>定価</div>
                  <div>仕切価格</div>
                </th>
                <th>
                  <div>納品予定日</div>
                  <div>納品日</div>
                  <div>受入検収日</div>
                </th>
                <th>
                  <div>お客様へコメント</div>
                  <div>お客様からの回答</div>
                </th>
                <th>ステータス</th>
                <th style="width:30px"></th>
              </tr>
            </thead>
            <tbody>
              <tr each={item,index in list_cart}>
                <!--<td>{item.cart_seq_related ? item.cart_seq_related + '\n' + '(' + item.cart_seq + ')': item.cart_seq}</td>-->
                <td>
                  <div>{item.cart_seq}</br>{item.cart_seq_related ? '(' + item.cart_seq_related + ')':''}</div>
                  <div>{item.cart_seq_mitsumori_related}</div>
                </td>
                <td>
                  <div>{item.order_date}</div>
                  <div>{item.updatedate}</div>
                </td>
                <td class="left">
                  <dl>
                    <dt>品番</dt>
                    <dd><a href="{(item.is_deleted == 1 || !item.item_sku_exist) ? '' : (s08_allow == true ? '#s09' + '/basic_details/' + encodeURIComponent(item.item_sku) : '#search' + '/basic_details/' + encodeURIComponent(item.item_sku)) }" style="{ (item.is_deleted == 1 || !item.item_sku_exist) ? 'color:black;text-decoration:none;cursor: auto;' : '' }">{item.supp_sku}<span class="msg-item-sku-exist">{(item.is_deleted == 1 || !item.item_sku_exist) && item.inquiry != 1 ? 'この商品はカタログから削除されています' : ''}</span></a></dd>
                  </dl>
                  <dl>
                    <dt>品名</dt>
                    <dd>{item.item_name}</dd>
                  </dl>
                  <dl>
                    <dt>容量・規格</dt>
                    <dd>{item.capacity} {(item.capacity && item.kikaku) ? '・' : '' } {item.kikaku}</dd>
                  </dl>
                  <dl>
                    <dt>販売元</dt>
                    <dd>{item.supp_co_name} {item.supp_name}</dd>
                  </dl>
                  <dl>
                    <dd>
                      <b class="discontinued" style="color:red;display:{(item.is_deleted == 1 ) ? 'block' : 'none'}">販売中止</b>
                    </dd>
                  </dl>
                  <div class="collapse" index="{index}"　id="detail-{index}">
                    <dl>
                      <dt>製造元</dt>
                      <dd>{item.maker_name}</dd>
                    </dl>
                    <dl style="display:{item.customer_use_code_1_title && item.customer_use_code_1_name ? 'block' : 'none'}">
                      <dt>{item.customer_use_code_1_title ? item.customer_use_code_1_title : ''}</dt>
                      <dd>{ item.customer_use_code_1_name }</dd>
                    </dl>
                    <dl style="display:{item.customer_use_code_2_title && item.customer_use_code_2_name ? 'block' : 'none'}">
                      <dt>{item.customer_use_code_2_title ? item.customer_use_code_2_title : ''}</dt>
                      <dd>{ item.customer_use_code_2_name }</dd>
                    </dl>
                    <dl style="display:{item.customer_use_code_3_title && item.customer_use_code_3_name ? 'block' : 'none'}">
                      <dt>{item.customer_use_code_3_title ? item.customer_use_code_3_title : ''}</dt>
                      <dd>{ item.customer_use_code_3_name }</dd>
                    </dl>
                    <dl style="display:{item.customer_use_code_4_title && item.customer_use_code_4_name ? 'block' : 'none'}">
                      <dt>{item.customer_use_code_4_title ? item.customer_use_code_4_title : ''}</dt>
                      <dd>{ item.customer_use_code_4_name }</dd>
                    </dl>
                    <dl style="display:{item.customer_use_code_5_title && item.customer_use_code_5_name ? 'block' : 'none'}">
                      <dt>{item.customer_use_code_5_title ? item.customer_use_code_5_title : ''}</dt>
                      <dd>{ item.customer_use_code_5_name }</dd>
                    </dl>
                  </div>

                  <div class="see-more" style="text-align: center;border-top: none !important">
                      <a class="show-detail collapsed" data-toggle="collapse" href="#detail-{index}"></a>
                  </div>
                </td>
                <td class="left" style="background-color: {(item.address_flag == '1') ? '#f9e5f1' : ''}">
                  <div>
                    <p>{ item.customer_co_name }</p>
                    <p>{ item.customer_dep_name }</p>
                    <p>{ item.customer_business_name }</p>
                    <p if={!item.customer_kikanname && !item.customer_sosikiname && !item.customer_tanto && !item.customer_email && !item.nonyu_zip && !item.nonyu_address1 && !item.nonyu_tel}>{ item.customer_user_name }</p>
                    <a class="s11-delivery-address-open" index={index} if={item.customer_kikanname || item.customer_sosikiname || item.customer_tanto || item.customer_email || item.nonyu_zip || item.nonyu_address1 || item.nonyu_tel}>{ item.customer_user_name }</a>
                    <div class="comment-box" if={ item.comment_spp }>
                      <a class="commentOpen">お客様より<i class="fa fa-commenting-o"></i></a>
                      <div class="text"><description id="description_{index}"></description></div>
                    </div>
                    <div style="margin-top: 5px;text-align: center;!important" if={item.attachment}>
                      <i class="fa fa-file file_cart"  title="{item.attachment}" onclick="{downloadFile}" fileName="{item.attachment}"></i>
                    </div>
                  </div>
                  <div>{ item.deliverydate }</div>
                </td>
                <td>
                  <div>
                    {item.suryo}                
                    <input type="hidden" id="suryo_{index}" value="{item.suryo}">
                  </div>
                  <div class="text-nowrap" if={item.delivery_suryo_rest > 0 && item.cart_seq_related}>(分納残：{item.delivery_suryo_rest})</div>
                  <!-- {(item.status == 4 || item.status == 12 || item.status == 5 || item.status == 6 ) ? (item.delivery_suryo > item.suryo || !item.delivery_suryo ? item.suryo : item.delivery_suryo) : item.delivery_suryo > item.suryo || !item.delivery_suryo ? '' : item.delivery_suryo} -->
                  
                  <div>
                    <input type="text" id="delivery_suryo_{index}" value="{(item.status == 4 || item.status == 12 || item.status == 5 || item.status == 6 ) ? (item.delivery_suryo > item.suryo || !item.delivery_suryo ? '' : item.delivery_suryo) : item.delivery_suryo > item.suryo || !item.delivery_suryo ? '' : item.delivery_suryo}" disabled="{(item.delivery_suryo > item.suryo || !item.delivery_suryo) && item.status != '16' ? 'disabled':''}" style="text-align: center;width:100%">
                    <div>
                      {item.delivery_suryo && item.suryo > item.delivery_suryo ? '分納' : ''}
                    </div>
                  </div>
                  <!-- <div if={ item.delivery_suryo < item.suryo && item.delivery_suryo > 0 && item.total_delivery_suryo < item.suryo && !item.cart_seq_related }><a class="S11-2-open" index={index}>分納</a></div> -->
                </td>
                <td class="right">
                  <div>
                     <input type="text" id="tanka_{index}" value="{item.tanka ? item.tanka : '0'}" onchange="{changeTanka}" style="width:100%;text-align:right"> 
                     <input type="hidden" id="tanka_{index}_old" value="{item.tanka}" disabled="disabled"> 
                  </div>
                  <div id="teika_tanka_{index}">{(item.delivery_suryo * item.tanka) == 0 ? '' : (item.delivery_suryo * item.tanka).toLocaleString('en') + '円'}</div>

                  <div if={item.extra_cost_div == '1'}><u class="tooltips" data-tooltip="別途送料が発生します。&#013;詳細はメーカーへお問合せ下さい。">※別途費用</u></div>
                  <div if={item.extra_cost_div == '2'}><u class="tooltips" data-tooltip="別途設置費用が発生します。&#013;詳細はメーカーへお問合せ下さい。">※別途費用</u></div>
                  <div if={item.extra_cost_div == '9'}><u class="tooltips" data-tooltip="別途諸費用が発生します。&#013;詳細はメーカーへお問合せ下さい。">※別途費用</u></div>

                </td>
                <td class="right">
                  <div>{item.teika_tanka ? item.teika_tanka.toLocaleString('en') + '円' : '' }</div>
                  <div>{item.dealer_tanka ? item.dealer_tanka.toLocaleString('en') + '円' : ''}</div>
                  <!-- <div if={ item.siire_tanka }>{item.siire_tanka}円</div> -->
                </td>
                <td>
                  <div> 

                    <input type="text" autocomplete="off" class="datepicker3 delivery_scheduled_date" id="delivery_scheduled_date_{index}" value="{item.delivery_scheduled_date}" placeholder="yyyy/mm/dd" style="width:90px">
                    <input type="hidden" class="datepicker3" id="delivery_scheduled_date_{index}_old" value="{item.delivery_scheduled_date}">

                  </div>
                  <!-- <div if={item.status != 7}>{convertDateTime(item.delivery_date)}</div> -->
                  <div if={item.status == 7 || item.status == 30 || item.status == 31}><input type="text" index={index} class="delivery_date datepicker3" id="delivery_date_{index}" value="{item.delivery_date}" placeholder="yyyy/mm/dd" style="width:90px"></div>
                  <div>
                    {item.status == 30 ? '' : convertDateTime(item.acceptance_date)}
                    <a href="" onclick="{postCartLink}" style="display:{item.status == 30 ? 'block' : 'none'}">受入検収</a>
                  </div>
                </td>
                <td>
                  <span id="comment_cst1_color_{item.cart_seq}">(<span id="comment_cst1_count_{item.cart_seq}">{ item.comment_cst1 ? item.comment_cst1.length : 0 }</span>/200)</span>
                  <textarea id="comment_cst1_{item.cart_seq}" class="comment_cst1" >{item.order_comment ? item.order_comment : item.comment_cst1;}</textarea>
                  <input type="hidden" id="comment_cst1_{index}_old" value="{item.comment_cst1}">
                  <div class="comment-box" if={ item.comment_to_dealer !== null } style="white-space: nowrap;">
                       <a class="commentToDealerOpen" index={index} onclick={ readComment }>お客様からの回答<i class="fa fa-commenting-o" index={index}></i></a>
                        <div class="text"><description id="description_comment_to_dealer_{index}"></description></div>
                  </div>
                </td>
                <td>
                  {(item.status == 4 || item.status == 12) ? '受注':''}
                  {(item.status == 5) ? 'キャンセル依頼':''}
                  {(item.status == 6) ? 'キャンセル済':''}
                  {(item.status == 7) ? '受注確定':''}
                  {(item.status == 8) ? '返品依頼':''}
                  {(item.status == 9) ? '返品了承済':''}
                  {(item.status == 30) ? '出荷確定':''}
                  {(item.status == 31) ? '受入検収済':''}
                  {(item.status == 15) ? '注文確認':''}
                  <div if={item.status == 16}>
                    注文確認
                    <p style="white-space: nowrap;">（回答済み）</p>
                  </div>
                  <a href="" onclick="{postCartDelete}" index={index} style="display: {(item.status == 4 || item.status == 12 || item.status == 7 || item.status == 15 || item.status == 16) ? 'block':'none'}">オーダー取消</a>
                </td>
                <td style="position: relative;">
                  <input type="checkbox" id="checkbox_status_{index}" class="checkbox_status" value="{item.status}" onchange="{changeStatus}" index={index} if={(item.item_sku_exist && item.is_deleted != 1) || item.inquiry == 1}>
                  <input type="checkbox" if={(!item.item_sku_exist || item.is_deleted == 1) && item.inquiry != 1} disabled="disabled">
                  <button style="margin-top: 10px;" index={index} onclick={updateCart}>修正</button>
                  
                  <input type="hidden" id="cart_seq_{index}" value="{item.cart_seq}">
                  <input type="hidden" id="return_acceptance_date_{index}" value="{item.return_acceptance_date}">
                  <input type="hidden" id="cancellation_acceptance_date_{index}" value="{item.cancellation_acceptance_date}">
                  
                  
                  <input type="hidden" id="sku_{index}" value="{item.sku}">
                  <input type="hidden" id="supp_co_cd_{index}" value="{item.supp_co_cd}">
                  <input type="hidden" id="customer_co_cd_{index}" value="{item.customer_co_cd}">
                  <input type="hidden" id="is_delete_{index}" value="{item.is_delete}">
                  <input type="hidden" id="cart_seq_download_{index}" value="{item.cart_seq}">
                </td>
              </tr>
            </tbody>
          </table>
          <div id="paging" class="text-center">
            <ul class="pagination" id="pagination_s11"></ul>
          </div>
        </div>
      </div>
    </div>
    <div class="o_modal" id="s11-delivery-address">
      <div class="o_modal_box delivery-address-modal">
        <div class="o_modal_head">
          <a id="s11-delivery-address-close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title">お届け先住所</h3>
            <div class="left">
              <p>{delivery_address.customer_kikanname}</p>
              <p>{delivery_address.customer_sosikiname}</p>
              <p>{delivery_address.customer_tanto}</p>
              <p>{delivery_address.customer_email}</p>
              <br>
              <p>{delivery_address.nonyu_zip}</p>
              <p>{delivery_address.nonyu_address1}</p>
              <p>{delivery_address.nonyu_address2}</p>
              <p>{delivery_address.nonyu_tel}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <script>
      /* popup $ */
      $(function(){
        $(".search-btn").click(function(e){
          var page = 1;
          thisTag.searchCart(page);
          thisTag.companiesSuggest();
        });
        $.each(thisTag.list_navigationF,function(i,e){
            if(e['navigation_id'] == 'F006'){
                if(e['used_status'] == 'N'){       
                    thisTag.delivery_date_visible = false;
                } else if(e['used_status'] == 'Y'){
                    thisTag.delivery_date_visible = true;
                    return false;
                }
            } else {             
                thisTag.delivery_date_visible = false;
            }
        });

        $.each(thisTag.list_cart,function(i,e){
            riot.tag('description', '', function(opts) {   
                this.root.innerHTML = opts.r;
            });
            riot.mount('#description_' + i, {
                r: e.comment_spp
            })
            riot.mount('#description_comment_to_dealer_' + i, {
                r: e.comment_to_dealer
            });
            thisTag.update();
        });
        $('#S11-2-close').on('click',function(e){
          $('#S11-2').fadeOut();
          $('.popup-text-html').html('');
          $('.popup-text-input').val('');
          $("#post_cart_popup").attr('index','');
        });
        $('#delivery_scheduled_date_popup').datetimepicker({
            format: 'Y/m/d',
            onShow:function( ct ){
                this.setOptions({
                    minDate: new Date()
                })
            },
            scrollInput: false,
            timepicker:false
        });
        $('.commentOpen').on('click',function(){
          if($(this).hasClass('active')){
            $(this).removeClass('active').html('お客様より<i class="fa fa-commenting-o"></i>');
            $(this).next('.text').hide();
          }else{
            $(this).addClass('active').html('閉じる<i class="fa fa-times"></i>');
            $(this).next('.text').show();
          }
        });
        $('.commentToDealerOpen').on('click',function(){
          if($(this).hasClass('active')){
            $(this).removeClass('active').html('お客様からの回答<i class="fa fa-commenting-o"></i>');
            $(this).next('.text').hide();
          }else{
            $(this).addClass('active').html('閉じる<i class="fa fa-times"></i>');
            $(this).next('.text').show();
          }
        });
      });
    </script>
    <script>

    /* global */
    var user_info = JSON.parse(localStorage.getItem('EcUserInfo'));
    this.list_cart = opts.result;
    this.total = opts.total;
    this.currentPage = 1;
    this.linkDownload = URL_API;
    this.accessTokenCognito = localStorage.getItem('accessTokenCognito');
    this.statusSelected = [4,5,6,7,8,9,30,31,12,15,16];
    this.list_navigationF = user_info.list_navigation.F;
    var thisTag = this; 
    this.navigation_list_cus_use_code = opts.navigation_list;
    this.list_comp = opts.list_comp;
    this.list_dep = opts.list_dep;
    this.customer_co_cd_select = '';
    this.customer_dep_cd_select = '';
    this.delivery_address = '';
    this.list_companies_suggest_search = [];
    this.list_download_checkbox = [];
    this.IWAI_SITE = IWAI_SITE;
    function disableCusDepCd() {
      if ($("#customer_co_cd_select").val() == "") {
        $('#customer_dep_cd_select').attr('disabled', 'disabled');
      } else {
        $('#customer_dep_cd_select').removeAttr('disabled');
      }
    }
    function updateDeliveryAddress(){
      $('.s11-delivery-address-open').on('click',function(e){
        thisTag.delivery_address =  thisTag.list_cart[$(e.target).attr('index')];
        thisTag.update(thisTag.delivery_address);
        $('#s11-delivery-address').fadeIn();
      });
      $('#s11-delivery-address-close').on('click',function(){
        $('#s11-delivery-address').fadeOut();
      });
    }
    $(function(){
        disableCusDepCd();
        updateDeliveryAddress();
        thisTag.companiesSuggest();
        $(document).on('change', 'input[type=checkbox][class=checkbox_status]', function (e) {
          if ($('#check_cart').val() == '1') {
            let i = $(e.target).attr('index');
            if ($(this).is(':checked')) {
              thisTag.list_download_checkbox.push($("#cart_seq_download_" + i).val());
            } else {
              var index = thisTag.list_download_checkbox.indexOf($("#cart_seq_download_" + i).val());
              if (index !== -1) {
                thisTag.list_download_checkbox.splice(index, 1);
              }
            }
          }
        });
        thisTag.testCheckStatus("#check_cart");
        var totalPages = Math.ceil(thisTag.total/LIMIT_ON_PAGE);
            thisTag.total_page = totalPages;
        var visiblePages = 1;
        if(totalPages != 0){
            visiblePages =  5;
        } 
        var $pagination = $('#pagination_s11');
        $pagination.twbsPagination('destroy');
        $pagination.twbsPagination({
            totalPages: totalPages,
            visiblePages: visiblePages,
            startPage: thisTag.currentPage,
            initiateStartPageClick: false,
            onPageClick: function (event, page) {
                thisTag.currentPage = page;
                thisTag.searchCart(page);
            }
        });

        // $("#status_select").on('change', function(e){
        //     var page = 1;
        //     thisTag.searchCart(page);
        // });

        // $("#orderdate_select").on('keyup', function(e){
        //   console.log("a");
        //     var page = 1;
        //     thisTag.searchCart(page);
        // });

        $("#check_cart").on('change', function(e){
            thisTag.testCheckStatus(this);
            thisTag.update({list_download_checkbox: []});
        });

        $('#customer_dep_cd_select').on('change',function() {
            thisTag.update({list_download_checkbox: []});
        });
        
        thisTag.checkIfFirstPage();  
        thisTag.checkIfLastPage(); 
        thisTag.pickDateTime();

        $('#customer_co_cd_select').on('change', function() {
          var customer_name = $(this).val();
          var check_name = arColumn(thisTag.list_companies_suggest_search, 'label', customer_name);
          if(check_name.length == 0 && customer_name != '') {
            return false;
          }
          if (customer_name == '') {
            thisTag.update({
              customer_co_cd_select: ''
            })
          }
          var page = 1;
          thisTag.update({
            customer_dep_cd_select: ''
          })
          $("#customer_dep_cd_select").val('');
          disableCusDepCd();
          thisTag.searchCart(page);
        })
    });

    this.checkInteger = function(e){
      var number = $(e.target).val().trim();
      if(number === '0'){
        alert('1以上の整数のみ入力できます。');
        $(e.target).val('');
        return false;
      }
      if(!thisTag.validateInteger(number)){
        alert('納入数量を正数で入力してください。');
        $(e.target).val('');
        return false;
      }
    }
    this.changeCusDepCdSelect = function(e){
      var page = 1;
      thisTag.update({
        customer_dep_cd_select: e.target.value
      });
      thisTag.searchCart(page);
    }
    this.changeStatusSelect = function(e){
      var page = 1;
      this.update({
        customer_co_cd_select: '',
        customer_dep_cd_select: ''
      })
      $("#customer_co_cd_select").val('');
      $("#customer_dep_cd_select").val('');
      disableCusDepCd();
      thisTag.searchCart(page);
      thisTag.companiesSuggest();
    }
    this.changeOrderDate = function(e){
      var page = 1;
      thisTag.searchCart(page);
    }
    this.changeTanka = function(e){
        var pattern = /^[0-9]*$/;
        var index = e.item.index;
        var suryo = $("#suryo_" + index).val();
        var delivery_suryo = $("#delivery_suryo_" + index).val();
        var tanka = $("#tanka_" + index).val();
        var msg = [];
        if(tanka == ''){
            msg.push('納入価額は入力必須です。\n');
        }
        if(tanka.length > 7){
            msg.push('納入価額を7文字以内に入力してください。\n');
        }
        if(!pattern.test(tanka) && tanka != ''){
            msg.push('納入価額を正数のみで入力してください。\n');
        } 
        if(msg.length > 0){
            alert(msg.join(""));
            var old_tanka = $("#tanka_" + index + "_old").val();
            $("#tanka_" + index).val(old_tanka == '' || old_tanka == null ? 0 : old_tanka);
            tanka = old_tanka;
        }
        if(delivery_suryo && tanka){
          var teika_tanka = parseInt(delivery_suryo) * (tanka == '' ? 0 : parseInt(tanka));
          $("#teika_tanka_" + index).html(teika_tanka.toLocaleString('en') + "円");
        } else {
          $("#teika_tanka_" + index).html('');
        }
        
    }

    this.convertDateTime = function(e){
        var new_date = e.substring(0,10);
        return new_date;
    }

    this.checkIfFirstPage = function(e){
        if(thisTag.currentPage == 1){
            $(".page-item.first").css({'display':'none'});
            $(".page-item.prev").css({'display':'none'});
        } else {
            $(".page-item.first").css({'display':'inline'});
            $(".page-item.prev").css({'display':'inline'});
        }
    }
    this.checkIfLastPage = function(e){
        var totalPage = Math.ceil(thisTag.total/LIMIT_ON_PAGE);
        if(thisTag.currentPage == totalPage){
            $(".page-item.next").css({'display':'none'});
            $(".page-item.last").css({'display':'none'});
        } else {
            $(".page-item.next").css({'display':'inline'});
            $(".page-item.last").css({'display':'inline'});
        }
    }

    this.pickDateTime = function(e){
        /*$(".delivery_scheduled_date").on('blur', function(e){
            
            var date = new Date();
            var currentDate = $(e.target).val();

            var date_regex_only_num =   /^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$/ ;

            if(date_regex_only_num.test(currentDate)){
                var y = currentDate.substring(0,4);
                var m = currentDate.substring(4,6);
                var d = currentDate.substring(6,8);
                currentDate = ''+y+'/'+m+'/'+d+'';
                $(e.target).val(currentDate);
            }

            var date_regex =   /^[0-9]{4}\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])$/ ;
            if(!(date_regex.test(currentDate)) && currentDate != '')
            {
                alert("本日以降の日付を選択してください。");
                $(this).val('');
                return false;
            }

            var yesterday = new Date(date.getTime());
            yesterday.setDate(date.getDate() - 1);

            if( new Date( currentDate ) < yesterday){
                alert("本日以降の日付を選択してください。");
                $(this).val('');
                return false;
            }

        });

        $(".delivery_date").on('blur', function(e){
          if(!IWAI_SITE) {
            var index = $(e.target).attr("index");
            var status = thisTag.list_cart[index].status;

            if(status != 7){
              return false;
            }
          }

            var date = new Date();
            var currentDate = $(e.target).val();

            var date_regex_only_num =   /^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$/ ;

            if(date_regex_only_num.test(currentDate)){
                var y = currentDate.substring(0,4);
                var m = currentDate.substring(4,6);
                var d = currentDate.substring(6,8);
                currentDate = ''+y+'/'+m+'/'+d+'';
                $(e.target).val(currentDate);
            }

            var date_regex =   /^[0-9]{4}\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])$/ ;
            if(!(date_regex.test(currentDate)) && currentDate != '')
            {
                alert("本日以降の日付を選択してください。");
                $(this).val('');
                return false;
            }

            var yesterday = new Date(date.getTime());
            yesterday.setDate(date.getDate() - 1);

            if( new Date( currentDate ) < yesterday){
                alert("本日以降の日付を選択してください。");
                $(this).val('');
                return false;
            }

        });
        $('.delivery_date').datetimepicker({
            format: 'Y/m/d',
            onShow:function( ct ){
                this.setOptions({
                    minDate: new Date()
                })
            },
            scrollInput: false,
            timepicker:false
        });*/
        
        DatepickerHoliday();

        /*$('.delivery_scheduled_date').datetimepicker({
            format: 'Y/m/d',
            onShow:function( ct ){
                this.setOptions({
                    minDate: new Date()
                })
            },
            scrollInput: false,
            timepicker:false
        });
        $('.order_start_date').datetimepicker({
          format: 'Y/m/d',
          onShow:function( ct ){
            this.setOptions({
               maxDate:$('.order_end_date').val()?$('.order_end_date').val():false
            })
          },

          timepicker:false
        });
        $('.order_end_date').datetimepicker({
          format: 'Y/m/d',
          onShow:function( ct ){
            this.setOptions({
               minDate:$('.order_start_date').val()?$('.order_start_date').val():false
            })
          },

          timepicker:false
        });*/
    }

    this.testCheckStatus = function(e){

        $(".checkbox_status").prop("checked",false);
        $(".checkbox_status").removeAttr("disabled");
        // $(".delivery_scheduled_date").attr("disabled","true");
        // $(".comment_cst1").attr("disabled","true");
        var status = $(e).val();
        var arrStatus = status.split(",");
        if (status == '1') {
          $(".checkbox_status").prop("checked",false);
          $(".checkbox_status").removeAttr("disabled");
        } else {
          $.each(thisTag.list_cart, function (index, value) {
            // $("#delivery_scheduled_date_" + index).attr("disabled","true");
            // $("#comment_cst1_" + index).attr("disabled","true");
            $("#delivery_suryo_" + index).attr("disabled", "true");
            if (arrStatus.indexOf(value.status) != -1) {
              $(".checkbox_status_" + index).removeAttr("disabled");
              if (value.status == 4 || value.status == 5 || value.status == 6 || value.status == 12 || value.status == 16 || value.status == 15) {
                // $("#tanka_" + index).removeAttr("disabled");
                $("#delivery_suryo_" + index).removeAttr("disabled");
              }
            } else {
              $("#checkbox_status_" + index).attr("disabled", "true");
              // $("#tanka_" + index).attr("disabled","true");
              if (value.status == 4 || value.status == 5 || value.status == 6 || value.status == 12 || value.status == 16 || value.status == 15) {
                // $("#tanka_" + index).removeAttr("disabled");
                $("#delivery_suryo_" + index).removeAttr("disabled");
              }
            }
          });
        }
    }
    this.validateInteger = function(number) {
        var re = /^([0-9]*)$/;
        return re.test(number);
      }
    this.changeStatus = function(e){
        var checkStatus = e.target.checked;
        var index = e.target.attributes.index.value;
        if(checkStatus == true){

            // $("#comment_cst1_" + index).removeAttr("disabled");
            // $("#delivery_scheduled_date_" + index).removeAttr("disabled");
        } 
        if(checkStatus == false) {
            // var old_comment = $("#comment_cst1_" + index + '_old').val();
            // var old_date = $("#delivery_scheduled_date_" + index + '_old').val();
            // $("#comment_cst1_" + index).val(old_comment);
            // $("#comment_cst1_" + index).attr("disabled","true");
            // $("#delivery_scheduled_date_" + index).val(old_date);
            // $("#delivery_scheduled_date_" + index).attr("disabled","true");
        }
    }
    this.checkTotalDeliverySuryo = function(data){

      var url_check = URL_API + '/api/check_total_delivery_suryo';
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var query_check = [];
      query_check.push('token=' + accessTokenCognito);
      url_check += '?' + query_check.join('&');
      var data_check = {
        suryo:data.suryo,
        delivery_suryo: data.delivery_suryo,
        cart_seq_related: data.cart_seq_related
      };

      $.ajax({
          url: url,
          type: 'POST',
          data:{
              data: data
          },
          success: function (res) {
              if(res.status == 100){
                  riot.mount('app','maintain',{ messege:res.messege });
                  return false;
              }
              if(res.message == 'delivery_suryo_too_big') {
                  if(!confirm('still ok ?')){
                  }
              }
          },
          error: function () {
              alert('error');
          }
      });

    }
    this.postCartDelete = function(e){
      
      var index = $(e.target).attr('index');
      var data = thisTag.list_cart[index];
      var raw_current_date = new Date();
      var date = raw_current_date.getDate() ;
      var month = raw_current_date.getMonth() + 1;
      var year = raw_current_date.getFullYear();
      var minutes = raw_current_date.getMinutes();
      var second = raw_current_date.getSeconds();
      var hour = raw_current_date.getHours();
      var current_date = year + "/" + ((month < 10) ? "0":"") + month + "/" + ((date < 10) ? "0":"") + date + " " + ((hour < 10) ? "0":"") + hour + ":" + ((minutes < 10) ? "0":"") + minutes + ":" + ((second < 10) ? "0":"") + second;
      
      var listCart = [];

      var status = data.status;
      var arrCart = {
            table: data.table,
            cart_seq: data.cart_seq,
            delivery_scheduled_date: data.delivery_scheduled_date,
            acceptance_date: current_date,
            comment_cst1: data.comment_cst1,
            tanka: data.tanka,
            delivery_suryo: data.delivery_suryo,
            status: 99,
            //===
            suryo: data.suryo,
            dealer_co_cd: data.dealer_co_cd,
            customer_co_cd: data.customer_co_cd,
            teika_tanka:data.teika_tanka,
            supp_sku: data.supp_sku,
            item_name: data.item_name,
            capacity: data.capacity,
            kikaku: data.kikaku,
            maker_name: data.maker_name,
            supp_co_cd: data.supp_co_cd,
            deliverydate: data.deliverydate,
            comment_usr: data.comment_usr,
            customer_use_code_1: data.customer_use_code_1,
            customer_use_code_2: data.customer_use_code_2,
            customer_kikanname: data.customer_kikanname,
            customer_sosikiname: data.customer_sosikiname,
            customer_tanto: data.customer_tanto,
            customer_email: data.customer_email,
            nonyu_zip: data.nonyu_zip,
            nonyu_address1: data.nonyu_address1,
            nonyu_address2: data.nonyu_address2,
            address_flag: data.address_flag
          };
          listCart.push(arrCart);
      var url = URL_API + '/api/cart/create';
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var query = [];
      query.push('token=' + accessTokenCognito);
      url += '?' + query.join('&');

      if(!confirm(' 注文管理番号：' + data.cart_seq + '　のオーダーを取り消します。お客様側の注文履歴からも削除されます。よろしいですか？')){
        return false;
      }

      $.ajax({
          url: url,
          type: 'POST',
          data:{
          data: listCart
          },
          success: function (res) {
              if(res.status == 100){
                  riot.mount('app','maintain',{ messege:res.messege });
                  return false;
              }
              if(res.message == 'success'){
                  alert('更新しました。');
                  var page = 1;
                  thisTag.searchCart(page);
              } else if(res.message == 'errors') {
                  alert('errors');
              }
          },
          error: function () {
              alert('error');
          }
      });
    }

    this.postCartLink = function(e){

        if(!confirm('受入検収を代行します。')){
          return false;
        }
        var data = e.item.item; 
        var raw_current_date = new Date();
        var date = raw_current_date.getDate() ;
        var month = raw_current_date.getMonth() + 1;
        var year = raw_current_date.getFullYear();
        var minutes = raw_current_date.getMinutes();
        var second = raw_current_date.getSeconds();
        var hour = raw_current_date.getHours();
        var current_date = year + "/" + ((month < 10) ? "0":"") + month + "/" + ((date < 10) ? "0":"") + date + " " + ((hour < 10) ? "0":"") + hour + ":" + ((minutes < 10) ? "0":"") + minutes + ":" + ((second < 10) ? "0":"") + second;
        var url = URL_API + '/api/cart/create';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        var query = [];
        query.push('token=' + accessTokenCognito);
        url += '?' + query.join('&');

        var listCart = [];
        var arrCart = {
            table: data.table,
            cart_seq: data.cart_seq,
            //delivery_scheduled_date: data.delivery_scheduled_date,
            acceptance_date: current_date,
            comment_cst1: data.comment_cst1,
            tanka: data.tanka,
            status: 31,
            inquiry: data.inquiry,
            //===
            suryo: data.suryo,
            dealer_co_cd: data.dealer_co_cd,
            customer_co_cd: data.customer_co_cd,
            teika_tanka:data.teika_tanka,
            supp_sku: data.supp_sku,
            delivery_suryo: data.delivery_suryo,
            item_name: data.item_name,
            capacity: data.capacity,
            kikaku: data.kikaku,
            maker_name: data.maker_name,
            supp_co_cd: data.supp_co_cd,
            deliverydate: data.deliverydate,
            comment_usr: data.comment_usr,
            customer_use_code_1: data.customer_use_code_1,
            customer_use_code_2: data.customer_use_code_2,
            customer_kikanname: data.customer_kikanname,
            customer_sosikiname: data.customer_sosikiname,
            customer_tanto: data.customer_tanto,
            customer_email: data.customer_email,
            nonyu_zip: data.nonyu_zip,
            nonyu_address1: data.nonyu_address1,
            nonyu_address2: data.nonyu_address2,
            address_flag: data.address_flag
        };

        listCart.push(arrCart);


        $.ajax({
            url: url,
            type: 'POST',
            data:{
                data: listCart,
                screen: 's11',
                cart_link: 0
            },
            success: function (res) {
                if(res.status == 100){
                    riot.mount('app','maintain',{ messege:res.messege });
                    return false;
                }
                if(res.message == 'success'){
                    var page = 1;
                    thisTag.searchCart(page);
                } else if(res.message == 'errors') {
                    alert('errors');
                }
            },
            error: function () {
                alert('error');
            }
        });
    }

    this.postCart = function(e) {

      // if(!$(".checkbox_status").is(":checked")){
      //   alert("注文を選択してください。");
      //   return false;
      // }
      var vl_status = $("#check_cart option:selected").data("status");
      if (thisTag.total == 0) {
        alert("カートが存在しません。");
        return false;
      }
      var item_sku_exist = true;
      var is_deleted = false;
      var listCart = [];
      var status = $('#check_cart').val();
      var status_text = $("#check_cart option:selected").data("st");
      var raw_current_date = new Date();
      var date = raw_current_date.getDate();
      var month = raw_current_date.getMonth() + 1;
      var year = raw_current_date.getFullYear();
      var minutes = raw_current_date.getMinutes();
      var second = raw_current_date.getSeconds();
      var hour = raw_current_date.getHours();
      var current_date = year + "/" + ((month < 10) ? "0" : "") + month + "/" + ((date < 10) ? "0" : "") + date + " " + ((hour < 10) ? "0" : "") + hour + ":" + ((minutes < 10) ? "0" : "") + minutes + ":" + ((second < 10) ? "0" : "") + second;
      // for (i = 0; i < thisTag.total; i++) {
      var errDeliverySuryo = [];
      var errDeliveryScheduledDate = [];
      var errDeliveryDate = [];
      var errTanka = [];
      var error = [];
      var list_download_checkbox = thisTag.list_download_checkbox;
      var comment_cst1_max_error = 0;
      if (status == '1') {
        var find = '/';
        var re = new RegExp(find, 'g');
        var status_select = $("#status_select").val();
        var start_date = $(".order_start_date").val().replace(re, '-');
        var end_date = $(".order_end_date").val().replace(re, '-');
        var customer_co_cd = thisTag.customer_co_cd_select;
        var customer_dep_cd = $('#customer_dep_cd_select').val();
        var page_url = thisTag.linkDownload + '/api/s11/download?token=' + thisTag.accessTokenCognito + '&status=' + status_select + '&start_date=' + start_date + '&end_date=' + end_date + '&customer_co_cd=' + customer_co_cd + '&customer_dep_cd=' + customer_dep_cd + '&list_download=' + list_download_checkbox;
        var currentdate = new Date();
        var date = ((currentdate.getDate() < 10) ? "0" : "") + currentdate.getDate();
        var month = (((currentdate.getMonth() + 1) < 10) ? "0" : "") + (currentdate.getMonth() + 1);
        var year = currentdate.getFullYear();
        var hour = ((currentdate.getHours() < 10) ? "0" : "") + currentdate.getHours();
        var minutes = ((currentdate.getMinutes() < 10) ? "0" : "") + currentdate.getMinutes();
        var second = ((currentdate.getSeconds() < 10) ? "0" : "") + currentdate.getSeconds();
        var req = new XMLHttpRequest();
        req.open("GET", page_url, true);

        req.responseType = "blob";
        req.onreadystatechange = function () {
          if (req.readyState === 4 && req.status === 200) {
            var filename = '受注履歴_' + year + month + date + hour + minutes + second + '.csv';
            if (typeof window.chrome !== 'undefined') {
              // Chrome version
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(req.response);
              link.download = filename;
              link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
              // IE version
              var blob = new Blob([req.response], {type: 'application/force-download'});
              window.navigator.msSaveBlob(blob, filename);
            } else {
              // Firefox version
              var file = new File([req.response], filename, {type: 'application/force-download'});
              window.open(URL.createObjectURL(file));
            }
          }
        };
        req.send();
      } else {
        $.each(thisTag.list_cart, function (i, e) {
          var table = e['table'];
          var cartSeq = $('#cart_seq_' + i).val();
          var delivery_scheduled_date = $("#delivery_scheduled_date_" + i).val();
          var delivery_date = $("#delivery_date_" + i).val();
          var comment_cst1 = $('#comment_cst1_' + cartSeq).val();
          var suryo = $("#suryo_" + i).val();
          var delivery_suryo = $("#delivery_suryo_" + i).val();
          var tanka = $("#tanka_" + i).val();
          // ====
          var old_tanka = e['tanka'];
          var teika_tanka = e['teika_tanka'];
          var supp_sku = e['supp_sku'];
          var item_name = e['item_name'];
          var capacity = e['capacity'];
          var kikaku = e['kikaku'];
          var maker_name = e['maker_name'];
          var supp_co_cd = e['supp_co_cd'];
          var deliverydate = e['deliverydate'];
          var comment_usr = e['comment_usr'];
          var customer_use_code_1 = e['customer_use_code_1'];
          var customer_use_code_2 = e['customer_use_code_2'];
          var dealer_co_cd = e['dealer_co_cd'];
          var dealer_dep_cd = e['dealer_dep_cd'];
          var customer_co_cd = e['customer_co_cd'];
          var customer_dep_cd = e['customer_dep_cd'];
          var ec_users_id = e['ec_users_id'];
          var inquiry = e['inquiry'];
          var supp_name = e['supp_name'];
          var customer_use_code_3 = e['customer_use_code_3'];
          var customer_use_code_4 = e['customer_use_code_4'];
          var customer_use_code_5 = e['customer_use_code_5'];
          var item_sku = e['item_sku'];
          var order_date = e['order_date'];
          var delivery_suryo_rest = 0;
          if (e['delivery_suryo_rest'] !== 'undefined') {
            delivery_suryo_rest = e['delivery_suryo_rest'];
          }
          // var teika_tanka = suryo * tanka;
          // var delivery_date = current_date;
          var return_acceptance_date = current_date;
          var cancellation_acceptance_date = current_date;
          var acceptance_date = current_date;
          var customer_kikanname = e['customer_kikanname'];
          var customer_sosikiname = e['customer_sosikiname'];
          var customer_tanto = e['customer_tanto'];
          var customer_email = e['customer_email'];
          var nonyu_zip = e['nonyu_zip'];
          var nonyu_address1 = e['nonyu_address1'];
          var nonyu_address2 = e['nonyu_address2'];
          var address_flag = e['address_flag'];
          var arrCart = [];

          if ($("#checkbox_status_" + i).is(":checked")) {
            if (tanka.trim() == '') {
              $("#tanka_" + i).val("");
              errTanka.push('empty');
            }
            if (status === '7' || status === '4,12,15,16') {
              if (delivery_scheduled_date.trim() == '') {
                $("#delivery_scheduled_date_" + i).val("");
                errDeliveryScheduledDate.push('empty');
              }
              // ===================================

            }
            if (delivery_suryo.trim() == '' && status !== '4,12') {
              $("#delivery_suryo_" + i).val("");
              errDeliverySuryo.push('empty');
            }
            // if(status === '7') {
            //   if(delivery_date.trim() == ''){
            //       $("#delivery_date_" + i ).val("");
            //       errDeliveryDate.push('empty');
            //   }
            // }
            if (delivery_suryo.trim() != '' && !thisTag.validateInteger(delivery_suryo)) {
              $("#delivery_suryo_" + i).val(e['delivery_suryo']);
              errDeliverySuryo.push('integer');
            }
            if (parseInt(delivery_suryo) > parseInt(suryo)) {
              $("#delivery_suryo_" + i).val(e['delivery_suryo']);
              errDeliverySuryo.push('bigger');
            }
            if (parseInt(delivery_suryo_rest) > 0) {
              if (parseInt(delivery_suryo) > parseInt(delivery_suryo_rest)) {
                $("#delivery_suryo_" + i).val(e['delivery_suryo']);
                errDeliverySuryo.push('bigger');
              }
            }
            if (status === '7' && delivery_date.trim() == '' ) {
              errDeliveryDate.push('empty_delivery_date');
            }
            if (e['is_deleted'] == 1) {
              is_deleted = true;
            }
            if (!e['item_sku_exist'] && e['inquiry'] != 1) {
              item_sku_exist = false;
            }
            if($('#comment_cst1_' + cartSeq).val().length >= 200){
                comment_cst1_max_error++;
            }

            switch (status) {
              case '4,12,15,16':
                arrCart = {
                  table: table,
                  cart_seq: cartSeq,
                  delivery_scheduled_date: delivery_scheduled_date,
                  comment_cst1: comment_cst1,
                  tanka: tanka,
                  delivery_suryo: delivery_suryo,
                  status: 7,
                  checked: 0,
                  inquiry: inquiry,
                  supp_name: supp_name,
                  //===
                  suryo: suryo,
                  dealer_co_cd: dealer_co_cd,
                  customer_co_cd: customer_co_cd,
                  teika_tanka: teika_tanka,
                  supp_sku: supp_sku,
                  item_name: item_name,
                  capacity: capacity,
                  kikaku: kikaku,
                  maker_name: maker_name,
                  supp_co_cd: supp_co_cd,
                  deliverydate: deliverydate,
                  comment_usr: comment_usr,
                  customer_use_code_1: customer_use_code_1,
                  customer_use_code_2: customer_use_code_2,
                  customer_kikanname: customer_kikanname,
                  customer_sosikiname: customer_sosikiname,
                  customer_tanto: customer_tanto,
                  customer_email: customer_email,
                  nonyu_zip: nonyu_zip,
                  nonyu_address1: nonyu_address1,
                  nonyu_address2: nonyu_address2,
                  address_flag: address_flag
                };
                listCart.push(arrCart);

                // check delivery
                if (parseInt(delivery_suryo) > 0 && parseInt(delivery_suryo_rest) > 0 && parseInt(delivery_suryo_rest) > parseInt(delivery_suryo)) {
                  if (e['cart_seq_related']) {
                    cartSeq = e['cart_seq_related'];
                  }
                  arrCart = {
                    is_delivery: 1,
                    table: table,
                    cart_seq_related: cartSeq,
                    tanka: tanka,
                    status: 4,
                    inquiry: inquiry,
                    supp_name: supp_name,
                    //===
                    suryo: suryo,
                    order_date: order_date,
                    dealer_co_cd: dealer_co_cd,
                    dealer_dep_cd: dealer_dep_cd,
                    customer_co_cd: customer_co_cd,
                    customer_dep_cd: customer_dep_cd,
                    teika_tanka: teika_tanka,
                    supp_sku: supp_sku,
                    item_sku: item_sku,
                    item_name: item_name,
                    capacity: capacity,
                    kikaku: kikaku,
                    maker_name: maker_name,
                    supp_co_cd: supp_co_cd,
                    ec_users_id: ec_users_id,
                    deliverydate: deliverydate,
                    comment_usr: comment_usr,
                    customer_use_code_1: customer_use_code_1,
                    customer_use_code_2: customer_use_code_2,
                    customer_use_code_3: customer_use_code_3,
                    customer_use_code_4: customer_use_code_4,
                    customer_use_code_5: customer_use_code_5,
                    customer_kikanname: customer_kikanname,
                    customer_sosikiname: customer_sosikiname,
                    customer_tanto: customer_tanto,
                    customer_email: customer_email,
                    nonyu_zip: nonyu_zip,
                    nonyu_address1: nonyu_address1,
                    nonyu_address2: nonyu_address2,
                    address_flag: address_flag
                  };
                  listCart.push(arrCart);
                }
                break;
              case '4,12':
                arrCart = {
                  table: table,
                  cart_seq: cartSeq,
                  delivery_scheduled_date: delivery_scheduled_date,
                  comment_cst1: comment_cst1,
                  tanka: tanka,
                  delivery_suryo: delivery_suryo,
                  status: 15,
                  checked: 0,
                  inquiry: inquiry,
                  supp_name: supp_name,
                  //===
                  suryo: suryo,
                  dealer_co_cd: dealer_co_cd,
                  customer_co_cd: customer_co_cd,
                  teika_tanka: teika_tanka,
                  supp_sku: supp_sku,
                  item_name: item_name,
                  capacity: capacity,
                  kikaku: kikaku,
                  maker_name: maker_name,
                  supp_co_cd: supp_co_cd,
                  deliverydate: deliverydate,
                  comment_usr: comment_usr,
                  customer_use_code_1: customer_use_code_1,
                  customer_use_code_2: customer_use_code_2,
                  customer_kikanname: customer_kikanname,
                  customer_sosikiname: customer_sosikiname,
                  customer_tanto: customer_tanto,
                  customer_email: customer_email,
                  nonyu_zip: nonyu_zip,
                  nonyu_address1: nonyu_address1,
                  nonyu_address2: nonyu_address2,
                  address_flag: address_flag
                };
                listCart.push(arrCart);
                break;
              case '5':
                arrCart = {
                  table: table,
                  cart_seq: cartSeq,
                  delivery_scheduled_date: delivery_scheduled_date,
                  comment_cst1: comment_cst1,
                  cancellation_acceptance_date: cancellation_acceptance_date,
                  tanka: tanka,
                  delivery_suryo: delivery_suryo,
                  status: 6,
                  checked: 0,
                  inquiry: inquiry,
                  supp_name: supp_name,
                  //===
                  suryo: suryo,
                  dealer_co_cd: dealer_co_cd,
                  customer_co_cd: customer_co_cd,
                  teika_tanka: teika_tanka,
                  supp_sku: supp_sku,
                  item_name: item_name,
                  capacity: capacity,
                  kikaku: kikaku,
                  maker_name: maker_name,
                  supp_co_cd: supp_co_cd,
                  deliverydate: deliverydate,
                  comment_usr: comment_usr,
                  customer_use_code_1: customer_use_code_1,
                  customer_use_code_2: customer_use_code_2,
                  customer_kikanname: customer_kikanname,
                  customer_sosikiname: customer_sosikiname,
                  customer_tanto: customer_tanto,
                  customer_email: customer_email,
                  nonyu_zip: nonyu_zip,
                  nonyu_address1: nonyu_address1,
                  nonyu_address2: nonyu_address2,
                  address_flag: address_flag
                };
                listCart.push(arrCart);
                break;
              case '7':
                if (vl_status == "1") {
                  arrCart = {
                    table: table,
                    cart_seq: cartSeq,
                    delivery_scheduled_date: "",
                    comment_cst1: comment_cst1,
                    delivery_date: "",
                    status: 4,
                    checked: 0,
                    inquiry: inquiry,
                    supp_name: supp_name,
                    //===
                    suryo: suryo,
                    dealer_co_cd: dealer_co_cd,
                    customer_co_cd: customer_co_cd,
                    delivery_suryo: "",
                    tanka: old_tanka,
                    teika_tanka: teika_tanka,
                    supp_sku: supp_sku,
                    item_name: item_name,
                    capacity: capacity,
                    kikaku: kikaku,
                    maker_name: maker_name,
                    supp_co_cd: supp_co_cd,
                    comment_usr: comment_usr,
                    customer_use_code_1: customer_use_code_1,
                    customer_use_code_2: customer_use_code_2,
                    customer_kikanname: customer_kikanname,
                    customer_sosikiname: customer_sosikiname,
                    customer_tanto: customer_tanto,
                    customer_email: customer_email,
                    nonyu_zip: nonyu_zip,
                    nonyu_address1: nonyu_address1,
                    nonyu_address2: nonyu_address2,
                    address_flag: address_flag
                  };
                } else {
                  arrCart = {
                    table: table,
                    cart_seq: cartSeq,
                    delivery_scheduled_date: delivery_scheduled_date,
                    comment_cst1: comment_cst1,
                    delivery_date: delivery_date ? delivery_date : current_date,
                    status: 30,
                    checked: 0,
                    inquiry: inquiry,
                    supp_name: supp_name,
                    //===
                    suryo: suryo,
                    dealer_co_cd: dealer_co_cd,
                    customer_co_cd: customer_co_cd,
                    delivery_suryo: delivery_suryo,
                    tanka: old_tanka,
                    teika_tanka: teika_tanka,
                    supp_sku: supp_sku,
                    item_name: item_name,
                    capacity: capacity,
                    kikaku: kikaku,
                    maker_name: maker_name,
                    supp_co_cd: supp_co_cd,
                    comment_usr: comment_usr,
                    customer_use_code_1: customer_use_code_1,
                    customer_use_code_2: customer_use_code_2,
                    customer_kikanname: customer_kikanname,
                    customer_sosikiname: customer_sosikiname,
                    customer_tanto: customer_tanto,
                    customer_email: customer_email,
                    nonyu_zip: nonyu_zip,
                    nonyu_address1: nonyu_address1,
                    nonyu_address2: nonyu_address2,
                    address_flag: address_flag
                  };
                }
                listCart.push(arrCart);
                break;
              case '8':
                arrCart = {
                  table: table,
                  cart_seq: cartSeq,
                  delivery_scheduled_date: delivery_scheduled_date,
                  comment_cst1: comment_cst1,
                  return_acceptance_date: return_acceptance_date,
                  status: 9,
                  checked: 0,
                  inquiry: inquiry,
                  supp_name: supp_name,
                  //===
                  suryo: suryo,
                  dealer_co_cd: dealer_co_cd,
                  customer_co_cd: customer_co_cd,
                  delivery_suryo: delivery_suryo,
                  teika_tanka: teika_tanka,
                  tanka: old_tanka,
                  supp_sku: supp_sku,
                  item_name: item_name,
                  capacity: capacity,
                  kikaku: kikaku,
                  maker_name: maker_name,
                  supp_co_cd: supp_co_cd,
                  deliverydate: deliverydate,
                  comment_usr: comment_usr,
                  customer_use_code_1: customer_use_code_1,
                  customer_use_code_2: customer_use_code_2,
                  customer_kikanname: customer_kikanname,
                  customer_sosikiname: customer_sosikiname,
                  customer_tanto: customer_tanto,
                  customer_email: customer_email,
                  nonyu_zip: nonyu_zip,
                  nonyu_address1: nonyu_address1,
                  nonyu_address2: nonyu_address2,
                  address_flag: address_flag
                };
                listCart.push(arrCart);
                break;
              default:
            }

          }
          if ($("#checkbox_status_" + i).not(":checked")) {
            // arrCart = {
            //     cart_seq: cartSeq,
            //     tanka: tanka,
            //     delivery_scheduled_date: delivery_scheduled_date,
            //     comment_cst1: comment_cst1
            // };
            // listCart.push(arrCart);
          }
        });

        if (!listCart.length) {
          alert("更新データにチェックを入れてください");
          return false;

        }

        var arrNewErr = [];
        if (!item_sku_exist) {
          arrNewErr.push("存在しない商品が含まれています。\n");
        }
        if (is_deleted) {
          arrNewErr.push("販売中止された商品が含まれています。\n");
        }
        if (vl_status == 0) {
          if (errDeliverySuryo.indexOf('empty') >= 0) {
            arrNewErr.push("納入数量は入力必須です。\n");
          }
          if (errDeliverySuryo.indexOf('bigger') >= 0) {
            arrNewErr.push("注文数量よりも小さい値を入力してください。\n");
          }
          if (errDeliverySuryo.indexOf('integer') >= 0) {
            arrNewErr.push("納入数量を正数で入力してください。\n");
          }
        }
        if (errDeliveryDate.indexOf('empty') >= 0) {
          arrNewErr.push('納品日は入力必須です。\n');
        }
        if(status_text==0){
          if (errDeliveryScheduledDate.indexOf('empty') >= 0) {
            arrNewErr.push('納品予定日は入力必須です。\n');
          }
        }

        if (errTanka.indexOf('empty') >= 0) {
          arrNewErr.push("納入価額は入力必須です。\n");
        }
        if(comment_cst1_max_error){
          arrNewErr.push("お客様へコメントを200文字以内で入れてください。\n");
        }
        if (arrNewErr.length > 0) {
          alert(arrNewErr.join(''));
          return false;
        }
        if(status_text==1){
          if (errDeliveryScheduledDate.indexOf('empty') >= 0) {
            //arrNewErr.push('納品予定日は入力必須です。\n');
             if(!confirm("納品予定日が未入力です。処理を継続しますか")) {
               return false;
            }
          }
        }
        if (errDeliveryDate.indexOf('empty_delivery_date') >= 0) {
          if(!confirm('納品日が未入力です。納品日には当日日付を設定します。\n 処理を継続しますか。')){
            return false;
          }
        }
        var url = URL_API + '/api/cart/create';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        var query = [];
        query.push('token=' + accessTokenCognito);
        url += '?' + query.join('&');
        console.log(JSON.stringify(listCart));
        $.ajax({
          url: url,
          type: 'POST',
          data: {
            data: listCart,
            screen: 's11'
          },
          success: function (res) {
            if (res.status == 100) {
              riot.mount('app', 'maintain', {messege: res.messege});
              return false;
            }
            if (res.message == 'success') {
              alert('更新しました。');
              var page = 1;
              thisTag.searchCart(page);
            } else if (res.message == 'errors') {
              alert('errors');
            }
          },
          error: function () {
            alert('error');
          }
        });
      }
    }

    this.searchCart = function(page){
        var status = $("#status_select").val();
        var customer_co_cd = thisTag.customer_co_cd_select;
        var customer_dep_cd = thisTag.customer_dep_cd_select;
        var order_date_s11 = $("#orderdate_select").val();
        var order_start_date = $(".order_start_date").val();
        var order_end_date = $(".order_end_date").val();
        switch(status) {
            case '0':
                thisTag.statusSelected = [4,5,6,7,8,9,30,31,12,15,16];
                break;
            case '4,12':
                thisTag.statusSelected = [4,12];
                break;
            case '5':
                thisTag.statusSelected = 5;
                break;
            case '6':
                thisTag.statusSelected = 6;
                break;
            case '7':
                thisTag.statusSelected = 7;
                break;
            case '8':
                thisTag.statusSelected = 8;
                break;
            case '9':
                thisTag.statusSelected = 9;
                break;
            case '30':
                thisTag.statusSelected = 30;
                break;
            case '31':
                thisTag.statusSelected = 31;
                break;
            case '15':
                thisTag.statusSelected = 15;
                break;
            case '16':
                thisTag.statusSelected = 16;
                break;
            default:
        }

        var screen = 's11';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        var url = URL_API + '/api/cart/list';
        var querySuggest = [];

        querySuggest.push('token=' + accessTokenCognito);
        querySuggest.push('status=' + thisTag.statusSelected);
        querySuggest.push('screen=' + screen);
        querySuggest.push('page=' + page);
        if(order_start_date != ''){
          querySuggest.push('order_start_date=' + order_start_date);
        }
        if(order_end_date != ''){
          querySuggest.push('order_end_date=' + order_end_date);
        }
        if(customer_co_cd != ''){
          querySuggest.push('customer_co_cd=' + customer_co_cd);
        }
        if(customer_dep_cd != ''){
          querySuggest.push('customer_dep_cd=' + customer_dep_cd);
        }
        // if(order_date_s11 != ''){
        //   querySuggest.push('order_date_s11=' + order_date_s11);
        // }
        
        // querySuggest.push('order_order_date=' + order_order_date);
        url += '?' + querySuggest.join('&');

        $.ajax({
            url: url,
            type: 'GET',
            timeout: 60000,
            success: function(data){
                if(data.status == 100){
                    riot.mount('app','maintain',{ messege:data.messege });
                    return false;
                }
                if(data.message == 'success'){
                    
                    var totalPages = Math.ceil(data.total/LIMIT_ON_PAGE);
                    thisTag.total_page = totalPages;
                    var visiblePages = 1;
                    if(totalPages != 0){
                        visiblePages =  5;
                    } 
                    var $pagination = $('#pagination_s11');
                    $pagination.twbsPagination('destroy');
                    $pagination.twbsPagination({
                        totalPages: totalPages,
                        visiblePages: visiblePages,
                        startPage: page,
                        initiateStartPageClick: false,
                        onPageClick: function (event, page) {
                            thisTag.currentPage = page;
                            thisTag.searchCart(page);
                        }
                    });

                    thisTag.list_cart = data.cart_list;
                    thisTag.update({
                      list_dep: data.list_dep
                    });
                    $.each($('#customer_dep_cd_select').children('option'), function(i, val) {
                      if($(val).val() == thisTag.customer_dep_cd_select) {
                          $(val).prop('selected', true);
                      }
                    });
                    thisTag.navigation_list_cus_use_code = data.navigation_list;
                    thisTag.update(thisTag.navigation_list_cus_use_code);
                    thisTag.update(thisTag.list_cart);
                    thisTag.testCheckStatus("#check_cart");
                    thisTag.pickDateTime();
                    thisTag.checkIfFirstPage();
                    thisTag.checkIfLastPage();
                    updateDeliveryAddress();
                    $('.commentOpen').on('click',function(){
                      if($(this).hasClass('active')){
                        $(this).removeClass('active').html('お客様より<i class="fa fa-commenting-o"></i>');
                        $(this).next('.text').hide();
                      }else{
                        $(this).addClass('active').html('閉じる<i class="fa fa-times"></i>');
                        $(this).next('.text').show();
                      }
                    });
                    $('.commentToDealerOpen').on('click',function(){
                      if($(this).hasClass('active')){
                        $(this).removeClass('active').html('お客様からの回答<i class="fa fa-commenting-o"></i>');
                        $(this).next('.text').hide();
                      }else{
                        $(this).addClass('active').html('閉じる<i class="fa fa-times"></i>');
                        $(this).next('.text').show();
                      }
                    });
                    $.each(thisTag.list_cart,function(i,e){
                        riot.tag('description', '', function(opts) {   
                            this.root.innerHTML = opts.r;
                        });
                        riot.mount('#description_' + i, {
                            r: e.comment_spp
                        })
                        riot.mount('#description_comment_to_dealer_' + i, {
                            r: e.comment_to_dealer
                        });
                        thisTag.update();
                    });
                } else {
                    alert("fail");
                }

            },
            error: function (xhr, stt, err) {
                alert('error');
            }
        });
    }

    this.companiesSuggest = function(e) {
      var status = $("#status_select").val();
      switch(status) {
          case '0':
              thisTag.statusSelected = [4,5,6,7,8,9,30,31,12,15,16];
              break;
          case '4,12':
              thisTag.statusSelected = [4,12];
              break;
          case '5':
              thisTag.statusSelected = 5;
              break;
          case '6':
              thisTag.statusSelected = 6;
              break;
          case '7':
              thisTag.statusSelected = 7;
              break;
          case '8':
              thisTag.statusSelected = 8;
              break;
          case '9':
              thisTag.statusSelected = 9;
              break;
          case '30':
              thisTag.statusSelected = 30;
              break;
          case '31':
              thisTag.statusSelected = 31;
              break;
          case '15':
              thisTag.statusSelected = 15;
              break;
          case '16':
              thisTag.statusSelected = 16;
              break;
          default:
      }
      var query = [];
      var url = URL_API + '/api/cart/companies_suggest';
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      query.push('token=' + accessTokenCognito);
      query.push('status=' + thisTag.statusSelected);
      query.push('screen=s11');
      url += '?' + query.join('&');
      $.ajax({
          url: url,
          type: 'GET',
          success: function (res) {
              if(res.status == 100){
                  riot.mount('app','maintain',{ messege:res.messege });
                  return false;
              }
              thisTag.update({list_companies_suggest_search: res.cust_list});
              updateDeliveryAddress();
              thisTag.getListSuggestCompanies();
          },
          error: function () {
              alert('error');
          }
      });
      thisTag.update({list_download_checkbox: []});
    }

    this.updateCart = function(e) {
      var index = $(e.target).attr('index');
      var cart_seq = $('#cart_seq_' + index).val();
      if($('#comment_cst1_' + cart_seq).val().length >= 200){
        alert("お客様へコメントを200文字以内で入れてください。");
        return false;
      }
      if(!confirm("納品予定日・納入日・お客様へのコメントのみ修正可能です。このまま修正してよろしいですか？")) {
        return false;
      }
      var delivery_scheduled_date = $('#delivery_scheduled_date_' + index).val();
      var comment_cst1 = $('#comment_cst1_' + cart_seq).val();
      var delivery_date = $('#delivery_date_' + index).val();
      var data = {
        cart_seq: cart_seq,
        delivery_scheduled_date: delivery_scheduled_date,
        comment_cst1: comment_cst1
      }
      if(typeof delivery_date != 'undefined') {
        data.delivery_date = delivery_date
      }
      var url = URL_API + '/api/cart/update_single_cart';
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var query = [];
      query.push('token=' + accessTokenCognito);
      query.push('screen=s11');
      url += '?' + query.join('&');
      $.ajax({
          url: url,
          type: 'POST',
          data: data,
          success: function (res) {
            if(res.status == 100){
                riot.mount('app','maintain',{ messege:res.messege });
                return false;
            }
            if(res.message == 'success'){
                alert('更新しました。');
            } else if(res.message == 'errors') {
                alert('errors');
            }
          },
          error: function () {
              alert('error');
          }
      });
    }
    
    this.getListSuggestCompanies = function() {
      let list = thisTag.list_companies_suggest_search;
      let res = [];
      for (var i = 0; i <= list.length - 1; i++) {
        res.push({value: list[i].label, label: list[i].label, comp_index: i});
      }
      $("#customer_co_cd_select").autocompleter("destroy");
      $('#customer_co_cd_select').autocompleter({ 
        limit:10000,
        highlightMatches:true, 
        source: res, 
        callback: function(value, index, object) {
          if($("#customer_co_cd_select").val() != '' && thisTag.list_companies_suggest_search[object.comp_index].comp_code) {
            thisTag.update({customer_co_cd_select: thisTag.list_companies_suggest_search[object.comp_index].comp_code});
            if($('#customer_co_cd_select').val().length > 14){
              $(".top-wrapper").css("display","block");
              $(".filters").css("width","100%");
              $(".check-box").css("float","right");
              $(".green-btn").css("margin","5px");
            }else{
              $(".top-wrapper").css("display","flex");
              $(".filters").css("width","55%");
              $(".green-btn").css("margin","0px");
            }
          } else {
            thisTag.update({customer_co_cd_select: ''});
          }
          thisTag.update({list_download_checkbox: []});
        }
      });
    }
    </script>

  <script>
    DatepickerIntialize();
    $(function() {
      $(document).on('keyup', '.comment_cst1', function() {
        // $(this).val() // get the current value of the input field.
        var id = $(this).attr('id');
        var idExtract = id.split('_');
        var index = idExtract[idExtract.length - 1];
        var thisVal = $(this).val();
        // set the counter
        $('#comment_cst1_count_'+index).text(thisVal.length);
        if( thisVal.length >= 200 ) {
              $('#comment_cst1_color_'+index).css('color', 'red');
        } else {
            $('#comment_cst1_color_'+index).css('color', '');
        }
      });
    });
  </script>
  <script>
    DatepickerHoliday();
  </script>

</order-history-s>
