<EC84>
  <link rel="stylesheet" href="css/EC84.css">
  <link rel="stylesheet" href="css/EC84-modal.css?v=1">
  <link rel="stylesheet" href="./css/assets/css/bootstrap.min.css">

  <div class="main">
    <div class="content">
      <div class="page-title">
        <h2>顧客管理</h2>
      </div>
      <div class="form-wrapper">
        <table>
          <tbody>
            <tr>
              <th></th>
              <td></td>
              <th></th>
              <td></td>
              <th></th>
            </tr>
            <tr>
              <th width="110px">お客様法人名</th>
              <td width="400px">
                <div class="div-wraper-autocompleter"><input type="text" id="comp_name_search"></div>
              </td>
              <th width="150px"></th>
              <td width="150px" style="text-align: center;">
                <button type="reset" class="reset-btn"><i class="fa fa-refresh"></i>クリア</button></td>
              <td width="150px">
                <button　style="background:#1C6BC0; color:#FFFFFF; border-radius:5px;" type="button" class="submit" id="submit_search">検索</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="result-wrapper">
        <!-- <div class="result-head">
          <p class="head-text">検索結果は { total } 件です。</p>
          <div class="btn-wrapper">
            <button type="button" class="submit" id="EC84-add-Open">法人を追加</button>
          </div>
        </div> -->
        <table class="blue-table">
          <thead>
            <tr>
              <th>お客様法人名</th>
              <th>販売価格端数処理</th>
              <th><span class="order-cmnt-cls">受注履歴回答コメント</span> <br> <!-- <button class='change-comp-order-comment-cls' onclick={changeCompOrderComment()}>追加・更新</button>--></th>
              <th><span class="mitsumori-cmnt-cls">見積回答コメント</span></th>
              <th><span class="mitsumori-kigen-cls">見積期限</span></th>
              <th>ユーザーグループ名 <br> <button class='add-user-group-name-cls' onclick={userGroupName()}>追加・更新</button></th>
              <th width="60px"></th>
            </tr>
          </thead>
          <tbody>
            <tr each={customer in dealerCustomers}>
              <td> <span class="EC84-customer-modal-Open td-text-decoration" onclick={setDepartmentModalValues(customer.customer_co_cd)}>{customer.dealer_customer_name}</span> </td>
              <td>
                <select name="price_rounding" id="price_rounding_{customer.customer_co_cd}" class="user-price-rounding" style="width:200px">
                    <option value="" selected={customer.price_rounding == null || customer.price_rounding == ''} >小数点切り捨て</option>
                    <option value="1" selected={customer.price_rounding == 1}>小数点第一位を四捨五入</option>
                    <option value="3" selected={customer.price_rounding == 3}>下１桁を四捨五入</option>
                    <option value="5" selected={customer.price_rounding == 5}>下１桁を0または5に切り捨て</option>
                    <option value="2" selected={customer.price_rounding == 2}>下1桁を0に切り捨て</option>
                  </select> 
              </td>
              <td style="padding:10px !important;"><!-- <a class="copy-txt-cls" value={customer.seq} style="font-size: 10px;　display:block;" >[コピー]</a>--><textarea style="width:150px !important;" class="order-cmnt-{customer.seq}">{customer.order_comment}</textarea></td>
              <td style="padding:10px;"><textarea style="width:150px !important;" class="mitsumori-cmnt-{customer.seq}">{customer.mitsumori_comment}</textarea></td>
              <td> 
                <select class="mitsumori_term_flg" name="mitsumori_term_flg" id="mitsumori_term_flg_{customer.seq}">
                    <option value="" selected={customer.mitsumori_term_flg == '0' || customer.mitsumori_term_flg == null || customer.mitsumori_term_flg == ''} >1か月</option>
                    <option value="1" selected={customer.mitsumori_term_flg == '1'} >3か月</option>
                    <option value="2" selected={customer.mitsumori_term_flg == '2'} >6か月</option>
                    <option value="9" selected={customer.mitsumori_term_flg == '9'} >カレンダー選択</option>
                </select>

                <div name="mitsumori_term_date" hidden={customer.mitsumori_term_flg != '9'}>                  
                  <div class="input-group">
                    <input type="text" id={customer.seq} class="form-control mitsumori_term_date_{customer.seq}" placeholder="yyyy/mm/dd" value="{customer.mitsumori_term_date}" aria-describedby="icon_{customer.seq}">
                    <span id="icon_{customer.seq}" class="input-group-addon mitsumori-term-date"  style="cursor: pointer; color:blue;"><i class="fa fa-calendar"></i></span>
                  </div>
                </div>
              </td>

              <td> 
                <select class="user-group-name user-group-cus-{customer.customer_co_cd}" name="user_group" id="userGroup_{customer.seq}" style="width:100px">
                    <option value="" selected={customer.user_group_code == null || customer.user_group_code == ''} >一つ選択してください</option>

                    <option each={user_group in all_user_group} if={user_group.delete_flg == '1'} value="{user_group.seq}" selected={customer.user_group_code == user_group.seq}>{user_group.user_group_name}</option>

                  </select>
                </td>
              <td><button style="background:#2EB533; color:#FFFFFF; border-radius:5px;" class='update-btn' onclick={updateCompanyPriceRounding(customer.customer_co_cd, customer.seq)} >更新</button></td>
            </tr>
          </tbody>
        </table>
        <div id="paging" class="text-center">
          <ul class="pagination" id="pagination_ec84"></ul>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-wrapper">

    <link rel="stylesheet" href="css/EC84-modal.css?v=1">

    <!-- =========== Show dapartment lists in modal=========== -->
    <div class="o_modal" id="EC84-edit">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="EC84-customer-modal-Close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title">{ modal_customer_name }</h3>
            <h3 class="modal-title">{ this_user_group_name }</h3>
            <div class="modal-form-box">
              <input type="hidden" id="comp_code_key" value="{element.comp_code}">
              <table>
                <tr >
                    <th>事業所名</th>
                    <th>所在地</th>
                    <th>管轄部署</th>
                    <th>担当者登録</th>
                  </tr>
                </thead>
                <tbody>
                  <tr each={dealer_customer in modal_dealer_customers}>

                    <td> { dealer_customer.cus_kyoten_name } </td>
                    <td> { dealer_customer.pref } </td>
                    <td> { dealer_customer.dep_kyoten_name } </td>
                    <td class="td-text-decoration"> <span onclick={ assignUser(dealer_customer) }>担当者（{ dealer_customer.dealer_tanto_counter }）</span>   </td>

                  </tr>

              </table>
              <div class="btn-wrapper">

                <button type="button" class="submit" id="EC84-customer-modal-Close">戻る</button>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <companies-add-modal name="companies_add_modal"></companies-add-modal> -->
    <!-- <companies-edit-modal name="companies_edit_modal"></companies-edit-modal> -->
  </div>

  <div class="modal-wrapper">

  <!--  <link rel="stylesheet" href="css/EC84-modal.css?v=1"> -->

    <!-- =========== Second modal for updating dealer_customers dept_name and tantos=========== -->
    <div class="o_modal" id="EC84-edit-second-modal">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a class="EC84-second-modal-close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title">{ modal_customer_name }</h3>
            <h3 class="modal-title">{ 　modal_customer_cus_kyoten_name　 } ({　modal_customer_cus_kyoten_code })</h3>
            <div class="modal-form-box">
              
              <div>

                <p>担当事業所</p>
                <input type="text" readonly value={ modal_customer_dep_kyoten_name }>

              </div>
              
              <div class='margin-top-30'>

                <p>施設担当者</p>
                <select id="dealer_tanto_select">

                    <option each={dealer_user in dealer_users} value="{dealer_user.id}"> { dealer_user.name } </option>

                </select> 

                <button type="button" class="add-dealer-usr-btn" id="addDealerUser">追加</button>

              </div>

              <div class='margin-top-30'>

                <div each={ec_user in selected_dealer_users}>

                  <input readonly type="text" value="{ ec_user.name }"> 
                  <span onclick={ removeUserName(ec_user.id) }>×削除</span>

                </div>

              </div>

              <div class="btn-wrapper margin-top-30" style="text-align: left;">

                <button type="button" class="submit" id="updateDealerTantoCd">更新</button>
                <button type="button" class="EC84-second-modal-close submit">戻る</button>
                <input type="hidden" value={this_dealer_customer}>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <companies-add-modal name="companies_add_modal"></companies-add-modal> -->
    <!-- <companies-edit-modal name="companies_edit_modal"></companies-edit-modal> -->
  </div>

  <div class="modal-wrapper">

  <!--  <link rel="stylesheet" href="css/EC84-modal.css?v=1"> -->

    <!-- =========== Modal for updating user_group_master TBL=========== -->
    <div class="o_modal" id="userGroupNameModal">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="user-group-name-modal-close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title user-group-modal-title">新規ユーザーグループ名追加</h3>
            <div class="modal-form-box">
              <table>
                <thead>
                  <tr>
                    <th>新規ユーザーグループ名 <button hidden class="reset-user-group-val"><i class="fa fa-refresh"></i>クリア</button></th>

                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>
                      <input type="text" id="userGroupNameVal" style="width: 45%;">
                      <button type="button" class="user-group-save-btn" onclick={ saveUserGroup() }>追加</button>
                      <input type="hidden" id="userGroupMasterSeq" value="">
                      <input type="hidden" id="userGroupMasterType" value="">
                    </td>
                  </tr>
                </tbody>
              </table>

            <h3 class="modal-title">ユーザーグループ名 更新・削除</h3>
            <div class="modal-form-box">
              <table>
                <thead>
                  <tr>
                    <th>ユーザーグループ名</th>
                    <th></th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <tr each={user_group in all_user_group} if={user_group.delete_flg == '1'}>
                    <td> {user_group.user_group_name}</td>
                    <td><button onclick={changeUserGroupVals(user_group.seq, 'update', user_group.user_group_name)} >更新</button></td>
                    <td><button onclick={changeUserGroupVals(user_group.seq, 'delete','')} >削除</button></td>
                  </tr>
                </tbody>
              </table>
              <div class="btn-wrapper">

                <button type="button" class="submit" id="user-group-name-modal-close">戻る</button>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    </div>
    <div class="o_modal" id="changeCompOrderCommentModal">
      <div class="o_modal_box small-modal-cls">
        <div class="o_modal_head">
          <a class="comp-order-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 comp-order-comment-modal-title">受注履歴画面回答コメント</h3>
            <div class="modal-form-box">
              <table>
                <tbody>
                  <tr>
                    <td>
                      <textarea type="text" id="compOrderCommentVal">{compOrderComment}</textarea>
                      <button type="button" class="comp-order-comment-update-btn-cls" onclick={ updateCompOrderBtn() }>更新</button>
                      <button type="button" class="comp-order-comment-modal-close">閉じる</button>
                    </td>
                  </tr>
                </tbody>
              </table>
          </div>
        </div>
      </div>
    </div>
    <!-- <companies-add-modal name="companies_add_modal"></companies-add-modal> -->
    <!-- <companies-edit-modal name="companies_edit_modal"></companies-edit-modal> -->
  </div>
  <script>
  this.ecUsersInfo =  JSON.parse(getItem('EcUserInfo'));
  this.compOrderComment = '';
  this.companies = [];
  this.departments = opts.department;
  this.users_edit = '';
  this.condition = false;
  this.max_oem_co_cd = '';
  this.total = 0;
  this.list_companies_suggest_search = [];
  this.list_companies_suggest_dropdown = [];
  this.comp_code_search = '';
  this.element = {};
  this.comp_name; // companies name by user login
  this.price_rounding = [
    {
      name: '小数点切り捨て',
      value: ''
    },
    {
      name: '小数点第一位を四捨五入',
      value: 1
    },
    {
      name: '下1桁四捨五入',
      value: 3
    },
    {
      name: '下１桁を0または5に切り捨て',
      value: 5  
    },
    {
      name: '下1桁を0に切り捨て',
      value: 2  
    }
  ];

  this.del_flg_list = [
    {
      name: '使用中',
      value: 0
    },
    {
      name: '削除',
      value: 1
    },
  ];
  this.prefectures = [
    {
      name: '',
      code: ''
    },
    {
    name:'北海道',
    code: '1'
    },
    {
    name:'青森県',
    code: '2'
    },
    {
    name:'岩手県',
    code: '3'
    },
    {
    name:'宮城県',
    code: '4'
    },
    {
    name:'秋田県',
    code: '5'
    },
    {
    name:'山形県',
    code: '6'
    },
    {
    name:'福島県',
    code: '7'
    },
    {
    name:'茨城県',
    code: '8'
    },
    {
    name:'栃木県',
    code: '9'
    },
    {
    name:'群馬県',
    code: '10'
    },
    {
    name:'埼玉県',
    code: '11'
    },
    {
    name:'千葉県',
    code: '12'
    },
    {
    name:'東京都',
    code: '13'
    },
    {
    name:'神奈川県',
    code: '14'
    },
    {
    name:'新潟県',
    code: '15'
    },
    {
    name:'富山県',
    code: '16'
    },
    {
    name:'石川県',
    code: '17'
    },
    {
    name:'福井県',
    code: '18'
    },
    {
    name:'山梨県',
    code: '19'
    },
    {
    name:'長野県',
    code: '20'
    },
    {
    name:'岐阜県',
    code: '21'
    },
    {
    name:'静岡県',
    code: '22'
    },
    {
    name:'愛知県',
    code: '23'
    },
    {
    name:'三重県',
    code: '24'
    },
    {
    name:'滋賀県',
    code: '25'
    },
    {
    name:'京都府',
    code: '26'
    },
    {
    name:'大阪府',
    code: '27'
    },
    {
    name:'兵庫県',
    code: '28'
    },
    {
    name:'奈良県',
    code: '29'
    },
    {
    name:'和歌山県',
    code: '30'
    },
    {
    name:'鳥取県',
    code: '31'
    },
    {
    name:'島根県',
    code: '32'
    },
    {
    name:'岡山県',
    code: '33'
    },
    {
    name:'広島県',
    code: '34'
    },
    {
    name:'山口県',
    code: '35'
    },
    {
    name:'徳島県',
    code: '36'
    },
    {
    name:'香川県',
    code: '37'
    },
    {
    name:'愛媛県',
    code: '38'
    },
    {
    name:'高知県',
    code: '39'
    },
    {
    name:'福岡県',
    code: '40'
    },
    {
    name:'佐賀県',
    code: '41'
    },
    {
    name:'長崎県',
    code: '42'
    },
    {
    name:'熊本県',
    code: '43'
    },
    {
    name:'大分県',
    code: '44'
    },
    {
    name:'宮崎県',
    code: '45'
    },
    {
    name:'鹿児島県',
    code: '46'
    },
    {
    name:'沖縄県',
    code: '47'
    }
  ];

  var thisTag = this;
  var page = 1;
  this.data_tag = {};


  // This function is for updating companies price_rounding 
  updateCompanyPriceRounding( customer_co_cd, customer_seq ) {
    return function(e) {

      var price_rounding = $('#price_rounding_'+customer_co_cd).val();
      var user_group_code_val = $('#userGroup_'+customer_seq).val();
      var orderCmnt = $('.order-cmnt-'+customer_seq).val();
      var mitsumoriCmnt = $('.mitsumori-cmnt-'+customer_seq).val();
      var mitsumori_term_flg = $('#mitsumori_term_flg_'+customer_seq).val();
      var mitsumori_term_date = $('.mitsumori_term_date_'+customer_seq).val().length > 0 ? $('.mitsumori_term_date_'+customer_seq).val() : null;


      if(mitsumori_term_flg == '9' && mitsumori_term_date == null){
        alert('カレンダー選択の場合には、日付指定は必須です');
        return;
      }

      // For updating dealer_customers TBL user_group_code
      var data = {

        seq: customer_seq,
        user_group_code: user_group_code_val,
        price_rounding: price_rounding,
        order_comment: orderCmnt,
        mitsumori_comment: mitsumoriCmnt,
        mitsumori_term_flg: mitsumori_term_flg,
        mitsumori_term_date: mitsumori_term_date

      };

      var query = [];

      var url = URL_API + '/api/a02/dealer_customers/put';

      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      
      query.push('token=' + accessTokenCognito);

      url += '?' + query.join('&');

      $.ajax({

        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {
          data: data
        },
        success: function (res) {
          if(res.status == 100){
            riot.mount('app','maintain',{ messege:res.messege });
            return false;
          }
          alert("編集完了しました");
        },
        error: function (err) {
          alert('error');
        }

      });
      

    }

  }

  // This function remove ecuser from modal
  removeUserName( ec_user_id ) {

    return function(e) {

      var tmpSelectedDealerUsers = [];

      $.each( thisTag.selected_dealer_users, function( selected_users_key, selected_users_value ) {

        if( ec_user_id == selected_users_value.id ) {

          thisTag.dealer_users.push(selected_users_value);

        } else {

          tmpSelectedDealerUsers.push(selected_users_value);

        }

      });


      thisTag.update({

        dealer_users: thisTag.dealer_users,
        selected_dealer_users: tmpSelectedDealerUsers

      });

    }

  }

  // This function is for updating department modal value
  setDepartmentModalValues( customer_co_cd ) {

    return function(e) {

      var dealer_customer = '';
      var customer_name = '';
      var counter = 0;
      var addr = '';
      var modal_dealer_customers = [];

      var query = [];
    
      var url = URL_API + '/api/a02/dealer_customers/list';

      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      
      query.push('token=' + accessTokenCognito);

      if (customer_co_cd) {
        query.push('customer_co_cd=' + encodeURI(customer_co_cd));
      }

      url += '?' + query.join('&');

      $.ajax({
        url: url,
        type: 'GET',
        dataType: 'JSON',
        success: function (res) {

          if(res.status == 100){
            riot.mount('app','maintain', { messege:res.messege });
            return false;
          }

          $.each( res.dealer_customers_list.list, function( dealer_customer_key, dealer_customer_value ) {

            var counter = 0;
            counter += dealer_customer_value.dealer_tanto_cd ? 1 : 0;
            counter += dealer_customer_value.dealer_tanto_cd2 ? 1 : 0;
            counter += dealer_customer_value.dealer_tanto_cd3 ? 1 : 0;
            counter += dealer_customer_value.dealer_tanto_cd4 ? 1 : 0;
            counter += dealer_customer_value.dealer_tanto_cd5 ? 1 : 0;

            dealer_customer_value['dealer_tanto_counter'] = counter;

            if( thisTag.ecUsersInfo.member_authority == '2' || thisTag.ecUsersInfo.member_authority == '9' ) {

              if( dealer_customer_value.dealer_co_cd == thisTag.ecUsersInfo.kikan_code &&  dealer_customer_value.status == '1') {

                if(typeof dealer_customer_value.dealer_dep_cd !== 'undefined') {

                  if( dealer_customer_value.dealer_dep_cd != null) {

                    var tmp_dealer_dep_cd = dealer_customer_value.dealer_dep_cd;

                    if( tmp_dealer_dep_cd.length > 0 ) {

                      modal_dealer_customers.push( dealer_customer_value );

                    }

                  }

                }
              
              }

            } if( thisTag.ecUsersInfo.member_authority == '3' ) {

                if( dealer_customer_value.dealer_dep_cd == thisTag.ecUsersInfo.sosiki_code &&  dealer_customer_value.status == '1') {

                  if(typeof dealer_customer_value.dealer_dep_cd !== 'undefined') {

                    if( dealer_customer_value.dealer_dep_cd != null) {

                      var tmp_dealer_dep_cd = dealer_customer_value.dealer_dep_cd;

                      if( tmp_dealer_dep_cd.length > 0 ) {

                        modal_dealer_customers.push( dealer_customer_value );

                      }
                      
                    }

                  }
                
                }

              }

          });

          thisTag.update({

            modal_dealer_customers: modal_dealer_customers

          });

          getDepartmentValues(modal_dealer_customers);

        },
        error: function () {
            alert('error');
        }
      });


      $.each( thisTag.dealerCustomers, function( dealer_customer_key, dealer_customer_value ) {

          if( dealer_customer_value.customer_co_cd == customer_co_cd ) {

            dealer_customer = dealer_customer_value ;
            customer_name = dealer_customer.customer_co_name;
            
            return false;

          }

      });

      var get_user_group_name = $('.user-group-cus-'+customer_co_cd + ' option:selected').text();
      if( get_user_group_name == '一つ選択してください') { get_user_group_name = '';}
      customer_name = customer_name + ' (' + customer_co_cd + ')'; 
      var this_user_group_name = ' ユーザーグループ: ' + get_user_group_name;

      thisTag.update({

        modal_customer_name: customer_name,
        this_user_group_name: this_user_group_name,

      });

      $('#EC84-edit').fadeIn();
      
    }

  }

function getDepartmentValues(modal_dealer_customers) {

  $.each( modal_dealer_customers, function( dealer_customer_key, dealer_customer_value ) {

    if(typeof dealer_customer_value.customer_dep_cd !== 'undefined') {

      if( dealer_customer_value.customer_dep_cd != null && dealer_customer_value.customer_dep_cd != '' ) {

        var query = [];    
        var url = URL_API + '/api/ec84/departments_data/get';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        query.push('token=' + accessTokenCognito);
        query.push('kyoten_code=' + encodeURI(dealer_customer_value.customer_dep_cd));
        url += '?' + query.join('&');

        $.ajax({
          url: url,
          type: 'GET',
          dataType: 'JSON',
          success: function (res) {

            if(res.http == 100){
              riot.mount('app','maintain', { messege:res.messege });
              return false;
            }

            dealer_customer_value['cus_kyoten_name'] = res.departments[0].kyoten_name;
            dealer_customer_value['kyoten_code'] = res.departments[0].kyoten_code;
            dealer_customer_value['pref'] = res.departments[0].pref;

            thisTag.update({

              dealer_customer_value: dealer_customer_value             

            });

          },
          error: function () {
              alert('error');
          }
        });

      }

    }

    if( typeof dealer_customer_value.dealer_dep_cd !== 'undefined' ) {

      if( dealer_customer_value.dealer_dep_cd != null ) {

        var query = [];    
        var url = URL_API + '/api/ec84/departments_data/get';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        query.push('token=' + accessTokenCognito);
        query.push('kyoten_code=' + encodeURI(dealer_customer_value.dealer_dep_cd));
        url += '?' + query.join('&');

        $.ajax({
          url: url,
          type: 'GET',
          dataType: 'JSON',
          success: function (res) {

            if(res.http == 100){
              riot.mount('app','maintain', { messege:res.messege });
              return false;
            }

            dealer_customer_value['dep_kyoten_name'] = res.departments[0].kyoten_name;
            dealer_customer_value['dep_kyoten_code'] = res.departments[0].kyoten_code;

            thisTag.update({

              dealer_customer_value: dealer_customer_value             

            });

          },
          error: function () {
              alert('error');
          }
        });

      } 

    }

  });

}

  userGroupName() {

    return function(e) {

      $('#userGroupNameModal').fadeIn();

    }

  }

  changeCompOrderComment() {

    return function(e) {
      $('#changeCompOrderCommentModal').fadeIn();

    }

  }

  saveUserGroup() {

    return function(e) {

      var dealer_co_cd = thisTag.ecUsersInfo.kikan_code;
      var updated_by = thisTag.ecUsersInfo.id;
      var user_group_name = $('#userGroupNameVal').val();
      user_group_name = user_group_name.trim();
      var user_group_type = $('#userGroupMasterType').val();
      var user_group_seq = $('#userGroupMasterSeq').val();

      if( user_group_name.length <= 0 ) { alert('ユーザーグループ名を入力します。'); return false; }

      if( user_group_type == 'update' ) {

        if (!(confirm('更新します。よろしいですか。'))) { return false; } 
        var data = {

          seq: user_group_seq,
          updated_by: updated_by,
          user_group_name: user_group_name
            
        };
        var url = URL_API + '/api/a02/user_group_master/update';

      } else {

        if (!(confirm('追加します。よろしいですか。'))) { return false; } 
        var data = {

          dealer_co_cd: dealer_co_cd,
          updated_by: updated_by,
          user_group_name: user_group_name
            
        };
        var url = URL_API + '/api/a02/user_group_master/save';

      }

      var query = [];
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      query.push('token=' + accessTokenCognito);
      url += '?' + query.join('&');

      $.ajax({

        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {
            data: data
        },
        success: function (res) {

          if(res.http == 400){
              riot.mount('app','maintain',{ messege: 'Bad request' });
              return false;
          }

          if(res.message == 'success'){

            if( user_group_type == 'update' ) {

              var userGroup = thisTag.all_user_group;
              $.each( userGroup, function( userGroup_key, userGroup_value ) {

                if( userGroup_value.seq == user_group_seq ) {

                  userGroup[userGroup_key]['user_group_name'] = user_group_name;

                }

              });

              $('.reset-user-group-val').click();

            } else {

              var addData = {

                'seq': res.seq,
                'user_group_name': user_group_name,
                'delete_flg': '1'

              };

              var userGroup = thisTag.all_user_group;
              userGroup.push(addData);

              $('#userGroupNameVal').val("");

            }

            thisTag.update({

              all_user_group: userGroup

            });
            
            alert('更新しました。');

          }

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

      });

    }

  }

  updateCompOrderBtn() {

    return function(e) {

      var comp_order_comment = $("#compOrderCommentVal").val();
      var comp_code_key = thisTag.ecUsersInfo.kikan_code;
      
      if(comp_code_key != '' && comp_order_comment != '') {
        var data = {
          comp_code_key: comp_code_key,
          order_comment: comp_order_comment
        };

        var query = [];
        var url = URL_API + '/api/ec80/companies/update';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        query.push('token=' + accessTokenCognito);
        url += '?' + query.join('&');

        $.ajax({
          url: url,
          type: 'POST',
          dataType: 'JSON',
          data: {
            data: data
          },
          success: function (res) {

            if(res.status == 100){
              riot.mount('app','maintain',{ messege:res.messege });
              return false;
            }
            
            if (res.message == 'success') {
              $("#changeCompOrderCommentModal").fadeOut();
              thisTag.update({compOrderComment: comp_order_comment});
              alert("更新しました。");
            }

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

    }

  }
  changeUserGroupVals(seq, type, user_group_name) {

    return function(e) {

      if(type == 'update') { 

        $('#userGroupNameVal').val(user_group_name);
        $('.user-group-modal-title').text('ユーザーグループ名を更新する');
        $('.user-group-modal-title').css("color", "blue");

        $('.user-group-save-btn').text("更新");
        $('#userGroupMasterType').val('update');
        $('#userGroupMasterSeq').val(seq);
        $('.reset-user-group-val').show();

      }

      if(type == 'delete') { 

        if (!(confirm('削除します。よろしいですか。'))) { return false; } 
        var updated_by = thisTag.ecUsersInfo.id;
        var data = {

          seq: seq,
          updated_by: updated_by,
          delete_flg: '0'
            
        };
        var url = URL_API + '/api/a02/user_group_master/update';
        var query = [];
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        query.push('token=' + accessTokenCognito);
        url += '?' + query.join('&');

        $.ajax({

        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {
            data: data
        },
        success: function (res) {

          if(res.http == 400){
              riot.mount('app','maintain',{ messege: 'Bad request' });
              return false;
          }

          if(res.message == 'success'){


            var userGroup = thisTag.all_user_group;
            $.each( userGroup, function( userGroup_key, userGroup_value ) {

              if( userGroup_value.seq == seq ) {

                userGroup[userGroup_key]['delete_flg'] = '0';

              }

            });

            thisTag.update({

              all_user_group: userGroup

            });
            
            alert('更新しました。');

          }

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

      });


      }

    }

  }

  assignUser(thisDealerCustomer) {

    return function(e) {

      thisTag.update({

        modal_customer_cus_kyoten_name　: thisDealerCustomer.cus_kyoten_name,
        modal_customer_dep_kyoten_name　: thisDealerCustomer.dep_kyoten_name,
        modal_customer_cus_kyoten_code : thisDealerCustomer.customer_dep_cd,
        this_dealer_customer : thisDealerCustomer

      });

      if( thisDealerCustomer.dealer_dep_cd != null ) {

        var dealer_users = [];
        var selected_dealer_users = [];
        var query = [];    
        var url = URL_API + '/api/ec-users/list';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        // var sosiki_code = thisTag.ecUsersInfo.sosiki_code;
        query.push('token=' + accessTokenCognito);
        query.push('sosiki_code=' + encodeURI(thisDealerCustomer.dep_kyoten_code));
        url += '?' + query.join('&');

        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'JSON',
            success: function (res) {

              if(res.http == 100){
                riot.mount('app','maintain', { messege:res.messege });
                return false;
              }
              
              $.each( res.ec_users_list, function( user_key, user_val ){

                if( user_val.id == thisDealerCustomer.dealer_tanto_cd || user_val.id == thisDealerCustomer.dealer_tanto_cd2 || user_val.id == thisDealerCustomer.dealer_tanto_cd3 || user_val.id == thisDealerCustomer.dealer_tanto_cd4 || user_val.id == thisDealerCustomer.dealer_tanto_cd5 ) {

                  selected_dealer_users.push(user_val);

                } else {

                  if( user_val.member_authority == 1 && user_val.yobi3 != '1' ) {
                    
                    dealer_users.push(user_val);

                  }

                }

              });
              
              thisTag.update({

                dealer_users: dealer_users,
                selected_dealer_users: selected_dealer_users

              });

            },
            error: function () {
                alert('error');
            }
          });

        $('#EC84-edit-second-modal').fadeIn();

      } else {

        alert('部門コードが見つかりません');
        return false;

      }

    }

  }



  $(function(){
    
    thisTag.searchDealerCustomer(page);

    $(document).on('click', '.mitsumori-term-date', function(e) {
    console.log(e);
    var seq = e.currentTarget.id;
    seq = seq.replace('icon_', '');
    console.log(seq);
    $('.mitsumori_term_date_'+seq).datetimepicker({
      format: 'Y/m/d',
      onShow:function( ct ){
          this.setOptions({
              minDate: new Date()
          })
      },
      scrollInput: false,
      timepicker:false
    }).focus();
  });
    $(".reset-btn").on('click',function(){
      $("#comp_name_search").val("");
      thisTag.update({
        comp_code_search: ''
      });
    });

    $(".reset-user-group-val").on('click',function(){
      
        $('#userGroupNameVal').val('');
        $('.user-group-modal-title').text('新規ユーザーグループ名追加');
        $('.user-group-modal-title').css("color", "black");

        $('.user-group-save-btn').text("追加");
        $('#userGroupMasterType').val('');
        $('#userGroupMasterSeq').val('');
        $('.reset-user-group-val').hide();

    });

    

    $("#submit_search").on('click',function(){
      thisTag.searchDealerCustomer(page);
    });


    $(".add-dealer-usr-btn").on('click',function(){
      
      var selectedUserId = $('#dealer_tanto_select').val();
      var tmpDealerUsers = [];

      if( thisTag.selected_dealer_users.length + 1  > 5 ) {

        alert('5つ以上追加することはできません。');
        return false;

      }

      $.each( thisTag.dealer_users, function(dealer_user_key, dealer_user_val){

        if( selectedUserId == dealer_user_val.id ){

          thisTag.selected_dealer_users.push(dealer_user_val);

        } else {

          tmpDealerUsers.push(dealer_user_val);

        }

      });

      thisTag.update({

        selected_dealer_users: thisTag.selected_dealer_users,
        dealer_users: tmpDealerUsers

      });

    });

    $(document).on('change', '.mitsumori_term_flg', function(){
      if($(this).val() != '9'){
        $(this).parent().find('div[name="mitsumori_term_date"]').prop('hidden', true);
      }else{
        $(this).parent().find('div[name="mitsumori_term_date"]').prop('hidden', false);        
      }
    });


    // Update dealer tanto cd
    $(document).on('click', '#updateDealerTantoCd', function(e){

      var selectedDealerUsers = thisTag.selected_dealer_users;
    
      if( selectedDealerUsers.length > 0 ) {

        var dealer_tanto_cd = dealer_tanto_cd2 = dealer_tanto_cd3 = dealer_tanto_cd4 = dealer_tanto_cd5 = null;
        thisTag.this_dealer_customer.dealer_tanto_cd = thisTag.this_dealer_customer.dealer_tanto_cd2 = thisTag.this_dealer_customer.dealer_tanto_cd3 = thisTag.this_dealer_customer.dealer_tanto_cd4 = thisTag.this_dealer_customer.dealer_tanto_cd5 = null;

        $.each( selectedDealerUsers, function( user_key, user_val ) {

          if(user_key == 0) { dealer_tanto_cd = user_val.id; thisTag.this_dealer_customer.dealer_tanto_cd = user_val.id; }
          if(user_key == 1) { dealer_tanto_cd2 = user_val.id; thisTag.this_dealer_customer.dealer_tanto_cd2 = user_val.id; }
          if(user_key == 2) { dealer_tanto_cd3 = user_val.id; thisTag.this_dealer_customer.dealer_tanto_cd3 = user_val.id; }
          if(user_key == 3) { dealer_tanto_cd4 = user_val.id; thisTag.this_dealer_customer.dealer_tanto_cd4 = user_val.id; }
          if(user_key == 4) { dealer_tanto_cd5 = user_val.id; thisTag.this_dealer_customer.dealer_tanto_cd5 = user_val.id; }

        });

        var data = thisTag.this_dealer_customer;

        data = {
            seq : data.seq,
            dealer_tanto_cd: dealer_tanto_cd,
            dealer_tanto_cd2: dealer_tanto_cd2,
            dealer_tanto_cd3: dealer_tanto_cd3,
            dealer_tanto_cd4: dealer_tanto_cd4,
            dealer_tanto_cd5: dealer_tanto_cd5
        };

        var query = [];
        var url = URL_API + '/api/a02/dealer_customers/put';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');

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

        url += '?' + query.join('&');

        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'JSON',
            data: {
                data: data
            },
            success: function (res) {
                if(res.http == 400){
                    riot.mount('app','maintain',{ messege: 'Bad request' });
                    return false;
                }
                if(res.http == 404){
                    riot.mount('app','maintain',{ messege: 'Not Found' });
                    return false;
                }
                if(res.http == 409){
                    riot.mount('app','maintain',{ messege: 'Conflict' });
                    return false;
                }
                if(res.http == 500){
                    riot.mount('app','maintain',{ messege: 'Server error' });
                    return false;
                }
                if(res.http == 402){
                    riot.mount('app','maintain',{ messege: 'Bad gateway' });
                    return false;
                }


                // var tmp_modal_dealer_customers = [];

                $.each(thisTag.modal_dealer_customers, function( dealer_cus_key, dealer_cus_val ) {

                  // tmp_modal_dealer_customers.push(dealer_cus_val);

                  if( dealer_cus_val.seq == thisTag.this_dealer_customer.seq ) {

                    dealer_cus_val['dealer_tanto_counter'] = selectedDealerUsers.length;

                    thisTag.update({

                      modal_dealer_customers: thisTag.modal_dealer_customers,
                      this_dealer_customer: thisTag.this_dealer_customer

                    });

                  }

                });

                alert("更新しました");

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


      } else {

        alert('名前を1つ選択してください');
        return false;

      }

    });

    $(document).on('click', '#EC84-add-Open', function(e){
      // thisTag.data_tag.element = {};
      // riot.mount('companies-add-modal', 'companies-add-modal', {data_tag: thisTag.data_tag});
      // thisTag.tags.companies_add_modal.update(thisTag.data_tag);
      $('#EC84-add').fadeIn();
    });
    $(document).on('click', '#EC84-add-Close', function(e){
      $('#EC84-add').fadeOut();
      $("#add_new_comp_code").val(thisTag.max_oem_co_cd);
    });


    $(document).on('click', '#EC84-customer-modal-Close', function(e){
      $('#EC84-edit').fadeOut();
    });

    $(document).on('click', '#user-group-name-modal-close', function(e){
      $('#userGroupNameModal').fadeOut();
    });

    $(document).on('click', '.comp-order-comment-modal-close', function(e){
      $('#changeCompOrderCommentModal').fadeOut();
    });

    $(document).on('click', '.EC84-second-modal-close', function(e){
        
        $('#EC84-edit-second-modal').fadeOut();

    });

    $(document).on('click', '.copy-txt-cls', function(e){
        
        var dealerSeq = $(this).val();
        var compOrderCmnt = $('.order-cmnt-cls').text();
        $('.order-cmnt-'+dealerSeq).val(thisTag.compOrderComment);
    });

    $(document).on('change', '#add_flg', function(e) {
      let add_flg = $("#add_flg option:selected").val();
      if(add_flg != 'customer_flg') {
        $('#add_old_comp_code').prop('disabled', true);
      } else {
        $('#add_old_comp_code').prop('disabled', false);
      }
    });
    $("#comp_name_search").change(function(e) {
      if(!$(e.target).val()) {
        thisTag.update({comp_code_search: ''});
      }
    });
    // Clear Form
    // change 法人形態選択 addform
    $('#add_flg').on('change', function(){
      if ($(this).val() != 'customer_flg') {
        thisTag.update({
          price_rounding : [
            {
              name: '小数点切り捨て',
              value: ''
            }
          ]
        });
      } else {
        thisTag.update({
          price_rounding : [
            {
              name: '小数点切り捨て',
              value: ''
            },
            {
              name: '小数点第一位を四捨五入',
              value: 1
            },
            {
              name: '下1桁四捨五入',
              value: 3
            },
            {
              name: '下１桁を0または5に切り捨て',
              value: 5
            },
            {
              name: '下1桁を0に切り捨て',
              value: 2
            }
          ]
        });
      }
    });

    // change 法人形態選択 editform
    $('#edit_flg').on('change', function(){
      if ($(this).val() != 'customer_flg') {
        thisTag.update({
          price_rounding : [
            {
              name: '小数点切り捨て',
              value: ''
            }
          ]
        });
      } else {
        thisTag.update({
          price_rounding : [
            {
              name: '小数点切り捨て',
              value: ''
            },
            {
              name: '小数点第一位を四捨五入',
              value: 1
            },
            {
              name: '下1桁四捨五入',
              value: 3
            },
            {
              name: '下１桁を0または5に切り捨て',
              value: 5
            },
            {
              name: '下1桁を0に切り捨て',
              value: 2
            }
          ]
        });
      }
    });
  });
  
  $(document).on('click', '#EC84-add .reset-btn', function(e) {
    thisTag.clearInput();
  });


  $(document).on('click', '#EC84-edit .reset-btn', function(e) {
    thisTag.resetInput();
  });
  // Add Companies
  $(document).off('click', '#add_company_80');
  $(document).on('click', '#add_company_80', function(e) {
    if(!thisTag.validate("add")) {
      return false;
    }
    thisTag.add();
  });
  // Edit Companies
  $(document).off('click', '#edit_company_80');
  $(document).on('click', '#edit_company_80', function(e) {
    if(!thisTag.validate("edit")) {
      return false;
    }
    thisTag.edit();
  });
  this.validate = function(id) {
    var err = [];
    if($("#"+id+"_flg").val() == 'customer_flg' && $("#"+id+"_old_comp_code").val() == '') {
      err.push('管轄販売店名を選択してください。\n');
    }
    if($("#"+id+"_new_comp_code").val() == '') {
      err.push('法人コードは入力必須です。\n');
    }
    if($("#"+id+"_new_comp_code").val() != '' && !thisTag.checkLatin($("#"+id+"_new_comp_code").val())) {
      err.push('コードは半角英数を使用してください。\n');
    }
    if($("#"+id+"_comp_name").val() == '') {
      err.push('法人名は必須です。\n');
    }
    if($("#"+id+"_comp_name").val().length > 100) {
      err.push('法人名を100文字以内に入力してください。\n');
    }
    if($("#"+id+"_comp_ryaku").val().length > 100) {
      err.push('法人略称を100文字以内に入力してください。\n');
    }
    if($("#"+id+"_comp_kana").val() == '') {
      err.push('カナ索引は必須です。\n');
    }
    if($("#"+id+"_comp_kana").val().length > 100) {
      err.push('カナ索引を100文字以内に入力してください。\n');
    }
    
    if($("#"+id+"_comp_kana").val() != '' && !thisTag.checkKana($("#"+id+"_comp_kana").val())) {
      err.push('カナ索引をカタカナ文字で入力してください。\n');
    }

    if($("#"+id+"_comp_eng").val().length > 100) {
      err.push('法人名英語表記を100文字以内に入力してください。\n');
    }

    // only english or kana
    if($("#"+id+"_comp_eng").val() != '' && !thisTag.checkEnglish($("#"+id+"_comp_eng").val())) {
      err.push('法人名英語表記を半角文字で入力してください。\n');
    }
    if($("#"+id+"_post_code").val().length > 15) {
      err.push('郵便番号を15文字以内に入力してください。\n');
    }
    if($("#"+id+"_addr").val().length > 100) {
      err.push('所在地を100文字以内に入力してください。\n');
    }
    if($("#"+id+"_tel").val().trim().length > 15) {
      err.push('電話番号を15文字以内に入力してください。\n');
    }
    if($("#"+id+"_tel").val() != '' && !thisTag.checkNumberHyphen($("#"+id+"_tel").val().trim())) {
      err.push('電話番号を半角文字で入力してください。\n');
    }
    if($("#"+id+"_fax").val().trim().length > 15) {
      err.push('FAX番号を15文字以内に入力してください。\n');
    }
    if($("#"+id+"_fax").val() != '' && !thisTag.checkNumberHyphen($("#"+id+"_fax").val().trim())) {
      err.push('FAX番号を半角数字で入力してください。\n');
    }

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

  this.checkEnglish = function(word) {

    var pattEng = /^[a-zA-Z0-9$@$!%*?&#^-_. +]+$/i;

    var checkEng = pattEng.test(word);

    if(checkEng) {
      return true;
    }

    return false;
  }

  this.checkLatin = function(word) {

    var pattLatin = /^[a-zA-Z0-9]+$/i;

    var checkLatin = pattLatin.test(word);

    if(checkLatin) {
      return true;
    }

    return false;
  }

  this.checkKana = function(word) {
    var pattKanaFullWidth = /^[ァ-ンー]+$/i;
    // var pattKanaHalfWidth = /^[ｧ-ﾝﾞﾟ]|[ー]+$/i;

    // var checkKanHalfWidth = pattKanaHalfWidth.test(word);
    var checkKanFullWidth = pattKanaFullWidth.test(word);

    // if(checkKanHalfWidth) {
    //   return true;
    // }
    if(checkKanFullWidth) {
      return true;
    }
    return false;
  }

  this.checkNumberHyphen = function(number) {
    var pattNumber = /^[0-9]+$|([0-9]+(-[0-9]+))+$/i;
    var checkNumber = pattNumber.test(number);

    if(checkNumber) {
      return true;
    }
    return false;
  }

  this.searchDealerCustomer = function(page) {
      
    var query = []; var memAuth3 = 0;
    
    var url = URL_API + '/api/a02/dealer_customers/list';

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);

    if (this.ecUsersInfo.member_authority) {
      if (this.ecUsersInfo.member_authority == '3') {
        query.push('dealer_dep_cd=' + encodeURI(this.ecUsersInfo.sosiki_code));
        query.push('memAuth=3');
        memAuth3 = 1;
      }
    }

    if (this.ecUsersInfo.kikan_code) {
      query.push('dealer_co_cd=' + encodeURI(this.ecUsersInfo.kikan_code));
    }

    // query.push('page=' + page);
    // query.push('limit=' + LIMIT_ON_PAGE);

    url += '?' + query.join('&');

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


        //remove dealer_customers where dealer_customer.dealer_dep_cd is not NULL

        var tmpArr = [];
        var index = 0;

        $.each( res.dealer_customers_list.list, function( customer_key, customer_value ) {

          if ( customer_value.dealer_dep_cd ){

            if( (customer_value.dealer_dep_cd).length < 1) {

              tmpArr[index] = customer_value;
              index = index + 1;

            }else {
              if(memAuth3 == '1' && (customer_value.dealer_dep_cd).length > 1) {
                tmpArr[index] = customer_value;
                index = index + 1;
              }
            }

          } else {

            tmpArr[index] = customer_value;
            index = index + 1;

          }

        });

        res.dealer_customers_list.list = tmpArr;

        if( res.dealer_customers_list ) {

          // If user search for a customer
          if( $('#comp_name_search').val() != '' ) {

            var search_value = $('#comp_name_search').val();
            var customer_list = [];
              
            $.each( res.dealer_customers_list.list, function( customer_key, customer_value ) {

              if (customer_value.dealer_customer_name.indexOf( search_value ) >= 0){

                customer_list.push( customer_value );

              }

            });

            thisTag.getAllCompanyList( customer_list );

          } else {

            thisTag.getAllCompanyList( res.dealer_customers_list.list );

          }

        }

        thisTag.update({
          companies: res.companies,
          dealerCustomers: res.dealer_customers_list.list,
          total: res.total,
          max_oem_co_cd: res.max_oem_co_cd,
          condition: res.condition,
          list_companies_suggest_search: res.dealer_customers_list.list,
          comp_name: res.comp_name
        });
        

        var totalPages = Math.ceil(res.total/LIMIT_ON_PAGE);
        var visiblePages = 1;
        if(totalPages != 0){
            visiblePages =  5;
        } 

        var $pagination = $('#pagination_ec84');
        $pagination.twbsPagination('destroy');
        $pagination.twbsPagination({
          totalPages: totalPages,
          visiblePages: visiblePages,
          startPage: page,
          initiateStartPageClick: false,
          onPageClick: function (event, page) {
            thisTag.searchDealerCustomer(page);
          }
        });

        // thisTag.data_tag = {
        //   del_flg_list: thisTag.del_flg_list,
        //   max_oem_co_cd: thisTag.max_oem_co_cd, 
        //   condition: thisTag.condition, 
        //   prefectures: thisTag.prefectures, 
        //   price_rounding: thisTag.price_rounding,
        //   validate: thisTag.validate
        // };
        thisTag.getListSuggestCompanies(res.dealer_customers_list.list);
        if(thisTag.ecUsersInfo.kikan_code == '20000275') {
          thisTag.getListCompanies();
        }
      },
      error: function () {
          alert('error');
      }
    });
  }


  // Get all company list, check with dealer customer and update dealer customer list
  this.getAllCompanyList = function( dealer_customer_lists ) {

    var query = [];
    
    var url = URL_API + '/api/ec80/companies/get_all_companies';

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);

    url += '?' + query.join('&');

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

        if(typeof res.comp_order_comment !== 'undefined') {

          thisTag.update({

            compOrderComment: res.comp_order_comment,

          });
        }

        // search for dealer_customer.customer_co_cd == companies.comp_code
        var all_companies = res.companies_all;

        $.each( dealer_customer_lists, function( dealer_customer_key, dealer_customer_value ) {

          $.each( all_companies, function( company_key, company_value ) {

            if( dealer_customer_value.customer_co_cd == company_value.comp_code ) {

              dealer_customer_lists[dealer_customer_key]['pref'] = company_value.pref;
              dealer_customer_lists[dealer_customer_key]['dealer_customer_name'] = company_value.comp_name;

              return false;

            }

          });

        });


        if( typeof dealer_customer_lists !== 'undefined' ) {

          if( dealer_customer_lists.length >= 1 ) {

            thisTag.getAllUserGroup( dealer_customer_lists );

          }

        }

        thisTag.update({

          dealerCustomers: dealer_customer_lists,

        });


      },
      error: function () {
          alert('error');
      }
    });

  }


  // Get all user group from user group master table, check with dealer customer (delaer_co_cd) and update dealer customer list
  this.getAllUserGroup = function( dealer_customer_lists ) {

    var query = [];
    
    var url = URL_API + '/api/a02/user_group_master/list';

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);

    url += '?' + query.join('&');

    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'JSON',
      success: function (res) {

        if(res.http == 100){
          riot.mount('app','maintain', { messege:res.messege });
          return false;
        }

        // search for dealer_customer.customer_co_cd == companies.comp_code
        var all_user_group = res.user_group_master_list;
        var usersInfo = thisTag.ecUsersInfo;
        var dealer_user_group = [];
        var index = 0;

        $.each( all_user_group, function( user_group_key, user_group_value ) {

          if( usersInfo.kikan_code == user_group_value.dealer_co_cd ) {

            dealer_user_group[index] = user_group_value;
            index = index + 1;

            $.each( dealer_customer_lists, function( dealer_customer_key, dealer_customer_value ) {

              if( user_group_value.delete_flg == '0' ) {

                dealer_customer_lists[dealer_customer_key]['user_group_name'] = user_group_value.user_group_name;

              }

            });

          }

        });

        if( !(usersInfo.member_authority == '2' || usersInfo.member_authority == '3' || usersInfo.member_authority == '9') ){
                
          $('.user-group-name').attr('disabled','disabled');
          $('.user-price-rounding').attr('disabled','disabled');
          // $('.add-user-group-name-cls').hide();
          $('.update-btn').hide();
        
        }

        if(usersInfo.member_authority == '3'){
                
          $('.add-user-group-name-cls').attr('disabled','disabled');
        
        }

        thisTag.update({

          dealerCustomers: dealer_customer_lists,
          all_user_group: dealer_user_group

        });

      },
      error: function () {
          alert('error');
      }
    });

  }


  this.getListSuggestCompanies = function(list) {
    let res = [];
    for (var i = list.length - 1; i >= 0; i--) {
      res.push({value: list[i].dealer_customer_name, label: list[i].dealer_customer_name, comp_index: i});
    }
    $("#comp_name_search").autocompleter("destroy");
    $('#comp_name_search').autocompleter({ 
      limit:10000,
      highlightMatches:true, 
      source: res, 
      callback: function(value, index, object) {
        if($("#comp_name_search").val() != '' && thisTag.list_companies_suggest_search[object.comp_index].dealer_co_cd) {
          thisTag.update({comp_code_search: thisTag.list_companies_suggest_search[object.comp_index].dealer_co_cd});
        } else {
          thisTag.update({comp_code_search: ''});
        }
      }
    });
  }


  this.getListCompanies = function(e) {
    var query = [];
  
    var url = URL_API + '/api/ec80/companies/get_customer_list';

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);
    query.push('dealer_flg=1');

    url += '?' + query.join('&');

    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'JSON',
      success: function (res) {
        if(res.status == 100){
          riot.mount('app','maintain', { messege:res.messege });
          return false;
        }
        thisTag.update({list_companies_suggest_dropdown: res.companies});
      },
      error: function () {
          alert('error');
      }
    });
  }

  // ================================== Add Companies ===================================
  this.add = function(e) {  
    var flg = $("#add_flg").val();
    var dealer_tel = $("#add_flg").val();
    var comp_name = $("#add_comp_name").val();
    var comp_ryaku = $("#add_comp_ryaku").val();
    var comp_kana = $("#add_comp_kana").val();
    var comp_eng = $("#add_comp_eng").val();
    var post_code = $("#add_post_code").val();
    var new_comp_code = $("#add_new_comp_code").val();
    var addr = $("#add_addr").val();
    var tel = $("#add_tel").val();
    var fax = $("#add_fax").val();
    var del_flg = $("#add_del_flg").val();
    var price_rounding = $("#add_price_rounding").val();
    var pref_code = $("#add_prefectures option:selected").val();
    var pref = $("#add_prefectures option:selected").attr('pref');
    var old_comp_code = $("#add_old_comp_code option:selected").val();
    if(thisTag.ecUsersInfo.kikan_code != '20000275') {
      old_comp_code = $("#add_old_comp_code").attr('comp_code');
    }
    var data = {
      new_comp_name: comp_name,
      comp_ryaku: comp_ryaku,
      comp_kana: comp_kana,
      comp_eng: comp_eng,
      post_code: post_code,
      // new_comp_code: new_comp_code,
      old_comp_code: old_comp_code ? old_comp_code : '',
      addr: addr,
      tel: tel,
      fax: fax,
      del_flg: del_flg,
      price_rounding: price_rounding, 
      pref_code: pref_code ? pref_code : '', 
      pref: pref ? pref : '',
      condition: thisTag.condition
    };

    if(thisTag.condition && thisTag.ecUsersInfo.kikan_code == '20000275') {
      var dealer_tel = $("#add_old_comp_code option:selected").attr('tel');
      var dealer_fax = $("#add_old_comp_code option:selected").attr('fax');
      data.dealer_tel = dealer_tel;
      data.dealer_fax = dealer_fax;
    }
    if($("#add_new_comp_code").length) {
      var new_comp_code = $("#add_new_comp_code").val();
      data.new_comp_code = new_comp_code;
    }

    if($("#add_up_comp_code").length) {
      var up_comp_code = $("#add_up_comp_code").val();
      data.up_comp_code = up_comp_code;
    }

    var query = [];

    var url = URL_API + '/api/ec80/companies/create';

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);
    query.push('flg=' + flg);

    url += '?' + query.join('&');

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

        if(res.exist) {
          alert("法人コードには重複データの入力できません。");
          return true;
        } else {
          alert("追加しました。");
          return true;
        }
        thisTag.clearInput();
        $('#add_old_comp_code').prop('disabled', false);
        $('#EC84-add').fadeOut();
        $("#submit_search").trigger('click');
      },
      error: function (err) {
        alert('error');
      }
    });
  }

  this.checkCompCode = function(e) {
    var comp_code = $(e.target).val();

    var query = [];
  
    var url = URL_API + '/api/ec80/companies/check_comp_code_exist';

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);
    query.push('comp_code=' + comp_code);

    url += '?' + query.join('&');

    $.ajax({
      url: url,
      type: 'GET',
      dataType: 'JSON',
      success: function (res) {
        if(res.status == 100){
          riot.mount('app','maintain', { messege:res.messege });
          return false;
        }
        if(res.exist) {
          alert("入力されたIDは既に存在しています。");
          $("#add_new_comp_code").val(thisTag.max_oem_co_cd);
        }
      },
      error: function () {
          alert('error');
      }
    });
  }

  this.clearInput = function(e) {
    $("#add_comp_name").val('');
    $("#add_comp_ryaku").val('');
    $("#add_comp_kana").val('');
    $("#add_comp_eng").val('');
    $("#add_post_code").val('');
    $("#add_new_comp_code").val(thisTag.max_oem_co_cd);
    $("#add_old_comp_code").prop("selectedIndex", 0);
    $("#add_addr").val('');
    $("#add_tel").val('');
    $("#add_fax").val('');
    $("#add_del_flg").val('0');
    $("#add_price_rounding").val('');
    $("#add_prefectures").val('');
    $("#add_flg").val('customer_flg');
  }

  // ================================== Edit Companies ===================================

  this.edit = function(e) { 
      var comp_code_key = $("#comp_code_key").val(); 
      var flg = $("#edit_flg").val();
      var dealer_tel = $("#edit_flg").val();
      var comp_name = $("#edit_comp_name").val();
      var comp_ryaku = $("#edit_comp_ryaku").val();
      var comp_kana = $("#edit_comp_kana").val();
      var comp_eng = $("#edit_comp_eng").val();
      var post_code = $("#edit_post_code").val();
      var new_comp_code = $("#edit_new_comp_code").val();
      var addr = $("#edit_addr").val();
      var tel = $("#edit_tel").val();
      var fax = $("#edit_fax").val();
      var del_flg = $("#edit_del_flg").val();
      var price_rounding = $("#edit_price_rounding").val();
      var pref_code = $("#edit_prefectures option:selected").val();
      var pref = $("#edit_prefectures option:selected").attr('pref');
      var old_comp_code = $("#edit_old_comp_code option:selected").val();
      
      var data = {
        comp_code_key: comp_code_key,
        new_comp_name: comp_name,
        comp_ryaku: comp_ryaku,
        comp_kana: comp_kana,
        comp_eng: comp_eng,
        post_code: post_code,
        // new_comp_code: new_comp_code,
        old_comp_code: old_comp_code ? old_comp_code : '',
        addr: addr,
        tel: tel,
        fax: fax,
        del_flg: del_flg,
        price_rounding: price_rounding, 
        pref_code: pref_code ? pref_code : '', 
        pref: pref ? pref : '',
        condition: thisTag.condition
      };

      if($("#edit_new_comp_code").length) {
        var new_comp_code = $("#edit_new_comp_code").val();
        data.new_comp_code = new_comp_code;
      }

      if($("#edit_up_comp_code").length) {
        var up_comp_code = $("#edit_up_comp_code").val();
        data.up_comp_code = up_comp_code;
      }

      var query = [];

      var url = URL_API + '/api/ec80/companies/update';

      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      
      query.push('token=' + accessTokenCognito);
      query.push('flg=' + flg);

      url += '?' + query.join('&');

      $.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {
          data: data
        },
        success: function (res) {
          if(res.status == 100){
            riot.mount('app','maintain',{ messege:res.messege });
            return false;
          }
          alert("編集完了しました。");
          $('#EC84-edit').fadeOut();
          $("#submit_search").trigger('click');
        },
        error: function (err) {
          alert('error');
        }
      });
    }

    this.resetInput = function(e) {
      $("#edit_comp_name").val(thisTag.element.comp_name);
      $("#edit_comp_ryaku").val(thisTag.element.comp_ryaku);
      $("#edit_comp_kana").val(thisTag.element.comp_kana);
      $("#edit_comp_eng").val(thisTag.element.comp_eng);
      $("#edit_post_code").val(thisTag.element.post_code);
      $("#edit_addr").val(thisTag.element.addr);
      $("#edit_tel").val(thisTag.element.tel);
      $("#edit_fax").val(thisTag.element.fax);
      $("#edit_del_flg").val(thisTag.element.del_flg);
      $("#edit_price_rounding").val(thisTag.element.price_rounding);
      $("#edit_prefectures").val(thisTag.element.pref_code);
    }
  </script>
</EC84>
