<order-history-s-mc>
    <link rel="stylesheet" href="css/S22.css">
     <style type="text/css">
      .link-download {
        padding: 3px 6px;
        border-radius: 2px;
        text-shadow: 1px 1px 0px rgba(255,255,255,0.3);
        white-space: nowrap;
        background: -moz-linear-gradient(top, #fcfcfc 1%, #efefef 50%, #e8e8e8 50%, #dddddd 100%);
        background: -webkit-linear-gradient(top, #fcfcfc 1%,#efefef 50%,#e8e8e8 50%,#dddddd 100%);
        background: linear-gradient(to bottom, #fcfcfc 1%,#efefef 50%,#e8e8e8 50%,#dddddd 100%);
        filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#dddddd',GradientType=0 );
        user-select:none;
        border: 1px solid #888;
      }
      .s22 dl dt,.s22 dl dd {
        display: inline-block;
      }
      .s22 dl dt {
        width: 100px;
        text-align: right;
      }
      .s22 dl dd {
        width: 200px;
      }
      .s22 label {
        cursor: pointer;
      }
      .prefecture, .maker_dealer_list {
        width: 150px !important;
        display: block;
        margin: 0px auto;
      }

      /*  pop up  */
      .popup {
        position: relative;
        display: inline-block;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      /* The actual popup */
      .popup .popuptext {
        visibility: hidden;
        width: 160px;
        background-color: #555;
        color: #fff;
        text-align: center;
        border-radius: 6px;
        padding: 8px 0;
        position: absolute;
        z-index: 1;
        bottom: 125%;
        left: 50%;
        margin-left: -80px;
      }

      /* Popup arrow */
      .popup .popuptext::after {
        content: "";
        position: absolute;
        top: 100%;
        left: 50%;
        margin-left: -5px;
        border-width: 5px;
        border-style: solid;
        border-color: #555 transparent transparent transparent;
      }

      /* Toggle this class - hide and show the popup */
      .popup .show {
        visibility: visible;
        -webkit-animation: fadeIn 1s;
        animation: fadeIn 1s;
      }

      /* Add animation (fade in the popup) */
      @-webkit-keyframes fadeIn {
        from {opacity: 0;} 
        to {opacity: 1;}
      }

      @keyframes fadeIn {
        from {opacity: 0;}
        to {opacity:1 ;}
      }
    </style>
    <div class="main">
      <div class="content">
        <div class="page-title">
          <h2>受注履歴</h2>
        </div>
        <div class="form-wrapper s22">
          <table>
            <tr>
              <td>
                <dl>
                  <dt>品番</dt>
                  <dd>
                   <input type="text" id="supp_sku">
                  </dd>
                </dl>
              </td>
              <td>
                <dl style="display: inline-block;">
                  <dt>BPM管理番号</dt>
                  <dd style="display: inline;">
                    <input type="text" id="cart_seq_from" style="width: 200px;"> ~ <input type="text" id="cart_seq_to" style="width: 200px;">
                  </dd>
                </dl>
                <dl style="display: inline-block;">
                  <dt>メール</dt>
                  <dd>
                    <ul style="margin-left: 20px;">
                      <li style="display: inline-block;"><label for="nouki_reply_flg_1">送信済</label><input type="checkbox" id="nouki_reply_flg_1" value="1"></li>
                      <li style="display: inline-block;"><label for="nouki_reply_flg_0">未送信</label><input type="checkbox" id="nouki_reply_flg_0" value=""></li>
                    </ul>
                  </dd>
                </dl>
              </td>
            </tr>
            <tr>
              <td>
                <dl>
                  <dt>受注状況</dt>
                  <dd>
                    <select id="dog_status">
                      <option value=""></option>
                      <option value="在庫切">在庫切れ</option>
                      <option value="分納">分納</option>
                      <option value="出荷">出荷済み</option>
                      <option value="未処理">未処理</option>
                    </select>
                  </dd>
                </dl>
              </td>
              <td>
                <dl>
                  <dt>注文期間</dt>
                  <dd style="width: 500px;"><input type="text" placeholder="yyyy/mm/dd" class="order_start_date" > ~ <input type="text" class="order_end_date" placeholder="yyyy/mm/dd"></dd>
                </dl>
                 
              </td>
              <td>
                <button class="search-btn reset-btn" style="margin-right: 50px;"><i class="fa fa-search"></i>検索</button>
              </td>
            </tr>
          </table>
        </div>
        <div class="top-wrapper">
          <div class="select-box">
            <select id="status_select" onchange="{changeStatusSelect}">
              <option value="0" selected>ステータスで絞り込む</option>
              <option value="4">PCA受注データ未作成</option>
              <option value="14">注文書待ち</option>
              <option value="5">キャンセル依頼</option>
              <option value="6">キャンセル済</option>
              <option value="7">PCA受注データ作成済み</option>
              <option value="8">返品依頼受付中</option>
              <option value="9">返品承認済</option>
              <option value="10">返品処理完了</option>
              <option value="30">出荷確定</option>
              <option value="31">受入検収済</option>
              <option value="32">出荷連絡済</option>
            </select>
          </div>
          <!-- <div class="middle-box"><a href="javascript:void(0)" id="popup-s22">出荷データ不一致画面（{ total_diff }件）</a></div> -->
          <div class="check-box">
            <span style="display: none;">チェックした注文を</span>
            <select id="check_cart">
              <option value="4" selected="selected">PCA受注データを作成する</option>
              <option value="14">注文書発行済み受注確定する</option>
              <option value="5">キャンセル承認する</option>
              <option value="comment_cst">コメントを送信する</option>
              <option value="30">出荷連絡メールを送信する</option>
              <option value="30_32_accept_return">返品受付をする</option>
              <option value="8">返品承認する</option>
              <option value="9">返品処理を完了する</option>
              <option value="6_no_mail">キャンセル済みにする（メールなし）</option>
              <option value="dealer_co_dep_cd">販売店確定（ステータス推移なし・メールなし）</option>
              <option value="30_no_mail">出荷確定にする（メールなし）</option>
              <option value="32_no_mail">出荷連絡済みにする（メールなし）</option>
            </select>
            <button onclick="{postCart}">更新</button>
          </div>
        </div>
        <div class="table-wrapper">
          <div style="overflow-y:scroll; height: 600px; width: 101.3%;">
          <table class="blue-table">
            <thead class="header-result">
              <tr>
                <th style="width:83px">注文管理番号</th>
                <th style="width:82px">
                  <div>ご注文日</div>
                  <div>キャンセル/<br>返品依頼日</div>
                </th>
                <th style="width:234px">製品情報</th>
                <th style="width:139px">
                  <div>お客様</div>
                  <!-- <div>コード</div> -->
                </th>
                <th style="width:50px">
                  <div>注文<br>数量</div>
                  <div>納入<br>数量</div>
                </th>
                <th style="width:85px">
                  <div>BPM販売価格</div>
                  <div>BPM仕切価格</div>
                  <div>送料<a class="s22-postage-modal-open"><i class="fa fa-question-circle" style="color: #2E5A8B; font-size:15px; padding:5px;">
                </th>
                <!--  <th style="width:82px">
                   <div>定価</div>
                   <div>仕切価格</div>
                 </th> -->
                <th style="width:57px">
                  <div>受注金額</div>
                </th>
                <!-- <th>
                  <div>希望納期</div>
                  <div>納品予定日</div>
                </th> -->
                <th style="width:190px">
                  <div>販売店</div>
                  <div>販売店選択</div>
                </th>
                <th style="width:150px" colspan="2">
                  販売店とお客様へのコメント
                </th>
                <th style="width:90px">DOG受注状況</th>
                <th style="width:70px">ステータス</th>
                <th style="width:70px">
                  <div>納品日</div>
                  <div>受入検収日</div>
                </th>
                <th style="width:30px"></th>
              </tr>
            </thead>
            <tbody>
              <tr each={item,index in list_cart}>
                <input type="hidden" id="cart_seq_{index}" value="{item.cart_seq}">
                <!--<td>{item.cart_seq_related ? item.cart_seq_related + '\n' + '(' + item.cart_seq + ')': item.cart_seq}</td>-->
                <td style="width:83px">
                  <p>{!item.cart_seq_related ? 'BPM' + item.cart_seq : 'BPM' + item.cart_seq_related}</p>
                  <p>{item.cart_seq_related ? '(' + 'BPM' + item.cart_seq + ')':''}</p>
                  <p><span style="color: red;">{item.check_mb_hatyu == 1 ? '不適合' : ''}</span></p>
                  
                </td>
                <td order_date style="width:82px">
                  <div>{item.order_date}</div>
                  <div>{item.cancellation_request_date} {item.return_request_date}</div>
                </td>
                <td class="left" style="width: 234px">
                  <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 ? 'この商品はカタログから削除されています' : ''}</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.maker_name}</dd>
                  </dl>
                  <dl>
                    <dt>販売元</dt>
                    <dd>{item.supp_co_name}</dd>
                  </dl>
                  <dl>
                    <dd>
                      <b class="discontinued" style="color:red;display:{(item.is_deleted == 1 ) ? 'block' : 'none'}">販売中止</b>
                    </dd>
                  </dl>
                </td>
                <td class="left" style="width: 139px">
                  <div>
                    <!-- <p customer_dep_name>{ item.customer_dep_name }</p>
                    <p customer_business_name>{ item.customer_business_name }</p>
                    <p customer_user_name>{ item.customer_user_name }</p> -->
                    <p kikan_name>{ item.kikan_name }</p>
                    <p shozoku_name>{ item.shozoku_name }</p>
                    <div class="user_info" if={item.name} style="border-top: none;">
                      <a class="user_info_link" id="user_info_{index}_link" index="{index}" onclick="{showUserInfo}">
                        { item.name }
                      </a>
                    </div>
                    
                  </div>
                  <div class="comment-box" if={ item.comment_usr } comment_usr>
                    <a class="commentOpenUsr">メーカー向けコメント<i class="fa fa-commenting-o"></i></a>
                    <div class="text"><description-comment-usr id="description_comment_usr_{index}"></description-comment-usr></div>
                  </div>
                  <div class="comment-box" if={ item.comment_spp } comment_spp>
                    <a class="commentOpenSpp">販売店向けコメント<i class="fa fa-commenting-o"></i></a>
                    <div class="text"><description-comment-spp id="description_comment_spp_{index}"></description-comment-spp></div>
                  </div>
                  <div class="comment-box" if={ item.recommended_dealer_name } recommended_dealer_name>
                    <a class="commentOpenReco">希望販売店<i class="fa fa-commenting-o"></i></a>
                    <div class="text"><description-recommended-dealer-name id="description_recommended_dealer_name_{index}"></description-recommended-dealer-name></div>
                  </div>
                  <div class="customer_use_code_3 text-center" if={item.customer_use_code_3} style="border-top: none;">
                      <a class="customer_use_code_3_link " id="customer_use_code_3_{index}_link" index="{index}" onclick="{showCustomerUseCode3}">
                        発注先
                      </a>
                    </div>
                </td>
                <td style="width: 50px">
                  <div suryo>
                    {item.suryo}
                    <input type="hidden" id="suryo_{index}" value="{item.suryo}" old_value="{item.suryo}" onchange="{changeSuryo}" if={(item.status == 4 || item.status == 12 || item.status == 5 )}>
                  </div>
                  <!-- {(item.status == 4 || item.status == 12 || item.status == 5 || item.status == 8 ) ? (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 delivery_suryo>
                    <p>{item.delivery_suryo}</p>
                    <!-- <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 ? 'disabled':''}" style="text-align: center;width:100%"> -->
                    <input type="hidden" id="delivery_suryo_{index}" value="{item.delivery_suryo}">
                    <p>{ item.cart_seq_related ? checkStatusRelated(item.status) : ''}</p>
                  </div>
                  <!-- <div if={ item.cart_seq_related }>分納</div> -->
                </td>
                <td class="right" style="width: 85px">
                  <div tanka>
                  {item.tanka ? item.tanka.toLocaleString('en') + '円' : '' }</div>
                  <!-- <div>{item.dealer_tanka ? item.dealer_tanka.toLocaleString('en') + '円' : ''}</div> -->
                  <div if={ item.siire_tanka } siire_tanka>
                    {item.siire_tanka.toLocaleString('en') + '円' }
                  </div>
                  <div if={item.postage}>{item.postage.toLocaleString('en') + '円' }</div>
                </td>
                <td style="width:57px">
                  <div siire_tanka_suryo>
                    { (item.siire_tanka * item.suryo) ? (item.siire_tanka * item.suryo).toLocaleString('en') + '円' : '' }
                  </div>
                </td>
                <!-- <td>
                  <div deliverydate>
                    { item.deliverydate }
                  </div>
                  <div> 
                    <input type="text" class="delivery_scheduled_date" id="delivery_scheduled_date_{index}" value="{item.delivery_scheduled_date}" placeholder="yyyy/mm/dd" style="width:90px">
                    <input type="hidden" id="delivery_scheduled_date_{index}_old" value="{item.delivery_scheduled_date}">
                  </div>
                </td> -->
                <td style="width: 190px">
                  <div dealer_co_name dealer_dep_name>
                    <!-- dealer_co_name -->
                    {item.dealer_co_name} {item.dealer_dep_name}
                  </div>
                  <div>
                    <!-- <select if={item.list_maker_dealer && !item.dealer_co_name} id="maker_dealer_{index}">
                      <option each={item_maker,index_maker in item.list_maker_dealer} value="{item_maker.dealer_co_cd}|{item_maker.dealer_dep_cd}">{item_maker.dealer_co_name} {item_maker.dealer_dep_name}</option>
                    </select> -->
                    <select id="prefecture_{index}" class="prefecture" index={index} if={item.status == 4 || !item.dealer_co_cd}>
                      <option value="">----</option>
                      <option each={ item_prefecture in list_prefectures } value="{item_prefecture}" selected="{item_prefecture == item.prefecture ? 'selected' : ''}">{item_prefecture}</option>
                    </select>
                    <select class="maker_dealer_list" id="maker_dealer_{index}" if={item.status == 4 || !item.dealer_co_cd} index={index}>
                      <option value="">----</option>
                      
                    </select>
                  </div>
                </td>
                <td style="width:150px" colspan="2">
                  <div>
<!--                  出荷情報  -->
                    { item.delivery_info }
                  </div>
                  <div if={typeof item.comment_dog !== 'undefined'}>
                    <textarea id="comment_dog_{index}" class="comment_dog" cols='4' rows="2" index={index} if={item.comment_enable}>{item.comment_dog}</textarea>
                    <textarea id="comment_dog_disabled_{index}" class="comment_dog_disabled" cols='4' rows="2" index={index} if={!item.comment_enable} disabled="{!item.comment_enable ? 'disabled' : ''}"></textarea>
                  </div>
                  <div class="comment_cst1" if={typeof item.comment_dog !== 'undefined'} style="border-top: none;">
                    <a class="comment_cst1_link" id="comment_cst1_{index}_link" index="{index}" onclick="{showCommentCst1}">
                      送信履歴
                    </a>
                  </div>
                  <div style="border-top: none;">
                    <div if={item.comment_cst1 && item.nouki_reply_date}>
                      <p>送信日時:{item.nouki_reply_date ? moment(item.nouki_reply_date).format('YYYY-MM-DD') : ''}</p>
                    </div>
                    <input type="hidden" id="comment_cst1_{index}_old" value="{item.comment_cst1}">
                  </div>
                </td>
                <td style="width:90px">
                  <div if={ item.mb_hatyu_status }>
                      <span>{item.mb_hatyu_status}</span>
                  </div>
                </td>
                <td style="width:70px">
                  {(item.status == 4) ? 'PCA受注データ未作成':''}
                  {(item.status == 5) ? 'キャンセル依頼':''}
                  {(item.status == 6) ? 'キャンセル済':''}

                  <div class="status-box" if={item.status == 7 && item.mb_hatyu_cd && item.mb_meisai_cd == '0' && item.mb_kyoten_cd == '' }>
                    <a class="statusToolTip" style="color: {(item.status == 7 && item.mb_hatyu_cd && item.mb_meisai_cd == '0' && item.mb_kyoten_cd == '') ? 'red' : 'black'};">{(item.status == 7) ? 'PCA受注データ作成済み' : '' }</a>
                    <div class="text">
                      <description-status-tooltip id="description_status_tooltip_{index}"></description-status-tooltip>
                    </div>
                  </div>

                  <span if={item.status == 7 && !(item.mb_hatyu_cd && item.mb_kyoten_cd == '' && item.mb_meisai_cd == '0')}>PCA受注データ作成済み</span>
                  {(item.status == 8) ? '返品依頼受付中':''}
                  {(item.status == 9) ? '返品承認済':''}
                  {(item.status == 10) ? '返品処理完了':''}
                  {(item.status == 14) ? '注文書待ち':''}
                  {(item.status == 30) ? '出荷確定':''}
                  {(item.status == 31) ? '受入検収済':''}
                  {(item.status == 32) ? '出荷連絡済':''}
                  <!-- <a href="" onclick="{postCartDelete}" index={index} style="display: {(item.status == 4 || item.status == 12 || item.status == 7) ? 'block':'none'}">オーダー取消</a> -->
                </td>
                <td style="width:70px">
                  <div>{convertDateTime(item.delivery_date)}</div>
                  <!-- <div>
                    {item.status == 30 ? '' : convertDateTime(item.acceptance_date)}
                    <a href="" onclick="{postCartLink}" style="display:{item.status == 30 ? 'block' : 'none'}">受入検収</a>
                  </div> -->
                </td>
                <td style="width:30px">
                  <input type="checkbox" id="checkbox_status_{index}" class="checkbox_status" value="{item.status}" onchange="{changeStatus}" index={index}>
                  <!-- <input type="checkbox" if={item.is_deleted == 1} disabled="disabled"> -->
                  
                  <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}">
                </td>
              </tr>
            </tbody>
          </table>
          </div>
          <div id="paging" class="text-center">
            <ul class="pagination" id="pagination_s22"></ul>
          </div>
        </div>
      </div>
    </div>
    <div class="o_modal" id="comment-cst1-modal">
      <div class="o_modal_box comment-cst1-modal">
        <div class="o_modal_head">
          <a id="comment-cst1-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 class="comment-break">{comment_cst1}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--  pop up name  -->
    <div class="o_modal" id="show-user-info-modal">
      <div class="o_modal_box show-user-info-modal">
        <div class="o_modal_head">
          <a id="show-user-close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title">{name}</h3>
            <div class="left">
              <p class="comment-break">
                ・郵便番号： { zip } <br/>
                ・都道府県： { prefecture } <br/>
                ・住所： { city } - { address } - { building } <br/>
                ・電話番号： { telephone } <br/>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--  customer-use-code-3 modal  -->
    <div class="o_modal" id="customer-use-code-3-modal">
      <div class="o_modal_box customer-use-code-3-modal">
        <div class="o_modal_head">
          <a id="customer-use-code-3-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 class="text-center">{ name }</p>
               <p class="comment-break">
                 
                {nonyu_saki ? '・施設名：' + nonyu_saki : ''} <br/>
                {nonyu_zip ? '・郵便番号：' + nonyu_zip : ''} <br/>
                {nonyu_address1 ? '・住所：' + nonyu_address1 : ''} <br/>
                {nonyu_tel ? '・電話番号：' + nonyu_tel : ''} <br/>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="modal-wrapper">
      <div class="o_modal" id="s22-2">
        <div class="o_modal_box">
          <div class="o_modal_head">
            <a id="s22-2-close"><i class="fa fa-times"></i></a>
          </div>
          <div class="o_modal_body">
            <div class="o_modal_main">
              <h3 class="modal-title">分納作成</h3>
              <table class="modal-table">
                <tr>
                  <th>注文管理番号</th>
                  <td class="popup-text-html" id="cart_seq_popup"></td>
                </tr>
                <tr>
                  <th>受注日</th>
                  <td class="popup-text-html" id="order_date_popup"></td>
                </tr>
                <tr>
                  <th>品番</th>
                  <td class="popup-text-html" id="supp_sku_popup"></td>
                </tr>
                <tr>
                  <th>品名</th>
                  <td class="popup-text-html" id="item_name_popup"></td>
                </tr>
                <tr>
                  <th>容量・規格</th>
                  <td class="popup-text-html" id="kikaku_capacity_popup"></td>
                </tr>
                <tr>
                  <th>製造元</th>
                  <td class="popup-text-html" id="maker_name_popup"></td>
                </tr>
                <tr>
                  <th>販売元</th>
                  <td class="popup-text-html" id="supp_co_name_popup"></td>
                </tr>
                <tr>
                  <th>お客様</th>
                  <td class="popup-text-html" id="customer_co_dep_user_name_popup"></td>
                </tr>
                <tr>
                  <th>注文数量</th>
                  <td class="popup-text-html" id="suryo_popup"></td>
                </tr>
                <tr>
                  <th>納品数量</th>
                  <td><input type="text" class="popup-text-input" id="delivery_suryo_popup"></td>
                </tr>
                <tr>
                  <th>納入価格</th>
                  <td><input type="text" class="popup-text-input" id="tanka_popup"></td>
                </tr>
                <tr>
                  <th>納入金額</th>
                  <td id="suryo_tanka_popup"></td>
                </tr>
                <tr>
                  <th>納品予定日</th>
                  <td><input type="text" class="popup-text-input" id="delivery_scheduled_date_popup"></td>
                </tr>
                <tr>
                  <th>お客様へコメント</th>
                  <td><textarea class="popup-text-input" id="comment_cst1_popup"></textarea></td>
                </tr>
              </table>
              <div class="btn-wrapper">
                <input type="hidden" id="customer_co_name_popup">
                <input type="hidden" id="customer_dep_name_popup">
                <input type="hidden" id="customer_user_name_popup">
                <input type="hidden" id="kikaku_popup">
                <input type="hidden" id="capacity_popup">
                <input type="hidden" id="sku_popup">
                <input type="hidden" id="supp_co_cd_popup">
                <input type="hidden" id="customer_co_cd_popup">
                <input type="hidden" id="teika_tanka_popup">
                <input type="hidden" id="siire_tanka_popup">
                <input type="hidden" id="customer_use_code_1_popup">
                <input type="hidden" id="customer_use_code_2_popup">
                <input type="hidden" id="customer_use_code_3_popup">
                <input type="hidden" id="customer_use_code_4_popup">
                <input type="hidden" id="customer_use_code_5_popup">
                <button type="button" id="post_cart_popup" onclick="{postCartPopup}" index="">分納を作成する</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="o_modal" id="s22-postage">
      <div class="o_modal_box" >
        <div class="o_modal_head">
          <a id="s22-postage-modal-close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body s22-postage-msg">
          <div>
            <sapn>ご注文金額合計</span>
            <sapn style="margin-left:20%;">送料</span>
          </div>

          <div class="s22-postage-msg-main"></div>
          
        </div>
      </div>
    </div>
    <diff-cart></diff-cart>
    <script>
      /* popup $ */
      $(function(){
        $(".search-btn").click(function(e){
          var page = 1;
          thisTag.searchCart(page);
        });
        $.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-comment-usr', '', function(opts) {   
                this.root.innerHTML = opts.r1;
            });
            riot.tag('description-comment-spp', '', function(opts) {
              this.root.innerHTML = opts.r1;
            });
            riot.mount('#description_comment_usr_' + i, {
                r1: e.comment_usr
            });
            riot.mount('#description_comment_spp_' + i, {
              r1: e.comment_spp
            });
            riot.tag('description-recommended-dealer-name', '', function(opts) {   
                this.root.innerHTML = opts.r2;
            });
            riot.mount('#description_recommended_dealer_name_' + i, {
                r2: e.recommended_dealer_name
            })
            riot.tag('description-status-tooltip', '', function(opts) {   
                this.root.innerHTML = opts.r3;
            });
            riot.mount('#description_status_tooltip_' + i, {
                r3: '得意先コードがブランクのため、PCAにデータが作成されていません。'
            })
            // thisTag.update();
        });

        // $.each(thisTag.list_cart,function(i,e){
        //     riot.tag('description-recommended-dealer-name', '', function(opts) {   
        //         this.root.innerHTML = opts.r;
        //     });
        //     riot.mount('#description-recommended-dealer-name' + i, {
        //         r: e.recommended_dealer_name
        //     })
        //     thisTag.update();
        // });
        $(document).on('click', '.s22-2-open',function(e){
          var index = $(e.target).attr('index');
          $("#cart_seq_popup").html(thisTag.list_cart[index].cart_seq);
          $("#order_date_popup").html(thisTag.list_cart[index].order_date);
          $("#supp_sku_popup").html(thisTag.list_cart[index].supp_sku);
          $("#item_name_popup").html(thisTag.list_cart[index].item_name);
          $("#kikaku_capacity_popup").html(thisTag.list_cart[index].kikaku + ((thisTag.list_cart[index].kikaku && thisTag.list_cart[index].capacity) ? thisTag.list_cart[index].kikaku + ' . ' : '') +  thisTag.list_cart[index].capacity);
          $("#maker_name_popup").html(thisTag.list_cart[index].maker_name);
          $("#supp_co_name_popup").html(thisTag.list_cart[index].supp_co_name);
          $("#customer_co_dep_user_name_popup").html(thisTag.list_cart[index].customer_co_name + ((thisTag.list_cart[index].customer_co_name && thisTag.list_cart[index].capacity) ? ' . ' : '') + thisTag.list_cart[index].customer_dep_name + ((thisTag.list_cart[index].customer_dep_name && thisTag.list_cart[index].customer_user_name) ? ' . ' : '') + thisTag.list_cart[index].customer_user_name);
          $("#suryo_popup").html(thisTag.list_cart[index].suryo);
          $("#delivery_suryo_popup").val('');
          $("#tanka_popup").val(thisTag.list_cart[index].tanka);

          $("#siire_tanka_popup").val(thisTag.list_cart[index].siire_tanka);
          $("#teika_tanka_popup").val(thisTag.list_cart[index].teika_tanka);
          $("#suryo_tanka_popup").html(thisTag.list_cart[index].suryo * thisTag.list_cart[index].tanka);
          $("#delivery_scheduled_date_popup").val(thisTag.list_cart[index].delivery_scheduled_date);
          $("#comment_cst1_popup").val(thisTag.list_cart[index].comment_cst1);

          $("#customer_co_name_popup").val(thisTag.list_cart[index].customer_co_name);
          $("#customer_dep_name_popup").val(thisTag.list_cart[index].customer_dep_name);
          $("#customer_user_name_popup").val(thisTag.list_cart[index].customer_user_name);
          $("#kikaku_popup").val(thisTag.list_cart[index].sku);
          $("#capacity_popup").val(thisTag.list_cart[index].sku);
          $("#sku_popup").val(thisTag.list_cart[index].sku);
          $("#supp_co_cd_popup").val(thisTag.list_cart[index].supp_co_cd);

          $("#customer_co_cd_popup").val(thisTag.list_cart[index].customer_co_cd);

          $("#customer_use_code_1_popup").val(thisTag.list_cart[index].customer_use_code_1);
          $("#customer_use_code_2_popup").val(thisTag.list_cart[index].customer_use_code_2);
          $("#customer_use_code_3_popup").val(thisTag.list_cart[index].customer_use_code_3);
          $("#customer_use_code_4_popup").val(thisTag.list_cart[index].customer_use_code_4);
          $("#customer_use_code_5_popup").val(thisTag.list_cart[index].customer_use_code_5);
          
          $("#post_cart_popup").attr('index',index);
          $('#s22-2').fadeIn();
        });
        $('#s22-2-close').on('click',function(e){
          $('#s22-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
        });
        $('.commentOpenUsr').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();
          }
        });
        $('.commentOpenSpp').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();
          }
        });
        $('.commentOpenReco').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();
          }
        });
        $('.statusToolTip').on('click',function(){
          if($(this).hasClass('active')){
            $(this).removeClass('active').html('PCA受注データ作成済み');
            $(this).next('.text').hide();
          }else{
            $(this).addClass('active').html('閉じる<i class="fa fa-times"></i>');
            $(this).next('.text').show();
          }
        });

        $('.s22-postage-modal-open').on('click',function(e){
            $('#s22-postage').fadeIn();
        });

        $('#s22-postage-modal-close').on('click',function(){
            $('#s22-postage').fadeOut();
        });

      });
    </script>
    <script>

    /* global */
    var user_info = JSON.parse(localStorage.getItem('EcUserInfo'));
    this.list_cart = opts.result;
    this.total = opts.total;
    this.maker_dealer_list = opts.maker_dealer_list;
    this.genPostageList = opts.genPostageList;
    this.currentPage = 1;
    this.linkDownload = URL_API;
    this.comment_cst1 = '';
    this.accessTokenCognito = localStorage.getItem('accessTokenCognito');
    this.statusSelected = [4,14,5,6,7,8,9,30,31,12];
    this.list_navigationF = user_info.list_navigation.F;
    this.navigation_list_cus_use_code = opts.navigation_list;
    this.list_cart_changed = [];
    this.list_prefectures = arMergeKeepBase(list_prefectures, opts.prefecture);
    var thisTag = this; 
    // this.total_diff = opts.total_diff;
    // this.on("mount", function(){
    //   // thisTag.getMakerDealer();
    // });
    // this.getMakerDealer = function (){
    //   var url = URL_API + '/api/get_maker_dealer_dropdown';
    //   var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    //   var query = [];
    //   query.push('token=' + accessTokenCognito);
    //   url += '?' + query.join('&');

    //   $.ajax({
    //       url: url,
    //       type: 'GET',
    //       success: function (res) {
    //           if(res.status == 100){
    //               riot.mount('app','maintain',{ messege:res.messege });
    //               return false;
    //           }
    //           if(res.status == 200) {
    //             console.log(res);
    //           }
    //       },
    //       error: function () {
    //           alert('error');
    //       }
    //   });
    // }

    this.showCommentCst1 = function (e) {
      var index = $(e.target).attr("index");
      var comment_cst1 = thisTag.list_cart[index].comment_cst1;
      thisTag.update({ comment_cst1: comment_cst1 });
      $('#comment-cst1-modal').fadeIn();
    }

    this.showUserInfo = function (e) {
      var index = $(e.target).attr("index");
      var name = thisTag.list_cart[index].name;
      var zip = thisTag.list_cart[index].zip;
      var telephone = thisTag.list_cart[index].telephone;
      var city = thisTag.list_cart[index].city;
      var address = thisTag.list_cart[index].address;
      var building = thisTag.list_cart[index].building;
      var prefecture = thisTag.list_cart[index].prefecture_customer;
      thisTag.update({ name: name, zip: zip, telephone: telephone, city: city, address: address, building: building, prefecture: prefecture });
      $('#show-user-info-modal').fadeIn();
    }

    this.showCustomerUseCode3 = function (e) {
      var index = $(e.target).attr("index");
      var customer_use_code_3 = thisTag.list_cart[index].customer_use_code_3;
      var nonyu_saki = '';
      var nonyu_zip = '';
      var nonyu_address1 = '';
      var nonyu_tel = '';
      if(customer_use_code_3 == 1) {
        var name =  '販売店';
      } else if(customer_use_code_3 == 2) {
        var name = 'ご登録住所';
      } else if (customer_use_code_3 == 3) {
        var name = 'その他住所';
        var nonyu_saki = thisTag.list_cart[index].nonyu_saki;
        var nonyu_zip = thisTag.list_cart[index].nonyu_zip;
        var nonyu_address1 = thisTag.list_cart[index].nonyu_address1;
        var nonyu_tel = thisTag.list_cart[index].nonyu_tel;
      }
      thisTag.update({ name: name, nonyu_saki: nonyu_saki, nonyu_zip: nonyu_zip, nonyu_address1: nonyu_address1, nonyu_tel: nonyu_tel});
      $('#customer-use-code-3-modal').fadeIn();
    }

    $(function(){
        $(".maker_dealer_list").each(function(i, e){
          var index = $(this).attr('index');
          var cart = thisTag.list_cart[index];
          var list_option = '';
          $("#maker_dealer_" + index).html("<option value=''>----</option");
          $.each(thisTag.maker_dealer_list, function(ii, ee) {
            let selected = '';
            if(cart.dealer_co_cd == ee.dealer_co_cd && cart.dealer_dep_cd == ee.dealer_dep_cd){
              selected = 'selected';
            }
            list_option += "<option value='" 
              + ee.dealer_co_cd + "|" + ee.dealer_dep_cd + "' " + selected + ">"
              + ee.dealer_co_name + " " + ee.dealer_dep_name
              + "</option>";
          })
          $("#maker_dealer_" + index).append(list_option);
        });
        $(".prefecture").change(function(e){
            thisTag.getMakerDealer(e);
        });
        
        $('#comment-cst1-close').on('click',function(e){
          $('#comment-cst1-modal').fadeOut();
          thisTag.update({ comment_cst1: '' });
        });

        $('#show-user-close').on('click',function(e){
          $('#show-user-info-modal').fadeOut();
        });

        $('#customer-use-code-3-close').on('click',function(e){
          $('#customer-use-code-3-modal').fadeOut();
        });

        $('#link-download').click(function() {
            $('#progress').css({"display":"inline"});
            var that = this;
            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 page_url = thisTag.linkDownload + '/api/s22/download?token=' + thisTag.accessTokenCognito + '&status=' + status_select + '&start_date=' + start_date + '&end_date=' + end_date;
            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.addEventListener("progress", function (evt) {
                if(evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    $("#progress").val(percentComplete);

                    if(evt.loaded === evt.total){
                        setTimeout(function(){
                            $('#progress').css({"display":"none"});
                        },1000);
                    }
                }
            }, false);

            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();
        });

        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_s22');
        $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.commentCstChange();
        thisTag.checkIfFirstPage();  
        thisTag.checkIfLastPage(); 
        thisTag.pickDateTime();

        $('#popup-s22').click(function() {
            var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            var url = URL_API + '/api/cart/list_diff_mc?token=' + accessTokenCognito;
            var response = {};
            $.ajax({
                url: url,
                type: 'GET',
                async:false,
                success: function(rp) {
                    response = rp.response;
                }
            });
            riot.mount('diff-cart',{ response : response });
            $('#s22-1-open').fadeIn();
        })

        var postAge = thisTag.genPostageList;
        var postAgeMsg = ''; 
        for (var i = 0;i < postAge.length; i++) {
            if (!postAge[i]['cart_total_max']) {
                postAgeMsg += '<p>'+(postAge[i]['cart_total_min']).toLocaleString('en')+'円以上 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '+(postAge[i]['postage']).toLocaleString('en')+'円</p>';   
            }

            if (!postAge[i]['cart_total_min']) {
                postAgeMsg += '<p>&nbsp; '+(postAge[i]['cart_total_max']+1).toLocaleString('en')+'円未満 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '+(postAge[i]['postage']).toLocaleString('en')+'円</p>';   
            }

            if (postAge[i]['cart_total_max'] && postAge[i]['cart_total_min']) {
                postAgeMsg += '<p>'+(postAge[i]['cart_total_max']+1).toLocaleString('en')+'円未満'+'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'+(postAge[i]['postage']).toLocaleString('en')+'円</p>';
            }
        }
        $('.s22-postage-msg-main').append(postAgeMsg);
    });
    this.commentCstChange = function(e) {
      $('.comment_cst1').on('change',function(){
        var index = $(this).attr('index');
        var cart_seq = thisTag.list_cart[index].cart_seq;
        var comment_cst1 = $(this).val();
        var check = false;
        if(jQuery.isEmptyObject(thisTag.list_cart_changed)){
          thisTag.list_cart_changed[index] = {
            cart_seq: cart_seq,
            comment_cst1: comment_cst1
          };
        }
        $.each(thisTag.list_cart_changed, function(i, e){
          if(e){
            if(parseInt(cart_seq) == parseInt(e.cart_seq)){
              check = true;
            } 
          }
        });
        if(check){
          thisTag.list_cart_changed[index].comment_cst1 = comment_cst1;
        } else {
          thisTag.list_cart_changed[index] = {
            cart_seq: cart_seq,
            comment_cst1: comment_cst1
          };
        }
        thisTag.update(thisTag.list_cart_changed);
      });
      
      $(".comment_cst2").on('change', function(e){
        var index = $(this).attr('index');
        var cart_seq = thisTag.list_cart[index].cart_seq;
        var comment_cst2 = $(this).val();
        var check = false;
        if(jQuery.isEmptyObject(thisTag.list_cart_changed)){
          thisTag.list_cart_changed[index] = {
            cart_seq: cart_seq,
            comment_cst2: comment_cst2
          };
        }
        $.each(thisTag.list_cart_changed, function(i, e){
          if(e){
            if(parseInt(cart_seq) == parseInt(e.cart_seq)){
              check = true;
            } 
          }
        });
        if(check){
          thisTag.list_cart_changed[index].comment_cst2 = comment_cst2;
        } else {
          thisTag.list_cart_changed[index] = {
            cart_seq: cart_seq,
            comment_cst2: comment_cst2
          };
        }
        thisTag.update(thisTag.list_cart_changed);
      });

      $('.comment_dog').on('change',function(){
        var index = $(this).attr('index');
        var cart_seq = thisTag.list_cart[index].cart_seq;
        var comment_dog = $(this).val();
        var check = false;
        if(jQuery.isEmptyObject(thisTag.list_cart_changed)){
          thisTag.list_cart_changed[index] = {
            cart_seq: cart_seq,
            mb_hatyu_seq:  thisTag.list_cart[index].mb_hatyu_seq,
            mb_hatyu_cd:  thisTag.list_cart[index].mb_hatyu_cd,
            comment_dog: comment_dog,
            delivery_info: thisTag.list_cart[index].delivery_info
          };
        }

        $.each(thisTag.list_cart_changed, function(i, e){
          if(e){
            if(parseInt(cart_seq) == parseInt(e.cart_seq)){
              check = true;
            }
          }
        });
        if(check){
          thisTag.list_cart_changed[index].comment_dog = comment_dog;
          thisTag.list_cart_changed[index].delivery_info = thisTag.list_cart[index].delivery_info;
        } else {
          thisTag.list_cart_changed[index] = {
            cart_seq: cart_seq,
            mb_hatyu_seq:  thisTag.list_cart[index].mb_hatyu_seq,
            mb_hatyu_cd:  thisTag.list_cart[index].mb_hatyu_cd,
            comment_dog: comment_dog,
            delivery_info: thisTag.list_cart[index].delivery_info
          };
        }
        thisTag.update(thisTag.list_cart_changed);
      });
    }
    this.getMakerDealer = function(e) {
      var prefecture = $(e.target).find(":selected").val();
      var index = $(e.target).attr('index');
      var url = URL_API + '/api/cart/getListFollowPrefecture';
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');

      var querySuggest = [];

      querySuggest.push('token=' + accessTokenCognito);
      querySuggest.push('prefecture=' + prefecture);

      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'){
                  if(data.prefecture){
                      $("#maker_dealer_" + index).html("<option value=''></option>");
                      var list_option = '';
                      $.each(data.prefecture, function(i, e) {
                          list_option += 
                            "<option value='" + e.dealer_co_cd + "|" + e.dealer_dep_cd + "'>"
                            + e.dealer_co_name + " " + e.dealer_dep_name
                            + "</option>"
                          ;
                      })
                      $("#maker_dealer_" + index).append(list_option);
                      $("#check_cart").on('change', function(e){
                          thisTag.testCheckStatus(this);
                      });
                  }
              }
          },
          error: function (xhr, stt, err) {
              alert('error');
          }
      })
    }
    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.changeStatusSelect = function(e){
      var page = 1;
      thisTag.searchCart(page);
    }
    this.changeOrderDate = function(e){
      var page = 1;
      thisTag.searchCart(page);
    }
    this.changeSuryo = function(e){
        var suryo = $(e.target).val();
        var old_suryo = $(e.target).attr('old_value');
        if(suryo != ''){
          var regex_int = /^[0-9]*$/;
          if(!regex_int.test(suryo)){
            alert('数量の入力が必須です。');
            $(e.target).val(old_suryo);
          } else {
            if(parseInt(suryo) > parseInt(old_suryo)){
              alert("キャンセル希望数量が注文数以上ので、処理できません。");
              $(e.target).val(old_suryo);
            }
          }
        } else {
          alert('数量に整数を入力してください。');
          $(e.target).val(old_suryo);
        }
    }
    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.validateComment = function(e){
        var value = $(e.target).val();
        if(value.length > 100){
            alert("お客様へコメントを100文字以内に入れてください");
            $(e.target).val("");
            return false;
        }
    }

    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_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(",");
        // console.log(status);
        // console.log("======================================================================================================");
        $.each(thisTag.list_cart, function( index, value ) {
            // console.log("====================================" + value.cart_seq + "==================================");
            // $("#delivery_scheduled_date_" + index).attr("disabled","true");
            // $("#comment_cst1_" + index).attr("disabled","true");
            $("#delivery_suryo_" + index).attr("readonly", true);
            // $("#suryo_" + index).attr("readonly", true);
            var checkVisible = true;
            if(arrStatus.indexOf(value.status) != -1){         
                $(".checkbox_status_" + index).removeAttr("disabled");
                if(value.status == 4 || value.status == 5 || value.status == 8 || value.status == 12 || value.status == 30){
                    // $("#tanka_" + index).removeAttr("readonly");
                    $("#delivery_suryo_" + index).removeAttr("readonly");
                    // $("#suryo_" + index).removeAttr("readonly");
                }
            } else {
              switch(status) {
                case "comment_cst":
                  // console.log("comment_cst");
                  if ($('#comment_dog_disabled_' + index).length == 0) {
                    $(".checkbox_status_" + index).removeAttr("disabled");
                  } else checkVisible = false;
                  break;
                case "6_no_mail":
                  if(value.status == 4 || value.status == 7) {
                    $(".checkbox_status_" + index).removeAttr("disabled");
                  } else {
                    checkVisible = false;
                  }
                  break;
                case "30_no_mail":
                  if(value.status == 7) {
                    $(".checkbox_status_" + index).removeAttr("disabled");
                  } else {
                    checkVisible = false;
                  }
                  break;
                case "32_no_mail":
                  if(value.status == 7 || value.status == 30) {
                    $(".checkbox_status_" + index).removeAttr("disabled");
                  } else {
                    checkVisible = false;
                  }
                  break;
                case "dealer_co_dep_cd":
                    if(value.status == 4) {
                      $(".checkbox_status_" + index).removeAttr("disabled");
                    } else {
                      checkVisible = false;
                    }
                  break;
                case "30_32_accept_return":
                    if (value.status == 30 || value.status == 32) {
                      $(".checkbox_status_" + index).removeAttr("disabled");
                    } else {
                      checkVisible = false;
                    }
                  break;
                default:
                  checkVisible = false;
                  break;
              }

              if(!checkVisible){
                $("#checkbox_status_" + index).attr("disabled","true");
                // $("#tanka_" + index).attr("readonly","true");
                if(value.status == 4 || value.status == 5 || value.status == 8 || value.status == 12 || value.status == 30){
                    // $("#tanka_" + index).removeAttr("readonly");
                    $("#delivery_suryo_" + index).removeAttr("readonly");
                    // $("#suryo_" + index).removeAttr("readonly");
                }
              }
            }
        });
    }
    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 = {
            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
          };
          listCart.push(arrCart);
      var url = URL_API + '/api/cart/create_mc_screen';
      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.postCartPopup = function(e){
      if(!confirm('分納の受注をします。')){
        return false;
      }
      // ====== param check total suryo
      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('&');

      // ====== param to post cart
      var index = $(e.target).attr('index');
      var data = thisTag.list_cart[index]; 
      var url = URL_API + '/api/cart/create_mc_screen';
      var delivery_suryo = $("#delivery_suryo_popup").val().trim();
      var tanka = $("#tanka_popup").val();
      var delivery_scheduled_date = $("#delivery_scheduled_date_popup").val();
      var comment_cst1 = $("#comment_cst1_popup").val();
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var query = [];
      query.push('token=' + accessTokenCognito);
      url += '?' + query.join('&');

      
      var listCart = [];
      var arrCart = {
          cart_seq_related: data.cart_seq,
          delivery_scheduled_date: delivery_scheduled_date,
          comment_cst1: comment_cst1,
          tanka: tanka,
          delivery_suryo: delivery_suryo,
          status: 7,
          //===
          suryo: data.suryo,
          dealer_co_cd: data.dealer_co_cd,
          customer_co_cd: data.customer_co_cd,
          customer_dep_cd: data.customer_dep_cd,
          // teika_tanka:data.teika_tanka,
          customer_co_name: data.customer_co_name,
          customer_dep_name: data.customer_dep_name,
          customer_user_name: data.customer_user_name,
          supp_sku: data.supp_sku,
          item_name: data.item_name,
          capacity: data.capacity,
          kikaku: data.kikaku,
          maker_name: data.maker_name,
          supp_co_name: data.supp_co_name,
          item_sku:data.item_sku,
          supp_co_cd: data.supp_co_cd,
          order_date: data.order_date,
          deliverydate: data.deliverydate,
          ec_users_id: data.ec_users_id,
          teika_tanka: data.teika_tanka,
          siire_tanka: data.siire_tanka,
          // comment_usr: data.comment_usr,
          customer_use_code_1: data.customer_use_code_1,
          customer_use_code_2: data.customer_use_code_2,
          customer_use_code_3: data.customer_use_code_3,
          customer_use_code_4: data.customer_use_code_4,
          customer_use_code_5: data.customer_use_code_5
      };
      listCart.push(arrCart);
      if(delivery_suryo.length == 0){
        alert('納入数量を正数で入力してください。');
        return false;
      }
      if(delivery_suryo == 0){
        alert('1以上の整数のみ入力できます。');
        $("#delivery_suryo_popup").val('');
        return false;
      }
      if(!thisTag.validateInteger(delivery_suryo)){
          alert('納入数量を正数で入力してください。');
          $("#delivery_suryo_popup").val('');
          return false;
      }
      if(!thisTag.validateInteger(tanka)){
          alert('納品価格は0以上の正数を入力してください。');
          $("#tanka_popup").val('');
          return false;
      }
      if(delivery_suryo >= data.suryo){
          alert('納品数量は注文数量以下の数字を入力してください。');
          $("#delivery_suryo_popup").val('');
          return false;
      }
      
      $.ajax({
          url: url_check,
          type: 'POST',
          data:{
              cart_seq: data.cart_seq,
              data: arrCart
          },
          success: function (res) {
              if(res.status == 100){
                  riot.mount('app','maintain',{ messege:res.messege });
                  return false;
              }
              if(res.message == 'delivery_suryo_too_big') {
                alert('分納の合計が注文数量以下になるように入力してください。');
                $("#delivery_suryo_popup").val('');
                return false;
                $.ajax({
                    url: url,
                    type: 'POST',
                    data:{
                        data: listCart,
                        screen: 's22_popup'
                    },
                    success: function (res) {
                        if(res.status == 100){
                            riot.mount('app','maintain',{ messege:res.messege });
                            return false;
                        }
                        if(res.message == 'success'){
                            alert("更新しました。");
                            $('#s22-2').fadeOut();
                            var page = 1;
                            thisTag.searchCart(page);
                            return false;
                        } else if(res.message == 'errors') {
                            alert('errors');
                        }
                    },
                    error: function () {
                        alert('error');
                    }
                });
              } else {
                $.ajax({
                    url: url,
                    type: 'POST',
                    data:{
                        data: listCart,
                        screen: 's22_popup'
                    },
                    success: function (res) {
                        if(res.status == 100){
                            riot.mount('app','maintain',{ messege:res.messege });
                            return false;
                        }
                        if(res.message == 'success'){
                            alert("更新しました。");
                            $('#s22-2').fadeOut();
                            var page = 1;
                            thisTag.searchCart(page);
                            return false;
                        } else if(res.message == 'errors') {
                            alert('errors');
                        }
                    },
                    error: function () {
                        alert('error');
                    }
                });
              }
          },
          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_mc_screen';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        var query = [];
        query.push('token=' + accessTokenCognito);
        url += '?' + query.join('&');

        var listCart = [];
        var arrCart = {
            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,
            //===
            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
        };

        listCart.push(arrCart);


        $.ajax({
            url: url,
            type: 'POST',
            data:{
                data: listCart,
                screen: 's22',
                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;
        // } 

        if(thisTag.total == 0){
          alert("カートが存在しません。");
          return false;
        }
        var item_sku_exist = true;
        var is_deleted = false;
        var listCart = [];
        var status = $('#check_cart').val();
        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 errTanka = [];
        var errDealerCoCd = [];
        var error = [];
        $.each(thisTag.list_cart, function(i,e){
            var cartSeq = $('#cart_seq_' + i).val();
            var delivery_scheduled_date = $("#delivery_scheduled_date_" + i).val();
            var comment_cst1 = $('#comment_cst1_' + i).val();
            var comment_cst2 = $('#comment_cst2_' + i).val();
            var suryo = $("#suryo_" + i ).val();
            var delivery_suryo = $("#delivery_suryo_" + i ).val();
            var tanka = $("#tanka_" + i ).val();
            // ====
            var comment_dog = e['comment_dog'];
            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 dealer_co_cd = '';
            var dealer_dep_cd = '';
            var maker_dealer = $("#maker_dealer_" + i);
            if(typeof maker_dealer.val() !== 'undefined' && maker_dealer.val()){
              maker_dealer = maker_dealer.val().split("|");
              dealer_co_cd = maker_dealer[0];
              dealer_dep_cd = maker_dealer[1];
            }
            var customer_co_cd = e['customer_co_cd'];
            // 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 return_processingcomplete_date = current_date;
            var arrCart = {};

            if($("#checkbox_status_" + i).is(":checked")){
                
                if(e['is_deleted'] == 1){
                  is_deleted = true;
                }
                if(!e['item_sku_exist']){
                  item_sku_exist = false;
                }
                
                switch(status) {
                    case 'comment_cst':
                        if(thisTag.list_cart_changed[i]){
                            arrCart.cart_seq = parseInt(cartSeq);
                            // arrCart.comment_dog = comment_dog;
                            if(thisTag.list_cart_changed[i].comment_cst1){
                              arrCart.comment_cst1 = thisTag.list_cart_changed[i].comment_cst1
                            }
                            if(thisTag.list_cart_changed[i].comment_cst2){
                              arrCart.comment_cst2 = thisTag.list_cart_changed[i].comment_cst2
                            }
                            listCart.push(arrCart);
                        } else if(comment_dog){
                            arrCart.cart_seq = parseInt(cartSeq);
                            arrCart.mb_hatyu_seq = e['mb_hatyu_seq'];
                            arrCart.mb_hatyu_cd = e['mb_hatyu_cd'];
                            arrCart.comment_dog = e['comment_dog'];
                            arrCart.delivery_info = e['delivery_info'];
                            listCart.push(arrCart);
                        }
                        
                        
                        break;
                    case '6_no_mail':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            status: 6,
                            
                        };
                        listCart.push(arrCart);
                        break;
                    case '30_no_mail':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            status: 30,
                            
                        };
                        listCart.push(arrCart);
                        break;
                    case '32_no_mail':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            status: 32,
                            
                        };
                        listCart.push(arrCart);
                        break;
                    case 'dealer_co_dep_cd':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            dealer_co_cd: dealer_co_cd,
                            dealer_dep_cd: dealer_dep_cd,
                        };
                        listCart.push(arrCart);
                        break;
                    case '4':
                        if(!dealer_co_cd){
                          errDealerCoCd.push("empty");
                        } 
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            delivery_suryo: delivery_suryo,
                            status: 4,
                            
                            //===
                            dealer_co_cd: dealer_co_cd,
                            dealer_dep_cd: dealer_dep_cd,
                            supp_co_cd: supp_co_cd,
                        };
                        if(comment_cst1){
                          arrCart.comment_cst1 = comment_cst1;
                        }
                        if(comment_cst2){
                          arrCart.comment_cst2 = comment_cst2;
                        }
                        listCart.push(arrCart);
                        break;
                    case '5':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            cancellation_acceptance_date: cancellation_acceptance_date,
                            status: 6,
                            
                            //===
                            suryo: suryo,
                        };
                        listCart.push(arrCart);
                        break;
                    case '8':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            return_acceptance_date: return_acceptance_date,
                            status: 9,
                            
                            //===
                            suryo: suryo,
                        };
                        listCart.push(arrCart);
                        break;
                    case '9':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            return_processingcomplete_date: return_processingcomplete_date,
                            status: 10,
                            
                            //===
                            suryo: suryo,
                        };
                        listCart.push(arrCart);
                        break;
                    case '30':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            status: 32,
                            
                            //===
                        };
                        if (comment_dog) {
                          arrCart.mb_hatyu_seq = e['mb_hatyu_seq'];
                          arrCart.mb_hatyu_cd = e['mb_hatyu_cd'];
                          if (e['comment_enable']) {
                            arrCart.comment_dog = e['comment_dog'];
                          }
                          arrCart.delivery_info = e['delivery_info'];
                        }
                        listCart.push(arrCart);
                        break;
                    case '14':
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            status: 14,
                        };
                        listCart.push(arrCart);
                        break;
                    case '30_32_accept_return':
                        var newCartSeq = e['cart_seq_related'] ? e['cart_seq_related'] : cartSeq;
                        arrCart = {
                            cart_seq: parseInt(cartSeq),
                            status: 8,
                            cart_seq_related: newCartSeq
                        };
                        listCart.push(arrCart);
                        break;
                    default:
                }
            }
            if($("#checkbox_status_" + i).not(":checked")) {
              // arrCart = {
              //     cart_seq: cartSeq,
              //     dealer_co_cd: dealer_co_cd,
              //     dealer_dep_cd: dealer_dep_cd,
              // };
              // listCart.push(arrCart);
            }
        });
        if(!$.isEmptyObject(thisTag.list_cart_changed)){
          var status_excerpt = [
            '6_no_mail',
            '30_no_mail',
            '32_no_mail',
            'dealer_co_dep_cd',
            'comment_cst'
          ];

          var list_cart_changed = [];
          $.each(thisTag.list_cart_changed, function(i_changed, e_changed) {
            if(e_changed){
              list_cart_changed.push(e_changed);
            }
          });
          $.each(listCart, function(i_cart, e_cart) {
            if(list_cart_changed){
              $.each(list_cart_changed, function(i_changed, e_changed) {
                if(e_changed && parseInt(e_cart.cart_seq) == parseInt(e_changed.cart_seq)) {
                  if (e_changed.mb_hatyu_seq && e_changed.comment_dog) {
                    listCart[i_cart].mb_hatyu_seq = e_changed.mb_hatyu_seq;
                    listCart[i_cart].comment_dog = e_changed.comment_dog;
                    listCart[i_cart].mb_hatyu_cd = e_changed.mb_hatyu_cd;
                    listCart[i_cart].delivery_info = e_changed.delivery_info;
                  }
                }
              });
            }
          });
          // console.log(status_excerpt.indexOf(status));
          if(status_excerpt.indexOf(status) === -1 ) { // check if status post cart not in status_excerpt
            $.each(listCart, function(i_cart, e_cart) { // loop list cart
              if(list_cart_changed){
                $.each(list_cart_changed, function(i_changed, e_changed) { //loop list cart that user type comment cst
                  if(e_changed && parseInt(e_cart.cart_seq) == parseInt(e_changed.cart_seq)) { // find cart_seq exist in list cart
                    if(e_changed.comment_cst1){ // check if type comment cst 1
                      listCart[i_cart].comment_cst1 =  e_changed.comment_cst1;
                    }
                    if(e_changed.comment_cst2){ // check if type comment cst 2
                      listCart[i_cart].comment_cst2 =  e_changed.comment_cst2;
                    }
                  } else { // if find cart_seq not found then push new cart in to list_cart
                    // listCart.push(e_changed)
                  }
                });
              }
            });
          }
        }

        if(!listCart.length){
          return false;
        }

        // if(listCart.length > 1) {
        //   alert("処理対象は１つのみ選択してください。");
        //   return false;
        // }
        var arrNewErr = [];
        // if(!item_sku_exist){
        //   arrNewErr.push("存在しない商品が含まれています。\n");
        // }
        // if(is_deleted){
        //   arrNewErr.push("販売中止された商品が含まれています。\n");
        // }
        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(errDealerCoCd.indexOf('empty') >= 0){
          arrNewErr.push("販売店は選択必須です。\n");
        }
        // if(errDeliveryScheduledDate.indexOf('empty') >= 0){
        //   arrNewErr.push('納品予定日は入力必須です。\n');
        // }
        // if(errTanka.indexOf('empty') >= 0){
        //   arrNewErr.push("納入価額は入力必須です。\n");
        // }
        if(arrNewErr.length > 0){
          alert(arrNewErr.join(''));
          return false;
        }

        var send_mail = true;
        var status_check_sendmail = [
          '6_no_mail',
          '30_no_mail',
          '32_no_mail',
          'dealer_co_dep_cd',
          '14'
        ];
        if(status_check_sendmail.indexOf(status) != -1 ) {
          send_mail = false;
        }
        var url = URL_API + '/api/cart/create_mc_screen';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        var query = [];
        query.push('token=' + accessTokenCognito);
        url += '?' + query.join('&');

        $.ajax({
            url: url,
            type: 'POST',
            data:{
                data: listCart,
                screen: 's22',
                sendmail: send_mail,
                post_cart_status: status
            },
            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 order_date_s22 = $("#orderdate_select").val();
        var order_start_date = $(".order_start_date").val();
        var order_end_date = $(".order_end_date").val();
        var supp_sku = $("#supp_sku").val();
        var cart_seq_from = $("#cart_seq_from").val();
        var cart_seq_to = $("#cart_seq_to").val();
        var dog_status = $("#dog_status").val();
        var nouki_reply_flg_1 = $("#nouki_reply_flg_1").is(':checked');
        var nouki_reply_flg_0 = $("#nouki_reply_flg_0").is(':checked');


        switch(status) {
            case '0':
                thisTag.statusSelected = [4,5,6,7,8,9,10,14,30,31,32];
                break;
            case '4':
                thisTag.statusSelected = [4];
                break;
            case '14':
                thisTag.statusSelected = 14;
                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 '10':
                thisTag.statusSelected = 10;
                break;
            case '30':
                thisTag.statusSelected = 30;
                break;
            case '31':
                thisTag.statusSelected = 31;
                break;
            case '32':
                thisTag.statusSelected = 32;
                break;
            default:
        }

        var screen = 's22';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        var url = URL_API + '/api/cart/list_mc';
        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(supp_sku){
          querySuggest.push('supp_sku=' + encodeURIComponent(supp_sku));
        }
        if(cart_seq_from){
          querySuggest.push('cart_seq_from=' + cart_seq_from);
        }
        if(cart_seq_to){
          querySuggest.push('cart_seq_to=' + cart_seq_to);
        }
        if(dog_status){
          querySuggest.push('dog_status=' + encodeURIComponent(dog_status));
        }        
        var nouki_reply_flg = [];
        if(nouki_reply_flg_1){
          nouki_reply_flg.push(1);
        }
        if(nouki_reply_flg_0){
          nouki_reply_flg.push(0);
        }
        if(nouki_reply_flg){
          querySuggest.push('nouki_reply_flg=' + nouki_reply_flg);        
        }
        url += '?' + querySuggest.join('&');

        $.ajax({
            url: url,
            type: 'GET',
            timeout: 600000,
            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_s22');
                    $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.navigation_list_cus_use_code = data.navigation_list;
                    thisTag.update(thisTag.navigation_list_cus_use_code);
                    thisTag.update(thisTag.list_cart);
                    thisTag.list_cart_changed = [];
                    thisTag.update(thisTag.list_cart_changed);
                    $(".maker_dealer_list").each(function(i, e){
                      var index = $(this).attr('index');
                      var cart = thisTag.list_cart[index];
                      var list_option = '';
                      $("#maker_dealer_" + index).html("<option value=''>----</option");
                      $.each(thisTag.maker_dealer_list, function(ii, ee) {
                        let selected = '';
                        if(cart.dealer_co_cd == ee.dealer_co_cd && cart.dealer_dep_cd == ee.dealer_dep_cd){
                          selected = 'selected';
                        }
                        list_option += "<option value='" 
                          + ee.dealer_co_cd + "|" + ee.dealer_dep_cd + "' " + selected + ">"
                          + ee.dealer_co_name + " " + ee.dealer_dep_name
                          + "</option>";
                      })
                      $("#maker_dealer_" + index).append(list_option);
                    });
                    $(".prefecture").change(function(e){
                        thisTag.getMakerDealer(e);
                    });
                    
                    $('.commentOpenUsr').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();
                      }
                    });
                    $('.commentOpenSpp').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();
                      }
                    });
                    $('.commentOpenReco').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();
                      }
                    });
                    $('.statusToolTip').on('click',function(){
                      if($(this).hasClass('active')){
                        $(this).removeClass('active').html('PCA受注データ作成済み');
                        $(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-comment-usr', '', function(opts) {
                          this.root.innerHTML = opts.r1;
                        });
                        riot.tag('description-comment-spp', '', function(opts) {
                          this.root.innerHTML = opts.r1;
                        });
                        riot.mount('#description_comment_usr_' + i, {
                          r1: e.comment_usr
                        });
                        riot.mount('#description_comment_spp_' + i, {
                          r1: e.comment_spp
                        });
                        riot.tag('description-recommended-dealer-name', '', function(opts) {   
                            this.root.innerHTML = opts.r2;
                        });
                        riot.mount('#description_recommended_dealer_name_' + i, {
                            r2: e.recommended_dealer_name
                        })
                        riot.tag('description-status-tooltip', '', function(opts) {   
                            this.root.innerHTML = opts.r3;
                        });
                        riot.mount('#description_status_tooltip_' + i, {
                            r3: '得意先コードがブランクのため、PCAにデータが作成されていません。'
                        })
                        // thisTag.update();
                    });
                    thisTag.commentCstChange();
                    thisTag.testCheckStatus("#check_cart");
                    thisTag.pickDateTime();
                    thisTag.checkIfFirstPage();
                    thisTag.checkIfLastPage(); 
                } else {
                    alert("fail");
                }

            },
            error: function (xhr, stt, err) {
                alert('error');
            }
        });
    }
    this.checkStatusRelated = function(status) {
        var result = '';
        switch(status) {
            case '5':
                result = 'キャンセル数';
                break;
            case '6':
                result = 'キャンセル数';
                break;
            case '8':
                result = '返品数';
                break;
            case '9':
                result = '返品数';
                break;
            case '30':
                result = '分納';
                break;
            case '31':
                result = '分納';
                break;
            case '32':
                result = '出荷連絡済';
                break;
            default:
                break;
        }
        return result;
    }
    </script>

</order-history-s-mc>
