<ec23>
  <link rel="stylesheet" href="css/EC23.css?v=1" type="text/css" />
  <div class="main">
    <div class="content">
      <div class="page-title">
        <h2>見積フォルダ</h2>
      </div>
      <div class="search-wrapper">
        
      </div>
      <div class="table-head">
        <div class="table-head-left">
          <select id="types">
            <option value="0">ステータスで絞り込む</option>
            <option value="1">未依頼</option>
            <option value="2">回答待ち</option>
            <option value="3">回答済み</option>
            <option value="5">見積不可</option>
            <option value="9">削除済み</option>
          </select>
          <!-- <button class="search-btn">検索</button> -->           
        </div>
        <div class="table-head-right">
          <button class="color-btn red-btn" onclick="{addCartAll}"><i class="fa fa-shopping-cart"></i> 一括カート入れ</button>
          <button class="color-btn gray-btn" onclick="{deleteItemCartAll}"><i class="fa fa-times"></i> 一括削除</button>
          <button class="color-btn green-btn submit-checked" onclick="{estimateForUnsolicited}"> 一括見積依頼</button>
        </div>
      </div>
      <div class="table-wrapper">
        <table class="blue-table">
          <thead>
            <tr>
              <th>
                <div>管理番号</div>
                <div>最終更新日</div>
              </th>
              <th style="width:30%">製品情報</th>
              <th>販売店</th>
              <th>見積依頼者</th>
              <th style="width:45px">数量</th>
              <th style="width:70px">
                <div>納入価格</div>
                <div>納入金額</div>
              </th>
              <th style="width:70px">
                <div>定価</div>
                <div>合計</div>
              </th>
              <th>
                <div>販売店への<br/>コメント</div>
                <div>ファイル添付</div>
              </th>
              <th style="width:82px">
                <div>依頼日</div>
                <div>回答日</div>
              </th>
              <th>
                <div>ステータス</div>
                <div>見積期限</div>
                <div>注文履歴</div>
              </th>
              <th style="width:70px"></th>
              <th style="width:20px">一括<br>処理</th>
            </tr>
          </thead>
          <tbody>
            <tr each="{item,index in cart_list}">
              <td style="text-align: center">
                <div >{item.cart_seq}</div>
                <div>{item.updatedate}</div>
              </td>
              <td class="left">
                <dl >
                  <dt>品番</dt>  
                  <dd><a href="{ (item.is_deleted == 1 || !item.item_sku_exist) ? '' : ('#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}</a></dd>
                </dl>
                <dl>
                  <dt>品名</dt>
                  <dd>{item.item_name}</dd>
                </dl>
                <dl>
                  <dt>容量・規格</dt>
                  <dd>{item.capacity}{item.kikaku}</dd>
                </dl>
                <dl>
                  <dt>販売元</dt>
                  <dd>{item.sales_origin_maker_name} {item.supp_name}</dd>
                </dl>
                <dl>
                  <dt>製造元</dt>
                  <dd>{item.maker_name}</dd>
                </dl>
                <dl>
                  <dd><b class="discontinued" style="color:red;display:{(item.is_deleted == 1 ) ? 'block' : 'none'}">販売中止</b></dd>
                </dl>
              </td>
              <td>{item.dealer_co_name} { item.dealer_dep_name }</td>
              <td>{item.customer_user_name}</td>
              <td>
                <input type="text" class="suryo spinner" id="suryo_{index}" name="suryo" value="{item.suryo ? item.suryo : 1}" index={index}>
              </td>
              <td style="{(item.tanka_change_flg==1)?'background-color: #f9e5f1':''}">
                <div if={item.mitsumori_status == 1 || item.mitsumori_status == 2}>{ !isNaN(parseInt(item.tanka)) && item.tanka && item.tanka != 0 ? parseInt(item.tanka).toLocaleString('en') + '円' : (item.mitsumori_status == 2 ? '見積依頼中' : '') }</div>
                <div if={item.mitsumori_status == 1 || item.mitsumori_status == 2}>{ !isNaN(parseInt(item.tanka * item.suryo)) && item.tanka && item.tanka != 0 ? parseInt(item.tanka * (item.suryo  ? item.suryo : 1)).toLocaleString('en') + '円' : (item.mitsumori_status == 2 ? '見積依頼中' : '') }</div>
                <div if={item.mitsumori_status == 3 || item.mitsumori_status == 9 || item.mitsumori_status == 5}>{ !isNaN(parseInt(item.tanka)) && item.tanka != 0 ? parseInt(item.tanka).toLocaleString('en') + '円' : '' }</div>
                <div if={item.mitsumori_status == 3 || item.mitsumori_status == 9  || item.mitsumori_status == 5}>{ !isNaN(parseInt(item.tanka * item.suryo)) && (item.tanka>0 && 0< item.tanka) != 0 ? parseInt(item.tanka * (item.suryo ? item.suryo : 1)).toLocaleString('en') + '円' : '' } </div>
              </td>
              <td>
                <div if={ IWAI_SITE}>
                  
                  <div if={item.iwai_con==0}>
                    { (!isNaN(parseInt(item.teika_tanka)) && item.teika_tanka != 0) ? parseInt(item.teika_tanka ? item.teika_tanka : '').toLocaleString('en') + '円' : '' }
                  </div>
                  <!-- <div if={item.iwai_con==1}>
                    <div if={item.mitsumori_status == 1 || item.mitsumori_status == 2}>
                      { !isNaN(parseInt(item.teika_tanka)) && item.teika_tanka && item.teika_tanka != 0 ? parseInt(item.teika_tanka).toLocaleString('en') + '円' : (item.mitsumori_status == 2 ? '見積依頼中' : '') }
                    </div>
                    <div if={item.mitsumori_status == 1 || item.mitsumori_status == 2}>
                      { (!isNaN(parseInt(item.teika_tanka * item.suryo)) && (item.teika_tanka * item.suryo) != 0) ? parseInt(item.teika_tanka * (item.suryo ? item.suryo : 1)).toLocaleString('en') + '円' : '' }
                    </div>
                    <div if={item.mitsumori_status == 3 || item.mitsumori_status == 9 || item.mitsumori_status == 5}>{ !isNaN(parseInt(item.teika_tanka)) && (item.teika_tanka>0 && 0< item.teika_tanka) ? parseInt(item.teika_tanka).toLocaleString('en') + '円' : '' }</div>

                    <div if={item.mitsumori_status == 3 || item.mitsumori_status == 9}>{ (!isNaN(parseInt(item.teika_tanka * item.suryo)) && (item.teika_tanka * item.suryo) != 0) ? parseInt(item.teika_tanka * (item.suryo ? item.suryo : 1)).toLocaleString('en') + '円' : '' }
                    </div>
                  </div> -->
                </div>
                <div if={!IWAI_SITE}>
                  <div if={item.mitsumori_status == 1 || item.mitsumori_status == 2}>
                    { !isNaN(parseInt(item.teika_tanka)) && item.teika_tanka && item.teika_tanka != 0 ? parseInt(item.teika_tanka).toLocaleString('en') + '円' : (item.mitsumori_status == 2 ? '見積依頼中' : '') }
                  </div>
                  <div if={item.mitsumori_status == 1 || item.mitsumori_status == 2}>
                    { (!isNaN(parseInt(item.teika_tanka * item.suryo)) && (item.teika_tanka * item.suryo) != 0) ? parseInt(item.teika_tanka * (item.suryo ? item.suryo : 1)).toLocaleString('en') + '円' : '' }
                  </div>
                  <div if={item.mitsumori_status == 3 || item.mitsumori_status == 9 || item.mitsumori_status == 5}>{ !isNaN(parseInt(item.teika_tanka)) && (item.teika_tanka>0 && 0< item.teika_tanka) ? parseInt(item.teika_tanka).toLocaleString('en') + '円' : '' }</div>

                  <div if={item.mitsumori_status == 3 || item.mitsumori_status == 9}>{ (!isNaN(parseInt(item.teika_tanka * item.suryo)) && (item.teika_tanka * item.suryo) != 0) ? parseInt(item.teika_tanka * (item.suryo ? item.suryo : 1)).toLocaleString('en') + '円' : '' }
                  </div>
                </div>
              </td>
              <td>
                <div>
                    <span id="comment_usr_color_{item.cart_seq}">(<span id="comment_usr_count_{item.cart_seq}">{ item.comment_usr ? item.comment_usr.length : 0 }</span>/200)</span>
                    <textarea id="comment_usr_{item.cart_seq}" class="comment_usr" name="comment_usr" onchange="{updateCart}">{item.comment_usr}</textarea>
                </div>
                <div>
                  <div style="display: flex;align-items: center;justify-content: center;" if={((item.is_deleted != 1 &&  item.item_sku_exist) || (item.inquiry == 1)) && (item.mitsumori_status == 1 || item.mitsumori_status == 2)}>
                    <i class="fa fa-paperclip add_file file_cart" id="add_file_{index}" index="{index}" if={!item.attachment}></i>
                    <i class="fa fa-times delete-file-icon" id="delete-file-icon_{index}" onclick="{deleteFile}" index="{index}" style="display: none" if={!item.attachment}></i>
                    <button onclick={updateFile} class="" style="margin-left: 5px" type="button" if={item.mitsumori_status == 2 && !item.attachment}>更新</button>
                    <input class="file_upload" id="file_upload_{index}" index={index} type="file" name="file" style="display: none;">
                    <i class="fa fa-file file_cart" onclick="{downloadFile}" if={item.attachment} fileName="{item.attachment}" title="{item.attachment}"></i>

                    <i class="fa fa-times delete-file-icon" id="delete-file-icon_{index}" if={item.attachment && item.mitsumori_status == 2} onclick="{deleteFile}" index="{index}" style="" fileName="{item.attachment}" title="{item.attachment}"></i>
                  </div>
                  <div style="text-align: center;!important" if={item.mitsumori_status == 3 && item.attachment}>
                    <i class="fa fa-file file_cart" onclick="{downloadFile}" fileName="{item.attachment}" title="{item.attachment}"></i>
                  </div>
                </div>
              </td> 
              <td>
                <div if={item.mitsumori_status != 1 }>{item.mitsumori_request_date}</div>
                <div>{item.mitsumori_reply_date}</div>
              </td>
              <td>
                <div style="text-align: center;"  if={item.mitsumori_status==5}>見積不可</div>
                <div style="text-align: center;" >
                  <p >
                    <virtual each={status in mitsumoriStatus} if={status.value == item.mitsumori_status} >
                       {status.label}
                    </virtual>
                  </p>
                  <a class="commentBtn" onclick="{commentModalOpen}" index={index} style="display:{(item.mitsumori_status != 3 || ( item.comment_cst1 == '' || item.comment_cst1 == null ) ) ? 'none':'block'}">回答コメント<i class="fa fa-commenting-o"></i></a>
                  <a class="commentBtn" onclick="{commentModalOpen}" index={index} style="display:{(item.mitsumori_status != 5 || ( item.comment_cst1 == '' || item.comment_cst1 == null ) ) ? 'none':'block'}">回答コメント<i class="fa fa-commenting-o"></i></a>
                  <div style="text-align: center;!important" if={item.attachment1}>
                    <i class="fa fa-file file_cart" onclick="{downloadFile}" fileName="{item.attachment1}" title="{item.attachment1}"></i>
                  </div>
                </div>
                  <div style="text-align: center;{(item.mitsumori_deadline_change_flg  == 1) ? 'background:#f9e5f1':''}" if={item.mitsumori_deadline}>
                    見積期限
                    {item.mitsumori_deadline}
                  </div>
                  <div style="text-align: center;">
                     <virtual each={status in mitsumoriStatusRelated} if={status.value == item.cart_seq_mitsumori_related_status} >
                         {status.label}
                      </virtual>
                  </div>
              </td>
              <td class="btnTd" if={item.dealerCusFlg}>
                  <button class="color-btn red-btn {compareDate(item.mitsumori_deadline) ? 'tooltips' : ''}" data-tooltip={compareDate(item.mitsumori_deadline) ? '見積期限が過ぎています' : ''} onclick={!compareDate(item.mitsumori_deadline) && (item.scm_bio || item.inquiry == 1) ? addCart : ''} index="{index}" style="display:{item.mitsumori_status != 3 || ((!item.item_sku_exist || item.is_deleted == 1) && item.inquiry != 1)  ? 'none' : 'block' }" disabled={compareDate(item.mitsumori_deadline) || (!item.scm_bio && item.inquiry != 1) ? 'disabled' : ''}><i class="fa fa-shopping-cart"></i>カート</button>
                  <button if={item.mitsumori_status == 1 && item.scm_bio} class="color-btn green-btn" onclick={estimateForSingleUnsolicited} index={index}>見積依頼</button>

                  <button if={item.mitsumori_status == 5 && (item.sku==item.item_sku && item.sku) && item.scm_bio} class="color-btn green-btn" onclick={estimateForSingleUnsolicited} index={index} dt="1">見積依頼へ</button>

                  <button class="color-btn gray-btn" onclick="{deleteItemCart}"><i class="fa fa-times"></i>削除</button>
                  <span class="msg-item-sku-exist">{ ((item.inquiry != 1) && (item.is_deleted == 1 || !item.item_sku_exist)) ? 'この商品はカタログから削除されています' : ''}</span>
                  <input type="hidden" id="check_checked_{index}" value="{item.is_deleted}">
              </td>
              <td if={!item.dealerCusFlg}>
                  <p style="width:100px">この販売店事業所への発注／見積依頼は行えません</p>
                  <input type="hidden" id="check_checked_{index}" value="{item.is_deleted}">
              </td>
              <td style="position: relative;">
                <input if={item.dealerCusFlg}  type="checkbox" class="checked-action-{index}" disabled={compareDate(item.mitsumori_deadline) || !item.scm_bio ? 'disabled' : ''}>
                <div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div id="paging" class="text-center">
          <ul class="pagination" id="pagination_carts"></ul>
        </div>
        <!-- <div class="btn-wrapper">
          <p>ボタン押下で未依頼分の見積依頼をします。</p>
          <button class="color-btn green-btn" onclick="{ estimateForUnsolicited }">見積を依頼する</button>
        </div> -->
      </div>
    </div>
  </div>
  <div class="modal-wrapper">
    <div class="o_modal" id="comment-modal">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="comment-modal-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="comment-box">
              <p><description id="description_{comment_index}"></description></p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script>
    /* global $ */
    this.IWAI_SITE = IWAI_SITE;
    this.cart_list = opts.cart_list;
    this.mitsumoriStatus = [
      {value: '1', label: '未依頼'}, 
      {value: '2', label: '回答待ち'}, 
      {value: '3', label: '回答済み'},
      {value: '9', label: '削除済み'}
    ];
    this.mitsumoriStatusRelated = [
      {value: '0', label: 'カート内'}, 
      {value: '4', label: '注文済'}, 
      {value: '5', label: 'キャンセル依頼'},
      {value: '6', label: 'キャンセル済'},
      {value: '7', label: '受注確定'},
      {value: '8', label: '返品依頼'},
      {value: '9', label: '返品済'},
      {value: '10', label: '返品処理完了'},
      {value: '11', label: '承認待ち'},
      {value: '12', label: '承認済み'},
      {value: '13', label: '却下済み'},
      {value: '21', label: 'チェックアウト済'},
      {value: '30', label: '納品済'},
      {value: '31', label: '受入検収済'},
      {value: '32', label: '出荷連絡済'},
      {value: '99', label: 'カート内削除'}
    ];
    this.currentPage = 1;
    this.sort_field = 'updatedate';
    this.sort_value = 'desc';
    this.comment_cst1 = '';
    this.comment_index = '';
    var checkUploaded = false;
    thisTag = this;

    $(function(){
      thisTag.getCartList(thisTag.currentPage);
      // $('.search-btn').click(function(){
      //     thisTag.getCartList(thisTag.currentPage);
      // });
      $('.btn-wrapper').hide();
      $('#comment-modal-close').on('click',function(){
        $('#comment-modal').fadeOut();
      });
      // $('.search-btn').trigger('click');
      $("#types").on('change', function(e){
          var page = 1;
          thisTag.getCartList(page);
      });
      $.each(thisTag.cart_list,function(i,e){
        riot.tag('description', '', function(opts) {   
            this.root.innerHTML = opts.r;
        });
        riot.mount('#description_' + i, {
            r: e.comment_cst1
        })
        thisTag.update();
      });
    })
    $(document).on('keyup', '.comment_usr', function() {
      var id = $(this).attr('id');
      var idExtract = id.split('_');
      var index = idExtract[idExtract.length - 1];
      var thisVal = $(this).val();
      // set the counter
      $('#comment_usr_count_'+index).text(thisVal.length);
      console.log(thisVal.length);
      if( thisVal.length >= 200 ) {
          $('#comment_usr_color_'+index).css('color', 'red');
      } else {
          $('#comment_usr_color_'+index).css('color', '');
      }
    });
    this.compareDate = function(date) {
      var d = new Date();
      var thisDate = d.getFullYear() + '/' + convertDateTime(d.getMonth() + 1) + '/' + convertDateTime(d.getDate());
      var today = new Date(thisDate);
      if(date == '') {
        return false;
      }
      var dateCompare = new Date(date);
      if(dateCompare.getTime() >= today.getTime()) {
        return false;
      }
      return true;
    }
    
    this.updateFile = function (e) {
      var item = e.item;
      let i = item.index;
      var formData = new FormData();
      var data = [];
      if ($('#file_upload_' + i).val() != '' && $('#file_upload_' + i).val() !== undefined) {
        file_upload = $("#file_upload_" + i)[0].files[0];
        formData.append('file_upload_' + item.item.cart_seq, file_upload);
        data.push({
          cart_seq: item.item.cart_seq,
        });
        formData.append('cart_info', JSON.stringify(data));
        var query = [];
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        query.push('token=' + accessTokenCognito);
        query.push('sendmail_flg=' + 0);
        var url = URL_API + '/api/cart/create';
        url += '?' + query.join('&');

        $.ajax({
          url: url,
          type: 'POST',
          timeout: 60000,
          dataType: 'JSON',
          data: formData,
          mimeType: "multipart/form-data",
          contentType: false,
          cache: false,
          processData: false,
          success: function (res) {
            if (res.status == 100) {
              riot.mount('app', 'maintain', {messege: res.messege});
              return false;
            }
            if (res.status == 'not_authorize') {
              var url = "#";
              $(location).attr("href", url);
              return false;
            }
            if (res.message == 'success') {
              alert('ファイルを添付しました。');
              var page = 1;
              thisTag.getCartList(page);
            } else if (res.message == 'errors') {
              alert('ファイルがまだアップできていません。');
            }
          },
          error: function (xhr, stt, err) {
            alert('ファイルがまだアップできていません。');
          }
        });
      }
    }

    function convertDateTime(dateTime){
        if(dateTime.toString().length<2){
            dateTime = '0' + dateTime.toString();
        }
        return dateTime
    }
    this.getCartList = function(page){
      countTotalCart();
       thisTag.currentPage = page; 
       // var inTypes = [];
       // $( "input[name='types[]']" ).each(function(){ 
       //     if($(this).prop( "checked" )){
       //         inTypes.push($(this).val());    
       //     }
       // });
        var inTypes = $("#types").val();
        var query = [];
        var screen = 'ec23';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
         query.push('token=' + accessTokenCognito);
         if(inTypes != 0){
             query.push('mitsumori_status='+inTypes);
         } else if(inTypes == 0){
             inTypes = [1,2,3,5];
             query.push('mitsumori_status='+inTypes);
         }
         query.push('sort_field=' + thisTag.sort_field);
         query.push('sort_value=' + thisTag.sort_value);
         query.push('screen=' + screen);
         query.push('page=' + page);
         query.push('limit=' + LIMIT_ON_PAGE);
          var url = URL_API + '/api/cart/list';
         
         url += '?' + query.join('&');

         $.ajax({
             url: url,
             type: 'GET',
             timeout: 60000,
             success: function (res) {
                  if(res.status == 100){
                      riot.mount('app','maintain',{ messege:res.messege });
                      return false;
                  }
                  if(res.status == 'not_authorize'){
                      var url = "#";
                      $(location).attr("href", url );
                      return false;
                  }
                  if(res.message == 'success'){

                     thisTag.cart_list = res.cart_list;
                     thisTag.cart_list = thisTag.cart_list.filter(function(item) {
                            if(item.comment_usr){
                              item.comment_usr = item.comment_usr.replace(/<br>/g, "\n");  
                            }
                             return item;

                      });
                     if(res.cart_list.length>0 ){
                         $('.btn-wrapper').show();
                     }else{
                         $('.btn-wrapper').hide();
                     }
                     var totalPages = Math.ceil(res.total/LIMIT_ON_PAGE);
                        thisTag.total_page = totalPages;
                    var visiblePages = 1;
                    if(totalPages != 0){
                        visiblePages =  5;
                    } 
                    var $pagination = $('#pagination_carts');
                    $pagination.twbsPagination('destroy');
                    $pagination.twbsPagination({
                        totalPages: totalPages,
                        visiblePages: visiblePages,
                        startPage: thisTag.currentPage,
                        initiateStartPageClick: false,
                        onPageClick: function (event, page) {

                            thisTag.getCartList(page);
                        }
                    });
                     
                     thisTag.update(thisTag.cart_list);
                     selectFile();
                     var spinner = $( ".spinner" ).spinner();
                     $( ".suryo" ).spinner({
                        stop: function( event, ui ) {
                            var index = event.target.attributes.index.value;
                            var target = $(event.target);
                            var thisTr = $(event.target).parents('tr');
                            var suryo = thisTr.find("input[name='suryo']").val();
                            
                            if(suryo.length > 10){
                                alert('数量を10文字以内に入力してください。');
                                suryo = thisTr.find("input[name='suryo']").val(1)
                                return false;
                            }

                            var patt = /^(0)?(\.\d+)?$/;
                            var patt2 = /^([1-9]+)([0-9]*)$/;
                            if(!patt2.test(suryo)){
                                alert('数量を正数のみで入力してください。');
                                thisTr.find("input[name='suryo']").val(1);
                                suryo = 1;
                            }
                            thisTag.cart_list[index].suryo = suryo;
                            thisTag.update(thisTag.cart_list);
                            $.each(thisTag.cart_list,function(i,e){
                                riot.tag('description', '', function(opts) {   
                                    this.root.innerHTML = opts.r;
                                });
                                riot.mount('#description_' + i, {
                                    r: e.comment_cst1
                                })
                                thisTag.update();
                            });
                        }
                    });
                    $.each(thisTag.cart_list,function(i,e){
                        riot.tag('description', '', function(opts) {   
                            this.root.innerHTML = opts.r;
                        });
                        riot.mount('#description_' + i, {
                            r: e.comment_cst1
                        })
                        thisTag.update();
                    });
                 }
             },
             error: function (xhr, stt, err) {
                 alert('error');
             }
         });
       
    }
    /*  ↓↓↓ NEW ↓↓↓  */
    this.commentModalOpen = function(e){
        $('#comment-modal').fadeIn();
        var comment = e.item.item.comment_cst1;
        thisTag.comment_index = e.item.index;
        thisTag.comment_cst1 = comment;
        thisTag.update(thisTag.comment_cst1);
        thisTag.update(thisTag.comment_index);
        $.each(thisTag.cart_list,function(i,e){
            riot.tag('description', '', function(opts) {   
                this.root.innerHTML = opts.r;
            });
            riot.mount('#description_' + i, {
                r: e.comment_cst1
            })
            thisTag.update();
        });
    }
    this.addCart = function(e){
        var target = $(e.target);
        var thisTr = $(e.target).parents('tr');
        var index = $(target).attr("index");
        var agent = localStorage.getItem('agent_id');
        var deleted = $("#check_checked_"+index).val();
        if(deleted == 1){
          alert("商品の販売が中止されました。");
          return false;
        }
        
        var suryo = thisTr.find(".suryo").val();
        if(suryo == ''){
          alert("数量は必須項目です。");
          thisTr.find(".suryo").val(1);
          return false;
        }
        var item = e.item.item;
        var query = [];
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            query.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/cart/create';
        
        url += '?' + query.join('&');
        var supplier_system_sku = item.supplier_system_sku;
        if(supplier_system_sku == '' || supplier_system_sku == null){
          supplier_system_sku = item.supp_sku;
        }
        var data = [];
            data.push({
                cart_seq_mitsumori_related: item.cart_seq,
                dealer_co_cd: item.dealer_co_cd,
                dealer_co_name: item.dealer_co_name,
                dealer_dep_cd: item.dealer_dep_cd,
                dealer_dep_name: item.dealer_dep_name,
                customer_co_cd:item.customer_co_cd,
                customer_dep_cd:item.customer_dep_cd,
                supp_co_cd: item.supp_co_cd,
                supp_co_name: item.supp_co_name,
                maker_name:item.maker_name,
                supp_sku: item.supp_sku,
                item_sku: item.item_sku,
                supplier_system_sku: supplier_system_sku,
                item_name: item.item_name,
                capacity: item.capacity,
                kikaku: item.kikaku,
                suryo: item.suryo,
                tanka: item.tanka,
                teika_tanka: item.list_price,
                agent_users_id: agent,
                inquiry: item.inquiry,
                supp_name: item.supp_name,
                // comment_cst1:'見積管理番号：' + item.cart_seq,
                // mitsumori_request_date: mitsumori_request_date
                status: 0
            });

        $.ajax({
            url: url,
            type: 'POST',
            timeout: 60000,
            data: {
                data: data
            },
            success: function (res) {
                if(res.status == 100){
                    riot.mount('app','maintain',{ messege:res.messege });
                    return false;
                }
                if(res.status == 'not_authorize'){
                    var url = "#";
                    $(location).attr("href", url );
                    return false;
                }
                if(res.message == 'success'){
                    alert('カートに追加しました。\nカート画面から発注処理を行ってください。');
                    var page = 1;
                    thisTag.getCartList(page);
                }else if(res.message == 'errors'){
                    alert("処理が実行できませんでした。時間をおいて再度お試しください。同様のメッセージが再度出る場合はお手数ですがシステム提供者にご連絡ください。");
                }
            },
            error: function (xhr, stt, err) {
                alert('error');
            }
        });
    }
    
    this.deleteItemCart = function(e){
        var target = $(e.target);
        var thisTr = $(e.target).parents('tr');
        var agent = localStorage.getItem('agent_id');
        var item = e.item;
        var query = [];
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            query.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/cart/delete';

        url += '?' + query.join('&');
        
        var data = [];
            data.push({
                cart_seq: item.item.cart_seq,
                agent_users_id: agent,
                old_attachment: item.item.attachment
            });

       $.ajax({
            url: url,
            type: 'POST',
            timeout: 60000,
            data: {
                data: data
            },
            success: function (res) {
                if(res.status == 100){
                    riot.mount('app','maintain',{ messege:res.messege });
                    return false;
                }
                if(res.status == 'not_authorize'){
                    var url = "#";
                    $(location).attr("href", url );
                    return false;
                }
                if(res.message == 'success'){
                    alert('削除しました。');
                    var page = 1;
                    thisTag.getCartList(page);
                }
            },
            error: function (xhr, stt, err) {
                alert('error');
            }
        }); 
    }
    this.updateSuryoCart = function(e){
        var target = $(e.target);
        var thisTr = $(e.target).parents('tr');
        var suryo = thisTr.find("input[name='suryo']").val();
        
        if(suryo.length > 10){
            alert('数量を10文字以内に入力してください。');
            suryo = thisTr.find("input[name='suryo']").val(1)
            return false;
        }
        var patt = /^(0)?(\.\d+)?$/;
        var patt2 = /^([1-9]+)([0-9]*)$/;
        if(!patt2.test(suryo)){
            alert('数量を正数のみで入力してください。');
            thisTr.find("input[name='suryo']").val(1);
            suryo = 1;
        }
        var itemUpdate = e.item;
        itemUpdate.item.suryo = suryo;
        this.cart_list = this.cart_list.filter(function(item) {
           if(this.item.cart_seq == item.cart_seq){
               return this;
           }else{
               return item;
           }
           
        }, itemUpdate);
    }
    this.updateCart = function(e){
        var target = $(e.target);
        var thisTr = $(e.target).parents('tr');
        var comment_usr = thisTr.find("textarea[name='comment_usr']").val();
        var itemUpdate = e.item;
        itemUpdate.item.comment_usr = comment_usr;
        this.cart_list = this.cart_list.filter(function(item) {
           if(this.item.cart_seq == item.cart_seq){
               return this;
           }else{
               return item;
           }
        }, itemUpdate);
        
    }
    this.estimateForUnsolicited = function(e){
        var checkSuryo = true;
        var item_sku_exist = true;
        var is_deleted = false;
        var pattern = /^[0-9]*$/;
        var checkMitsumoriStatus = true;
        var error = [];
        var submitChecked = $(e.target).hasClass("submit-checked");
        var query = [];
        var comment_usr_max_error = 0;
        var agent = localStorage.getItem('agent_id');
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            query.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/cart/create';
        

        url += '?' + query.join('&');
        
        var data = [];
        var formData = new FormData();
        var d = new Date();
        var mitsumori_request_date = d.getFullYear() + '-' + convertDateTime(d.getMonth()+1) + '-' + convertDateTime(d.getDate()) + ' ' + convertDateTime(d.getHours()) + ':' +convertDateTime(d.getMinutes()) + ':' + convertDateTime(d.getSeconds());
        for (var i = 0; i < thisTag.cart_list.length; i++) {
            var checked = $(".checked-action-" + i).is(":checked");
            if (checked && $('#file_upload_' + i).val() != '' && $('#file_upload_' + i).val() !== undefined) {
              file_upload = $("#file_upload_" + i)[0].files[0];
              formData.append('file_upload_' + thisTag.cart_list[i].cart_seq, file_upload);
            }
        }
        $.each(thisTag.cart_list, function( index, item ) {
          if(submitChecked){
            var checked = $(".checked-action-" + index).is(":checked");
            if(checked) {
              if(item.is_deleted == 1){
                  is_deleted = true;
              }
              if(!item.item_sku_exist){
                  item_sku_exist = false;
              }

              var suryo = $("#suryo_" + index).val();
              if(suryo == '' || !pattern.test(suryo)){
                checkSuryo = false;
                $("#suryo_" + index).val(1);
              }

              if(item.mitsumori_status == '1'){
                  if(item.comment_usr){
                      item.comment_usr = item.comment_usr.replace(/\n/g, "<br>");  
                  }
                  data.push({
                      cart_seq: item.cart_seq,
                      dealer_co_cd: item.dealer_co_cd,
                      dealer_dep_cd: item.dealer_dep_cd,
                      suryo: item.suryo,
                      comment_usr: item.comment_usr,
                      mitsumori_status: 2,
                      agent_users_id: agent,
                      mitsumori_request_date: mitsumori_request_date
                  });
                  
              } else {
                checkMitsumoriStatus = false;
              }
              if($('#comment_usr_' + item.cart_seq).val().length >= 200){
                comment_usr_max_error++;
              }
            }
          } else {
            if(item.is_deleted == 1){
                is_deleted = true;
            }
            if(!item.item_sku_exist){
                item_sku_exist = false;
            }
            var suryo = $("#suryo_" + index).val();
            if(suryo == '' || !pattern.test(suryo)){
              checkSuryo = false;
              $("#suryo_" + index).val(1);
            }

            if(item.mitsumori_status == '1'){
                if(item.comment_usr){
                    item.comment_usr = item.comment_usr.replace(/\n/g, "<br>");  
                }
                data.push({
                    cart_seq: item.cart_seq,
                    dealer_co_cd: item.dealer_co_cd,
                    dealer_dep_cd: item.dealer_dep_cd,
                    suryo: item.suryo,
                    comment_usr: item.comment_usr,
                    mitsumori_status: 2,
                    agent_users_id: agent,
                    mitsumori_request_date: mitsumori_request_date
                });
                formData.append('cart_info', JSON.stringify(data));
            } else {
              checkMitsumoriStatus = false;
            }
          }
        });
        // $('.suryo').each(function(i,e){
        //   if(e.value == '' || !pattern.test(e.value)){
        //     checkSuryo = false;
        //   }
        // });
        formData.append('cart_info', JSON.stringify(data));
        if(checkMitsumoriStatus == false) {
            error.push("未依頼の処理対象を選択してください\n");
        }
        if(checkSuryo == false){
            error.push("数量は必須項目です。\n");
        }
        if(!item_sku_exist || is_deleted){
            error.push("カタログから削除された商品が含まれています。\nその商品を見積フォルダから削除の上、再度見積依頼をお願いします。\n");
        }
        if(comment_usr_max_error){
          error.push("販売店へのコメントを200文字以内で入れてください。\n");
        }
        if(error.length > 0){
            alert(error.join(""));
            return false;
        }

        if(data.length>0){
           $.ajax({
                url: url,
                type: 'POST',
                timeout: 60000,
                dataType: 'JSON',
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache : false,
                processData: false,
                success: function (res) {
                    if(res.status == 100){
                        riot.mount('app','maintain',{ messege:res.messege });
                        return false;
                    }
                    if(res.status == 'not_authorize'){
                        var url = "#";
                        $(location).attr("href", url );
                        return false;
                    }
                    if(res.message == 'success'){
                        alert('見積依頼をしました。\n販売店からの見積回答をお待ちください。');
                        var page = 1;
                        thisTag.getCartList(page);
                    }else if(res.message == 'errors'){
                        thisTag.cart_list = thisTag.cart_list.filter(function(item) {
                            if(item.comment_usr){
                              item.comment_usr = item.comment_usr.replace(/<br>/g, "\n");  
                            }
                             return item;

                        });
                        thisTag.update();
                        
                        // var msg = [];
                        // for(var i in res.errors){
                        //     var errors = res.errors[i];
                        //     for( var k in errors){
                        //         for(var h in errors[k]){
                        //             if($.inArray(errors[k][h], msg ) == -1){
                        //                 msg.push(errors[k][h]);
                        //             }
                        //         }
                        //     }
                        // }
                        
                        // alert(msg.join("\n"));
                        alert("処理が実行できませんでした。時間をおいて再度お試しください。同様のメッセージが再度出る場合はお手数ですがシステム提供者にご連絡ください。");
                    }
                },
                error: function (xhr, stt, err) {
                    alert('error');
                }
            });
       }else{
           alert('処理対象を選択してください。');
       }
       
    }
    
    this.addCartAll = function(e){
        var checkSuryo = true;
        var item_sku_exist = true;
        var item_mitsu_status_wrong = true;
        var is_deleted = false;
        var pattern = /^[0-9]*$/;
        var error = [];
        var query = [];
        var agent = localStorage.getItem('agent_id');
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            query.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/cart/create';
        
        url += '?' + query.join('&');
        
        var data = [];
        $.each(thisTag.cart_list, function( index, item ) {

          var checked = $(".checked-action-" + index).is(":checked");

          if(checked) {

            if(item.is_deleted == 1){
                is_deleted = true;
            }

            if(!item.item_sku_exist && item.inquiry != 1){
                  item_sku_exist = false;
            }
            if(IWAI_SITE) {
              var suryo = $("#suryo_" + index).val();
              if(suryo == '' || !pattern.test(suryo)){
                checkSuryo = false;
                $("#suryo_" + index).val(1);
              }
            }

            if(item.mitsumori_status == 3) {
              data.push({
                cart_seq_mitsumori_related: item.cart_seq,
                dealer_co_cd: item.dealer_co_cd,
                dealer_co_name: item.dealer_co_name,
                dealer_dep_cd: item.dealer_dep_cd,
                customer_co_cd:item.customer_co_cd,
                customer_dep_cd:item.customer_dep_cd,
                supp_co_cd: item.supp_co_cd,
                supp_co_name: item.supp_co_name,
                maker_name:item.maker_name,
                supp_sku: item.supp_sku,
                item_sku: item.item_sku,
                item_name: item.item_name,
                capacity: item.capacity,
                kikaku: item.kikaku,
                suryo: item.suryo,
                tanka: item.tanka,
                teika_tanka: item.list_price,
                agent_users_id: agent,
                inquiry: item.inquiry,
                // comment_cst1:'見積管理番号：' + item.cart_seq,
                status: 0
              });
            } else {
              item_mitsu_status_wrong = false;
            }
            
          }
          
        });

        if(!item_mitsu_status_wrong) {
            error.push("カートに入れられる商品はステータス：「回答済み」のみとなります\n");
        }
        
        if(IWAI_SITE) {
          if(checkSuryo == false){
              error.push("数量は必須項目です。\n");
          }
        }

        if(!item_sku_exist || is_deleted){
            error.push("カタログから削除された商品が含まれています。\nその商品を見積フォルダから削除の上、再度見積依頼をお願いします。\n");
        }

        if(error.length > 0){
            alert(error.join(""));
            return false;
        }

        if(data.length>0){
           $.ajax({
                url: url,
                type: 'POST',
                timeout: 60000,
                data: {
                    data: data
                },
                success: function (res) {
                    if(res.status == 100){
                        riot.mount('app','maintain',{ messege:res.messege });
                        return false;
                    }
                    if(res.status == 'not_authorize'){
                        var url = "#";
                        $(location).attr("href", url );
                        return false;
                    }
                    if(res.message == 'success'){
                        alert('カートに追加しました。\nカート画面から発注処理を行ってください。');
                        var page = 1;
                        thisTag.getCartList(page);
                    } else if(res.message == 'errors'){
                        
                    }
                },
                error: function (xhr, stt, err) {
                    alert('error');
                }
            });
       } else {
           alert('処理対象を選択してください。');
       }
       
    }
    this.deleteItemCartAll = function(e){
        
        if(!confirm("選択した商品を削除しますか")) {
          return false;
        }
        
        var query = [];
        var agent = localStorage.getItem('agent_id');
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            query.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/cart/delete';
        
        url += '?' + query.join('&');
        
        var data = [];
        $.each(thisTag.cart_list, function( index, item ) {

          var checked = $(".checked-action-" + index).is(":checked");

          if(checked) {
            data.push({
                cart_seq: item.cart_seq,
                agent_users_id: agent,
                old_attachment: item.attachment
            });
          }
              
        });

        if(data.length > 0){
           $.ajax({
                url: url,
                type: 'POST',
                timeout: 60000,
                data: {
                    data: data
                },
                success: function (res) {
                    if(res.status == 100){
                        riot.mount('app','maintain',{ messege:res.messege });
                        return false;
                    }
                    if(res.status == 'not_authorize'){
                        var url = "#";
                        $(location).attr("href", url );
                        return false;
                    }
                    if(res.message == 'success'){
                        alert('削除しました。');
                        var page = 1;
                        thisTag.getCartList(page);
                    } else if(res.message == 'errors'){
                        
                    }
                },
                error: function (xhr, stt, err) {
                    alert('error');
                }
            });
       }else{
           alert('処理対象を選択してください。');
       }
    }

    this.downloadFile = function(e){
      var fileName = $(e.target).attr('fileName');
      fileName = JSON.stringify(fileName);
      var agent = localStorage.getItem('agent_id');
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var query = [];
      query.push('token=' + accessTokenCognito);
      query.push('fileName=' + fileName);
      var url = URL_API + '/api/cart/downloadFile';
      url += '?' + query.join('&');
      var req = new XMLHttpRequest();
      req.open("GET", url, true);
      req.onloadstart = function () {
        $('#img-loader').show();
      }
      req.onloadend = function () {
        $('#img-loader').hide();
      }
      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"});
                  },60000);
              }
          }
      }, false);

      req.responseType = "blob";
      req.onreadystatechange = function () {
        var fileName = $(e.target).attr('fileName');
        if (req.readyState === 4) {
            if (req.status === 200) {
                var filename = $(e.target).attr('fileName');
                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));
                }
            } else if (req.status === 400) {
              alert("ファイルがダウンロードできません。");
              return false;
            }
            $('#img-loader').hide();
        }
      };
      req.send();
    }
    
    this.deleteFile = function (e) {
      var index = $(e.target).attr('index');
      if (index) {
        $('#file_upload_' + index).val('');
        $('#delete-file-icon_' + index).hide();
        noFile(index);
      }
      var fileName = $(e.target).attr('fileName');
      if (fileName) {
          var item = e.item;
          var query = [];
          var accessTokenCognito = localStorage.getItem('accessTokenCognito');
          query.push('token=' + accessTokenCognito);
          query.push('sendmail_flg=' + 0);
          var url = URL_API + '/api/cart/create';
          
          url += '?' + query.join('&');
          
          var data = [];
              data.push({
                  cart_seq: item.item.cart_seq,
                  old_attachment: item.item.attachment,
                  backup_flag: 0,
                  attachment: '',
              });
          $.ajax({
              url: url,
              type: 'POST',
              timeout: 60000,
              data: {
                data: data,
              },
              success: function (data) {
                  if(data.status == 100){
                      riot.mount('app','maintain',{ messege:data.messege });
                      return false;
                  }
                  if(data.message == 'success'){
                      var page = 1;
                      thisTag.getCartList(page);
                  }
               
              },
              error: function (xhr, stt, error) {
                  alert('エラー');
              }
          });
        
      }
    }

    this.estimateForSingleUnsolicited = function(e){

        var checkSuryo = true;
        var item_sku_exist = true;
        var is_deleted = false;
        var pattern = /^[0-9]*$/;
        var checkMitsumoriStatus = true;
        var error = [];
        var submitChecked = $(e.target).hasClass("submit-checked");
        var query = [];
        var comment_usr_max_error = 0;
        var agent = localStorage.getItem('agent_id');
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            query.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/cart/create';
        var i = $(e.target).attr('index');
        var item = thisTag.cart_list[i];
        url += '?' + query.join('&');
        var data = [];
        var formData = new FormData();
        var d = new Date();
        var mitsumori_request_date = d.getFullYear() + '-' + convertDateTime(d.getMonth()+1) + '-' + convertDateTime(d.getDate()) + ' ' + convertDateTime(d.getHours()) + ':' +convertDateTime(d.getMinutes()) + ':' + convertDateTime(d.getSeconds());
        if ($('#file_upload_' + i).val() != '' && $('#file_upload_' + i).val() !== undefined) {
          file_upload = $("#file_upload_" + i)[0].files[0];
          formData.append('file_upload_' + thisTag.cart_list[i].cart_seq, file_upload);
        }
        
        if (item.is_deleted == 1) {
          is_deleted = true;
        }
        if (!item.item_sku_exist) {
          item_sku_exist = false;
        }
        var suryo = $("#suryo_" + i).val();
        if (suryo == '' || !pattern.test(suryo)) {
          checkSuryo = false;
          $("#suryo_" + i).val(1);
        }
        if (item.mitsumori_status == '1' || item.mitsumori_status == '5') {
            var dr = $(e.target).attr('dt');
            if((dr=='1' && dr!="undefined") && (item.comment_usr=="" || item.comment_usr=='null' || item.comment_usr==null)){
              alert("販売店へのコメントは入力必須です。");
              return false;
            }
            if(item.comment_usr){
                item.comment_usr = item.comment_usr.replace(/\n/g, "<br>");
            }
            if($('#comment_usr_' + item.cart_seq).val().length >= 200){
              comment_usr_max_error++;
            }
            data.push({
                cart_seq: item.cart_seq,
                dealer_co_cd: item.dealer_co_cd,
                dealer_dep_cd: item.dealer_dep_cd,
                suryo: item.suryo,
                comment_usr: item.comment_usr,
                mitsumori_status: 2,
                agent_users_id: agent,
                mitsumori_request_date: mitsumori_request_date
            });
            formData.append('cart_info', JSON.stringify(data));
        } else {
          checkMitsumoriStatus = false;
        }
        formData.append('cart_info', JSON.stringify(data));
        if (checkMitsumoriStatus == false) {
            error.push("未依頼の処理対象を選択してください\n");
        }
        if (checkSuryo == false) {
            error.push("数量は必須項目です。\n");
        }
        if (!item_sku_exist || is_deleted) {
            error.push("カタログから削除された商品が含まれています。\nその商品を見積フォルダから削除の上、再度見積依頼をお願いします。\n");
        }
        if(comment_usr_max_error){
          error.push("販売店へのコメントを200文字以内で入れてください。\n");
        }
        if (error.length > 0) {
            alert(error.join(""));
            return false;
        }

        if (data.length>0) {
           $.ajax({
            url: url,
            type: 'POST',
            timeout: 60000,
            dataType: 'JSON',
            data: formData,
            mimeType: "multipart/form-data",
            contentType: false,
            cache : false,
            processData: false,
            success: function (res) {
              if(res.status == 100){
                riot.mount('app','maintain',{ messege:res.messege });
                return false;
              }
              if(res.status == 'not_authorize'){
                var url = "#";
                $(location).attr("href", url );
                return false;
              }
              if(res.message == 'success'){
                alert('見積依頼をしました。\n販売店からの見積回答をお待ちください。');
                var page = 1;
                thisTag.getCartList(page);
              }else if(res.message == 'errors'){
                thisTag.cart_list = thisTag.cart_list.filter(function(item) {
                  if(item.comment_usr){
                    item.comment_usr = item.comment_usr.replace(/<br>/g, "\n");
                  }
                  return item;
                });
                thisTag.update();
                alert("処理が実行できませんでした。時間をおいて再度お試しください。同様のメッセージが再度出る場合はお手数ですがシステム提供者にご連絡ください。");
              }
            },
            error: function (xhr, stt, err) {
              alert('error');
            }
        });
      } else {
        alert('処理対象を選択してください。');
      }
    }
    </script>
    
</ec23>