<order-cart>
    <link rel="stylesheet" href="./css/order-cart.css">
    <link rel="stylesheet" href="./css/common.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>
    /* datepicker */
    .ui-datepicker-calendar .day-sunday > a,
    .ui-datepicker-calendar .day-holiday > a {
      background: #ffc0c0;
    }
    .ui-datepicker-calendar .day-saturday > a {
      background: #c0d0ff;
    }
    </style>
    <div class="main">
        <div class="content">
            <div class="page-title">
                <h2>注文用カート</h2>
            </div>
            <h3 class="data-empty">カートに商品はありません</h3>
            <div class="order-list">
                <p class="required-text" style="text-align:right"><b>＊</b>が付いている項目は必須項目です。</p>
                <div class="order-item-box">
                    <table class="order-item">
                        <tbody each = { element, index in list_cart } id="{ 'item_' + index }" class="result-cart">
                            <tr>
                                <td class="left" style="width:50%">
                                    <dl>
                                        <dt>販売元メーカー</dt>
                                        <dd>{ element.sales_origin_maker_name } {element.supp_name}</dd>
                                    </dl>
                                    <dl>
                                        <dt>製造元メーカー</dt>
                                        <dd>{ element.maker_name }</dd>
                                    </dl>
                                    <dl>
                                        <dt>品番</dt>
                                        <dd><a href="{ (element.is_deleted == 1 || element.item_sku == '' || element.item_sku == null || !element.item_sku_exist) ? '' : '#search/basic_details/' + encodeURIComponent(element.item_sku) }" target="" style="{ (element.is_deleted == 1 || !element.item_sku_exist) ? 'color:black;text-decoration:none;cursor:auto;' : '' }">{ element.supp_sku }</a></dd>
                                    </dl>
                                    <dl>
                                        <dt>品名</dt>
                                        <dd>{ element.item_name }</dd>
                                    </dl>
                                    <dl>
                                        <dt>容量・規格</dt>
                                        <dd>{ element.capacity } {(carts.capacity != '' && carts.kikaku != '') ? '・' : '' } { element.kikaku }</dd>
                                    </dl>
                                    <dl>
                                        <dt>販売店</dt>
                                        <dd>{ element.dealer_co_name } { element.dealer_dep_name }</dd>
                                    </dl>
                                </td>
                                <td>
                                    <dl>
                                        <dt>定価</dt>
                                        <dd data-test="price_test_cafe">{  !isNaN(parseFloat(element.list_price)) ? (element.list_price == 0  ? 'お見積り' : parseFloat(element.list_price).toLocaleString('en') + '円' ) : 'お見積り' }</dd>
                                        <input type="hidden" id="{ 'teika_tanka_' + index}" value="{ element.list_price }">
                                    </dl>
                                    <dl>
                                        <dt>納入価格</dt>
                                        <dd data-test="price_sale_test_cafe">{ !isNaN(parseFloat(element.tanka)) ? ( parseFloat(element.tanka).toLocaleString('en') + '円' ) : 'お見積り' } <span id="{'tooltip' + index}" style="color: red;" data-toggle="tooltip" data-placement="bottom" title="前回発注時から価格変更あり" hidden><i class="fa fa-exclamation-circle"></i></span></dd>
                                    </dl>
                                </td>
                                <td style="position: relative;">
                                    <dl>
                                        <dt><span>数量</span><span class="required-text">＊</span></dt>
                                        <dd>
                                            <input type="text" id="{ 'suryo_' + index }" class="order-input spinner cart-suryo" name="{ index }" value="{ element.suryo }" min="1" tabindex="{index}" maxLength="10" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);">
                                            <span class="msg-item-sku-exist" style="position: absolute;width: 200px;top:90px;">{(element.is_deleted == 1 || !element.item_sku_exist) && element.inquiry != 1 ? 'この商品はカタログから削除されています' : ''}</span>
                                            <div class='alert-item-deleted' style="box-shadow: 1px 1px 1px 1px;font-weight: bold;font-size: 16px;padding: 5px 10px;border: 1px solid;color: red;border-radius: 6px;position:absolute;bottom:-10px;right:-12px;display:{(element.is_deleted == 1) ? 'block' : 'none'}"><h4>販売中止</h4></div>
                                            <input type="hidden" id="{ 'tanka_' + index }" class="cart-tanka" value="{element.tanka}">
                                            <input type="hidden" id="check_deleted_{index}" value="{element.is_deleted}">
                                            <input type="hidden" id="cart_seq_{index}" value="{element.cart_seq}">
                                        </dd>
                                    </dl>
                                </td>
                                <td>
                                    <dl>
                                        <dt>納入金額</dt>
                                        <dd id="{ 'total_price_' + index }">{ !isNaN(parseFloat(element.tanka)) ? (parseInt(element.tanka * element.suryo).toLocaleString('en') + '円'): 'お見積り' }</dd>
                                    </dl>
                                    <dl>
                                        <dt if={element.tax_div != 1}>消費税({ element.tax_div == '2' ? '8%' : '10%'})</dt>
                                        <dd id="{ 'total_rate_price_' + index }">{element.tax_div == '1' ? '消費税（非課税）0' : parseInt((element.tanka * element.suryo) * (element.tax_div == '2' ? 0.08 : 0.1)).toLocaleString('en') }円</dd>
                                        <input type="hidden" id="tax_product_{index}" value="{ parseInt((element.tanka * element.suryo) * (element.tax_div == '2' ? 0.08 : 0.1)) }">
                                        <input type="hidden" id="tax_rate_{index}" value="{ element.tax_div  == 1 ? '0' : element.tax_div == '2' ? '8' : '10'}">
                                    </dl>
                                </td>
                                <td class="center"  ><button class="reset-btn" id="{ index }" style="z-index:10;display: { arColumn(list_button, 'navigation_id', 'B002').length ? 'inline' : 'none' }" onclick ={ deleteCart } value="{ index }"><i class="fa fa-times" aria-hidden="true" style="z-index: 0;"></i>削除</button></td>
                            </tr>
                            <tr>
                                <td class="comment">
                                    <dl>
                                        <dt>販売店向けコメント <span id="{'comment_spp_color_' + index}">(<span id="{'comment_spp_count_' + index}">{ element.comment_spp ? element.comment_spp.length : 0 }</span>/200)</span></dt>
                                        <dd><textarea class="comment_spp" id="{'comment_spp_' + index}">{ element.comment_spp }</textarea></dd>
                                    </dl>
                                    <dl>
                                        <dt>社内コメント <span id="{'comment_usr_color_' + index}">(<span id="{'comment_usr_count_' + index}">{ element.comment_usr ? element.comment_usr.length : 0 }</span>/200)</span></dt>
                                        <dd><textarea class="comment_usr" id="{'comment_usr_' + index}">{ element.comment_usr }</textarea></dd>
                                    </dl>
                                </td>
                                <td class="codeTd" colspan="4">
                                    <dl style="display: { arColumn(list_field, 'navigation_id', 'F006').length ? 'block' : 'none'}">
                                      <dt><span>{arColumn(list_field, 'navigation_id', 'F006')[0]['display_contents']}</span></dt>
                                      <dd><input type="text" class="datepicker3 comment_deliverydate" name="{'comment_deliverydate_' + index}" id="{'comment_deliverydate_' + index}" value="{ element.deliverydate }" autocomplete="off" placeholder="yyyy/mm/dd"></dd>
                                    </dl>
                                    <dl style="display: { arColumn(list_field, 'navigation_id', 'F001').length ? 'block' : 'none'}">
                                        <dt><span>{ arColumn(list_field, 'navigation_id', 'F001')[0]['display_contents'] }</span><span class="required-text">＊</span></dt>
                                        <dd>
                                            <select id="customer_use_code_1_{index}" data-test="customer_use_code_1">
                                                <option value="">----</option>
                                                <option each = { e, i in cus_use_code_1 } selected="{(element.customer_use_code_1 == e.code_value) ? 'selected' : ''}" value="{ e.code_value }">{ e.code_value } : { e.code_definition }</option>
                                            </select>
                                        </dd>
                                    </dl>
                                    <dl style="display: { arColumn(list_field, 'navigation_id', 'F002').length ? 'block' : 'none'}">
                                        <dt><span>{ arColumn(list_field, 'navigation_id', 'F002')[0]['display_contents'] }</span><span class="required-text">＊</span></dt>
                                        <dd>
                                            <select id="customer_use_code_2_{index}" data-test="customer_use_code_2">
                                                <option value="">----</option>
                                                <option each = { e, i in cus_use_code_2 } selected="{element.customer_use_code_2 == e.code_value ? 'selected' : ''}" value="{ e.code_value }" >{ e.code_value } : { e.code_definition }</option>
                                            </select>
                                        </dd>
                                    </dl>
                                    <dl style="display: { arColumn(list_field, 'navigation_id', 'F003').length ? 'block' : 'none'}">
                                        <dt><span>{ arColumn(list_field, 'navigation_id', 'F003')[0]['display_contents'] }</span><span class="required-text required-star"></span></dt>
                                        <dd>
                                            <select id="customer_use_code_3_{index}" data-test="customer_use_code_3">
                                                <option value="">----</option>
                                                <option each = { e, i in cus_use_code_3 } selected="{element.customer_use_code_3 == e.code_value ? 'selected' : ''}" value="{ e.code_value }" >{ e.code_value } : { e.code_definition }</option>
                                            </select>
                                        </dd>
                                    </dl>
                                </td>
                            </tr>
                            <tr>
                                <td style="text-align: left; !important">
                                  <div if={(element.is_deleted != 1 &&  element.item_sku_exist) || element.inquiry == 1}>
                                    <i class="fa {element.attachment ? 'fa-file' : 'fa-paperclip'} add_file file_cart" id="add_file_{index}" index="{index}"></i>
                                    <input class="file_upload" id="file_upload_{index}" index={index} type="file" name="file" style="display: none;">
                                    <span class="file_cart_name">{element.attachment}</span>
                                    <input id="old_file_name_{index}" type="hidden" value="{element.attachment}">
                                    <i class="fa fa-times delete-file-icon" id="delete-file-icon_{index}" onclick="{deleteFile}" index="{index}" fileName="{element.attachment}" style="{element.attachment ? '' : 'display: none'}"></i>
                                  </div>
                                    
                                </td>
                            </tr>
                        </tbody>
                        <tfoot>
                        <tr>
                            <td class="delivery_address">
                                <dl>
                                    <b style="font-size: 15px;">お届け先住所</b><button class="delivery-address-change-open" id="delivery-address-change-open" style="margin-left: 10px; display: inline-block">変更</button>
                                </dl>
                                <dl>
                                    {delivery_address.kikan_name}
                                </dl>
                                <dl>
                                    {delivery_address.sosiki_name}
                                </dl>
                                <dl>
                                    {delivery_address.name}
                                </dl>
                                <dl>
                                    {delivery_address.email}
                                </dl>
                                <br>
                                <dl>
                                    {delivery_address.zip}
                                </dl>
                                <dl>
                                    {delivery_address.address1}
                                </dl>
                                <dl>
                                    {delivery_address.address2}
                                </dl>
                                <dl>
                                    {delivery_address.telephone}
                                </dl>
                            </td>
                        </tr>
                        <tr>
                                <td class="left">
                                    <button class="color-btn orange-btn" type="button" style="display: { arColumn(list_button, 'navigation_id', 'B002').length ? 'inline' : 'none' }"　onclick={ redirectOrderCart2 }>内容確認へ進む</button>
                                </td>
                                <td colspan="3">
                                    <dl>
                                        <dt>小計</dt>
                                        <dd id="total"></dd>
                                    </dl>
                                    <dl>
                                        <dt>消費税計</dt>
                                        <dd id="tax"></dd>
                                    </dl>
                                    <dl class="total">
                                        <dt>合計</dt>
                                        <dd id="total_all"></dd>
                                    </dl>
                                    <dl>
                                        <dd style="text-align: left;font-size: 11px;"><b style="color:red;">{msg}</b></dd>
                                    </dl>
                                </td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                    <input type="hidden" id="approverRequester" value="0">
                </div>
            </div>
        </div>
    </div>
    <div class="modal-wrapper">
        <delivery-address-change-open></delivery-address-change-open>
    </div>
    
    <script>
        var user_info = JSON.parse(localStorage.getItem('EcUserInfo'));
        this.list_button = user_info.list_navigation.B;
        this.list_field = user_info.list_navigation.F;
        this.list_cart = opts.result;
        this.cus_use_code_1 = opts.cus_use_code_1;
        this.cus_use_code_2 = opts.cus_use_code_2;
        this.cus_use_code_3 = opts.cus_use_code_3;
        this.delivery_address = opts.delivery_address;
        this.msg = '';
        this.latest_tanka = [];
        var thistag = this;
        var list_cart_update = this.list_cart

        this.on('mount', function () {
            if (!list_cart_update.length) {
                $('.order-list').hide();
            } else {
                $('.data-empty').hide();
            }
            thistag.checkPriceToVisibleMsg();
            this.updateTotal();
             selectFile();
        });

        $(function(){
            var spinner = $( ".spinner" ).spinner();
            /*$(".comment_deliverydate").on('blur', function(e){
                
                var date = new Date();
                var currentDate = $(e.target).val();
 
                var date_regex_only_num =   /^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$/ ;

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

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

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

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

            });*/

            $( ".cart-suryo" ).spinner({
                stop: function( event, ui ) {
                    var id = event.target.id;
                    var suryo = $('#'+id).val();

                    if(suryo <= 0){
                        alert('0以上の正数を入力してください。');
                        $('#' + id).val('1');
                    }
                    thistag.suryoChange(event);
                },
            });

        // =====================

            /*$('.comment_deliverydate').datetimepicker({
                format: 'Y/m/d',
                onShow:function( ct ){
                    this.setOptions({
                        minDate: new Date()
                    })
                },
                timepicker:false
            });*/
            // $('.comment_deliverydate').datetimepicker('update', '');
           
        // ====================
            
            if(ec31_cart_list.length > 0){
                $.each(thistag.list_cart,function(index,element){
                    jQuery.grep(ec31_cart_list, function( n, i ) {
                        if(n.cart_seq == element.cart_seq){
                            thistag.list_cart[index]['suryo'] = n.suryo; 
                        } 
                    });
                });
                thistag.update(thisTag.list_cart);
                thistag.updateTotal();
            }

            // Get customer user code list
            if(typeof opts.cus_use_code_list == 'undefined') {
                var query = [];
                var accessTokenCognito = localStorage.getItem('accessTokenCognito');
                var customer_use_code = ['customer_use_code_1','customer_use_code_2'];

                query.push('token=' + accessTokenCognito);
                query.push('status=Y');
                query.push('field=' + customer_use_code);

                var url = URL_API + '/api/ec31/customer_use_code';
                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;

                      } 

                      thistag.update({
                          cus_use_code_list: res.cus_user_code_list,
                          delivery_address: res.delivery_address,
                      });
                    },
                    error: function (xhr, stt, err) {
                      alert('error');
                    }
                });
            }

            $('.comment_spp').on('input', function() { 
                // $(this).val() // get the current value of the input field.
                var id = $(this).attr('id');
                var index = id[id.length - 1];
                var thisVal = $(this).val();

                // set the counter
                $('#comment_spp_count_'+index).text(thisVal.length);


                if( thisVal.length >= 200 ) {
                     $('#comment_spp_color_'+index).css('color', 'red');
                } else {
                    $('#comment_spp_color_'+index).css('color', '');
                }

            });

            $('.comment_usr').on('input', function() { 
                // $(this).val() // get the current value of the input field.
                var id = $(this).attr('id');
                var index = id[id.length - 1];
                var thisVal = $(this).val();

                // set the counter
                $('#comment_usr_count_'+index).text(thisVal.length);


                if( thisVal.length >= 200 ) {
                     $('#comment_usr_color_'+index).css('color', 'red');
                } else {
                    $('#comment_usr_color_'+index).css('color', '');
                }

            });

            // Applying conditions from the requirement
            var query = [];
            var accessTokenCognito = localStorage.getItem('accessTokenCognito');

            query.push('token=' + accessTokenCognito);

            var url = URL_API + '/api/get_approver_info';
            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 (typeof res.approval_list[0] !== 'undefined') {

                    var approverInfo = res.approval_list[0];

                    if(typeof thistag.list_cart !== 'undefined') {

                        if(typeof thistag.list_cart[0] !== 'undefined') {

                            if( approverInfo.approver_ec_users_id ==  thistag.list_cart[0].ec_users_id ) {

                                console.log(approverInfo.approver_ec_users_id);
                                $('.required-star').text('＊');
                                $('#approverRequester').val(1);

                            }

                        }

                    }

                }
              
            },
            error: function (xhr, stt, err) {

              alert('error');

            }

            });  

            $('#delivery-address-change-open').on('click',function(){
                thistag.getDeliveryAddress();
            });
        
            var query = [];
            $.each(thistag.list_cart,function(index,element){
                query.push(element.item_sku);                
            });
            var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            var url = URL_API + '/api/cart/check_tanka?token=' + accessTokenCognito;

            $.ajax({
                url: url,
                type: 'GET',
                data: {data: query},
                async: false,
                dataType: 'json',
                success: function (res) {
                    thistag.latest_tanka = res;
                },
                error: function (xhr, stt, error) {
                    console.log(xhr, stt, error);
                    alert('error');
                }
            });

            $.each(thistag.list_cart,function(index,element){
                var tanka = thistag.latest_tanka[element.item_sku];
                if(element.tanka != tanka && tanka !== 0 && element.item_sku.length > 0){
                    $('#tooltip'+index).prop('hidden', false);
                }else{
                    $('#tooltip'+index).prop('hidden', true);                            
                }
            });
        });

        this.getDeliveryAddress = function () {
            var accessTokenCognito = localStorage.getItem('accessTokenCognito');

            // get comment values to update later after the ajax call
            var updateCartList = thistag.updateCartList();

            $.ajax({
                url: URL_API + '/api/ec31/list_delivery_address?token=' + accessTokenCognito,
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    if(data.status == 100){
                        riot.mount('app','maintain',{ messege: data.messege });
                        return false;
                    }
                    riot.mount('delivery-address-change-open', {cart_list: updateCartList, cus_use_code_list:thistag.cus_use_code_list, address_from_ec_user: data.address_from_ec_user, list_delivery_address: data.list_delivery_address, delivery_address_ec31: thistag.delivery_address});

                    $('#delivery-address-change').fadeIn();
                },
                error: function (xhr, stt, error) {
                    alert('error');
                }
            });
        }


        this.updateCartList = function(){

            if (list_cart_update.length > 0) {
                var check_deleted = 0;
                var check_required_deliverydate = 0;
                var check_rule_deliverydate = 0;
                var check_required_deliverydate_cus_code_1 = 0;
                var check_required_deliverydate_cus_code_2 = 0;
                var check_required_deliverydate_cus_code_3 = 0;
                var error = [];
                var suryo_error = 0;
                var total = 0;
                var item_sku_exist = true;
                var tax = 0;
                var data = [];
                var isCusCodeSelected = 1;
                var dataOutMitsumori = 0;
                var formData = new FormData();

                for(var i = 0; i < list_cart_update.length; i++) {
                    var deleted = $("#check_deleted_"+i).val();
                    if(deleted == 1){
                       check_deleted = 1;
                    }

                    /*if($('#comment_deliverydate_'+i).parent().parent().css('display') !== 'none' && $('#comment_deliverydate_'+i).val() == ""){
                        check_required_deliverydate = 1;
                    }*/
                    
                    var date = new Date();
                    var yesterday = new Date(date.getTime());
                    yesterday.setDate(date.getDate() - 1);

                    if(  $('#comment_deliverydate_'+i).parent().parent().css('display') !== 'none' && new Date( $('#comment_deliverydate_'+i).val() ) < yesterday){
                        $('#comment_deliverydate_'+i).val('');
                        check_rule_deliverydate = 1;
                    }

                    if( $('#customer_use_code_1_'+i).parent().parent().css('display') !== 'none' &&  $('#customer_use_code_1_'+i).val() == 0){
                        check_required_deliverydate_cus_code_1 = 1;
                    }

                    if($('#customer_use_code_2_'+i).parent().parent().css('display') !== 'none' && $('#customer_use_code_2_'+i).val() == 0){
                        check_required_deliverydate_cus_code_2 = 1;
                    }

                    if($('#customer_use_code_3_'+i).parent().parent().css('display') !== 'none' && $('#customer_use_code_3_'+i).val() == 0 && $('#approverRequester').val() == 1 ){
                        check_required_deliverydate_cus_code_3 = 1;
                    }
                    if($('#suryo_' + i).val() <= 0){
                        suryo_error++;
                    }
                    if ((list_cart_update[i].cart_seq_mitsumori_related == null || list_cart_update[i].cart_seq_mitsumori_related == '') && (list_cart_update[i].tanka == null || list_cart_update[i].tanka == '')) {
                        dataOutMitsumori++;
                    }
                    list_cart_update[i].siire_tanka = list_cart_update[i].tanka;
                    list_cart_update[i].list_price = list_cart_update[i].list_price;
                    list_cart_update[i].suryo = $('#suryo_' + i).val();
                    list_cart_update[i].comment_usr = $('#comment_usr_' + i).val();
                    list_cart_update[i].comment_spp = $('#comment_spp_' + i).val();
                    list_cart_update[i].deliverydate = $('#comment_deliverydate_'+i).val();
                    list_cart_update[i].customer_use_code_1 = $("#customer_use_code_1_"+i).val();
                    list_cart_update[i].customer_use_code_2 = $("#customer_use_code_2_"+i).val();
                    list_cart_update[i].customer_use_code_3 = $("#customer_use_code_3_"+i).val();
                    list_cart_update[i].tax_rate = $('#tax_rate_' + i).val();
                    list_cart_update[i].tax_product = $('#tax_product_' + i).val();
                    list_cart_update[i].attachment = list_cart_update[i].attachment;
                    list_cart_update[i].inquiry = list_cart_update[i].inquiry;
                    list_cart_update[i].supp_name = list_cart_update[i].supp_name;
                    var product_price = $('#suryo_' + i).val() * list_cart_update[i].tanka;
                    total += parseInt(product_price);
                    tax += parseInt($('#tax_product_' + i).val());
                    if(!list_cart_update[i].item_sku_exist && list_cart_update[i].inquiry != 1){
                        item_sku_exist = false;
                    }

                }

                if( check_required_deliverydate_cus_code_3 ) {
                    error.push("予算科目は必須項目です。\n");
                }

                if(!item_sku_exist){
                    error.push("カタログから削除された商品が含まれています。\nその商品をカートから削除の上、再度内容確認に進んでください。\n");
                }
                if(suryo_error > 0){
                    error.push("0以上の正数を入力してください。\n");
                }
                if(check_required_deliverydate == 1){
                    error.push("希望納期は必須項目です。\n");
                }
                if(check_rule_deliverydate == 1){
                    error.push("希望納期に本日以降の日付を選択してください。\n");
                }
                if(check_required_deliverydate_cus_code_1 == 1){
                    error.push("コストセンターコードは必須項目です。\n");
                }
                if(check_required_deliverydate_cus_code_2 == 1){
                    error.push("科目コードは必須項目です。\n");
                }
                if(check_deleted == 1){
                    error.push("カート内に販売中止の商品が存在しています。\n");
                }
                if (dataOutMitsumori >= 1) {
                    error.push("納入価格0円の商品が含まれています。その商品をカートから削除の上、再度処理を行ってください。\n");
                }
                if(error.length > 0){
                    var err = error.join(" ");
                    alert(err);
                    return false;
                }
                return list_cart_update;
            } else {
                alert('選択する商品がありません');
            }
            return list_cart_update;
        }

        this.checkPriceToVisibleMsg = function(e){
            $.each(thistag.list_cart, function(i, e){
                if(parseInt(e.tanka) === parseInt(e.list_price)){
                    thistag.msg = '※納入価格に「お見積り」が含まれる場合、定価をベースに算出しています。';
                }
            });
            thistag.update(thistag.msg);
        }
        this.updateTotal = function (e) {
            var list_cart = thistag.list_cart;
            var total = 0;
            var total_tax = 0;
            for(var i = 0; i < list_cart.length; i++) {
                let tax = list_cart[i].tax_div == '2' ? 0.08 : 0.1;
                if (!isNaN($('#suryo_' + i).val()) && !isNaN($('#tanka_' + i).val())) {
                    let total_product = $('#suryo_' + i).val() * $('#tanka_' + i).val();
                    total_tax += total_product * tax;
                    total += total_product;
                }
            }
            var total_convert = parseInt(total).toLocaleString('en');
            // var tax = total * 0.08;
            var tax_convert = parseInt(total_tax).toLocaleString('en');
            var total_all_convert = parseInt(total + total_tax).toLocaleString('en');
            $('#total').text(total_convert + '円');
            $('#tax').text(tax_convert + '円');
            $('#total_all').text(total_all_convert + '円');
        }
        this.deleteCart = function (e) {
            var index = e.target.value;
            var list_cart = thistag.list_cart;
            var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            var url = URL_API + '/api/cart/create?token=' + accessTokenCognito;
            var data = [];
            data.push({
                cart_seq: list_cart[index].cart_seq,
                status: 99,
                old_attachment: list_cart[index].attachment,
                backup_flag:0
            });
            $.ajax({
                url: url,
                type: 'POST',
                timeout: 20000,
                data: {
                    data: data
                },
                success: function (data) {
                    if(data.status == 100){
                        riot.mount('app','maintain',{ messege:data.messege });
                        return false;
                    }
                    riot.route.exec();
                    // list_cart_update.splice(index, 1);
                    // alert('カートから削除しました。');
                    // $('#item_' + index).remove();
                    // // update total
                    // var total = 0;
                    // $('table.order-item').find('tbody.result-cart').each(function () {
                    //    var tanka = $(this).find('input[type=hidden]').val();
                    //    if (!isNaN($(this).find('input[type=hidden]').val()) && !isNaN($(this).find('input[type=number].cart-suryo').val())) {
                    //         total += $(this).find('input[type=hidden]').val() * $(this).find('input[type=number].cart-suryo').val();
                    //    }
                    // });
                    // var total_convert = parseFloat(total).toLocaleString('en');
                    // var tax = Math.floor(total * 0.08);
                    // var tax_convert = parseFloat(tax).toLocaleString('en');
                    // var total_all_convert = parseFloat(total + tax).toLocaleString('en');
                    // $('#total').text(total_convert + '円');
                    // $('#tax').text(tax_convert + '円');
                    // $('#total_all').text(total_all_convert + '円');
                },
                error: function (xhr, stt, error) {
                    alert('error');
                }
            });
        }
        this.noteAll = function () {
            var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            var agent = localStorage.getItem('agent_id');
            var url = URL_API + '/api/cart/create?token=' + accessTokenCognito;
            var data = [];
            $.each(list_cart_update, function (index, element) {
                data.push({
                    cart_seq: element.cart_seq,
                    dealer_co_cd: element.dealer_co_cd,
                    suryo: $('#suryo_'+index).val(),
                    comment_usr: $('#comment_usr_'+index).val(),
                    comment_spp: $('#comment_spp_'+index).val(),
                    deliverydate: $('#comment_deliverydate_'+index).val(),
                    customer_use_code_1: $("#customer_use_code_1_" + index).val(),
                    customer_use_code_2: $("#customer_use_code_2_" + index).val(),
                    customer_use_code_3: $("#customer_use_code_3_" + index).val(),
                    agent_users_id: agent,
                    status: 0
                });
            });
            $.ajax({
                url: url,
                type: 'POST',
                timeout: 20000,
                data: {
                    data: data
                },
                success: function (data) {
                    if(data.status == 100){
                        riot.mount('app','maintain',{ messege:data.messege });
                        return false;
                    }
//                    for(var i = 0; i < list_cart_update.length; i++) {
//                        $('#item_' + i).remove();
//                    }
//                    list_cart_update = [];
                    alert('カート内容を保存しました。');
                },
                error: function (e) {
                    alert('エラー');
                }
            });
        }
        this.redirectOrderCart2 = function () {
            if (list_cart_update.length > 0) {
                var check_deleted = 0;
                var check_required_deliverydate = 0;
                var check_rule_deliverydate = 0;
                var latest_tanka = [];
                var check_required_deliverydate_cus_code_1 = 0;
                var check_required_deliverydate_cus_code_2 = 0;
                var check_required_deliverydate_cus_code_3 = 0;
                var error = [];
                var apos_error = 0;
                var suryo_error = 0;
                var total = 0;
                var item_sku_exist = true;
                var tax = 0;
                var data = [];
                var isCusCodeSelected = 1;
                var dataOutMitsumori = 0;
                var comment_usr_err = 0;
                var comment_sup_err = 0;
                var formData = new FormData();
                var isTankaUpdated = false;

                var accessTokenCognito = localStorage.getItem('accessTokenCognito');
                var url = URL_API + '/api/cart/check_tanka?token=' + accessTokenCognito;

                for(var i = 0; i < list_cart_update.length; i++) {
                    if(list_cart_update[i].item_sku.length > 0){
                        var tanka = thistag.latest_tanka[list_cart_update[i].item_sku];
                        if(list_cart_update[i].tanka != tanka && tanka != 0){
                            if(!isTankaUpdated){
                                latest_tanka.push("前回発注時から価格変更があります。");
                                isTankaUpdated = true;
                            }
                            latest_tanka.push(list_cart_update[i].supp_sku + ":" + list_cart_update[i].item_name);
                        }
                    }

                    var deleted = $("#check_deleted_"+i).val();
                    if(deleted == 1){
                       check_deleted = 1;
                    }

                    /*if($('#comment_deliverydate_'+i).parent().parent().css('display') !== 'none' && $('#comment_deliverydate_'+i).val() == ""){
                        check_required_deliverydate = 1;
                    }*/
                    
                    var date = new Date();
                    var yesterday = new Date(date.getTime());
                    yesterday.setDate(date.getDate() - 1);

                    if ($('#comment_spp_' + i).val().includes("'") || $('#comment_usr_' + i).val().includes("'")) {
                        apos_error++;
                    }

                    if(  $('#comment_deliverydate_'+i).parent().parent().css('display') !== 'none' && new Date( $('#comment_deliverydate_'+i).val() ) < yesterday){
                        $('#comment_deliverydate_'+i).val('');
                        check_rule_deliverydate = 1;
                    }

                    if( $('#customer_use_code_1_'+i).parent().parent().css('display') !== 'none' &&  $('#customer_use_code_1_'+i).val() == 0){
                        check_required_deliverydate_cus_code_1 = 1;
                    }

                    if($('#customer_use_code_2_'+i).parent().parent().css('display') !== 'none' && $('#customer_use_code_2_'+i).val() == 0){
                        check_required_deliverydate_cus_code_2 = 1;
                    }

                    if($('#customer_use_code_3_'+i).parent().parent().css('display') !== 'none' && $('#customer_use_code_3_'+i).val() == 0 && $('#approverRequester').val() == 1 ){
                        check_required_deliverydate_cus_code_3 = 1;
                    }
                    if($('#suryo_' + i).val() <= 0){
                        suryo_error++;
                    }

                    if($('#comment_usr_' + i).val().length >= 200){
                        comment_usr_err = 1;
                    }

                    if($('#comment_spp_' + i).val().length >= 200){
                        comment_sup_err = 1;
                    }

                    if ((list_cart_update[i].cart_seq_mitsumori_related == null || list_cart_update[i].cart_seq_mitsumori_related == '') && (list_cart_update[i].tanka == null || list_cart_update[i].tanka == '')) {
                        dataOutMitsumori++;
                    }
                    list_cart_update[i].siire_tanka = list_cart_update[i].tanka;
                    list_cart_update[i].list_price = list_cart_update[i].list_price;
                    list_cart_update[i].suryo = $('#suryo_' + i).val();
                    list_cart_update[i].comment_usr = $('#comment_usr_' + i).val();
                    list_cart_update[i].comment_spp = $('#comment_spp_' + i).val();
                    list_cart_update[i].deliverydate = $('#comment_deliverydate_'+i).val();
                    list_cart_update[i].customer_use_code_1 = $("#customer_use_code_1_"+i).val();
                    list_cart_update[i].customer_use_code_1_text = $("#customer_use_code_1_"+i+' :selected').text();
                    list_cart_update[i].customer_use_code_2 = $("#customer_use_code_2_"+i).val();
                    list_cart_update[i].customer_use_code_2_text = $("#customer_use_code_2_"+i+' :selected').text();
                    list_cart_update[i].customer_use_code_3 = $("#customer_use_code_3_"+i).val();
                    list_cart_update[i].customer_use_code_3_text = $("#customer_use_code_3_"+i+' :selected').text();
                    list_cart_update[i].tax_rate = $('#tax_rate_' + i).val();
                    list_cart_update[i].tax_product = $('#tax_product_' + i).val();
                    list_cart_update[i].attachment = list_cart_update[i].attachment;
                    list_cart_update[i].inquiry = list_cart_update[i].inquiry;
                    list_cart_update[i].supp_name = list_cart_update[i].supp_name;
                    var product_price = $('#suryo_' + i).val() * list_cart_update[i].tanka;
                    total += parseInt(product_price);
                    tax += parseInt($('#tax_product_' + i).val());
                    if(!list_cart_update[i].item_sku_exist && list_cart_update[i].inquiry != 1){
                        item_sku_exist = false;
                    }
                    if ($('#file_upload_' + i).val() != '' && $('#file_upload_' + i).val() !== undefined) {
                        file_upload = $("#file_upload_" + i)[0].files[0];
                        formData.append('file_upload_' + list_cart_update[i].cart_seq, file_upload);
                        var fileName = $('#file_upload_' + i).val().split('\\')[$('#file_upload_' + i).val().split('\\').length - 1];
                        data.push({
                            cart_seq: list_cart_update[i].cart_seq,
                            old_attachment: list_cart_update[i].attachment
                        });
                    }
                }
                formData.append('cart_info', JSON.stringify(data));

                if( check_required_deliverydate_cus_code_3 ) {
                    error.push("予算科目は必須項目です。\n");
                }

                if (apos_error) {
                    error.push("コメント欄及びお届け先に「'」は入力できません。\n");
                }
                if(!item_sku_exist){
                    error.push("カタログから削除された商品が含まれています。\nその商品をカートから削除の上、再度内容確認に進んでください。\n");
                }
                if(suryo_error > 0){
                    error.push("0以上の正数を入力してください。\n");
                }
                if(comment_usr_err == 1){
                    error.push("社内コメントは200文字以内で入力してください。\n");
                }
                if(comment_sup_err == 1){
                    error.push("販売店向けコメントは200文字以内で入力してください\n");
                }
                if(check_required_deliverydate == 1){
                    error.push("希望納期は必須項目です。\n");
                }
                if(check_rule_deliverydate == 1){
                    error.push("希望納期に本日以降の日付を選択してください。\n");
                }
                if(check_required_deliverydate_cus_code_1 == 1){
                    error.push("コストセンターコードは必須項目です。\n");
                }
                if(check_required_deliverydate_cus_code_2 == 1){
                    error.push("科目コードは必須項目です。\n");
                }
                if(check_deleted == 1){
                    error.push("カート内に販売中止の商品が存在しています。\n");
                }
                if (dataOutMitsumori >= 1) {
                    error.push("納入価格0円の商品が含まれています。その商品をカートから削除の上、再度処理を行ってください。\n");
                }
                if(error.length > 0){
                    var err = error.join(" ");
                    alert(err);
                    return false;
                }
                if(latest_tanka.length > 0){
                    latest_tanka.push("内容確認へ進んでよろしいですか。")
                    var lt_tanka = latest_tanka.join("\n");
                    if(!confirm(lt_tanka)){
                        return false;
                    }
                }
                if (data.length > 0) {
                    var query = [];
                    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
                    query.push('token=' + accessTokenCognito);
                    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'){
                                var list_cart = res.listCart;
                                for(var i = 0; i < list_cart_update.length; i++) {
                                    for(var j = 0; j < list_cart.length; j++) {
                                        if (list_cart_update[i].cart_seq == list_cart[j].cart_seq) {
                                            list_cart_update[i].attachment = list_cart[j].attachment;
                                            break;
                                        }
                                    }
                                }
                                riot.mount('app', 'order-cart-2', { result: list_cart_update, total:  total, tax: tax, cus_use_code_1: opts.cus_use_code_1,cus_use_code_2: opts.cus_use_code_2, cus_use_code_3: thistag.cus_use_code_3, delivery_address: thistag.delivery_address});
                            }else if(res.message == 'errors'){
                                alert('ファイルがまだアップできていません。');
                            }
                        },
                        error: function (xhr, stt, err) {
                            alert('ファイルがまだアップできていません。');
                        }
                    });
                    return false;
                } else {
                    riot.mount('app', 'order-cart-2', { result: list_cart_update, total:  total, tax: tax, cus_use_code_1: opts.cus_use_code_1,cus_use_code_2: opts.cus_use_code_2, cus_use_code_3: opts.cus_use_code_3, delivery_address: thistag.delivery_address});
                }
            } else {
                alert('選択する商品がありません');
            }
        }

        function filterSuryo(arr,cart_seq,suryo){
         
            var suryo_change = false;
            if(ec31_cart_list.length > 0){
                jQuery.grep(arr, function( n, i ) {
                    if(n.cart_seq == cart_seq){
                        suryo_change = true;
                        ec31_cart_list[i].suryo = suryo;
                    } 
                });
                if(!suryo_change){
                    ec31_cart_list.push({cart_seq:cart_seq,suryo:suryo});
                }
            } else {
                ec31_cart_list.push({cart_seq:cart_seq,suryo:suryo});
            }
            suryo_change = false;
        }
        this.suryoChange = function(e) {
            var index = e.target.attributes.tabindex.value;
            var suryo = $('#suryo_'+index).val();
            var suryo_change = false;
            var arr_index = '';
            var list_cart = thistag.list_cart;
            var total = 0;
            var total_tax = 0;
            var cart_seq = $('#cart_seq_' + index).val();
            filterSuryo(ec31_cart_list,cart_seq,suryo);
            var total_price =  !isNaN(parseFloat($('#tanka_'+index).val())) ? ($('#tanka_'+index).val() * suryo +'円') : 'お見積り';
            $('#total_price_' + index).text(total_price);
            var total_rate_price = ($('#tanka_'+index).val() * suryo) * (list_cart[index].tax_div == '2' ? 0.08 : 0.1);

            $('#total_rate_price_'+index).text(parseInt(total_rate_price).toLocaleString('en')+'円');
            $("#tax_product_" + index).val(parseInt(total_rate_price));
            for(var i = 0; i < list_cart.length; i++) {
                let tax = list_cart[i].tax_div == '2' ? 0.08 : 0.1;
                if (!isNaN($('#suryo_' + i).val()) && !isNaN($('#tanka_' + i).val())) {
                    let total_product = $('#suryo_' + i).val() * $('#tanka_' + i).val();
                    total_tax += total_product * tax;
                    total += total_product;
                }
            }
            var total_convert = parseInt(total).toLocaleString('en');
            var tax_convert = parseInt(total_tax).toLocaleString('en');
            var total_all_convert = parseInt(total + total_tax).toLocaleString('en');
            $('#total').text(total_convert + '円');
            $('#tax').text(tax_convert + '円');
            $('#total_all').text(total_all_convert + '円');
        }
        this.deleteFile = function (e) {
          var index = $(e.target).attr('index');
          var fileName = $(e.target).attr('fileName');
          if (index) {
            noFile(index);
            $('#file_upload_' + index).val('');
            $('#file_upload_' + index).next().first().text($('#old_file_name_' + index).val());
            $('#delete-file-icon_' + index).hide();
          }
          if (fileName) {
              var item = e.item;
              var query = [];
              var accessTokenCognito = localStorage.getItem('accessTokenCognito');
                  query.push('token=' + accessTokenCognito);
              var url = URL_API + '/api/cart/create';
              
              url += '?' + query.join('&');
              
              var data = [];
                  data.push({
                      cart_seq: item.element.cart_seq,
                      old_attachment: item.element.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'){
                          riot.route.exec();
                      }
                   
                  },
                  error: function (xhr, stt, error) {
                      alert('エラー');
                  }
              });
            
          }
        }

    </script>
    <script>
    DatepickerHoliday();
    </script>

</order-cart>
