<EC80>
  <link rel="stylesheet" href="css/EC80.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 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="EC80-add-Open">法人を追加</button>
          </div>
        </div>
        <table class="blue-table">
          <thead>
            <tr>
              <th width="60px"></th>
              <th>法人名</th>
              <th>法人コード</th>
              <th>法人形態</th>
              <th>都道府県</th>
              <th>管轄販売店名</th>
            </tr>
          </thead>
          <tbody>
            <tr each={company, index in companies_list}>
                <td if={company.first_item} rowspan="{company.dealer_list_count}"><button class="EC80-edit-Open" index={company.company_index}>編集</button></td>
                <td if={company.first_item} rowspan="{company.dealer_list_count}">{company.comp_name}</td>
                <td if={company.first_item} rowspan="{company.dealer_list_count}">{company.comp_code}</td>
                <td if={company.first_item} rowspan="{company.dealer_list_count}">
                  {company.supplier_flg == 1 ? 'サプライヤ' : ''}
                  {company.dealer_flg == 1 ? '販売店' : ''}
                  {company.customer_flg == 1 ? 'エンドユーザー' : ''}
                </td>
                <td if={company.first_item} rowspan="{company.dealer_list_count}">{company.pref}</td>
                <td>{company.dealer_comp_name}</td>
    
            </tr>
          </tbody>
        </table>
        <div id="paging" class="text-center">
          <ul class="pagination" id="pagination_ec80"></ul>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-wrapper">
    <!-- =========== Add Companies =========== -->
    <link rel="stylesheet" href="css/EC80-modal.css?v=1">
    <div class="o_modal" id="EC80-add">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="EC80-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>
                    <select id="add_flg">
                      <option value="customer_flg">エンドユーザー</option>
                      <option value="dealer_flg" if={ecUsersInfo.kikan_code == '20000275'}>販売店</option>
                      <option value="supplier_flg" if={ecUsersInfo.kikan_code == '20000275'}>サプライヤ</option>
                    </select>
                  </td>
                </tr>
                <tr>
                <tr>
                  <th>法人コード</th>
                  <td><input type="text" id="add_new_comp_code" value="{max_oem_co_cd}" onchange="{checkCompCode}"></td>
                </tr>
                <tr if={ecUsersInfo.kikan_code == '20000275'}>
                  <th>上位法人コード</th>
                  <td><input type="text" id="add_up_comp_code"></td>
                </tr>
                <tr>
                  <th>法人名</th>
                  <td><input type="text" id="add_comp_name" autocomplete="off"></td>
                </tr>
                <tr>
                  <th>法人名略称</th>
                  <td><input type="text" id="add_comp_ryaku"></td>
                </tr>
                <tr>
                  <th>カナ索引</th>
                  <td><input type="text" id="add_comp_kana"></td>
                </tr>
                <tr>
                  <th>法人名英語表記</th>
                  <td><input type="text" id="add_comp_eng"></td>
                </tr>
                <tr>
                  <th>郵便番号</th>
                  <td><input type="text" id="add_post_code"></td>
                </tr>
                <tr>
                  <th>都道府県</th>
                  <td>
                    <select id="add_prefectures">
                      <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_addr"></td>
                </tr>
                <tr>
                  <th>電話番号</th>
                  <td><input type="text" id="add_tel"></td>
                </tr>
                <tr>
                  <th>FAX番号</th>
                  <td><input type="text" id="add_fax"></td>
                </tr>
                <tr>
                  <th>使用状況</th>
                  <td>
                    <select id="add_del_flg">
                      <option value="{item.value}" each={item,index in del_flg_list}>{item.name}</option>
                    </select>
                  </td>
                </tr>
                <!-- <tr>
                  <th>販売価格端数処理</th>
                  <td>
                    <select id="add_price_rounding">
                      <option value="{item.value}" each={item,index in price_rounding}>{item.name}</option>
                    </select>
                  </td>
                </tr> -->
              </table>

              <br>
              <table class="blue-table" id="addDealerTbl">
                <thead>
                  <tr>
                    <th>管轄販売店名</th>
                    <th>販売価格端数処理</th>
                    <th if={ecUsersInfo.kikan_code == '20000275'}>
                      <button type="button" action="add" class="addDealer" onclick={addDealer}>追加</button>
                    </th>
                  </tr>
                </thead>
                <tbody class="addDealerBodyTable">
                  <tr class="dealer-item-add" class="" index="0">
                    <td>
                      <input type="text" class="add_old_comp_code" value="{comp_name}" comp_code="{ecUsersInfo.kikan_code}" if={condition} readonly="true">
                      <div style="" class="div-wraper-autocompleter text-left"  if={ecUsersInfo.kikan_code == '20000275'}>
                        <input type="text" id="add_old_comp_code_0" class="add_old_comp_code" comp_code="" tel="" fax="">
                      </div>
                      <input type="hidden" class="comp_code_">
                    </td>
                    <td>
                      <select id="add_price_rounding_0" class="add_price_rounding">
                        <option value="{item.value}" each={item,index in price_rounding}>{item.name}</option>
                      </select>
                    </td>
                    <td if={ecUsersInfo.kikan_code == '20000275'}>
                      <button type="button" class="delete-dealer-add" index="0">削除</button>
                    </td>
                  </tr>
                </tbody>
              </table>
              <div class="btn-wrapper">
                <button type="reset" class="reset-btn"><i class="fa fa-refresh"></i>クリア</button>
                <button type="button" class="submit" id="add_company_80">登録</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- =========== Edit Companies =========== -->
    <div class="o_modal" id="EC80-edit">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="EC80-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="comp_code_key" value="{element.comp_code}">
              <table>
                <tr>
                  <th>法人形態選択</th>
                  <td>
                    <select id="edit_flg" disabled="disabled">
                      <option value="customer_flg" selected="{element.customer_flg == 1 ? 'selected' : ''}">エンドユーザー</option>
                      <option value="dealer_flg" selected="{element.dealer_flg == 1 ? 'selected' : ''}">販売店</option>
                      <option value="supplier_flg" if={ecUsersInfo.kikan_code == '20000275'} selected="{element.supplier_flg == 1 ? 'selected' : ''}">サプライヤ</option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>法人コード</th>
                  <td><input type="text" value="{element.comp_code}" readonly="true" class="disabled-input"></td>
                </tr>
                <tr if={ecUsersInfo.kikan_code == '20000275'}>
                  <th>上位法人コード</th>
                  <td><input type="text" id="edit_up_comp_code" value="{element.up_comp_code}"></td>
                </tr>
                <tr>
                  <th>法人名</th>
                  <td><input type="text" id="edit_comp_name" value="{element.comp_name}"></td>
                </tr>
                <tr>
                  <th>法人名略称</th>
                  <td><input type="text" id="edit_comp_ryaku" value="{element.comp_ryaku}"></td>
                </tr>
                <tr>
                  <th>カナ索引</th>
                  <td><input type="text" id="edit_comp_kana" value="{element.comp_kana}"></td>
                </tr>
                <tr>
                  <th>法人名英語表記</th>
                  <td><input type="text" id="edit_comp_eng" value="{element.comp_eng}"></td>
                </tr>
                <tr>
                  <th>郵便番号</th>
                  <td><input type="text" id="edit_post_code" value="{element.post_code}"></td>
                </tr>
                <tr>
                  <th>都道府県</th>
                  <td>
                    <select id="edit_prefectures">
                      <option each={item,index in prefectures} value="{item.code}" pref="{item.name}" selected="{element.pref_code == item.code ? 'selected' : '' }">{item.name}</option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>所在地</th>
                  <td><input type="text" id="edit_addr" value="{element.addr}"></td>
                </tr>
                <tr>
                  <th>電話番号</th>
                  <td><input type="text" id="edit_tel" value="{element.tel}"></td>
                </tr>
                <tr>
                  <th>FAX番号</th>
                  <td><input type="text" id="edit_fax" value="{element.fax}"></td>
                </tr>
                <tr>
                  <th>使用状況</th>
                  <td>
                    <select id="edit_del_flg">
                      <option value="{item.value}" each={item,index in del_flg_list} selected="{element.del_flg == item.value ? 'selected' : '' }">{item.name}</option>
                    </select>
                  </td>
                </tr>
              </table>
              <br>
              <table class="blue-table" id="editDealerTbl" if="{element.customer_flg == 1}">
                <thead>
                  <tr>
                    <th>管轄販売店名</th>
                    <th>販売価格端数処理</th>
                    <th if={ecUsersInfo.kikan_code == '20000275'}>
                      <button type="button" action="edit" class="addDealer" onclick={addDealer}>追加</button>
                    </th>
                  </tr>
                </thead>
                <tbody class="editDealerBodyTable">
                  <tr class="dealer-item-edit" class="" index="0" if={element.dealer_list_count == 0}>
                    <td>
                      <input type="text" class="edit_old_comp_code" value="{comp_name}" comp_code="{ecUsersInfo.kikan_code}" if={condition} readonly="true">
                      <div style="" class="div-wraper-autocompleter text-left"  if={ecUsersInfo.kikan_code == '20000275'}>
                        <input type="text" id="edit_old_comp_code_0" class="edit_old_comp_code" comp_code="" tel="" fax="">
                      </div>
                      <input type="hidden" class="comp_code_">
                    </td>
                    <td>
                      <select id="edit_price_rounding_0" class="edit_price_rounding">
                        <option value="{item.value}" each={item,index in price_rounding}>{item.name}</option>
                      </select>
                    </td>
                    <td if={ecUsersInfo.kikan_code == '20000275'}>
                      <button type="button" class="delete-dealer-edit" index="0">削除</button>
                    </td>
                   </tr>
                </tbody>
              </table>
              <div class="btn-wrapper">
                <button type="reset" class="reset-btn"><i class="fa fa-refresh"></i>クリア</button>
                <button type="button" class="submit" id="edit_company_80">更新</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>
    <table id="hiddenEditDealerBodyTable" style="display: none">
      <tr each="{dealer_item, index_dealer in element.dealer_list}" class="hidden_dealer-item-edit" index="{index_dealer}">
        <td>
          <input type="hidden" class="dealer_seq" id="hidden_dealer_seq_{index_dealer}" value="{dealer_item.seq}">
          <!-- <input type="text" class="hidden_edit_old_comp_code" value="{comp_name}" comp_code="{ecUsersInfo.kikan_code}" if={condition} readonly="true"> -->
          <!-- <div style="" class="div-wraper-autocompleter text-left" if={ecUsersInfo.kikan_code == '20000275'}> -->
          <div style="" class="div-wraper-autocompleter text-left">
            <input type="text" id="hidden_edit_old_comp_code_{index_dealer}" value="{dealer_item.dealer_comp_name}" class="hidden_edit_old_comp_code" comp_code="{dealer_item.dealer_co_cd}" tel="" fax="" disabled="disabled">
          </div>
        </td>
        <td>
          <select id="hidden_edit_price_rounding_{index_dealer}" class="hidden_edit_price_rounding">
            <option if={element.customer_flg != 1} value="">小数点切り捨て</option>
            <option if={element.customer_flg == 1}  value="{item.value}" each={item,index in price_rounding} selected="{dealer_item.price_rounding == item.value ? 'selected' : '' }">{item.name}</option>
          </select>
        </td>
        <td if={ecUsersInfo.kikan_code == '20000275'}>
          <button type="button" class="delete-dealer-edit" index={index_dealer}>削除</button>
        </td>
      </tr>
    </table>
  </div>
  <script>
  this.ecUsersInfo =  JSON.parse(getItem('EcUserInfo'));
  this.companies = [];
  this.companies_list = [];
  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桁を0に切り捨て',
      value: 2
    },
    {
      name: '下１桁を四捨五入',
      value: 3
    },
    {
      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 = {};

  $(function(){
    thisTag.searchCompanies(page);
    $(document).on('click', '.delete-dealer-add', function(e){
      let index = $(this).attr('index');
      thisTag.deleteItem($(this), index, 'class', 'dealer-item-add');
    });
    $(document).on('click', '.delete-dealer-edit', function(e){
      let index = $(this).attr('index');
      thisTag.deleteItem($(this), index, 'class', 'dealer-item-edit');
    });
    
    $(document).on('change', '.add_old_comp_code', function(e){
      let comp_name = $(this).val();
      if (comp_name == '') {
        $(this).attr('comp_code', '');
        $(this).attr('tel', '');
        $(this).attr('fax', '');
      } else {
        thisTag.deleteInputValue($(this), comp_name);
      }
    });

    $(document).on('change', '.edit_old_comp_code', function(e){
      let comp_name = $(this).val();
      if (comp_name == '') {
        $(this).attr('comp_code', '');
        $(this).attr('tel', '');
        $(this).attr('fax', '');
      } else {
        thisTag.deleteInputValue($(this), comp_name);
      }
    });

    $(".reset-btn").on('click',function(){
      $("#comp_name_search").val("");
      thisTag.update({
        comp_code_search: ''
      });
    });
    $("#submit_search").on('click',function(){
      thisTag.searchCompanies(page);
    });
    $(document).on('click', '#EC80-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);
      $('#EC80-add').fadeIn();
    });
    $(document).on('click', '#EC80-add-Close', function(e){
      $('#EC80-add').fadeOut();
      $("#add_new_comp_code").val(thisTag.max_oem_co_cd);
    });
    $(document).on('click','.EC80-edit-Open', function(e){
      thisTag.update({element: thisTag.companies[$(e.target).attr('index')]});
      thisTag.reappendDealer(thisTag.element);
      let dealer_list_count = thisTag.element.dealer_list_count;
      if (dealer_list_count > 0) {
        for (var i = 0; i < dealer_list_count; i++) {
          thisTag.addAutoCompleteDealer('edit_old_comp_code_' + i, []);
        }
      $('.edit_old_comp_code:not(:disabled,:first)').parents('tr').remove();
      } else {
        $('.edit_old_comp_code:not(:disabled)').parents('tr:first').val('');
        $('.edit_old_comp_code:not(:disabled)').parents('tr:first').attr('comp_code', '');
        $('.edit_old_comp_code:not(:disabled)').parents('tr:first').find('.edit_price_rounding').prop("selectedIndex", 0);
        let firstId = $('.edit_old_comp_code:first').attr('id');
        thisTag.addAutoCompleteDealer(firstId,[]);
      }
      $('#EC80-edit').fadeIn();
    });
    $(document).on('click', '#EC80-edit-Close', function(e){
      $('#EC80-edit').fadeOut();
    });
    $(document).on('change', '#add_flg', function(e) {
      let add_flg = $("#add_flg option:selected").val();
      if(add_flg != 'customer_flg') {
        $('#addDealerTbl').hide();
        $('.dealer-item-add:not(:first)').remove();
        $(".add_price_rounding option:first").attr('selected','selected');
      } else {
        if (thisTag.ecUsersInfo.kikan_code != '20000275') {
          $('.add_old_comp_code:first').val(this.comp_name);
        } else {
          $('.add_old_comp_code:first').val('');
        }
        $('#addDealerTbl').show();
        $('.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桁を0に切り捨て',
              value: 2
            },
            {
              name: '下１桁を四捨五入',
              value: 3
            },
            {
              name: '下１桁を0または5に切り捨て',
              value: 5
            }
          ]
        });
      }
    });

    // 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桁を0に切り捨て',
              value: 2
            },
            {
              name: '下１桁を四捨五入',
              value: 3
            },
            {
              name: '下１桁を0または5に切り捨て',
              value: 5
            }
          ]
        });
      }
    });
  });
  
  $(document).on('click', '#EC80-add .reset-btn', function(e) {
    thisTag.clearInput();
  });
  $(document).on('click', '#EC80-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+"_new_comp_code").val() == '') {
      err.push('法人コードは入力必須です。\n');
    }
    if($("#"+id+"_new_comp_code").val() != '' && (!thisTag.checkLatin($("#"+id+"_new_comp_code").val()) || ($("#"+id+"_new_comp_code").val() != undefined && $("#"+id+"_new_comp_code").val().length > 8))) {
      err.push('コードは8文字以内で半角英数字を使用してください。\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 ($("#"+id+"_flg").val() == 'customer_flg') {
      let valuesAlreadySeen = [];
      $("."+id+"_old_comp_code").each(function() {
        if ($(this).val() == '' || $('.dealer-item-' + id +':first').css('display') == 'none') {
          err.push('管轄販売店名を選択してください。\n');
          return false;
        } else {
          let value = $(this).attr('comp_code');
          if (valuesAlreadySeen.indexOf(value) !== -1) {
            err.push('管轄販売店が重複されています。\n');
            return false;
          }
          valuesAlreadySeen.push(value);
        }
          
      });
      
    }

    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.searchCompanies = function(page) {
      
    var query = [];
    
    var url = URL_API + '/api/ec80/companies/get_all_companies';

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

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

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

        let companies_list_res = res.companies;
        let companies = [];
        for (var i = 0; i < companies_list_res.length; i++) {
          if (companies_list_res[i].dealer_list_count >= 1) {
            for (var j = 0; j < companies_list_res[i].dealer_list_count; j++) {
              if (j == 0) {
                companies.push({
                  comp_code: companies_list_res[i].comp_code,
                  comp_name: companies_list_res[i].comp_name,
                  customer_flg: companies_list_res[i].customer_flg,
                  dealer_flg: companies_list_res[i].dealer_flg,
                  supplier_flg: companies_list_res[i].supplier_flg,
                  pref: companies_list_res[i].pref,
                  dealer_comp_name: companies_list_res[i].dealer_list[j].dealer_comp_name,
                  dealer_list_count: companies_list_res[i].dealer_list_count,
                  first_item: true,
                  company_index: i,
                });
              } else {
                companies.push({
                  comp_code: companies_list_res[i].comp_code,
                  comp_name: companies_list_res[i].comp_name,
                  customer_flg: companies_list_res[i].customer_flg,
                  dealer_flg: companies_list_res[i].dealer_flg,
                  supplier_flg: companies_list_res[i].supplier_flg,
                  pref: companies_list_res[i].pref,
                  dealer_comp_name: companies_list_res[i].dealer_list[j].dealer_comp_name,

                });
              }
            }
          } else {
            companies.push({
                comp_code: companies_list_res[i].comp_code,
                comp_name: companies_list_res[i].comp_name,
                customer_flg: companies_list_res[i].customer_flg,
                dealer_flg: companies_list_res[i].dealer_flg,
                supplier_flg: companies_list_res[i].supplier_flg,
                pref: companies_list_res[i].pref,
                first_item: true,
                company_index: i,
              });
          }
        }

        thisTag.update({
          companies_list: companies,
          companies: res.companies,
          total: res.total,
          max_oem_co_cd: res.max_oem_co_cd,
          condition: res.condition,
          list_companies_suggest_search: res.companies_all,
          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_ec80');
        $pagination.twbsPagination('destroy');
        $pagination.twbsPagination({
          totalPages: totalPages,
          visiblePages: visiblePages,
          startPage: page,
          initiateStartPageClick: false,
          onPageClick: function (event, page) {
            thisTag.searchCompanies(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.companies_all);
        if(thisTag.ecUsersInfo.kikan_code == '20000275') {
          thisTag.getListCompanies();
        }
      },
      error: function () {
          alert('error');
      }
    });
  }

  this.getListSuggestCompanies = function(list) {
    let res = [];
    for (var i = 0; i< list.length; i++) {
      res.push({value: list[i].comp_name, label: list[i].comp_name, comp_index: i});
    }
    $("#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].comp_code) {
          thisTag.update({comp_code_search: thisTag.list_companies_suggest_search[object.comp_index].comp_code});
        } 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});
        let firstId = $('.add_old_comp_code:first').attr('id');
        thisTag.addAutoCompleteDealer(firstId,[]);
      },
      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 new_up_comp_code = $("#add_new_up_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').each(function(index, el) {
      if ($(this).attr('comp_code')) {
        let index = $(this).parents('tr').attr('index');
        let price_rounding_item = $('#add_price_rounding_' + index + ' option:selected').val() != undefined ? $('#add_price_rounding_' + index + ' option:selected').val() : '';
        old_comp_code.push({
          dealer_co_cd: $(this).attr('comp_code'),
          price_rounding: price_rounding_item
        });
        
      }
    });

    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.length > 0 ? old_comp_code : '',
      addr: addr,
      tel: tel,
      fax: fax,
      del_flg: del_flg,
      pref_code: pref_code ? pref_code : '', 
      pref: pref ? pref : '',
      condition: thisTag.condition
    };

    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("追加しました。");
        }
        thisTag.clearInput();
        $('.add_old_comp_code:first').prop('disabled', false);
        $('#EC80-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_0").val('');
    $("#add_price_rounding_0").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');
    $("#add_up_comp_code").val('');
    $("#add_new_up_comp_code").val('');
    $('.dealer-item-add:not(:first)').remove();
    $('.dealer-item-add:first').show();
  }

  // ================================== 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 up_comp_code = $("#edit_up_comp_code").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 pref_code = $("#edit_prefectures option:selected").val();
      var pref = $("#edit_prefectures option:selected").attr('pref');
      let index = $(this).parents('tr').attr('index');
      var old_comp_code = [];
      var old_dealer_seq = extractColumn(thisTag.element.dealer_list, 'seq');
      var dealerLists = [];
      if (typeof(thisTag.companies[0]['dealer_list']) != "undefined" && thisTag.companies[0]['dealer_list'] !== null) {
        dealerLists = thisTag.companies[0]['dealer_list'];
      }
      $('.edit_old_comp_code').each(function(index, el) {
        if ($(this).attr('comp_code')) {
          let index = $(this).parents('tr').attr('index');
          let price_rounding_item = $('#edit_price_rounding_' + index + ' option:selected').val() != undefined ? $('#edit_price_rounding_' + index + ' option:selected').val() : '';
          let seq = $('#dealer_seq_' + index).val();
          if (seq != '' && seq != undefined) {
            var networkIdTo = null;
            if (dealerLists.length) {
              $.each( dealerLists, function( dKey, dValue ) {
                if(dValue['seq'] == seq) {
                  networkIdTo = dValue['network_id_to'];
                  return false;
                }
              });
            }
             old_comp_code.push({
              seq: seq,
              dealer_co_cd: $(this).attr('comp_code'),
              price_rounding: price_rounding_item,
              network_id_to: networkIdTo
            });
          } else {
            old_comp_code.push({
              dealer_co_cd: $(this).attr('comp_code'),
              price_rounding: price_rounding_item
            });
          }
          
        }
      });

      var data = {
        comp_code_key: comp_code_key,
        up_comp_code: up_comp_code,
        new_comp_name: comp_name,
        comp_ryaku: comp_ryaku,
        comp_kana: comp_kana,
        comp_eng: comp_eng,
        post_code: post_code,
        new_comp_code: thisTag.element.comp_code,
        old_comp_code: old_comp_code ? old_comp_code : '',
        old_dealer_seq: old_dealer_seq,
        addr: addr,
        tel: tel,
        fax: fax,
        del_flg: del_flg,
        pref_code: pref_code ? pref_code : '', 
        pref: pref ? pref : '',
        condition: thisTag.condition
      };
      // console.log(data);return false;

      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("編集完了しました。");
          $('#EC80-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);
      $("#edit_up_comp_code").val(thisTag.element.up_comp_code);
      thisTag.reappendDealer(thisTag.element);
      // $('.edit_old_comp_code:not(:disabled,:first)').parents('tr').remove();
      // $('.edit_old_comp_code:not(:disabled)').val('');
      // $('.edit_price_rounding').val('');
      // for (var i = 0; i < thisTag.element.dealer_list_count; i++) {
      //   $('#edit_price_rounding_' + i).val(thisTag.element.dealer_list[i].price_rounding);
      // }
  }

  this.addAutoCompleteDealer = function(id, list_added_comp_code) {

    let companies_suggest = thisTag.list_companies_suggest_dropdown;
    let res = [];
    for (var i = 0; i < companies_suggest.length; i++) {
        res.push({value: companies_suggest[i].comp_name, label: companies_suggest[i].comp_name, index: i});
    }
    $('#' + id).autocompleter("destroy");
    $('#' + id).autocompleter({ 
      limit:10000,
      highlightMatches:true, 
      source: res,
      callback: function(value, index, object) {
        if($('#' + id).val() != '' && companies_suggest[object.index].comp_code) {
          $('#' + id).attr({
              comp_code: companies_suggest[object.index].comp_code,
              tel: companies_suggest[object.index].tel,
              fax: companies_suggest[object.index].fax,
            });
        } else {
          $('#' + id).attr({
            comp_code: '',
            tel: '',
            fax: '',
          });
        }
      }
    });
  }

  this.deleteInputValue = function(element, comp_name) {
    let compCode = element.attr('comp_code');
    let companies = thisTag.list_companies_suggest_dropdown;
    let index = companies.map(function (company) { return company.comp_code; }).indexOf(compCode);
    if (index != -1 && companies[index].comp_name != comp_name) {
      element.val('');
      element.attr('comp_code', '');
      element.attr('tel', '');
      element.attr('fax', '');
      thisTag.addAutoCompleteDealer(element.attr('id'),[]);
    }
  }

  this.deleteItem = function(element, index, attribute, name) {
    if (attribute == 'class') {
      if ($('tr.' + name).length == 1) {
        element.parents('tr[index=' + index + ']').first().hide();
      } else element.parents('tr[index=' + index + ']').first().remove();
    }
  }

  this.addDealerItem = function(action) {
    let count_group = $('.dealer-item-' + action).length + 1;
    let index = parseInt($('.dealer-item-' + action +':last').attr('index')) + 1;
    if (action == 'add') {
      let add_flg = $("#add_flg option:selected").val();
      if (add_flg != 'customer_flg') return false;
    }
    if (count_group > 5) return false;
    if ($('.dealer-item-' + action +':first').css('display') == 'none') {
      index = '0';
      let dealer_item = $('.dealer-item-' + action +':first');
      this.changeElementAttribute(action, index, dealer_item);
      thisTag.addAutoCompleteDealer(action + '_old_comp_code_' + index, []);
      $('.dealer-item-' + action +':first').show();
      return false;
    }

    let dealer_item = $('.dealer-item-' + action + ':first').clone();
    let new_dealer_item = this.changeElementAttribute(action, index, dealer_item);
    $('.' + action +'DealerBodyTable').append(new_dealer_item);
    thisTag.addAutoCompleteDealer(action + '_old_comp_code_' + index, []);
  }

  this.changeElementAttribute = function(action, index, dealer_item) {
    dealer_item.attr('index', index);
    // remove useless attr/elements
    dealer_item.find('.autocompleter.autocompleter-closed').remove();
    dealer_item.find('#dealer_seq_0').remove();
    // change button
    let deleteDealerBtn = dealer_item.find('.delete-dealer-' + action);
    deleteDealerBtn.attr('index', index);
    // change price_rouding
    let addPriceRounding = dealer_item.find('.' + action +'_price_rounding');
    addPriceRounding.attr('id', '' + action +'_price_rounding_' + index);
    addPriceRounding.find(":selected").removeAttr('selected');
    // change suggest input
    let suggestDealer = dealer_item.find('.' + action +'_old_comp_code');
    suggestDealer.val('');
    suggestDealer.attr('id', action + '_old_comp_code_' + index);
    suggestDealer.removeAttr('disabled');
    suggestDealer.attr('comp_code', '');
    suggestDealer.attr('tel', '');
    suggestDealer.attr('fax', '');
    suggestDealer.attr('value', '');
    suggestDealer.removeClass('autocompleter-node');
    suggestDealer.removeAttr('autocomplete');
    return dealer_item;
  }

  this.reappendDealer = function(element) {
    if (element.dealer_list_count > 0) {
      $('.editDealerBodyTable').empty();
      var dealer_list = element.dealer_list;
      dealer_items = $("#hiddenEditDealerBodyTable").find('> tbody > tr').clone();
      dealer_items.each(function(index, el) {
        let index_dealer = $(this).attr('index');
        //change class and id of elements
        $(this).removeClass('hidden_dealer-item-edit');
        $(this).addClass('dealer-item-edit');

        let dealer_seq = $(this).find('.dealer_seq');
        dealer_seq.attr('id', 'dealer_seq_' + index_dealer);

        let edit_old_comp_code = $(this).find('.hidden_edit_old_comp_code');
        edit_old_comp_code.removeClass('hidden_edit_old_comp_code');
        edit_old_comp_code.addClass('edit_old_comp_code');

        let dealer_suggest = $(this).find('#hidden_edit_old_comp_code_' + index_dealer);
        dealer_suggest.attr('id', 'edit_old_comp_code_' + index_dealer);

        let priceRounding = $(this).find('.hidden_edit_price_rounding');
        priceRounding.removeClass('hidden_edit_price_rounding');
        priceRounding.addClass('edit_price_rounding');
        priceRounding.attr('id', 'edit_price_rounding_' + index_dealer);
      });
      $('.editDealerBodyTable').append(dealer_items);
      
    } else {
      dealer_items_pre = $(".editDealerBodyTable>tr")
      dealer_items_pre.each(function(index, el) {
        if ($('tr.dealer-item-edit').length == 1) {
          $(this).hide();
        } else $(this).remove();
      });
      thisTag.addDealerItem('edit');
    }
  }

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

  </script>
</EC80>

