<s05>
  <link rel="stylesheet" href="css/S05.css" type="text/css" />
  <link rel="stylesheet" href="css/common.css" type="text/css" />
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://rawgit.com/jquery/jquery-ui/master/ui/i18n/datepicker-ja.js"></script>

  <style>
/* Popup container - can be anything you want */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* datepicker */
.ui-datepicker-calendar .day-sunday > a,
.ui-datepicker-calendar .day-holiday > a {
  background: #ffc0c0;
}
.ui-datepicker-calendar .day-saturday > a {
  background: #c0d0ff;
}

/* The actual popup */
.popup .show_pop_up {
  visibility: hidden;
  /*width:200px;*/
  border: 1px solid #bbb;
  background-color: #e8effc;
  color: #000;
  text-align: center;
  border-radius: 6px;
  padding: 8px 5px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 0;
  margin-left: -140px;
  border-left: 6px solid #ccc;
  border-bottom: 10px solid #ccc;
  border-right: 6px solid #ccc;
  border-top: 15px solid #ccc;
}
.confirm-msg-footer{
  border-top: 1px solid lightgray;
  padding: 5px
}
.pop-up-text{
  padding: 5px
}
/* Popup arrow */
.popup .show_pop_up::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: 30px;
  border-width: 17px;
  border-style: solid;
  border-color: #ccc transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}
.popup .hide {
  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">
        <!-- <table>
          <tr>
            <td>
              <input type="text" class="mitsumori_request_start_date" placeholder="yyyy/mm/dd"> ~ <input type="text" class="mitsumori_request_end_date" placeholder="yyyy/mm/dd">
            </td>
            <td>
              <button class="search-btn"><i class="fa fa-search"></i>見積依頼日で絞り込む</button>
            </td>
          </tr>
        </table> -->
        <div class="row">
            <div class="form-row">
              <div class="form-group col-md-3">
                <label for="from-date">見積依頼日(から)</label>
                <input type="text" class="form-control mitsumori_request_start_date datepicker" id="from-date" placeholder="YY/MM/DD">
              </div>
              <div class="form-group col-md-1" style="margin:0px;padding:0px;width:15px">
                <label style="margin-top:30px;position:absolute;padding: 0;">～</label>
              </div>
              <div class="form-group col-md-3">
                <label for="to-date">見積依頼日(まで)</label>
                <input type="text" class="form-control mitsumori_request_end_date datepicker1" id="to-date" placeholder="YY/MM/DD">
              </div>
              
              <div class="form-group col-md-3">
                <label for="cart-seq">管理番号</label>
                <input type="text" class="form-control cartSeq" id="cartSeq" placeholder="管理番号">
              </div>
              <div class="form-group col-md-2 align-class" style="margin-top:20px">
                <button class="btn btn-primary pull-right align-class btn-md search-btn-main"><i class="fa fa-search"></i> 検索</button>
              </div>
            </div>
          </div>
      </div>
      <div class="select-box" id="search_select_box">
        <div class="d-flex mitsumori-filter" style="width:65%;">
          <select id="mitsumori_status" onchange="{filterByMitsumoriStatus}">
              <option each="{mitsumoriStatus in mitsumoriStatuses}" selected="{mitsumoriStatus.select}" value="{mitsumoriStatus.value}">{mitsumoriStatus.label}</option> 
          </select>
          <div class="div-wraper-autocompleter" style="width:100% !important;"><input style="width:100%;" type="text" id="customer_co_cd" placeholder="顧客で絞り込む"></div>
          <select style="width:55%;" id="customer_dep_cd">
              <option value="">顧客部署で絞り込む</option>
              <option each="{ list in kyotenNameList }" value="{list.kyoten_code}">{list.kyoten_name}</option>
          </select>
        </div>
        <div class="btn-groups">
          <button class="add-new-cart" style="width: 200px;background: #f1c232">新規見積回答を作成する</button>
          <button class="color-btn green-btn" onclick="{addCarts}">一括見積回答</button>
        </div>
      </div>
      <div class="table-wrapper" id="search-table">
        <table class="blue-table">
          <thead>
            <tr>
              <th style="width:82px">
                <div>管理番号</div>
                <div>見積依頼日</div>
                <div>最終更新日</div>
              </th>
              <th>お客様</th>
              <th style="width:30%">製品情報</th>
              <th style="width:50px">数量</th>
              <th style="width:70px">
                <div>納入価格</div>
                <div>納入金額</div>
              </th>
              <th style="width:70px">
                <div>定価</div>
                <div>合計</div>
              </th>
              <th>お客様への<br>コメント</th>
              <th>
                <div>ステータス</div>
                <div>受注履歴</div>
              </th>
              <th style="width:100px">見積期限</th>
              <!-- <th if={mitsumori_status != 3}></th> -->
              <th></th>
              <th>回答<br/>対象</th>
            </tr>
          </thead>
          <tbody>
            <tr each={carts,index in cartsList}>
              <td>
                <div>{carts.cart_seq}</div>
                <div>{carts.mitsumori_request_date}</div>
                <div>{carts.updated_date}</div>
              </td>
              <td class="left">
                  <div>
                    { (carts.ec_users_id !== checkAll) ? (( kikanNameList[carts.ec_users_id].kikan_name ) ? kikanNameList[carts.ec_users_id].kikan_name+''+(kikanNameList[carts.ec_users_id].shozoku_name ? kikanNameList[carts.ec_users_id].shozoku_name : '') : carts.customer_co_name + '' + carts.customer_dep_name + '' + carts.customer_business_name) : (carts.customer_co_name + '' + carts.customer_dep_name) }
                  </div>
                  <div> { (carts.ec_users_id !== checkAll) ? (( kikanNameList[carts.ec_users_id].kikan_name ) ? kikanNameList[carts.ec_users_id].name : carts.customer_user_name) : ''}
                    <button class="customer-name-selection" index={index} if={carts.ec_users_id == checkAll}>お客様名選択</button>
                    <div style="margin-top: 5px;text-align: center;!important" if={carts.mitsumori_status != 1 && carts.attachment}>
                      <i class="fa fa-file file_cart" title="{carts.attachment}"  onclick="{downloadFile}" fileName="{carts.attachment}"></i>
                    </div>
                  </div>
              </td>
              <td class="left" style="{(carts.tanka_change_flg == 1 || carts.mitsumori_deadline_change_flg ==1) ? 'background:#f9e5f1':''}">
                <dl>
                  <dt>品番</dt>
                  <dd><a href="{(carts.is_deleted == 1 || !carts.item_sku_exist) ? '' : (s08_allow == true ? '#s09' + '/basic_details/' + encodeURIComponent(carts.item_sku) : '#search' + '/basic_details/' + encodeURIComponent(carts.item_sku)) }" style="{ (carts.is_deleted == 1 || !carts.item_sku_exist) ? 'color:black;text-decoration:none;cursor: auto;' : '' }">{carts.supp_sku}</a></dd>
                </dl>
                <dl>
                  <dt>品名</dt>
                  <dd>{carts.item_name}</dd>
                </dl>
                <dl>
                  <dt>容量・規格</dt>
                  <dd>{carts.capacity} {(carts.capacity != '' && carts.kikaku != '') ? '・' : '' } {carts.kikaku}</dd>
                </dl>
                <dl>
                  <dt>販売元</dt>
                  <dd>{carts.supp_co_name} {carts.supp_name}</dd>
                </dl>
                <dl>
                  <dt>製造元</dt>
                  <dd>{carts.maker_name}</dd>
                </dl>
                <dl style="float: right;margin-right: 10px" if={carts.inquiry == 1 && (carts.mitsumori_status == 2 || carts.mitsumori_status == 5)}>
                  <!-- <dt>販売元</dt> -->
                  <button index={index} class="inquiry-edit">製品情報更新</button>
                </dl>
                <dl>
                  <dd>
                    <b class="discontinued" style="color:red;display:{(carts.is_deleted == 1 ) ? 'block' : 'none'}">販売中止</b>
                  </dd>
                </dl>
                <p>
              </td>
              <td>
                <input type="hidden" class="cartSuryo" name="cartData[{index}][suryo]" index="{index}" readonly="{(carts.mitsumori_status == 2 || carts.mitsumori_status == 3) ? 'readonly':''}" id="suryo-{index}" value="{carts.suryo}">
                <span if={!(carts.inquiry == 1 && (carts.mitsumori_status == 2 || carts.mitsumori_status == 5))}> {carts.suryo}</span>
                <input if={(carts.inquiry == 1 && (carts.mitsumori_status == 2 || carts.mitsumori_status == 5)) || ((carts.mitsumori_status == 2 || carts.mitsumori_status == 5) && carts.suryo == null)} type="text" class="suryo" onchange="{changeSuryo}" id="suryo_{index}" name="suryo" value="{carts.suryo}" index={index}>
              </td>
              <td class="right" style="{(carts.tanka_change_flg == 1) ? 'background:#f9e5f1':''}">
                <div>
                  <input type="text" class="cartTanka" name="cartData[{index}][tanka]" index="{index}" id="tanka-{index}" value="{carts.tanka}" readonly="{(carts.mit_status != '000')?'readonly':''}" style="{(carts.mit_status != '000')?'background-color:#d1d1d1;cursor: pointer;opacity:0.6':''}">

                  <input type="hidden" class="cartTanka" name="cartData[{index}][Oldtanka]" index="{index}" id="old-tanka-{index}" value="{carts.tanka}" >
                </div>
                <div id="suryo-tanka-{index}">{ !isNaN(parseInt(carts.suryo_input * carts.tanka)) ? parseInt(carts.suryo_input * carts.tanka).toLocaleString('en') + '円' : '' }</div>
              </td>
              <td class="right">
                <div>
                  <input type="hidden" class="cartTeikaTanka" name="cartData[{index}][teika_tanka]" index="{index}" id="teika-tanka-{index}" readonly="{(carts.mitsumori_status == 2 || carts.mitsumori_status == 3) ? 'readonly':''}" value="{carts.teika_tanka}">
                  { !isNaN(parseInt(carts.teika_tanka)) ? parseInt(carts.teika_tanka).toLocaleString('en') + '円' : '' }
                </div>
                <div id="suryo-teika-tanka-{index}">{ !isNaN(parseInt(carts.suryo * carts.teika_tanka)) ? parseInt(carts.suryo * carts.teika_tanka).toLocaleString('en') + '円' : '' }</div>
              </td>
              <td>
                <span id="comment_cst1_color_{carts.cart_seq}">(<span id="comment_cst1_count_{carts.cart_seq}">{ carts.comment_cst1 ? carts.comment_cst1.length : 0 }</span>/200)</span>
                <textarea class="comment_cst1"  name="cartData[{index}][comment_cst1]" readonly="{(carts.mitsumori_status == 3 || carts.mitsumori_status == 5) ? 'readonly':''}" id="comment_cst1_{carts.cart_seq}" style="{(carts.mitsumori_status == 3 || carts.mitsumori_status == 5) ? 'color:#9c9c9c;cursor: pointer':''}">{carts.mitsumori_comment ? carts.mitsumori_comment : carts.comment_cst1;}</textarea>

                <div if={mitsumori_status != '3'}> 

                  <i class="fa fa-paperclip add_file file_cart" id="add_file_{index}" index="{index}"></i>
                  <i class="fa fa-times delete-file-icon" id="delete-file-icon_{index}" onclick="{deleteFile}" index="{index}" style="display: none"></i>
                  <input class="file_upload" id="file_upload_{index}" index={index} type="file" name="file" style="display: none;">

                </div>

                <div if={mitsumori_status == '3' && carts.attachment1}> 

                  <i class="fa fa-file file_cart" onclick="{downloadFile}" fileName="{carts.attachment1}" title="{carts.attachment1}"></i>

                </div>

              </td>
              <td>
                <div>
                  <p>{carts.mitsumori_status == 3 ? '回答済み' : ''}</p>
                  <p>{carts.mitsumori_status == 2 ? '未回答' : ''}</p>
                  <p>{carts.mitsumori_status == 9 ? '見積依頼削除' : ''}</p>
                  <p>{carts.mitsumori_status == 5 ? '見積不可' : ''}</p>
                </div>
                <div>
                  <!-- <virtual each={status in mitsumoriStatusRelated} if={status.value == carts.cart_seq_mitsumori_related_status} >
                  this was old conditions-->
                   <virtual each={status in mitsumoriStatusRelated} if={status.value == carts.cart_seq_mitsumori_related_status} >
                       {status.label}
                    </virtual>
                </div>
                <a class="commentBtn comment-modal-open" onclick="{commentModalOpen}" index={index} style="display:{ (carts.comment_usr == '' || carts.comment_usr == null ) ? 'none' : 'block'}">依頼コメント<i class="fa fa-commenting-o"></i></a>

                <div class="text-right" style="color: red" if={campaign_retail_price_end_date(carts.campaign_retail_price,carts.campaign_start_date,carts.campaign_end_date,carts.campaign_published_date,carts.campaign_close_date).length > 0}>
                  <p>キャンペーン中</p>
                  <p>{ !isNaN(parseInt(carts.campaign_retail_price)) && (carts.campaign_retail_price != 0) ? ( parseInt(carts.campaign_retail_price).toLocaleString('en') + '円' ) : 'お見積り' }</p>
                  <div style="border-top:0px;white-space: nowrap;" class="campaign_date_{index}">{ campaign_retail_price_end_date(carts.campaign_retail_price,carts.campaign_start_date,carts.campaign_end_date,carts.campaign_published_date,carts.campaign_close_date)}</div>
                </div>
              </td>
              <td style="{(carts.mitsumori_deadline_change_flg  == 1) ? 'background:#f9e5f1':''}">
                <input type="button" id="mitsumori_deadline_{carts.cart_seq}" class="mitsumori_deadline datepicker3" style="{(carts.tanka_change_flg == 1 || carts.mitsumori_deadline_change_flg ==1) ? 'color:#9c9c9c;cursor: pointer':''}" data-seq={carts.cart_seq} value={getMitsumoriDeadline(carts.mitsumori_deadline,carts.mitsumori_term_flg,carts.mitsumori_term_date)}></input>

                <input type="hidden" id="old_mitsumori_deadline_{carts.cart_seq}" data-seq={carts.cart_seq} value={getMitsumoriDeadline(carts.mitsumori_deadline,carts.mitsumori_term_flg,carts.mitsumori_term_date)} disabled={carts.mitsumori_status == 3 ? 'disabled' : ''}></input>
              </td>
              <td>
                <div if={mitsumori_status != 3}>
                <button if={carts.mitsumori_status == 2} class="color-btn green-btn" onclick={addCart} index={index} status_value="0">見積回答</button>
                <button style="color:black;margin-top: 5px" if={carts.mitsumori_status == 2 && carts.ec_users_id !== checkAll} class="color-btn" onclick={deleteItemCart} index={index}><i class="fa fa-times"></i>見積不可</button>
                <button style="color:white;margin-top: 5px; background:#AD0011;" if={carts.mitsumori_status == 2} class="color-btn" onclick={deleteItemRecord} index={index}><img style="padding: 1px;" src="img/trash.svg">見積削除</button>
                </div>
                <button if={carts.mitsumori_status == 3} style="color:white;margin-top: 5px;" class="btn btn-info popup" onclick={addToQuoteRevision} index={index}>見積修正
                  <div class="show_pop_up" id="myPopup_{index}">
                    <p class="pop-up-text">見積修正を行います。よろしいですか。</p>
                    <p class="confirm-msg-footer">
                      <span class="btn btn-default" onclick={notConfirm} index={index} >キャンセル</span>
                      <span class="btn btn-primary" onclick={addCart} index={index} status_value="1">OK</span>
                    </p>
                  </div>
                </button>
              </td>
              <td>
                <input type="checkbox" class="checkMitsumori" index='{index}' name="cartData[{index}][mitsumori_status]" value="{carts.mitsumori_status}" onclick="{ checkedMitsumori }" style="display: {carts.mitsumori_status == 3 || ((!carts.item_sku_exist || carts.is_deleted == 1) && (carts.inquiry != 1)) ? 'none' : 'block'}">
                <button class="edit_mitsumori_deadline" if={carts.mitsumori_status == 3 && carts.bought == 0} index={index} onclick="{editMitsumoriDeadline}">訂正</button>
                <span class="msg-item-sku-exist">{ ((carts.inquiry != 1) && (carts.is_deleted == 1 || !carts.item_sku_exist)) ? 'この商品はカタログから削除されています' : ''}</span>
                <input type="hidden" name="cartData[{index}][cart_seq]" value="{carts.cart_seq}">
                <input type="hidden" name="cartData[{index}][dealer_co_cd]" value="{carts.dealer_co_cd}">
                <input type="hidden" name="cartData[{index}][customer_co_cds]" value="{carts.customer_co_cd}">
              </td>
            </tr>
          </tbody>
        </table>
        <div id="paging" class="text-center">
          <ul class="pagination" id="pagination_s05"></ul>
        </div>
      </div>
      <div id="not-found" class="not-found text-center" style="display:none">
        <img src="img/not-found.png" alt="Result not found.">
      </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 class="o_modal" id="inquiry-edit">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="inquiry-edit-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="modal-form-box">
              <table>
                <tbody>
                  <tr>
                    <td class="field-name">品番<span class="required-text">＊</span></td>
                    <td>
                      <!-- <input type="hidden"> -->
                      <input type="text" id="inquiry_supp_sku" value="{element.supp_sku}">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">品名<span class="required-text">＊</span></td>
                    <td>
                      <input type="text" id="inquiry_item_name" value="{element.item_name}">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">容量</td>
                    <td>
                      <input type="text" id="inquiry_capacity" value="{element.capacity}">
                    </td>
                  </tr>
                   <tr>
                    <td class="field-name">規格</td>
                    <td>
                      <input type="text" id="inquiry_kikaku" value="{element.kikaku}">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">製造元</td>
                    <td>
                      <input type="text" id="inquiry_maker_name" value="{element.maker_name}">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">販売元</td>
                    <td>
                      <input type="text" id="inquiry_supp_name" value="{element.supp_name}">
                    </td>
                  </tr>
                </tbody>
              </table>
              <div class="btn-wrapper">
                <button type="button" class="submit" onclick="{updateInquiry}">更新</button>
              </div>
            </div>
            <!-- <div class="comment-box">
              <p><description id="description_{comment_index}"></description></p>
            </div> -->
          </div>
        </div>
      </div>
    </div>
    <!--  bottom-name  -->
     <div class="o_modal" id="customer-name-selection">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="customer-name-selection-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="modal-form-box">
              <table>
                <tbody>
                  <tr>
                    <td class="field-name">法人名</span></td>
                    <td>
                      <!-- <input type="hidden"> -->
                      <input type="text" id="customer_co_name" value="{element.customer_co_name}" readonly>
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">事業所名</span></td>
                    <td>
                      <input type="text" id="customer_dep_name" value="{element.customer_dep_name}" readonly>
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">お客様名</td>
                    <td>
                      <div class="div-wraper-autocompleter"><input type="text" name="ec_users_name" onfocus="this.value=''" id="ec_users_name" placeholder="サジェスト選択"></div>
                    </td>
                  </tr>
                   
                </tbody>
              </table>
              <div class="btn-wrapper">
                <button type="button" class="submit" id="update_ec_users">更新</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--  end bottom name  -->

    <div class="o_modal" id="add-new-cart">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="add-new-cart-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="modal-form-box">
              <table class="add-cart-tbl">
                <tbody>
                  <tr>
                    <td class="field-name">見積依頼日</td>
                    <td>
                      <!-- <input type="hidden"> -->
                      <input type="text" id="" class="date" value={today} disabled>
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">回答先法人名<span class="required-text">＊</span></td>
                    <td>
                      <div class="div-wraper-autocompleter no-margin">
                        <input type="text" id="companies_customer_comp_name">
                      </div>
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">回答先事業所名<span class="required-text">＊</span></td>
                    <td>
                      <div class="div-wraper-autocompleter no-margin">
                        <input type="text" id="departments_kyoten_name">
                      </div>
                    </td>
                  </tr>
                   <tr>
                    <td class="field-name">回答先担当者名<span class="required-text">＊</span></td>
                    <td>
                      <div class="div-wraper-autocompleter no-margin">
                        <input type="text" id="ecusers_name">
                      </div>
                    </td>
                  </tr>
                  <td class="field-name">品番<span class="required-text">＊</span></td>
                    <td>
                      <!-- <input type="hidden"> -->
                      <input type="text" id="add_supp_sku" value="">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">品名<span class="required-text">＊</span></td>
                    <td>
                      <input type="text" id="add_item_name" value="">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">容量</td>
                    <td>
                      <input type="text" id="add_capacity" value="">
                    </td>
                  </tr>
                   <tr>
                    <td class="field-name">規格</td>
                    <td>
                      <input type="text" id="add_kikaku" value="">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">販売元</td>
                    <td>
                      <input type="text" id="add_supp_name" value="">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">製造元</td>
                    <td>
                      <input type="text" id="add_maker_name" value="">
                    </td>
                  </tr>
                  <tr>
                    <td class="field-name">添付ファイル</td>
                    <td>
                      <input class="file_upload" id="file_upload_00" index=0 type="file" name="file">
                      <span class="file_name_00"></span>
                      <i class="fa fa-times delete-file-icon" id="delete-file-icon_00" onclick="{deleteFile00}" style="display: none" index="0"></i>
                    </td>
                  </tr>
                </tbody>
              </table>
              <div class="btn-wrapper">
                <button type="button" class="submit" onclick="{addNewCart}">更新</button>
              </div>
            </div>
            <!-- <div class="comment-box">
              <p><description id="description_{comment_index}"></description></p>
            </div> -->
          </div>
        </div>
      </div>
    </div>
    
  </div>
  <script>
  this.checkAll = 'all';
  this.kyotenNameList = opts.kyotenNameList;
  this.mitsumoriStatuses = [{value:null,label:'ステータスで絞り込む'},{value:2,label:'未回答',select:'selected'},{value:3,label:'回答済み'},{value:5,label:'見積不可'}];
  this.customer_co_cd = '';
  this.customer_dep_cd = '';
  this.mitsumori_status = 2;
  this.cartsList = opts.cartsList;
  this.kikanNameList = opts.kikanNameList;
  this.total = opts.total;
  this.changedCartsList = [];
  this.comment_usr = '';
  this.comment_index = '';
  this.element = {};
  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.list_companies_suggest_search = [];
  this.list_comp_name = [];
  this.list_dep_name = [];
  this.list_ecusers_name = [];
  this.comp_code_new = '';
  this.dep_code_new = '';
  this.ecuser_id_new = '';
  this.ec_users_suggest = [];
  this.ec_users_id_suggest = '';
  this.ecUsersInfo =  JSON.parse(getItem('EcUserInfo'));
  var d = new Date();
  this.today = d.getFullYear() + '/' + convertDateTime(d.getMonth() + 1) + '/' + convertDateTime(d.getDate());
  var thisTag = this;
  var page = 1;
  var totalPages = Math.ceil(this.total/LIMIT_ON_PAGE);
  var visiblePages = 1;
  if(totalPages != 0){
      visiblePages =  5;
  } 
  
  function disableCusDepCd() {
    if ($('#customer_co_cd').val() == "") {
      $('#customer_dep_cd').attr('disabled', 'disabled');
    } else {
      $('#customer_dep_cd').removeAttr('disabled');
    }
  }

    /* global $ */
  $(function(){
    selectFile();
    $("#ec_users_name").change(function(e) {
      if($(e.target).val() == '') {
        thisTag.update({ec_users_id_suggest: ''});
      }
    });
    $(document).off("click");
    $(document).on('click', '#update_ec_users', function(e){
      var url = URL_API + '/api/s05/update_ec_users_id';
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var query = [];
      query.push('token=' + accessTokenCognito);
      url += '?' + query.join('&');
      if(thisTag.ec_users_id_suggest == '') {
        alert('お客様名を選択してください');
        return false;
      }
      $.ajax({
        url: url,
        type: 'POST',
        data:{
          ec_users_id: thisTag.ec_users_id_suggest,
          cart_seq: thisTag.element.cart_seq,
          table: thisTag.element.table
        },
        success: function (res) {
          if(res.status == 100){
              riot.mount('app','maintain',{ messege:res.messege });
              return false;
          }
          alert("更新しました。");
          $('#customer-name-selection').fadeOut();
          thisTag.update({ec_users_id_suggest: ''});
          thisTag.update({ec_users_suggest: ''});
          $('#ec_users_name').trigger(":reset");
          searchCarts(page);
        },
        error: function () {
            alert('エラー');
        }
      });
    });

    $('.file_upload').on('change', function () {
      var index = $(this).attr('index');
      var fileName = $(this).val().split('\\')[$(this).val().split('\\').length - 1];
        if (fileName) {
          $('#delete-file-icon_' + index).show();
          var validateFile = checkFile($(this), fileName);
          if (!validateFile) {
            noFile(index);
            $('#file_upload_' + index).val('');
            $('#delete-file-icon_' + index).hide();
          } else {
            hasFile(index);
            $('.file_upload').hide();
            $('.file_name_0').text(fileName);
            $('#delete-file-icon_' + index).show();
          }
          
        } else {
          noFile(index);
          $('#delete-file-icon_' + index).hide();
        }
    })
    disableCusDepCd();
    thisTag.companiesSuggest();
    $.each(thisTag.cartsList,function(i,e){
        riot.tag('description', '', function(opts) {   
            this.root.innerHTML = opts.r;
        });
        riot.mount('#description_' + i, {
            r: e.comment_usr
        })
      var campaign_date = $(".campaign_date_"+i).html() ? $(".campaign_date_"+i).html().split("|") : '';
      var campaign_start_date = campaign_date[0] ? campaign_date[0] + '～<br>' : '';
      var campaign_end_date = campaign_date[1] ? campaign_date[1] + 'まで' : '';
      $(".campaign_date_" + i).html(campaign_start_date + "" + campaign_end_date);
        thisTag.update();
    });
    $('#pagination_s05').twbsPagination({
      totalPages: totalPages,
      visiblePages: visiblePages,
      startPage: thisTag.page,
        initiateStartPageClick: false,
      onPageClick: function (event, page) {
        searchCarts(page);
      }
    });

    $(document).on('click','.inquiry-edit', function(e){
      thisTag.update({element: thisTag.cartsList[$(e.target).attr('index')]});
      $('#inquiry-edit').fadeIn();
    });
    $(document).on('click', '#inquiry-edit-close', function(e){
      $('#inquiry-edit').fadeOut();
    });
    $(document).on('click','.customer-name-selection', function(e){
      $('#ec_users_name').val('');
      thisTag.update({element: thisTag.cartsList[$(e.target).attr('index')]});
      thisTag.ecUsersSuggest();
      $('#customer-name-selection').fadeIn();
    });
    $(document).on('click', '#customer-name-selection-close', function(e){
      thisTag.update({ec_users_id_suggest: ''});
      thisTag.update({ec_users_suggest: ''});
      $('#customer-name-selection').fadeOut();
    });

    $('.add-new-cart').on('click', function () {
      $('#add_supp_sku').val('');
      $('#add_item_name').val('');
      $('#add_capacity').val('');
      $('#add_kikaku').val('');
      $('#add_maker_name').val('');
      $('#add_maker_name').val('');
      $('#companies_customer_comp_name').val('');
      $('#departments_kyoten_name').val('');
      $('#ecusers_name').val('');
      thisTag.deleteFile00();
      $('#add-new-cart').fadeIn();
      thisTag.customersSuggest('get_co_name');
    });
    $(document).on('click','#add-new-cart-close', function(e){
      $('#add-new-cart').fadeOut();
    });

    $('#companies_customer_comp_name').on('change', function() {
        if($(this).val() == '') {
            thisTag.update({
                supplier_comp_code_search4: ''
            });
        }
    });

    $('#departments_kyoten_name').on('change', function() {
        if($(this).val() == '') {
            thisTag.update({
                supplier_comp_code_search4: ''
            });
        }
    });

    $('#ecusers_name').on('change', function() {
        if($(this).val() == '') {
            thisTag.update({
                supplier_comp_code_search4: ''
            });
        }
    });

    $("#customer_co_cd").on('change',function(e){
      var customer_name = $(this).val();
      var check_name = arColumn(thisTag.list_companies_suggest_search, 'label', customer_name);
      if(check_name.length == 0 && customer_name != '') {
        return false;
      }
      if (customer_name == '') {
        thisTag.update({
          customer_co_cd: '',
        });
      }
      thisTag.update({
        customer_dep_cd: ''
      });
      $("#customer_dep_cd").val('');
      disableCusDepCd();
      searchCarts(page);
    });
    $("#customer_dep_cd").on('change',function(e){
        thisTag.update({customer_dep_cd: $(this).children('option:selected').val() });
        searchCarts(page);
    });
    $(".cartTanka").on('change',function(e){
        checkValidateAndMultiplication(e.target);
    });
    $(".cartTeikaTanka").on('change',function(e){
        checkValidateAndMultiplication(e.target);
    });
    $(".cartSuryo").on('change',function(e){
        checkValidateAndMultiplication(e.target);
    });
    
    // $('.comment-modal-open').on('click',function(){
    //   $('#comment-modal').fadeIn();
    // });
    $('#comment-modal-close').on('click',function(){
      $('#comment-modal').fadeOut();
    });

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

    /*$('.mitsumori_request_start_date').datetimepicker({
      format: 'Y/m/d',
      onShow:function( ct ){
        this.setOptions({
            maxDate:$('.mitsumori_request_end_date').val()?$('.mitsumori_request_end_date').val():false
        })
      },
      timepicker:false
    });

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

    $(".search-btn-main").on('click', function(e) {
        var page = 1;
        searchCarts(page);
        thisTag.companiesSuggest();
    });

    // $('.add-attach-1-file-cls').change(function() {

    //   var fileIndex = $(this).attr('data-index');
    //   if(fileIndex) {
    //     var fileName = $('#fileAttachment1_'+fileIndex)[0].files[0].name;
    //     var validateFile = checkFile($(this), fileName);

    //     if(validateFile) {
    //       $("#fileAttachment1Name_"+fileIndex).show();
    //       $("#fileAttachment1Name_"+fileIndex).text(fileName);
    //       $("#delete-file-icon_"+fileIndex).show();
    //     }
    //   } else {
    //     alert('インデックスが見つかりません。');
    //     return 0;
    //   }

    // });

  });
  this.getMitsumoriDeadline = function(date, term_flg, term_date) {
    if(date == '') {
      var today = new Date();
      var nextMonthFlg = ( term_flg == '0' || term_flg == '' || term_flg == null ? 1 : (term_flg == '1' ? 3 : (term_flg == '2' ? 6 : (term_flg == '9' ? 9 : 0))));
      let nextMonth = new Date(today.getFullYear(), today.getMonth() + nextMonthFlg, today.getDate());
      let year = nextMonth.getFullYear();
      let month = nextMonth.getMonth() + 1;
      let date = nextMonth.getDate();
      var mitsumori_deadline = term_flg == '9' && term_date !== '' ? term_date : year + '/' + convertDateTime(month) + '/' + convertDateTime(date);

      return mitsumori_deadline;
    }
    return date;
  }
  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;
  }

  filterByMitsumoriStatus(e){
      thisTag.mitsumori_status = $(e.target).val();
      thisTag.update({
        customer_co_cd: '',
        customer_dep_cd: '',
        mitsumori_status: $(e.target).val()
      });
      $("#customer_co_cd").val('');
      $("#customer_dep_cd").val('');
      disableCusDepCd();
      var page = 1;
      searchCarts(page);
      thisTag.companiesSuggest();
  }
  this.commentModalOpen = function(e){
      $('#comment-modal').fadeIn();
      var comment = e.item.carts.comment_usr;
      thisTag.comment_usr = comment;
      thisTag.comment_index = e.item.index;
      thisTag.update(thisTag.comment_usr);
      thisTag.update(thisTag.comment_index);
      $.each(thisTag.cartsList,function(i,e){
          riot.tag('description', '', function(opts) {   
              this.root.innerHTML = opts.r;
          });
          riot.mount('#description_' + i, {
              r: e.comment_usr
          })
          thisTag.update();
      });
  }
  this.checkedMitsumori = function(e){
  //   var index = $(e.target).attr('index');
  //   var target = $(e.target);
  //   var mitsumori_status = thisTag.cartsList[index]['mitsumori_status'];
  //   if(target.not(":checked")){
  //     $('input[name="cartData['+index+'][suryo]"]').attr('readonly','readonly');
  //     $('input[name="cartData['+index+'][tanka]"]').attr('readonly','readonly');
  //     $('input[name="cartData['+index+'][teika_tanka]"]').attr('readonly','readonly');
  //     $('#comment_cst1_'+index).attr('readonly','readonly');
  //   }
  //   if(target.is(":checked") && mitsumori_status == 2 ){
  //     $('input[name="cartData['+index+'][suryo]"]').removeAttr('readonly'); 
  //     $('input[name="cartData['+index+'][tanka]"]').removeAttr('readonly'); 
  //     $('input[name="cartData['+index+'][teika_tanka]"]').removeAttr('readonly'); 
  //     $('#comment_cst1_'+index).removeAttr('readonly');      
  //   }
  //   // thisTag.changeCarts(e);
  }

  // function checkMitsu(indexElement){

  //   if($(indexElement).is(':checked')){
  //     $(indexElement).val('3');
  //   } else {
  //     $(indexElement).val('2');
  //   }
  //   console.log($(indexElement).val());
  // }
  function checkValidateAndMultiplication(indexElement){
    var error = [];
    var errSuryoLength = false;
    var errSuryoValidate = false;
    var errTankaLength = false;
    var errTankaValidate = false;
    var errTeikaTankaLength = false;
    var errTeikaTankaValidate = false;
    var indexField = $(indexElement).attr("index");
    var suryo = $("#suryo-" + indexField).val();
    var tanka = $("#tanka-" + indexField).val();
    var teika_tanka = $("#teika-tanka-" + indexField).val();
    if(suryo.length > 10){
      error.push('納入価格を10文字以内に入力してください。\n');

      errSuryoLength = true;
    }
    if( !validateTanka(suryo) ){
      error.push('納入価格を正数のみで入力してください。\n');

      errSuryoValidate = true;
    }
    if(tanka.length > 10){
      error.push('納入価格を10文字以内に入力してください。\n');

      errTankaLength = true;
    }
    if( !validateTanka(tanka) ){
      error.push('納入価格を正数のみで入力してください。\n');

      errTankaValidate = true;
    }
    if(teika_tanka.length > 10){
      error.push('定価を10文字以内に入力してください。\n');

      errTeikaTankaLength = true;
    }
    if( !validateTanka(teika_tanka) ){
      error.push('定価を正数のみで入力してください。\n');

      errTeikaTankaValidate = true;
    }
    if(errTankaLength || errTankaValidate || errTeikaTankaLength || errTeikaTankaValidate || errSuryoLength || errSuryoValidate){
      if(errSuryoLength || errSuryoValidate){
        $("#suryo-" + indexField).val(0);
      }
      if(errTankaLength || errTankaValidate){
        $("#tanka-" + indexField).val(0);
      }
      if(errTeikaTankaLength || errTeikaTankaValidate){
        $("#teika-tanka-" + indexField).val(0);
      }
      alert(error.join(""));
      return false;
    }
    // if(errStatus == true){
      // alert(error.join(""));
      // $(indexElement).val(0);
      // if(suryo == 0){
      //   $("#suryo-" + indexField).val(0);
      //   $("#suryo-tanka-" + indexField).html(0);
      //   $("#suryo-teika-tanka-" + indexField).html(0);
      // }
      // if(tanka == 0){
      //   $("#suryo-tanka-" + indexField).html(0);
      // }
      // if(teika_tanka == 0){
      //   $("#suryo-teika-tanka-" + indexField).html(0);
      // }
      // return false;
    // }
    var suryo_tanka = !isNaN(parseInt(suryo * tanka)) ? parseInt(suryo * tanka).toLocaleString('en') + '円' : '';
    var suryo_teika_tanka = !isNaN(parseInt(suryo * teika_tanka)) ? parseInt(suryo * teika_tanka).toLocaleString('en') + '円' : '';
    $("#suryo-tanka-" + indexField).html(suryo_tanka);
    $("#suryo-teika-tanka-" + indexField).html(suryo_teika_tanka);
  } 
  function convertDateTime(dateTime){
        if(dateTime.toString().length<2){
            dateTime = '0' + dateTime.toString();
        }
        return dateTime
  }
  const notFoundResult=(total)=>{
    if(total==0){
      $("#not-found").css("display","block");
      $("#search-table").css("display","none");
      $("#search_select_box").css("display","none");
    }else{
      $("#not-found").css("display","none");
      $("#search-table").css("display","block");
    }
  }
  function validateTanka(price) {
    var re = /^([0-9]*)$/;
    return re.test(price);
  }
  function searchCarts(page){
    thisTag.changedCartsList = [];
    var querySuggest = [];
    var mitsumori_request_start_date = $(".mitsumori_request_start_date").val();
    var mitsumori_request_end_date = $(".mitsumori_request_end_date").val();
    var cartSeq=$(".cartSeq").val();
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    var url = URL_API + '/api/s05/get_carts_list';
    querySuggest.push('token=' + accessTokenCognito);
    if(thisTag.customer_co_cd != ''){
        querySuggest.push('customer_co_cd='+thisTag.customer_co_cd);
    }
    if(thisTag.mitsumori_status != ''){
        querySuggest.push('mitsumori_status='+thisTag.mitsumori_status);
    }
    if(thisTag.customer_dep_cd != ''){
        querySuggest.push('customer_dep_cd='+thisTag.customer_dep_cd);
    }
    if(thisTag.mitsumori_request_start_date != ''){
        querySuggest.push('mitsumori_request_start_date=' + mitsumori_request_start_date);
    }
    if(thisTag.mitsumori_request_end_date != ''){
        querySuggest.push('mitsumori_request_end_date=' + mitsumori_request_end_date);
    }
    if(cartSeq != ''){
        querySuggest.push('cart_seq=' + cartSeq);
    }
    querySuggest.push('page='+page);
    querySuggest.push('limit=' +   LIMIT_ON_PAGE);
    querySuggest.push('screen=s05');
    url += '?' + querySuggest.join('&');
    $.ajax({
        url: url,
        type: 'GET',
        timeout: 60000,
        success: function(res){
            notFoundResult(res.total);
            if(res.status == 100){
                riot.mount('app','maintain',{ messege:res.messege });
                return false;
            }
            thisTag.cartsList = res.carts_list;
            var data = res;
            var results = data.carts_list;
            var totalPages = Math.ceil(data.total/LIMIT_ON_PAGE);
            var visiblePages = 1;
            if(totalPages != 0){
                visiblePages =  5;
            } 
            var $pagination = $('#pagination_s05');
            $pagination.twbsPagination('destroy');
            $pagination.twbsPagination({
              totalPages: totalPages,
              visiblePages: visiblePages,
              startPage: page,
              initiateStartPageClick: false,
              onPageClick: function (event, page) {
                searchCarts(page);
              }
            });

            thisTag.update(thisTag.cartsList);
            selectFile();
            thisTag.update({
              kyotenNameList: res.kyoten_name_list,
              kikanNameList: res.kikanNameList
            });

            $.each($('#customer_dep_cd').children('option'), function(i, val) {
              if($(val).val() == thisTag.customer_dep_cd) {
                $(val).prop('selected', true);
              }
            });
            // $(".checkMitsumori").on('click',function(e){
            //   checkMitsu(e.target);
            // });
            $(".cartTanka").on('change',function(e){
              checkValidateAndMultiplication(e.target);
            });
            $(".cartTeikaTanka").on('change',function(e){
              checkValidateAndMultiplication(e.target);
            });
            $(".cartSuryo").on('change',function(e){
              checkValidateAndMultiplication(e.target);
            });
            $.each(thisTag.cartsList,function(i,e){
                riot.tag('description', '', function(opts) {   
                    this.root.innerHTML = opts.r;
                });
                riot.mount('#description_' + i, {
                    r: e.comment_usr
                })
                var campaign_date = $(".campaign_date_"+i).html() ? $(".campaign_date_"+i).html().split("|") : '';
                var campaign_start_date = campaign_date[0] ? campaign_date[0] + '～<br>' : '';
                var campaign_end_date = campaign_date[1] ? campaign_date[1] + 'まで' : '';
                $(".campaign_date_" + i).html(campaign_start_date + "" + campaign_end_date);
                thisTag.update();
                DatepickerHoliday();
                /*$('.mitsumori_deadline').datetimepicker({
                    format: 'Y/m/d',
                    onShow:function( ct ){
                        this.setOptions({
                            minDate: new Date()
                        })
                    },
                    timepicker:false,
                    scrollInput: false
                });*/
            });
        },
        error: function (xhr, stt, err) {
            alert('エラー');
        }
    });
  }
  this.addCarts = function(e){

    var listCart = [];
    var error = [];
    var item_sku_exist = true;
    var inquiry = '';
    var is_deleted = false;
    var supp_sku_error = false;
    var suryo_error = false;
    var tanka_error = false;
    var checkLenght = $('.checkMitsumori').length;
    var customer_co_cd_selected = thisTag.customer_co_cd;
    var formData = new FormData();
    var comment_cst1_max_error = 0;
    // if($('.checkMitsumori').not(':checked').length == checkLenght){
    //   alert("回答対象を選択してください。");
    //   return false;
    // }

    $.each(thisTag.cartsList, function(i,e){
      var table = e['table'];
      var cartSeq = $('input[name="cartData['+i+'][cart_seq]"]').val();
      var suryo = $('input[name="cartData['+i+'][suryo]"]').val();
      var dealerCoCd = $('input[name="cartData['+i+'][dealer_co_cd]"]').val();
      var tanka = $('input[name="cartData['+i+'][tanka]"]').val();
      var teikaTanka = $('input[name="cartData['+i+'][teika_tanka]"]').val();
      var commentCst1 = $('#comment_cst1_'+cartSeq).val();
      var mitsumori_status = $('input[name="cartData['+i+'][mitsumori_status]"]').val();
      var supp_sku = e['supp_sku'];
      var item_name = e['item_name'];
      var capacity = e['capacity'];
      var kikaku = e['kikaku'];
      var maker_name = e['maker_name'];
      var supp_co_cd = e['supp_co_cd'];
      var deliverydate = e['deliverydate'];
      var comment_usr = e['comment_usr'];
      var customer_use_code_1 = e['customer_use_code_1'];
      var customer_use_code_2 = e['customer_use_code_2'];
      var dealer_co_cd = e['dealer_co_cd'];
      var dealer_dep_cd = e['dealer_dep_cd'];
      var dealer_tanto_cd = thisTag.ecUsersInfo.id;
      
      var arrCart = [];
      var d = new Date();
      var mitsumori_reply_date = d.getFullYear() + '-' + convertDateTime(d.getMonth()+1) + '-' + convertDateTime(d.getDate()) + ' ' + convertDateTime(d.getHours()) + ':' +convertDateTime(d.getMinutes()) + ':' + convertDateTime(d.getSeconds()); 
      var mitsumori_deadline = $('.mitsumori_deadline')[i].value;
      // arrCart = [cartSeq,suryo,dealerCoCd,tanka,teikaTanka,commentCst1,mitsumoriStatus];
      if($('input[name="cartData['+i+'][mitsumori_status]"]').is(":checked")){
        var mitsumoriStatus = 3;

        if ($('#file_upload_' + i).val() != '' && $('#file_upload_' + i).val() !== undefined) {
          file_upload = $("#file_upload_" + i)[0].files[0];
          formData.append('fileAttachment1_'+ cartSeq, file_upload);
          fileName = $("#file_upload_" + i)[0].files[0].name;
        }

        if(e['inquiry']){
            inquiry = 1;
            suryo = $('#suryo_' + i).val()
            if (suryo.length == 0) {
              suryo_error = true;
            }
        }
        if(tanka == ""){
          tanka_error = true;
        }
        arrCart = {
           table: table,
           cart_seq: cartSeq,
           suryo: suryo,
           dealer_co_cd: dealer_co_cd,
           dealer_dep_cd: dealer_dep_cd,
           tanka: tanka,
           teika_tanka: teikaTanka,
           comment_cst1: commentCst1,
           mitsumori_status: mitsumoriStatus ,
           mitsumori_reply_date: mitsumori_reply_date,
           checked: 0,
           //===
           supp_sku: supp_sku,
           item_name: item_name,
           capacity: capacity,
           kikaku: kikaku,
           maker_name: maker_name,
           supp_co_cd: supp_co_cd,
           deliverydate: deliverydate,
           comment_usr: comment_usr,
           customer_use_code_1: customer_use_code_1,
           customer_use_code_2: customer_use_code_2,
           mitsumori_deadline: mitsumori_deadline,
           dealer_tanto_cd: dealer_tanto_cd
        };
        listCart.push(arrCart);
        if(!e['item_sku_exist']){
            item_sku_exist = false;
        }
        if(e['supp_sku'].length == 0){
            supp_sku_error = true;
        }
        if($('#comment_cst1_' + cartSeq).val().length >= 200){
          comment_cst1_max_error++;
        }
      } else {
        // if( mitsumori_status != 3 ) {
        //   arrCart = {
        //     cart_seq: cartSeq,
        //     suryo: suryo,
        //     dealer_co_cd: dealer_co_cd,
        //     tanka: tanka,
        //     teika_tanka: teikaTanka,
        //     comment_cst1: commentCst1,
        //     mitsumori_reply_date: mitsumori_reply_date,
        //     //===
        //     supp_sku: supp_sku,
        //     item_name: item_name,
        //     capacity: capacity,
        //     kikaku: kikaku,
        //     maker_name: maker_name,
        //     supp_co_cd: supp_co_cd,
        //     deliverydate: deliverydate,
        //     comment_usr: comment_usr,
        //     customer_use_code_1: customer_use_code_1,
        //     customer_use_code_2: customer_use_code_2
        //   };
        //   listCart.push(arrCart);
        // }
      }
      if(e['is_deleted'] == 1){
          is_deleted = true;
      }
    });
    if(supp_sku_error){
        error.push("製品情報更新ボタンを押下して品番を入力してください。\n");
    }
    if(suryo_error){
        error.push("数量を入力してください。\n");
    }
    if(!item_sku_exist && inquiry != 1){
        error.push("存在しない商品が含まれています。\n");
    }
    if(tanka_error){
      error.push("納入価格を入力してください。\n");
    }
    if(comment_cst1_max_error){
      error.push("お客様へコメントを200文字以内で入れてください。\n");
    }
    if(error.length > 0){
        var err = error.join("");
        alert(err);
        return false;
    }

    if(!listCart.length) {
        alert("回答対象にチェックを入れてください");
        return false;
    }

    var url = URL_API + '/api/s05/update_carts_list';
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    var query = [];
    query.push('token=' + accessTokenCognito);
    url += '?' + query.join('&');
    var tmpData = {data: listCart, customer_co_cd_selected: customer_co_cd_selected};
    formData.append('cart_info', JSON.stringify(tmpData));

    $.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;
        }

        alert("見積回答しました。");
        var page = 1;
        searchCarts(page);
      },
      error: function () {
          alert('エラー');
      }
    });
  }

  this.changeCarts = function(e){
    // looped item
    var item = e.item.carts;
    var isNew = true;
    var checkTest = e.target.checked;
    var index = e.item.index;
    var d = new Date();
    var mitsumori_reply_date = d.getFullYear() + '-' + convertDateTime(d.getMonth()+1) + '-' + convertDateTime(d.getDate()) + ' ' + convertDateTime(d.getHours()) + ':' +convertDateTime(d.getMinutes()) + ':' + convertDateTime(d.getSeconds()); 
    thisTag.changedCartsList.push(index);
    // if(checkTest){
      // this.cartsList = this.cartsList.filter(function(carts) {
      //   if(carts.customer_co_cd == this.carts.supp_co_cd ){
      //       carts.mitsumori_status = $(e.target).val();
      //       carts.mitsumori_reply_date = mitsumori_reply_date;
      //       carts.comment_cst1 = $("#comment_cst1_" + cart_index).val();
      //       carts.teika_tanka = $("teika-tanka-" + cart_index).val();
      //       carts.tanke = $("tanka-" + cart_index).val();
      //       carts.suryo = $("suryo-" + cart_index).val();
      //   }
      //   return carts;
        
      // }, item);

      // this.changedCartsList = this.changedCartsList.filter(function(carts) {
      //     if(this.carts.customer_co_cd == carts.supp_co_cd){     isNew = false;
      //         return this;
      //     }else{
      //         return carts;
      //     }
      // }, item);

      // if(isNew){
      //     this.changedCartsList.push(item.carts);
      // }
    //   thisTag.changedCartsList.push(index);
    // } else {
    //   $.each(thisTag.changedCartsList,function(i,e){
    //     if(e == index){
    //       thisTag.changedCartsList.splice(i,1);
    //     }
    //   });
    // }
  }
  
  this.companiesSuggest = function(e) {
    var query = [];
    var url = URL_API + '/api/cart/companies_suggest';
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    query.push('token=' + accessTokenCognito);
    if(thisTag.mitsumori_status != ''){
        query.push('mitsumori_status='+thisTag.mitsumori_status);
    }
    query.push('screen=s05');
    url += '?' + query.join('&');

    $.ajax({
        url: url,
        type: 'GET',
        success: function (res) {
            if(res.status == 100){
                riot.mount('app','maintain',{ messege:res.messege });
                return false;
            }
            thisTag.update({list_companies_suggest_search: res.cust_list});
            thisTag.getListSuggestCompanies();
        },
        error: function () {
            alert('エラー');
        }
    });
  }

  this.customersSuggest = function(type) {
    var query = [];
    var url = URL_API + '/api/cart/customers_suggest';
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    query.push('token=' + accessTokenCognito);
    switch(type) {
      case 'get_co_name':
        query.push('get_co_name=1');
        break;
      case 'get_dep_name':
        if (!thisTag.comp_code_new) {
          return false;
        }
        query.push('get_dep_name=1');
        query.push('comp_code=' + thisTag.comp_code_new);
        break;
      case 'get_ec_users_name':
        if (!thisTag.comp_code_new || !thisTag.dep_code_new) {
          return false;
        }
        query.push('get_ec_users_name=1');
        query.push('comp_code=' + thisTag.comp_code_new);
        query.push('dep_code=' + thisTag.dep_code_new);
        break;
      default:
        return false;
    }
    
    query.push('screen=s05');
    url += '?' + query.join('&');

    $.ajax({
        url: url,
        type: 'GET',
        success: function (res) {
            if(res.status == 100){
                riot.mount('app','maintain',{ messege:res.messege });
                return false;
            }
            switch(type) {
              case 'get_co_name':
                thisTag.update({
                  list_comp_name: res.companies_customer_comp_name,
                  list_dep_name: [],
                  list_ecusers_name: [],
                  comp_code_new: '',
                  dep_code_new: '',
                  ecuser_id_new: ''
                });
                thisTag.getListCompName();
                $("#departments_kyoten_name").val('');
                $("#ecusers_name").val('');
                $("#departments_kyoten_name").autocompleter("destroy");
                $("#ecusers_name").autocompleter("destroy");
                break;
              case 'get_dep_name':
                thisTag.update({
                  list_dep_name: res.departments_kyoten_name,
                  list_ecusers_name: [],
                  dep_code_new: '',
                  ecuser_id_new: ''
                });
                $("#ecusers_name").val('');
                $("#ecusers_name").autocompleter("destroy");
                thisTag.getListDepName();
                break;
              case 'get_ec_users_name':
                thisTag.update({
                  list_ecusers_name: res.ecusers_name,
                  ecuser_id_new: ''
                });
                thisTag.getListUsersName();
                break;
              default:
                return false;
            }
        },
        error: function () {
            alert('エラー');
        }
    });
  }

  this.getListSuggestCompanies = function() {
    let list = thisTag.list_companies_suggest_search;
    let res = [];
    for (var i = 0; i <= list.length - 1; i++) {
      res.push({value: list[i].label, label: list[i].label, comp_index: i});
    }
    $("#customer_co_cd").autocompleter("destroy");
    $('#customer_co_cd').autocompleter({ 
      limit:10000,
      highlightMatches:true, 
      source: res, 
      callback: function(value, index, object) {
        if($("#customer_co_cd").val() != '' && thisTag.list_companies_suggest_search[object.comp_index].comp_code) {
          thisTag.update({customer_co_cd: thisTag.list_companies_suggest_search[object.comp_index].comp_code});
          if($('#customer_co_cd').val().length > 25){
            $("#search_select_box").css("display","block");
            $(".mitsumori-filter").css("width","100%");
            $(".btn-groups").css("float","right");
            $(".btn-groups").css("padding","5px");
          }else{
            $("#search_select_box").css("display","flex");
            $(".mitsumori-filter").css("width","65%");
            $(".add-new-cart").css("margin-left","5px");
            $(".btn-groups").css("padding","0px");
          }
        } else {
          thisTag.update({customer_co_cd: ''});
        }
      }
    });
  }

  this.getListCompName = function() {
    let list = thisTag.list_comp_name;
    let res = [];
    for (var i = 0; i < list.length; i++) {
      res.push({value: list[i].comp_name, label: list[i].comp_name, comp_index: i});
    }
    $("#companies_customer_comp_name").autocompleter("destroy");
    $('#companies_customer_comp_name').autocompleter({ 
      limit:10000,
      highlightMatches:true, 
      source: res, 
      callback: function(value, index, object) {
        if($("#companies_customer_comp_name").val() != '' && thisTag.list_comp_name[object.comp_index].comp_code) {
          thisTag.update({comp_code_new: thisTag.list_comp_name[object.comp_index].comp_code});
          $('#departments_kyoten_name').val('');
          $('#ecusers_name').val('');
          thisTag.customersSuggest('get_dep_name');
        } else {
          thisTag.update({comp_code_new: ''});
        }
      }
    });
  }

  this.getListDepName = function() {
    let list = thisTag.list_dep_name;
    let res = [];
    for (var i = 0; i < list.length; i++) {
      res.push({value: list[i].kyoten_name, label: list[i].kyoten_name, comp_index: i});
    }
    $("#departments_kyoten_name").autocompleter("destroy");
    $('#departments_kyoten_name').autocompleter({ 
      limit:10000,
      highlightMatches:true, 
      source: res, 
      callback: function(value, index, object) {
        if($("#departments_kyoten_name").val() != '' && thisTag.list_dep_name[object.comp_index].kyoten_code) {
          thisTag.update({dep_code_new: thisTag.list_dep_name[object.comp_index].kyoten_code});
          $('#ecusers_name').val('');
          thisTag.customersSuggest('get_ec_users_name');
        } else {
          thisTag.update({dep_code_new: ''});
        }
      }
    });
  }

  this.getListUsersName = function() {
    let list = thisTag.list_ecusers_name;
    let res = [];
    for (var i = 0; i < list.length; i++) {
      res.push({value: list[i].name, label: list[i].name, comp_index: i});
    }
    $("#ecusers_name").autocompleter("destroy");
    $('#ecusers_name').autocompleter({ 
      limit:10000,
      highlightMatches:true, 
      source: res, 
      callback: function(value, index, object) {
        if($("#ecusers_name").val() != '' && thisTag.list_ecusers_name[object.comp_index].id) {
          thisTag.update({ecuser_id_new: thisTag.list_ecusers_name[object.comp_index].id});
        } else {
          thisTag.update({ecuser_id_new: ''});
        }
      }
    });
  }

  this.editMitsumoriDeadline = function(e) {
    var index = $(e.target).attr('index');
    var cart_seq = thisTag.cartsList[index].cart_seq;
    var customer_co_cd = thisTag.cartsList[index].customer_co_cd;
    var query = [];
    var agent = localStorage.getItem('agent_id');
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        query.push('token=' + accessTokenCognito);
    var url = URL_API + '/api/s05/renew_carts_list';
    url += '?' + query.join('&');

    var data = {
      cart_seq: cart_seq,
      mitsumori_status: 2
    };

    $.ajax({
      url: url,
      type: 'POST',
      timeout: 60000,
      data: {
          data: data,
          customer_co_cd_selected: customer_co_cd
      },
      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;
            searchCarts(page);
        }
      },
      error: function (xhr, stt, err) {
          alert('エラー');
      }
    });
  }

  this.updateInquiry = function(e) {
    var cart_seq = thisTag.element.cart_seq;
    var supp_sku = $('#inquiry_supp_sku').val().trim();
    var item_name = $('#inquiry_item_name').val().trim();
    var capacity = $('#inquiry_capacity').val().trim();
    var kikaku = $('#inquiry_kikaku').val().trim();
    var maker_name = $('#inquiry_maker_name').val().trim();
    var supp_name = $('#inquiry_supp_name').val().trim();
    var updatedate = thisTag.element.updatedate;
    var model = thisTag.element.table;

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    var query = [];
    query.push('token=' + accessTokenCognito);
    query.push('sendmail_flg=' + 0);
    var url = URL_API + '/api/cart/create';
    url += '?' + query.join('&');
    var error = [];
    var data = [];

    // validate
    if(supp_sku.length == 0){
        error.push("品番入力が必須です\n");
    }

    if(item_name.length == 0){
        error.push("品名入力が必須です\n");
    }

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

    data.push({
      cart_seq: cart_seq, 
      supp_sku: supp_sku, 
      item_name: item_name, 
      capacity: capacity, 
      kikaku: kikaku, 
      maker_name: maker_name, 
      supp_name: supp_name,
      updatedate: updatedate,
      model: model
    });

    $.ajax({
      url: url,
      type: 'POST',
      timeout: 60000,
      data: {
          data: data,
          screen: 'S05_update_info'
      },
      success: function (res) {
          if(res.status == 100){
              riot.mount('app','maintain',{ messege:res.messege });
              return false;
          }
          if(data.status == 'not_authorize'){
              var url = "#";
              $(location).attr("href", url );
              return false;
          }
          if (data.message && data.errors) {
              alert('エラー');
          } else {
              $('#inquiry-edit').fadeOut();
              alert('更新しました。');
              var page = 1;
              searchCarts(page);
          }
      },
      error: function (xhr, stt, err) {
          alert('エラー');
      }
    });
  }

  this.checkLength = function(field_name, max_length, value, error) {
    if (value.length > max_length) {
      error = error.push(field_name + 'を' + max_length + '文字以内で入力してください\n');
    }
    return error;
  }

  this.addNewCart = function() {
    var supp_sku = $('#add_supp_sku').val().trim();
    var item_name = $('#add_item_name').val().trim();
    var capacity = $('#add_capacity').val().trim();
    var kikaku = $('#add_kikaku').val().trim();
    var maker_name = $('#add_maker_name').val().trim();
    var supp_name = $('#add_supp_name').val().trim();
    var co_name = $('#companies_customer_comp_name').val().trim();
    var dep_name = $('#departments_kyoten_name').val().trim();
    var user_name = $('#ecusers_name').val().trim();
    var customer_co_cd = thisTag.comp_code_new;
    var customer_dep_cd = thisTag.dep_code_new;
    var ec_users_id = thisTag.ecuser_id_new;

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    var query = [];
    query.push('token=' + accessTokenCognito);
    query.push('add_new_cart=1');
    query.push('screen_status=1');
    var url = URL_API + '/api/cart/create';
    url += '?' + query.join('&');
    var error = [];
    var data = [];
    var formData = new FormData();

    // validate
    if (co_name.length == 0 || !customer_co_cd) {
      error.push("回答先法人名を入力してください\n");
    }
    if (dep_name.length == 0 || !customer_dep_cd) {
      error.push("回答先事業所名を入力してください\n");
    }
    if (user_name.length == 0 || !ec_users_id) {
      error.push("お客様を入力してください\n");
    }
    if(supp_sku.length == 0){
        error.push("品番を入力してください\n");
    }
    if(item_name.length == 0){
        error.push("品名を入力してください\n");
    }

    if(supp_sku.length > 50){
        error.push("品番を50文字以内で入力してください\n");
    }
    if(item_name.length > 300){
        error.push("品名を300文字以内で入力してください\n");
    }
    if(capacity.length > 50){
        error.push("容量を50文字以内で入力してください\n");
    }
    if(kikaku.length > 50){
        error.push("規格を50文字以内で入力してください\n");
    }
    if(maker_name.length > 100){
        error.push("製造元を100文字以内で入力してください\n");
    }
    if(supp_name.length > 100){
        error.push("販売元を100文字以内で入力してください\n");
    }
    
    if(error.length > 0){
        var err = error.join("");
        alert(err);
        return false;
    }

    data.push({
      ec_users_id: ec_users_id,
      supp_name: supp_name,
      maker_name: maker_name,
      supp_sku: supp_sku, 
      item_name: item_name, 
      capacity: capacity, 
      kikaku: kikaku,
      inquiry: 1,
      mitsumori_status: 2,
      customer_co_cd:customer_co_cd,
      customer_dep_cd:customer_dep_cd,
      dealer_co_cd: thisTag.ecUsersInfo.kikan_code,
      dealer_dep_cd: thisTag.ecUsersInfo.sosiki_code,
      index_file: '0'
    });

    if ($('#file_upload_00').val() != '' && $('#file_upload_00').val() !== undefined) {
      file_upload = $("#file_upload_00")[0].files[0];
      formData.append('file_upload_00', file_upload);
    }
    formData.append('cart_info', JSON.stringify(data));
    $.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(data.status == 'not_authorize'){
              var url = "#";
              $(location).attr("href", url );
              return false;
          }
          if (data.message && data.errors) {
              alert('エラー');
          } else {
              alert('更新しました。');
              $('#add-new-cart').fadeOut();
              var page = 1;
              searchCarts(page);
          }
      },
      error: function (xhr, stt, err) {
          alert('エラー');
      }
    });
  }

   this.deleteFile00 = function (e) {
      $('#file_upload_00').val('');
      $('#delete-file-icon_00').hide();
      $('.file_name_00').text('');
      $('#file_upload_00').show();
    }
  var previous = null;
  this.addToQuoteRevision = function(e){
    var i = $(e.target).attr('index');
    var popup = document.getElementById(`myPopup_${i}`);
    popup.classList.toggle("show");
  }
  this.notConfirm = function(e){
    var i = $(e.target).attr('index');
    var popup = document.getElementById(`myPopup_${i}`);
    popup.fadeOut("hide");
  }
  this.addCart = function(e){
    var listCart = [];
    var error = [];
    var item_sku_exist = true;
    var inquiry = '';
    var is_deleted = false;
    var supp_sku_error = false;
    var suryo_error = false;
    var checkLenght = $('.checkMitsumori').length;
    var customer_co_cd_selected = thisTag.customer_co_cd;
    var i = $(e.target).attr('index');
    var mit_status=$(e.target).attr('status_value');
    var e = thisTag.cartsList[i];
    var table = e['table'];
    var cartSeq = $('input[name="cartData['+i+'][cart_seq]"]').val();
    var suryo = $('input[name="cartData['+i+'][suryo]"]').val();
    var dealerCoCd = $('input[name="cartData['+i+'][dealer_co_cd]"]').val();
    var tanka = $('input[name="cartData['+i+'][tanka]"]').val();
    var teikaTanka = $('input[name="cartData['+i+'][teika_tanka]"]').val();
    var commentCst1 = $('#comment_cst1_'+cartSeq).val();
    var mitsumori_status = $('input[name="cartData['+i+'][mitsumori_status]"]').val();
    var tanka_change_flg='';
    var mitsumori_deadline_change_flg='';
    if(mitsumori_status==3){
      var oldTanka = $('input[name="cartData['+i+'][Oldtanka]"]').val();
      var oldMitsumori = $(`#old_mitsumori_deadline_${cartSeq}`).val();
      var mitsumori = $(`#mitsumori_deadline_${cartSeq}`).val();
      if(tanka!=oldTanka){
        tanka_change_flg=1;
      }
      if(oldMitsumori!=mitsumori){
        mitsumori_deadline_change_flg=1;
      }
    }
    var supp_sku = e['supp_sku'];
    var item_name = e['item_name'];
    var capacity = e['capacity'];
    var kikaku = e['kikaku'];
    var maker_name = e['maker_name'];
    var supp_co_cd = e['supp_co_cd'];
    var deliverydate = e['deliverydate'];
    var comment_usr = e['comment_usr'];
    var customer_use_code_1 = e['customer_use_code_1'];
    var customer_use_code_2 = e['customer_use_code_2'];
    var dealer_co_cd = e['dealer_co_cd'];
    var dealer_dep_cd = e['dealer_dep_cd'];
    var dealer_tanto_cd = thisTag.ecUsersInfo.id;
    var formData = new FormData();

    var arrCart = [];
    var d = new Date();
    var mitsumori_reply_date = d.getFullYear() + '-' + convertDateTime(d.getMonth()+1) + '-' + convertDateTime(d.getDate()) + ' ' + convertDateTime(d.getHours()) + ':' +convertDateTime(d.getMinutes()) + ':' + convertDateTime(d.getSeconds()); 
    var mitsumori_deadline = $('.mitsumori_deadline')[i].value;
    var mitsumoriStatus = 3;
    if(e['inquiry']){
      inquiry = 1
    }

    suryo = $('#suryo_' + i).val();
    if (suryo == '') {
      suryo_error = true;
    }

    if(tanka == ""){
      error.push("納入価格を入力してください。\n");
    }
    if(e['ec_users_id'] == thisTag.checkAll) {
      error.push('お客様を入力してください。 \n');
    }

    if ($('#file_upload_' + i).val() != '' && $('#file_upload_' + i).val() !== undefined) {
      file_upload = $("#file_upload_" + i)[0].files[0];
      formData.append('fileAttachment1_'+cartSeq, file_upload);
      fileName = $("#file_upload_" + i)[0].files[0].name;
    }
    
    arrCart = {
      table: table,
      cart_seq: cartSeq,
      suryo: suryo,
      dealer_co_cd: dealer_co_cd,
      dealer_dep_cd: dealer_dep_cd,
      tanka: tanka,
      teika_tanka: teikaTanka,
      comment_cst1: commentCst1,
      mitsumori_status: mitsumoriStatus ,
      mitsumori_reply_date: mitsumori_reply_date,
      checked: 0,
      supp_sku: supp_sku,
      item_name: item_name,
      capacity: capacity,
      kikaku: kikaku,
      maker_name: maker_name,
      supp_co_cd: supp_co_cd,
      deliverydate: deliverydate,
      comment_usr: comment_usr,
      customer_use_code_1: customer_use_code_1,
      customer_use_code_2: customer_use_code_2,
      dealer_tanto_cd: dealer_tanto_cd,
      mitsumori_deadline: mitsumori_deadline,
      tanka_change_flg: tanka_change_flg,
      mitsumori_deadline_change_flg: mitsumori_deadline_change_flg,
    };
    listCart.push(arrCart);

    if(!e['item_sku_exist']){
      item_sku_exist = false;
    }
    if(e['supp_sku'].length == 0){
      supp_sku_error = true;
    }
    if(e['is_deleted'] == 1){
      is_deleted = true;
    }
    if(supp_sku_error){
      error.push("製品情報更新ボタンを押下して品番を入力してください。\n");
    }
    if(suryo_error){
      error.push("数量を入力してください。\n");
    }
    if(!item_sku_exist && inquiry != 1){
      error.push("存在しない商品が含まれています。\n");
    }
    if($('#comment_cst1_' + cartSeq).val() == "") {
      error.push('お客様へのコメントを入力してください。 \n');
    }else{
      if($('#comment_cst1_' + cartSeq).val().length >= 200){
        error.push("お客様へコメントを200文字以内で入れてください。\n");
      }
    }
    if(error.length > 0){
      var err = error.join("");
      alert(err);
      return false;
    }
    var url = URL_API + '/api/s05/update_carts_list';
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    var query = [];
    query.push('token=' + accessTokenCognito);
    url += '?' + query.join('&');
    var tmpData = {data: listCart, customer_co_cd_selected: customer_co_cd_selected,screen:'s05',mit_status:mit_status};
    formData.append('cart_info', JSON.stringify(tmpData));
    $.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;
        }

        alert("見積回答しました。");
        var page = 1;
        searchCarts(page);
      },
      error: function () {
        alert('エラー');
      }
    });
  }
  /*this function add by asif for deleting cart from table*/
  this.deleteItemCart = function(e){
    /*code code use for get current date*/
    var error = [];
    var i = $(e.target).attr('index');
    var e = thisTag.cartsList[i];
    var table = e['table'];
    var cart_seq = $('input[name="cartData['+i+'][cart_seq]"]').val();
    var commentCst1 = $('#comment_cst1_'+cart_seq).val();
    var customer_co_cd = $('input[name="cartData['+i+'][customer_co_cds]"]').val();
    if(commentCst1==''){
      alert('お客様へのコメントを入力してください。');
      return false;
    }else{
      if(commentCst1.length >= 200){
        alert("お客様へコメントを200文字以内で入れてください。");
        return false;
      }
    }
    var result = confirm("見積不可の処理を行います。よろしいですか。");
    if(result==false){
      return false;
    }
    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;
      /*end here*/
    var query = [];
    var agent = localStorage.getItem('agent_id');
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        query.push('token=' + accessTokenCognito);
    var url = URL_API + '/api/s05/remove_carts_from_so5';
    url += '?' + query.join('&');

    var data = {
      cart_seq: cart_seq,
      mitsumori_status: 5,
      comment_cst1: commentCst1,
      updatedate:current_date
    };
    $.ajax({
      url: url,
      type: 'POST',
      timeout: 60000,
      data: {
          data: data,
          customer_co_cd_selected: customer_co_cd
      },
      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;
            searchCarts(page);
        }
      },
      error: function (xhr, stt, err) {
          alert('エラー');
      }
    });
  }
  /*function for deleting record*/
  this.deleteItemRecord = function(e){
    if (confirm('削除します。よろしいですか？')){
      var i = $(e.target).attr('index');
      var e = thisTag.cartsList[i];
      var cart_seq = $('input[name="cartData['+i+'][cart_seq]"]').val();
      var model = e['table'];
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var query = [];
      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: cart_seq, 
        mitsumori_status: 9,
        model: model
      });

      $.ajax({
        url: url,
        type: 'POST',
        timeout: 60000,
        data: {
            data: data,
            screen: 'S05_update_info'
        },
        success: function (res) {
            if(res.status == 100){
                riot.mount('app','maintain',{ messege:res.messege });
                return false;
            }
            if(data.status == 'not_authorize'){
                var url = "#";
                $(location).attr("href", url );
                return false;
            }
            if (data.message && data.errors) {
                alert('エラー');
            } else {
                alert('更新しました。');
                var page = 1;
                searchCarts(page);
            }
        },
        error: function (xhr, stt, err) {
            alert('エラー');
        }
      });
    }
  }

this.ecUsersSuggest = function(e) {
      var query = [];
      var url = URL_API + '/api/s05/get_ec_users';
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var customer_co_cd = thisTag.element.customer_co_cd;
      var customer_dep_cd = thisTag.element.customer_dep_cd;
      var dealer_co_cd = thisTag.element.dealer_co_cd;
      query.push('token=' + accessTokenCognito);
      query.push('customer_co_cd=' + customer_co_cd);
      query.push('customer_dep_cd=' + customer_dep_cd);
      query.push('dealer_co_cd=' + dealer_co_cd);
      url += '?' + query.join('&');

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

              thisTag.update({ec_users_suggest: res.ec_users});
              thisTag.getListEcUsersNameSuggest();
          },
          error: function () {
              alert('エラー');
          }
      });
    }
 this.getListEcUsersNameSuggest = function() {
      let ec_users_suggest = thisTag.ec_users_suggest;
      let res = [];
      for (var i = 0; i < ec_users_suggest.length; i++) {
        res.push({value: ec_users_suggest[i].name, label: ec_users_suggest[i].name, index: i});
      }

      $("#ec_users_name").autocompleter("destroy");
      $('#ec_users_name').autocompleter({ 
        limit:10000,
        highlightMatches:true, 
        source: res, 
        callback: function(value, index, object) {
          if($("#ec_users_name").val() != '' && ec_users_suggest[object.index].id) {
            thisTag.update({
              ec_users_id_suggest: ec_users_suggest[object.index].id,
            });
          }
        }
        
      });
  }
  this.changeSuryo = function(e) {
    var index = $(this).attr('index');
    var suryo = $('#suryo_'+index).val();
    var only_num = /^([1-9]+)([0-9]*)$/ ;
    if (suryo.length > 0) {
      if(!only_num.test(suryo) || suryo == 0){
          $('#suryo_'+index).val('');
          alert("数量が正数を入力してください");
      } else {
        $('input[name="cartData['+index+'][suryo]"]').val(suryo);
        thisTag.cartsList[index].suryo_input = suryo;
        thisTag.update(thisTag.cart_list);
      }
    }
  }

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