<EC81>
  <link rel="stylesheet" href="css/EC81.css">
  <link rel="stylesheet" href="css/EC81-modal.css">
  <div class="main">
    <div class="content">
      <div class="page-title">
        <h2>事業所管理</h2>
      </div>
      <div class="form-wrapper">
        <table>
          <tbody>
            <tr>
              <th width="110px">法人名</th>
              <td width="400px">
                <div if={ list_companies_suggest_search.length != 1 } class="div-wraper-autocompleter"><input class="suggest-input" type="text" id="comp_name_search"></div>
                <span if={ list_companies_suggest_search.length == 1 } class="comp_name_text">{ list_companies_suggest_search[0].comp_name }</span>
                <input if={ list_companies_suggest_search.length == 1 } id="comp_name_search" type="hidden" value="{ list_companies_suggest_search[0].comp_name }">
              </td>
              <th width="150px"></th>
              <td></td>
              <td>
              </td>
            </tr>
            <tr>
              <th width="110px">事業所名</th>
              <td width="400px">
                <div class="div-wraper-autocompleter"><input type="text" id="kyoten_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 style="background:#FFFFFF; color:#1C6BC0; border-radius:5px;" type="button" class="submit" id="EC81-add-Open" disabled="{checkEditData().data == '1' && checkEditData().del_flg == '1' ? true : false}">事業所を追加</button>
          </div>
        </div>
        <table class="blue-table">
          <thead>
            <tr>
              <th width="60px"></th>
              <th>法人名</th>
              <th>法人コード</th>
              <th>事業所名</th>
              <th>事業所コード</th>
              <th>管轄販売店名</th>
              <th>管轄販売店事業所名</th>
            </tr>
          </thead>
          <tbody>
            <tr each={company, index in companies}>
              <td rowspan={(company.sum && company.sum != 1) ? company.sum : false} if={!company.is_dup}><button class="EC81-edit-Open" index={index} disabled="{(checkEditData().data == '1' && checkEditData().del_flg == '1') || company.departments.kyoten_code == null ? true : false}">編集</button></td>
              <td rowspan={(company.sum && company.sum != 1) ? company.sum : false} if={!company.is_dup}>{company.companies.comp_name}</td>
              <td rowspan={(company.sum && company.sum != 1) ? company.sum : false} if={!company.is_dup}>{company.companies.comp_code}</td>
              <td rowspan={(company.sum && company.sum != 1) ? company.sum : false} if={!company.is_dup}>{company.departments.kyoten_name}</td>
              <td rowspan={(company.sum && company.sum != 1) ? company.sum : false} if={!company.is_dup}>{company.departments.kyoten_code}</td>
              <td>{company.dealer_comp_name}</td>
              <td>{company.dealer_dep_name}</td>
            </tr>
          </tbody>
        </table>
        <div id="paging" class="text-center">
          <ul class="pagination" id="pagination_ec81"></ul>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-wrapper">
    <!-- =========== Add Companies =========== -->
    <link rel="stylesheet" href="css/EC81-modal.css">
    <div class="o_modal" id="EC81-add">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="EC81-add-Close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title">事業所登録</h3>
            <div class="modal-form-box">
              <table>
                <tr>
                  <th>法人名</th>
                  <td>
                    <div if={ list_companies_suggest_search.length != 1 } class="div-wraper-autocompleter"><input type="text" id="add_comp_code" disabled="{checkEditData().data == '1' ? true : false}"></div>
                    <span if={ list_companies_suggest_search.length == 1 } class="comp_name_text">{ list_companies_suggest_search[0].comp_name }</span>
                    <input if={ list_companies_suggest_search.length == 1 } id="add_comp_code" type="hidden" value="{ list_companies_suggest_search[0].comp_name }">
                  </td>
                </tr>
                
                <tr>
                  <th>事業所コード</th>
                  <td>
                    <input type="text" id="add_customer_dep_code" value="{max_oem_co_cd}">
                  </td>
                </tr>
                <tr>
                  <th>事業所名</th>
                  <td>
                    <div class="div-wraper-autocompleter">
                      <input class="suggest-input" type="text" id="add_kyoten_name" readonly="{checkEditData().data == '1' ? true : false}">
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>事業所名略称</th>
                  <td><input type="text" id="add_kyoten_ryaku" readonly="{checkEditData().data == '1' ? true : false}"></td>
                </tr>
                <tr>
                  <th>カナ索引</th>
                  <td><input type="text" id="add_kyoten_kana" readonly="{checkEditData().data == '1' ? true : false}"></td>
                </tr>
                <tr if={ecUesrsInfo.kikan_code == '20000275'}>
                  <th>上位事業所コード</th>
                  <td><input type="text" id="add_up_kyoten_code" readonly="{checkEditData().data == '1' ? true : false}"></td>
                </tr>
                <tr>
                  <th>都道府県</th>
                  <td>
                    <select id="add_prefectures" disabled="{checkEditData().data == '1' ? true : false}">
                      <option each={item,index in prefectures} value="{item.code}" pref="{item.name}">{item.name}</option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>郵便番号</th>
                  <td><input type="text" id="add_post_code" readonly="{checkEditData().data == '1' ? true : false}"></td>
                </tr>
                <tr>
                  <th>所在地</th>
                  <td><input type="text" id="add_addr" readonly="{checkEditData().data == '1' ? true : false}"></td>
                </tr>
                <tr>
                  <th>電話番号</th>
                  <td><input type="text" id="add_tel" readonly="{checkEditData().data == '1' ? true : false}"></td>
                </tr>
                <tr>
                  <th>FAX番号</th>
                  <td><input type="text" id="add_fax" readonly="{checkEditData().data == '1' ? true : false}"></td>
                </tr>
                <tr>
                  <th>使用状況</th>
                  <td>
                    <select id="add_del_flg" readonly="true" class="disabled-input" disabled="disabled">
                      <option value="{item.value}" each={item,index in del_flg_list}>{item.name}</option>
                    </select>
                    <input type="hidden" id="add_status" value="1" />
                  </td>
                </tr>
              </table>
              <table id="suggestionTbl-add">
                <tr>
                  <th>管轄販売店名</th>
                  <th>管轄販売店事業所名</th>
                  <th><button style="background:#FFFFFF; color:#1C6BC0; border-radius:5px;" type="button" action="add" onclick={handleChangeDealer}>追加</button> </th>
                </tr>
              </table>
              <div class="btn-wrapper">
                <button type="reset" class="reset-btn" onclick={ clearInput }><i class="fa fa-refresh"></i>クリア</button>
                <button style="background:#2EB533; color:#FFFFFF; border-radius:5px;" type="button" class="submit" id="add_company_81">登録</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- =========== Edit Companies =========== -->
    <div class="o_modal" id="EC81-edit">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="EC81-edit-Close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title">事業所更新</h3>
            <div class="modal-form-box">
              <input type="hidden" id="kyoten_code_key" value="{element.departments.kyoten_code}">
              <input type="hidden" id="edit_comp_code" value="{element.companies.comp_code}">
              <table>
                <tr>
                  <th>法人名</th>
                  <td><input type="text" value="{element.companies.comp_code}: {element.companies.comp_name}" readonly="true" class="disabled-input"></td>
                </tr>
                <tr>
                  <th>事業所コード</th>
                  <td><input type="text" value="{element.departments.kyoten_code}" readonly="true" class="disabled-input"></td>
                </tr>
                <tr>
                  <th>事業所名</th>
                  <td><input type="text" id="edit_kyoten_name" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.kyoten_name}"></td>
                </tr>
                <tr>
                  <th>事業所名略称</th>
                  <td><input type="text" id="edit_kyoten_ryaku" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.kyoten_ryaku}"></td>
                </tr>
                <tr>
                  <th>カナ索引</th>
                  <td><input type="text" id="edit_kyoten_kana" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.kyoten_kana}"></td>
                </tr>
                <tr if={ecUesrsInfo.kikan_code == '20000275'}>
                  <th>上位事業所コード</th>
                  <td><input type="text" id="edit_up_kyoten_code" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.up_kyoten_code}"></td>
                </tr>
                <tr>
                  <th>都道府県</th>
                  <td>
                    <select id="edit_prefectures" disabled="{checkEditData().data == '1' ? true : false}">
                      <option each={item,index in prefectures} value="{item.code}" pref="{item.name}" selected="{element.departments.pref_code == item.code ? 'selected' : '' }">{item.name}</option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>郵便番号</th>
                  <td><input type="text" id="edit_post_code" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.post_code}"></td>
                </tr>
                <tr>
                  <th>所在地</th>
                  <td><input type="text" id="edit_addr" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.addr}"></td>
                </tr>
                <tr>
                  <th>電話番号</th>
                  <td><input type="text" id="edit_tel" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.tel}"></td>
                </tr>
                <tr>
                  <th>FAX番号</th>
                  <td><input type="text" id="edit_fax" readonly="{checkEditData().data == '1' ? true : false}" value="{element.departments.fax}"></td>
                </tr>
                <tr>
                  <th>使用状況</th>
                  <td>
                    <select id="edit_del_flg" disabled="{checkEditData().del_flg == '1' ? true : false}">
                      <option value="{item.value}" each={item,index in del_flg_list} selected="{element.departments.del_flg == item.value ? 'selected' : '' }">{item.name}</option>
                    </select>
                    <input type="hidden" id="edit_status" value="{status}" />
                  </td>
                </tr>
              </table>
              <table id="suggestionTbl-edit">
                <tr>
                  <th>管轄販売店名</th>
                  <th>管轄販売店事業所名</th>
                  <th><button style="background:#FFFFFF; color:#1C6BC0; border-radius:5px;" type="button" action="edit" onclick={handleChangeDealer}>追加</button></th>
                </tr>
              </table>
              <div class="btn-wrapper">
                <button type="reset" class="reset-btn" onclick={ resetInput }><i class="fa fa-refresh"></i>クリア</button>
                <button type="button" class="submit" id="edit_company_81">更新</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <table>
    <!--  clone add  -->
    <tr class="dealer_clone" style="display: none">
      <td>
        <div class="div-wraper-autocompleter">
          <input type="text" class="suggest-input dealer_co_cd_input" index="0" dealer_co_cd="" disabled="{checkEditData().data == '1' ? true : false}">
        </div>
      </td>
      <td>
        <div class="div-wraper-autocompleter">
          <input type="text" class="suggest-input dealer_dep_cd_input" index="0" dealer_dep_cd="" disabled="{checkEditData().data == '1' ? true : false}">
        </div>
      </td>
      <td>
        <button　style="background:#DC3545; color:#FFFFFF; border-radius:5px;" type="button" class="remove-dealer" index="0">削除</button>
      </td>
    </tr>
  </table>

  <script>
  this.ecUsersInfo =  JSON.parse(getItem('EcUserInfo'));
  this.companies = [];
  this.users_edit = '';
  this.max_oem_co_cd = '';
  this.total = 0;
  this.list_companies_suggest_search = [];
  this.list_departments_suggest_search = [];
  this.list_departments_suggest_dropdown = [];
  this.list_dealer_customers_suggest_dropdown = [];
  this.comp_code_search = '';
  this.kyoten_code_search = '';
  this.comp_code_suggest = '';
  this.dealer_comp_code_suggest = '';
  this.list_dealer_comp_code_suggest = [];
  this.list_dealer_dep_code_suggest = [];
  this.list_dealer_seq = [];
  this.list_dealer_network_id_to = [];
  this.list_dealer_seq_not_delete = [];
  this.element = {};
  this.comp_name; // companies name by user login
  this.check_user;
  this.status = '';
  this.sosiki_code_mt = '';
  this.enable_sosiki_code = 1;
  this.in_oem_code = '';
  this.price_rounding = [
    {
      name: '小数点切り捨て',
      value: ''
    },
    {
      name: '下１桁を0または5に切り捨て',
      value: 5  
    }
  ];
  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.customer_flg = '';

  $(function(){
    thisTag.search(page, 'firstQuery');
    $(".form-wrapper .reset-btn").on('click',function(){
      if (thisTag.list_companies_suggest_search.length != 1) {
        $("#comp_name_search").val("");
        thisTag.update({ comp_code_search: '' });
        $("#kyoten_name_search").autocompleter("destroy");
      } else if ($('#comp_name_search').val() && thisTag.comp_code_search) {
        thisTag.setListSuggestDepartments(thisTag.list_departments_suggest_search);
      }
      $("#kyoten_name_search").val("");
      thisTag.update({ kyoten_code_search: ''});
    });
    $("#submit_search").on('click',function(){
      thisTag.search(page);
    });

    $(document).on('change', '.dealer_co_cd_input', function(){
      if ($(this).val().trim() == '') {
        $(this).attr('dealer_co_cd', '');
        var index = $(this).attr('index');
        $('.dealer_dep_cd_input[index=' + index +']').autocompleter('destroy');
        $('.dealer_dep_cd_input[index=' + index +']').val('');
        $('.dealer_dep_cd_input[index=' + index +']').attr('dealer_dep_cd', '');
      }
    });

    $(document).on('change', '.dealer_dep_cd_input', function(){
      if ($(this).val().trim() == '') {
        $(this).attr('dealer_dep_cd', '');
      }
    });
    $(document).off('click', '#EC81-add-Open');
    $(document).on('click', '#EC81-add-Open', function(e){
      if (thisTag.list_companies_suggest_search.length != 1) {
        thisTag.update({
          list_dealer_customers_suggest_dropdown: ''
        })
      }

      if (!thisTag.enable_sosiki_code) {
        $('#add_customer_dep_code').prop('disabled', true);
      } else $('#add_customer_dep_code').prop('disabled', false);

      $('.dealer_attach').remove();
      thisTag.addDealer('add');
      $('#EC81-add').fadeIn();
    });
    $(document).on('click', '#EC81-add-Close', function(e){
      thisTag.clearInput();
      $('#EC81-add').fadeOut();
    });
    $(document).off('click', '.EC81-edit-Open');
    $(document).on('click','.EC81-edit-Open', function(e){
      var element = thisTag.companies[$(e.target).attr('index')];
      let list_comp = [];
      let list_dep = [];
      let list_dealer_seq = [];
      let list_dealer_network_id_to = [];
      list_comp.push(element.dealer_customers.dealer_co_cd);
      list_dep.push(element.dealer_customers.dealer_dep_cd);
      list_dealer_seq.push(element.dealer_customers.seq);
      list_dealer_network_id_to.push(element.dealer_customers.network_id_to);

      for(let i = parseInt($(e.target).attr('index')) + 1; i < thisTag.companies.length; i++) {
        if(thisTag.companies[i].is_dup == 1) {
          list_comp.push(thisTag.companies[i].dealer_customers.dealer_co_cd);
          list_dep.push(thisTag.companies[i].dealer_customers.dealer_dep_cd);
          list_dealer_seq.push(thisTag.companies[i].dealer_customers.seq);
          list_dealer_network_id_to.push(thisTag.companies[i].dealer_customers.network_id_to);
        }
        else {
          break;
        }
      }

      thisTag.update({
        element: element, 
        dealer_comp_code_suggest: element.dealer_customers.dealer_co_cd,
        comp_code_suggest: element.companies.comp_code,
        customer_flg: element.companies.customer_flg,
        list_dealer_comp_code_suggest: list_comp,
        list_dealer_dep_code_suggest: list_dep,
        list_dealer_seq: list_dealer_seq,
        list_dealer_network_id_to: list_dealer_network_id_to,
        status: element.departments.del_flg == 1 ? 0 : 1
      });
      $('#suggestionTbl-edit .dealer_attach').remove();
      // append dealer
      thisTag.showEditDealer();
      // get data suggest and apply
      thisTag.changeCompCode('edit');
      thisTag.changeDealerCompCode();
      $('#EC81-edit').fadeIn();
    });
    $(document).on('click', '#EC81-edit-Close', function(e){
      $("#edit_kyoten_name").val(thisTag.element.departments.kyoten_name);
      $("#edit_kyoten_ryaku").val(thisTag.element.departments.kyoten_ryaku);
      $("#edit_kyoten_kana").val(thisTag.element.departments.kyoten_kana);
      $("#edit_kyoten_eng").val(thisTag.element.departments.kyoten_eng);
      $("#edit_post_code").val(thisTag.element.departments.post_code);
      $("#edit_addr").val(thisTag.element.departments.addr);
      $("#edit_tel").val(thisTag.element.departments.tel);
      $("#edit_fax").val(thisTag.element.departments.fax);
      $("#edit_del_flg").val(thisTag.element.departments.del_flg);
      let status = thisTag.element.departments.del_flg == 1 ? 0 : 1;
      $("#edit_status").val(status);
      $("#edit_prefectures").val(thisTag.element.departments.pref_code);
      $('#EC81-edit').fadeOut();
    });
    $("#comp_name_search").change(function(e) {
      if($(e.target).val() == '') {
        thisTag.update({comp_code_search: ''});
      }
    });
    
    $("#kyoten_name_search").change(function(e) {
      if($(e.target).val() == '') {
        thisTag.update({kyoten_code_search: ''});
      }
    });
    // Clear Form
  });

  $(document).on('change', '#add_comp_code', function(e) {
    if($(e.target).val() == '') {
      thisTag.update({
        comp_code_suggest: '',
        customer_flg: '',
        list_dealer_customers_suggest_dropdown: '',
        list_departments_suggest_dropdown: ''
      });
      $(".dealer_attach").remove();
      thisTag.addDealer('add');
    }
  });

  $(document).on('change', '#edit_del_flg', function() {
    if($(this).val() == 1) {
      thisTag.update({status: 0});
    }
    else {
      thisTag.update({status: 1});
    }
  })
  // Add Companies
  $(document).off('click', '#add_company_81');
  $(document).on('click', '#add_company_81', function(e) {
    if(!thisTag.validate("add")) {
      return false;
    }
    thisTag.add();
  });
  // Edit Companies
  $(document).off('click', '#edit_company_81');
  $(document).on('click', '#edit_company_81', function(e) {
    if(!thisTag.validate("edit")) {
      return false;
    }
    thisTag.edit();
  });
  this.validate = function(id) {
    var err = [];
    var list_comp = thisTag.getList($('#suggestionTbl-' + id +' .dealer_co_cd_input'), 'attribute', 'dealer_co_cd');
    var list_dep = thisTag.getList($('#suggestionTbl-' + id +' .dealer_dep_cd_input'), 'attribute', 'dealer_dep_cd');
    var comp_code = $("#"+id+"_comp_code").val();
    var check = true;
    for(let i = 0; i < thisTag.list_companies_suggest_search.length; i++) {
      if (comp_code == thisTag.comp_code_suggest + ': ' +thisTag.list_companies_suggest_search[i].comp_name) {
        check = true;
        break;
      } else {
        check = false;
      }
    }

    if(id == 'add') {
      if(! check) {
        err.push('法人名はリストから選択してください。\n');
      }
      if($("#"+id+"_comp_code").val() == '') {
        err.push('法人名を選択してください。\n');
      }
      if($("#"+id+"_comp_code").val().indexOf("'") >= 0) {
        err.push("法人名に「'」は入力できません。\n")
      }
      if($("#"+id+"_customer_dep_code").val().length > 8) {
        err.push('事業所コードを8桁以内で入力してください。\n');
      }
      if($("#"+id+"_customer_dep_code").val().indexOf("'") >= 0) {
        err.push("事業所コードに「'」は入力できません。\n")
      }
      if($("#"+id+"_customer_dep_code").val() == '') {
        err.push('事業所コードは入力必須です。\n');
      }
      if($("#"+id+"_customer_dep_code").val() != '' && !thisTag.checkLatin($("#"+id+"_customer_dep_code").val())) {
        err.push('コードは半角英数を使用してください。\n');
      }
    }
    
    if($("#"+id+"_kyoten_name").val() == '') {
      err.push('事業所名は必須です。\n');
    }
    if($("#"+id+"_kyoten_name").val().length > 100) {
      err.push('事業所名を100文字以内に入力してください。\n');
    }
    if($("#"+id+"_kyoten_name").val().indexOf("'") >= 0) {
      err.push("事業所名に「'」は入力できません。\n");
    }
    if($("#"+id+"_kyoten_ryaku").val().length > 100) {
      err.push('事業所略称を100文字以内に入力してください。\n');
    }
    if($("#"+id+"_kyoten_ryaku").val().indexOf("'") >= 0) {
      err.push("事業所名略称に「'」は入力できません。\n");
    }
    if($("#"+id+"_kyoten_kana").val() == '') {
      err.push('カナ牽引は必須です。\n');
    }
    if($("#"+id+"_kyoten_kana").val().length > 100) {
      err.push('カナ索引を100文字以内に入力してください。\n');
    }
    if($("#"+id+"_kyoten_kana").val() != '' && !thisTag.checkKana($("#"+id+"_kyoten_kana").val())) {
      err.push('カナ索引をカタカナ文字で入力してください。\n');
    }
    if($("#"+id+"_kyoten_kana").val().indexOf("'") >= 0) {
      err.push("カナ牽引に「'」は入力できません。\n");
    }
    if($("#"+id+"_post_code").val().length > 15) {
      err.push('郵便番号を15文字以内に入力してください。\n');
    }
    if($("#"+id+"_post_code").val().indexOf("'") >= 0) {
      err.push("郵便番号に「'」は入力できません。\n");
    }
    if($("#"+id+"_addr").val().length > 100) {
      err.push('所在地を100文字以内に入力してください。\n');
    }
    if($("#"+id+"_addr").val().indexOf("'") >= 0) {
      err.push("所在地に「'」は入力できません。\n");
    }
    if($("#"+id+"_tel").val().length > 15) {
      err.push('電話番号を15文字以内に入力してください。\n');
    }
    if($("#"+id+"_tel").val() != '' && !thisTag.checkNumberHyphen($("#"+id+"_tel").val())) {
      err.push('電話番号を半角文字で入力してください。\n');
    }
    if($("#"+id+"_tel").val().indexOf("'") >= 0) {
      err.push("電話番号に「'」は入力できません。\n");
    }
    if($("#"+id+"_fax").val().length > 15) {
      err.push('FAX番号を15文字以内に入力してください。\n');
    }
    if($("#"+id+"_fax").val() != '' && !thisTag.checkNumberHyphen($("#"+id+"_fax").val())) {
      err.push('FAX番号を半角数字で入力してください。\n');
    }
    if($("#"+id+"_fax").val().indexOf("'") >= 0) {
      err.push("FAX番号に「'」は入力できません。\n");
    }
    if(thisTag.checkArrayEmpty(list_dep) && thisTag.checkArrayIsUnique(list_comp)) {
      err.push('管轄販売店が重複されています。\n');
    }
    else {
      if(thisTag.checkDuplicates(list_comp, list_dep) == 'empty') {
        err.push('管轄販売店が重複されています。\n');
      }
      if(thisTag.checkDuplicates(list_comp, list_dep) == 'duplicate') {
        err.push('管轄販売店事業所が重複されています。\n');
      }
    }
    if((thisTag.comp_code_suggest != thisTag.ecUsersInfo.kikan_code && thisTag.check_user) || (thisTag.check_user && !thisTag.in_oem_code)) {
      if($('#suggestionTbl-' + id +' .dealer_attach').length == 0) {
        err.push('管轄販売店名を選択してください。\n');
        err.push('管轄販売店事業所を選択してください。\n');
      }
      if(thisTag.checkArrayRequire(list_comp)) {
        err.push('管轄販売店名を選択してください。\n');
      }
      if(thisTag.checkArrayRequire(list_dep)) {
        err.push('管轄販売店事業所を選択してください。\n');
      }
    }
    for(let i=0; i<list_comp.length; i++) {
      if($("#dealer_co_cd_"+ id +"_" + i).val().indexOf("'") >= 0) {
        err.push("管轄販売店名に「'」は入力できません。\n");
      }
      if($("#dealer_dep_cd_"+ id +"_" + i).val().indexOf("'") >= 0) {
        err.push("管轄販売店事業所名に「'」は入力できません。\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.checkArrayIsUnique = function(array) {
    let hasDuplicate = array.some(function(val, i){
      return array.indexOf(val) !== i;
    });
    return hasDuplicate
  }
  this.checkDuplicates = function(list_co_code, list_dep_code) {
    let duplicates = {};
    for (var i = 0; i < list_co_code.length; i++) {
      if(duplicates.hasOwnProperty(list_co_code[i])) {
          duplicates[list_co_code[i]].push(list_dep_code[i]);
      } else if (list_co_code.lastIndexOf(list_co_code[i]) !== i) {
          duplicates[list_co_code[i]] = [list_dep_code[i]];
      }
    }
    for(let i = 0; i < list_co_code.length; i++) {
      if(list_co_code[i] != '') {
        if(duplicates.hasOwnProperty(list_co_code[i])) {
          if(thisTag.checkArrayIsUnique(duplicates[list_co_code[i]])) {
            if(thisTag.checkArrayEmpty(duplicates[list_co_code[i]])) {
              return 'empty';
            }
            return 'duplicate';
          }
        }
      }
    }
    return false;
  }
  this.checkArrayRequire = function(array) {
    if(array.includes('')) {
      return true;
    }
    return false;
  }
  this.checkArrayEmpty = function(array) {
    let check_empty = true;
    for (var i = 0; i < array.length; i++) {
      if(array[i] != '') {
        check_empty = false;
        break;
      }
    }
    return check_empty;
  }
  this.search = function(page, checkFirstQuery) {
      
    var query = [];
    
    var url = URL_API + '/api/ec81/departments/get';

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

    if (thisTag.comp_code_search) {
      query.push('comp_code=' + encodeURI(thisTag.comp_code_search));
    } 

    if (thisTag.kyoten_code_search) {
      query.push('kyoten_code=' + encodeURI(thisTag.kyoten_code_search));
    } 

    if($("#kyoten_name_search").val() != '' && $("#comp_name_search").val() == '') {
      alert("法人名を選択してください");
      return false;
    }

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

    url += '?' + query.join('&');
    $('#img-loader').show();

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

        var first_comp = res.companies[0];
        var count = 1;
        for(let i = 1; i < res.companies.length; i++) {
          if(first_comp.companies.comp_code == res.companies[i].companies.comp_code && first_comp.departments.kyoten_code == res.companies[i].departments.kyoten_code && first_comp.departments.kyoten_code != null) {
            count++;
            res.companies[i].is_dup = 1;
          }
          else {
            first_comp = res.companies[i];
            count = 1;
          }
          first_comp.sum = count;
        }

        thisTag.update({
          companies: res.companies,
          total: res.total,
          max_oem_co_cd: res.max_oem_co_cd,
          list_companies_suggest_search: res.companies_suggest,
          comp_name: res.comp_name,
          enable_sosiki_code: res.enable_sosiki_code,
          in_oem_code: res.in_oem_code,
          check_user: res.check_user
        });

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

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

        thisTag.getListSuggestCompanies(res.companies_suggest, checkFirstQuery);
        if (thisTag.list_companies_suggest_search.length != 1) {
          thisTag.update({
            list_dealer_customers_suggest_dropdown: ''
          })
        }
        thisTag.update({ list_departments_suggest_dropdown: ''});
      },
      error: function () {
          alert('error');
      }
    });
  }

  this.getListSuggestCompanies = function(list, checkFirstQuery) {
    let res_search = [];
    let res_add = [];
    if (list.length == 1) {
      thisTag.update({comp_code_search: thisTag.list_companies_suggest_search[0].comp_code});
      thisTag.update({comp_code_suggest: thisTag.list_companies_suggest_search[0].comp_code});
      thisTag.update({customer_flg: thisTag.list_companies_suggest_search[0].customer_flg});
      if (checkFirstQuery) {
        thisTag.getListSuggestDepartments();
        thisTag.changeCompCode('add');
      }
    } else {

      for (var i = 0; i < list.length; i++) {
        res_search.push({value: list[i].comp_name, label: list[i].comp_name, comp_index: i});
        res_add.push({value: list[i].comp_code + ': ' + list[i].comp_name, label: list[i].comp_code + ': ' + list[i].comp_name, comp_index: i});
      }
      $("#comp_name_search").autocompleter("destroy");
      $('#comp_name_search').autocompleter({
        limit:10000,
        highlightMatches:true,
        source: res_search,
        callback: function(value, index, object) {
          if($("#comp_name_search").val() != '' && thisTag.list_companies_suggest_search[object.comp_index].comp_code) {
            thisTag.update({comp_code_search: thisTag.list_companies_suggest_search[object.comp_index].comp_code});
            thisTag.getListSuggestDepartments();
          } else {
            thisTag.update({comp_code_search: ''});
          }
        }
      });

      $("#add_comp_code").autocompleter("destroy");
      $('#add_comp_code').autocompleter({
        limit:10000,
        highlightMatches:true,
        source: res_add,
        callback: function(value, index, object) {
          if($("#add_comp_code").val() != '' && thisTag.list_companies_suggest_search[object.comp_index].comp_code) {
            thisTag.update({comp_code_suggest: thisTag.list_companies_suggest_search[object.comp_index].comp_code});
            thisTag.update({customer_flg: thisTag.list_companies_suggest_search[object.comp_index].customer_flg});
            thisTag.changeCompCode('add');
          } else {
            thisTag.update({comp_code_search: ''});
          }
        }
      });

    }
  }

  this.setListSuggestDepartments = function(list) {
    if(!list) {
      return [];
    }
    let res = [];
    for (var i = 0; i < list.length; i++) {
      if(list[i].kyoten_code) {
        res.push({value: list[i].kyoten_name, label: list[i].kyoten_name, comp_index: i});
      }
    }

    $("#kyoten_name_search").autocompleter("destroy");
    $('#kyoten_name_search').autocompleter({ 
      limit:10000,
      highlightMatches:true, 
      source: res, 
      callback: function(value, index, object) {
        if($("#kyoten_name_search").val() != '' && thisTag.list_departments_suggest_search[object.comp_index].kyoten_code) {
          thisTag.update({kyoten_code_search: thisTag.list_departments_suggest_search[object.comp_index].kyoten_code});
        } else {
          thisTag.update({kyoten_code_search: ''});
        }
      }
    });
  }

  this.getListSuggestDepartments = function(e) {

    var query = [];
    var url = URL_API + '/api/ec81/departments/suggest';
    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);
    query.push('comp_code=' + thisTag.comp_code_search);

    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_departments_suggest_search: res.departments_suggest, kyoten_code_search: ''});
        thisTag.setListSuggestDepartments(res.departments_suggest);
        $("#kyoten_name_search").val('');
      },
      error: function () {
          alert('error');
      }
    });
  }

  this.changeCompCode = function(action) {
    var comp_code = thisTag.comp_code_suggest;
    var customer_flg = thisTag.customer_flg;
    var query = [];

    var url = URL_API + (thisTag.ecUsersInfo.kikan_code == COMP_CODE_SAGBRAIN ? '/api/ec81/companies/suggest' : '/api/ec81/dealer_customer/suggest_comp_code');

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    
    query.push('token=' + accessTokenCognito);
    query.push('comp_code=' + comp_code);
    if(thisTag.customer_flg != '' && thisTag.customer_flg != null) {
      query.push('customer_flg=' + customer_flg);
    }
    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_dealer_customers_suggest_dropdown: res.list,
          list_departments_suggest_dropdown: ''
        });
        if (action == 'edit') {
          $.each(thisTag.list_dealer_comp_code_suggest, function(index, val) {
            for ( let i = 0; i < thisTag.list_dealer_customers_suggest_dropdown.length; i++) {
              if (val == thisTag.list_dealer_customers_suggest_dropdown[i].dealer_co_cd) {
                $('#dealer_co_cd_edit_' + index).val(thisTag.list_dealer_customers_suggest_dropdown[i].dealer_customer_name);
                break;
              }
            }
            thisTag.suggestDealerComp(thisTag.list_dealer_customers_suggest_dropdown, 'dealer_co_cd_edit_' + index)
          })
        } else {
          $('#suggestionTbl-' + action +' .dealer_attach').remove();
          thisTag.addDealer(action);
        }
      },
      error: function (err) {
        alert('error');
      }
    });
  }

  this.changeDealerCompCode = function(index, action, input) {
    if(index === undefined) {
      index = null;
    }
    if(action === undefined) {
      action = 'edit';
    }
    var dealer_co_cd = thisTag.dealer_comp_code_suggest;
    var query = [];

    var url = URL_API + '/api/ec81/departments/suggest';

    var accessTokenCognito = localStorage.getItem('accessTokenCognito');
    query.push('get_dealers=' + SPECIFIED_DATA);
    query.push('token=' + accessTokenCognito);
    query.push('comp_code=' + dealer_co_cd);
    if(index == null) {
      var list_dealer_co_cd = thisTag.list_dealer_comp_code_suggest;
      query.push('list_dealer_co_cd=' + list_dealer_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;
        }
        if (index == null) {
          $.each(thisTag.list_dealer_dep_code_suggest, function(key, value) {
            if (res.departments_suggest[key]) {
              let department = res.departments_suggest[key];
              for ( let i = 0; i < department.length; i++) {
                if (value == department[i].kyoten_code) {
                  $('#dealer_dep_cd_edit_' + key).val(department[i].kyoten_name);
                  break;
                }
              }
              thisTag.getSuggestDealerDep(department, 'dealer_dep_cd_' + action + '_' + key);
            }
          });
        }
      },
      error: function (err) {
        alert('error');
      }
    });
  }
  // ================================== Add Companies ===================================
  this.add = function(e) {  
    var kyoten_name = $("#add_kyoten_name").val();
    var kyoten_ryaku = $("#add_kyoten_ryaku").val();
    var kyoten_kana = $("#add_kyoten_kana").val();
    var post_code = $("#add_post_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 pref_code = $("#add_prefectures option:selected").val();
    var pref = $("#add_prefectures option:selected").attr('pref');
    var kyoten_code = $("#add_customer_dep_code").val();
    var list_dealer_co_cd = thisTag.getList($('#suggestionTbl-add .dealer_co_cd_input'), 'attribute', 'dealer_co_cd');
    var list_dealer_dep_cd = thisTag.getList($('#suggestionTbl-add .dealer_dep_cd_input'), 'attribute', 'dealer_dep_cd');
    var list_dealer_customer_name = thisTag.getList($('#suggestionTbl-add .dealer_co_cd_input'), 'value');
    var status = $('#add_status').val();
    var data = {
      kyoten_name: kyoten_name,
      kyoten_ryaku: kyoten_ryaku,
      kyoten_kana: kyoten_kana,
      post_code: post_code,
      kyoten_code: kyoten_code ? kyoten_code : '',
      addr: addr,
      tel: tel,
      fax: fax,
      del_flg: del_flg,
      pref_code: pref_code ? pref_code : '', 
      pref: pref ? pref : '',
      list_dealer_customer_name: list_dealer_customer_name ? list_dealer_customer_name : '',
      list_dealer_co_cd: list_dealer_co_cd ? list_dealer_co_cd : '',
      list_dealer_dep_cd: list_dealer_dep_cd ? list_dealer_dep_cd : '',
      status: status
    };

    if(thisTag.comp_code_suggest) {
      data.comp_code = thisTag.comp_code_suggest;
    }

    if($("#add_up_comp_code").length) {
      data.up_kyoten_code = $("#add_up_kyoten_code").val();
    }

    var query = [];
    var url = URL_API + '/api/ec81/departments/create';
    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.http == 400) {
          switch(res.type) {
            case "duplicate_dealer_customer": 
              alert("事業所と管轄販売店事業所は入力済みです。変更してください。");
              break;
            case "duplicate_kyoten_code":
              alert("入力された事業所コードは既に存在しています。");
              break;
            default:
              break;
          }
          return false;
        }
        alert("追加しました。");
        thisTag.clearInput();
        $('#EC81-add').fadeOut();
        if (thisTag.list_companies_suggest_search.length == 1) {
          thisTag.getListSuggestDepartments();
        }
        $("#submit_search").trigger('click');
      },
      error: function (xhr, stt, error) {
        alert('error');
      }
    });
  }

  this.clearInput = function(e) {
    $("#add_kyoten_name").val('');
    $("#add_kyoten_ryaku").val('');
    $("#add_kyoten_kana").val('');
    $("#add_kyoten_eng").val('');
    $("#add_post_code").val('');
    $("#add_customer_dep_code").val(thisTag.max_oem_co_cd);
    $("#add_dealer_comp_code_0").prop("selectedIndex", 0);
    $("#add_dealer_dep_code_0").prop("selectedIndex", 0);
    $("#add_addr").val('');
    $("#add_tel").val('');
    $("#add_fax").val('');
    $("#add_del_flg").val('0');
    $("#add_status").val('1');
    $("#add_prefectures").val('');
    thisTag.update({
      dealer_comp_code_suggest: '',
      list_departments_suggest_dropdown: ''
    });
    if (thisTag.list_companies_suggest_search.length != 1) {
      $("#add_comp_code").val('');
      thisTag.update({
        comp_code_suggest: '',
        customer_flg: '',
        list_dealer_customers_suggest_dropdown: ''
      })
    }
    $(".dealer_attach").remove();
    thisTag.addDealer('add');
  }

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

    this.edit = function(e) { 
      var kyoten_code_key = $("#kyoten_code_key").val();
      var kyoten_name = $("#edit_kyoten_name").val();
      var kyoten_ryaku = $("#edit_kyoten_ryaku").val();
      var kyoten_kana = $("#edit_kyoten_kana").val();
      var post_code = $("#edit_post_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 pref_code = $("#edit_prefectures option:selected").val();
      var pref = $("#edit_prefectures option:selected").attr('pref');
      var list_dealer_co_cd = thisTag.getList($('#suggestionTbl-edit .dealer_co_cd_input'), 'attribute', 'dealer_co_cd');
      var list_dealer_dep_cd = thisTag.getList($('#suggestionTbl-edit .dealer_dep_cd_input'), 'attribute', 'dealer_dep_cd');
      var list_dealer_customer_name = thisTag.getList($('#suggestionTbl-edit .dealer_co_cd_input'), 'value');
      var list_dealer_seq = thisTag.list_dealer_seq;
      var list_dealer_seq_not_delete = thisTag.getList($('#suggestionTbl-edit .dealer_attach'), 'attribute', 'dealer-seq');
      var status = $('#edit_status').val();
      // var old_dearler_dep_cd = thisTag.element.dealer_customers.dealer_dep_cd;
      var customer_co_cd = $("#edit_comp_code").val();
      var customer_dep_cd = $("#kyoten_code_key").val();
      var list_dealer_network_id_to = thisTag.list_dealer_network_id_to;
      var data = {
        kyoten_code_key: kyoten_code_key,
        kyoten_name: kyoten_name,
        kyoten_ryaku: kyoten_ryaku,
        kyoten_kana: kyoten_kana,
        post_code: post_code,
        addr: addr,
        tel: tel,
        fax: fax,
        del_flg: del_flg,
        pref_code: pref_code ? pref_code : '', 
        pref: pref ? pref : '',
        // old_dearler_dep_cd: old_dearler_dep_cd ? old_dearler_dep_cd : '',
        customer_co_cd: customer_co_cd ? customer_co_cd : '',
        customer_dep_cd: customer_dep_cd ? customer_dep_cd : '',
        list_dealer_customer_name: list_dealer_customer_name ? list_dealer_customer_name : '',
        list_dealer_co_cd: list_dealer_co_cd ? list_dealer_co_cd : '',
        list_dealer_dep_cd: list_dealer_dep_cd ? list_dealer_dep_cd : '',
        list_dealer_seq: list_dealer_seq ? list_dealer_seq : '',
        list_dealer_seq_not_delete: list_dealer_seq_not_delete ? list_dealer_seq_not_delete : '',
        list_dealer_network_id_to: list_dealer_network_id_to ? list_dealer_network_id_to : '',
        status: status
      };

      if($("#edit_up_comp_code").length) {
        data.up_kyoten_code = $("#edit_up_kyoten_code").val();
      }

      var query = [];

      var url = URL_API + '/api/ec81/departments/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.http == 400) {
            switch(res.type) {
              case "duplicate_dealer_customer": 
                alert("事業所と管轄販売店事業所は入力済みです。変更してください。");
                break;
              default:
                break;
            }
            thisTag.clearInput();
            $('#EC81-edit').fadeOut();
            $("#submit_search").trigger('click');
            return false;
          }

          alert("編集完了しました。");
          $('#EC81-edit').fadeOut();
          if (thisTag.list_companies_suggest_search.length == 1) {
            thisTag.getListSuggestDepartments();
          }
          $("#submit_search").trigger('click');
        },
        error: function (err) {
          alert('error');
        }
      });
    }

    this.resetInput = function(e) {
        $("#edit_kyoten_name").val(thisTag.element.departments.kyoten_name);
        $("#edit_kyoten_ryaku").val(thisTag.element.departments.kyoten_ryaku);
        $("#edit_kyoten_kana").val(thisTag.element.departments.kyoten_kana);
        $("#edit_kyoten_eng").val(thisTag.element.departments.kyoten_eng);
        $("#edit_post_code").val(thisTag.element.departments.post_code);
        //$("#edit_dealer_comp_code").val(thisTag.element.dealer_customers.dealer_co_cd);
        //$("#edit_dealer_dep_code").val(thisTag.element.dealer_customers.dealer_dep_cd);
        $("#edit_addr").val(thisTag.element.departments.addr);
        $("#edit_tel").val(thisTag.element.departments.tel);
        $("#edit_fax").val(thisTag.element.departments.fax);
        $("#edit_del_flg").val(thisTag.element.departments.del_flg);
        let status = thisTag.element.departments.del_flg == 1 ? 0 : 1;
        $("#edit_status").val(status);
        $("#edit_prefectures").val(thisTag.element.departments.pref_code);
        thisTag.update({
          comp_code_suggest: thisTag.element.dealer_customers.customer_co_cd, 
          dealer_comp_code_suggest: thisTag.element.dealer_customers.dealer_co_cd
        }); 
      $('#suggestionTbl-edit .dealer_attach').remove();
        // append dealer
        thisTag.showEditDealer();
        // get data suggest and apply
        thisTag.changeCompCode('edit');
        thisTag.changeDealerCompCode();
    }

    this.checkEditData = function() {
      // 0 = hidden
      // 1 = disabled
      // 2 = enabled
      let ecUsersInfo = thisTag.ecUsersInfo;
      let edit_deparment_data = 0;
      let edit_deparment_del_flg = 0;
      if(ecUsersInfo.member_type == 1 || ecUsersInfo.member_type == 2) {
        if(ecUsersInfo.yobi1 == 1) {
          edit_deparment_data = 2;
          edit_deparment_del_flg = 2;
        } else if(ecUsersInfo.member_authority == 9) {
          edit_deparment_data = 1;
          edit_deparment_del_flg = 1;
        }
      } else if(ecUsersInfo.member_type == 3 || ecUsersInfo.member_type == 4) {
        if(ecUsersInfo.yobi1 == 1) {
          edit_deparment_data = 1;
          edit_deparment_del_flg = 2;
        } else if(ecUsersInfo.member_authority == 9) {
          edit_deparment_data = 1;
          edit_deparment_del_flg = 1;
        } 
      } else if(ecUsersInfo.member_type === 0 || ecUsersInfo.member_type === '0') {
        edit_deparment_data = 2;
        edit_deparment_del_flg = 2;
      }
      
      edit_deparment_data = 2;
      edit_deparment_del_flg = 2;
      return {data: edit_deparment_data, del_flg: edit_deparment_del_flg};
    }

    this.getGroupIndex = function(suggestion) {
      let index = suggestion.slice(-1).attr('index');
      return index ? parseInt(index) : 0;
    }

    this.handleChangeDealer = function(e) {
      let action = $(e.target).attr('action');
      thisTag.addDealer(action);
    }

    this.showEditDealer = function() {
      $.each(thisTag.list_dealer_comp_code_suggest, function(index, value) {
        thisTag.showDealerOriginal('edit', index);
      })
    }

    this.showDealerOriginal = function(action, index) {

      var dealer_co_cd = thisTag.list_dealer_comp_code_suggest[index];
      var dealer_dep_cd = thisTag.list_dealer_dep_code_suggest[index];
      // get html to change
      let new_dealer = $('.dealer_clone').clone();
      let btn_delete = new_dealer.find('.remove-dealer');
      let dealer_co_cd_input = new_dealer.find('.dealer_co_cd_input');
      let dealer_dep_cd_input = new_dealer.find('.dealer_dep_cd_input');
      let count_groups = $('#suggestionTbl-' + action +' .dealer_attach').length + 1;
      // if(count_groups > 5) {
      //   return false;
      // }
      let next_index;
      if (count_groups == 1) {
        next_index = '0';
      } else next_index = parseInt($('#suggestionTbl-' + action +' .dealer_attach:last').attr('index')) + 1;

      //  change html
      new_dealer.attr({
        'class': 'dealer_attach',
        'dealer-seq': thisTag.list_dealer_seq[index],
        'index': next_index
      });
      new_dealer.show();
      btn_delete.attr('index', next_index);
      dealer_co_cd_input.attr({
        'id': 'dealer_co_cd_' + action + '_' + next_index,
        'index': next_index,
        'dealer_co_cd': dealer_co_cd
      });
      dealer_dep_cd_input.attr({
        'id': 'dealer_dep_cd_' + action + '_' + next_index,
        'index': next_index,
        'dealer_dep_cd': dealer_dep_cd
      });
      dealer_dep_cd_input.val();

      $('#suggestionTbl-edit').append(new_dealer);
    }

    this.addDealer = function (action, index) {
      let next_index = '0';
      // get html to change
      let new_dealer = $('.dealer_clone').clone();
      let btn_delete = new_dealer.find('.remove-dealer');
      let dealer_co_cd_input = new_dealer.find('.dealer_co_cd_input');
      let dealer_dep_cd_input = new_dealer.find('.dealer_dep_cd_input');
      let count_groups = $('#suggestionTbl-' + action +' .dealer_attach').length + 1;
      // if(count_groups > 5) {
      //   return false;
      // }
      if (count_groups == 1) {
        next_index = '0';
      } else next_index = parseInt($('#suggestionTbl-' + action +' .dealer_attach:last').attr('index')) + 1;

      //  change html
      new_dealer.attr({
        'class': 'dealer_attach',
        'index': next_index
      });
      new_dealer.show();
      btn_delete.attr('index', next_index);
      dealer_co_cd_input.attr({
        'id': 'dealer_co_cd_' + action + '_' + next_index,
        'index': next_index
      });
      dealer_dep_cd_input.attr({
        'id': 'dealer_dep_cd_' + action + '_' + next_index,
        'index': next_index
      });

      //  append html
      $('#suggestionTbl-' + action).append(new_dealer);

      //  add autocomplete for dealer_co_cd_input
      thisTag.suggestDealerComp(thisTag.list_dealer_customers_suggest_dropdown, 'dealer_co_cd_' + action + '_' + next_index);
    }

    this.getList = function(list_suggest, type, attribute) {
      let list = [];
      if(attribute === undefined) {
        attribute = null;
      }
      $.each(list_suggest, function(i, val) {
        switch(type) {
          case 'value':
            list.push($(this).val());
            break;
          case 'text':
            if($(this).val() == '') {
              list.push('');
            }
            else {
              list.push($(this).children("option:selected").text());
            }
            break;
          case 'attribute':
            if ($(this).attr(attribute) == undefined) {
              list.push("");
            } else list.push($(this).attr(attribute));
            break;
          default:
            break;
        }
      })
      return list;
    }

    $(document).on('click','.remove-dealer' , function(e) {
      $(this).parents('tr').remove();
    })

   // get data and suggest for dealer
    this.suggestDealerComp = function (list, id) {
      if (list.length == 1) {
        $('#' + id).attr('id', id + '_remove');
        $('#' + id + '_remove').after("<span id='" + id + "'>"+ list[0].dealer_customer_name +"</span>");
        $('#' + id).attr('dealer_co_cd', list[0].dealer_co_cd);
        $('#' + id).attr('index', $('#' + id + '_remove').attr('index'));
        $('#' + id).attr('class', 'suggest-input');
        $('#' + id).addClass('dealer_co_cd_input');
        thisTag.suggestDealerDep($('#' + id),'add');
        $('#' + id + '_remove').remove();
        return false;
      }
      var res_search = [];
      for (var i = 0; i < list.length; i++) {
        res_search.push({value: list[i].dealer_customer_name, label: list[i].dealer_customer_name, comp_index: i});
      }
      $("#" + id).autocompleter("destroy");
      $("#" + id).autocompleter({
        limit:10000,
        highlightMatches:true,
        source: res_search,
        callback: function(value, index, object) {
          if($(this).prev('.suggest-input').val() != '' && list[object.comp_index].dealer_co_cd) {
            $(this).prev('.suggest-input').attr('dealer_co_cd', list[object.comp_index].dealer_co_cd);
            thisTag.suggestDealerDep($(this).prev('.suggest-input'),'add');
          } else {
            $(this).prev('.suggest-input').attr('dealer_co_cd', '');
            thisTag.suggestDealerDep($(this), 'destroy');
          }
        }
      });
    }

    this.suggestDealerDep = function (input, action) {

      var index = input.attr('index');
      var tr = input.parents('.dealer_attach');
      var id_department = tr.find('.dealer_dep_cd_input').attr('id');

      if (action == 'destroy') {
        tr.find('.dealer_dep_cd_input').autocompleter("destroy");
        tr.find('.dealer_dep_cd_input').val("");
        return false
      } else {
        var dealer_co_cd = input.attr('dealer_co_cd');
        var query = [];
        var url = URL_API + '/api/ec81/departments/suggest';
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');

        query.push('token=' + accessTokenCognito);
        query.push('get_dealers=' + SPECIFIED_DATA);
        query.push('comp_code=' + dealer_co_cd);
        if(index == null) {
          var list_dealer_co_cd = thisTag.list_dealer_comp_code_suggest;
          query.push('list_dealer_co_cd=' + list_dealer_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;
            }
            thisTag.getSuggestDealerDep(res.departments_suggest, id_department);
          },
          error: function (err) {
            alert('error');
          }
        });
     
      }
      
    }

  this.getSuggestDealerDep = function (list, id) {
    if (list.length == 1) {
      $('#' + id).attr('id', id + '_remove');
      $('#' + id + '_remove').after("<span id='" + id + "'>"+ list[0].kyoten_name +"</span>");
      $('#' + id).attr('dealer_dep_cd', list[0].kyoten_code);
      $('#' + id).attr('index', $('#' + id + '_remove').attr('index'));
      $('#' + id).attr('class', 'suggest-input');
      $('#' + id).addClass('dealer_dep_cd_input');
      $('#' + id + '_remove').remove();
      return false;
    } else if ( $('#' + id).is('span') ) {
      let new_dealer = $('.dealer_clone').clone();
      let dealer_dep_cd_input = new_dealer.find('.dealer_dep_cd_input');
      let index = $('#' + id).attr('index')
      dealer_dep_cd_input.attr({
        'id': id,
        'index': index
      });
      $('#' + id).replaceWith(dealer_dep_cd_input);
    }
    var res_search = [];
    for (var i = 0; i < list.length; i++) {
      res_search.push({value: list[i].kyoten_name, label: list[i].kyoten_name, comp_index: i});
    }
    $("#" + id).autocompleter("destroy");
    $("#" + id).autocompleter({
      limit:10000,
      highlightMatches:true,
      source: res_search,
      callback: function (value, index, object) {
        if ($(this).prev('.suggest-input').val() != '' && list[object.comp_index].kyoten_code) {
          $(this).prev('.suggest-input').attr('dealer_dep_cd', list[object.comp_index].kyoten_code);
        } else {
          $(this).prev('.suggest-input').attr('dealer_dep_cd', list[object.comp_index].kyoten_code);
        }
      }
    });
  }

  </script>
</EC81>