<campaign-config>
  <link rel="stylesheet" href="css/S04.css">
  <link rel="stylesheet" href="css/common.css">
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <script src="https://rawgit.com/jquery/jquery-ui/master/ui/i18n/datepicker-ja.js"></script>
  
  <div class="main">
    <div class="content">
      <div class="page-title">
        <h2>キャンペーン設定</h2>
      </div>
        <div class="form-wrapper" id="s04_search">
        <table>
          <tr>
            <th style="width:65px">メーカー</th>
            <td><div class="div-wraper-autocompleter"><input type="text" id="companies_supplier"></div>
                <input type="hidden" class="companies_manufacture_code">
            </td>
            <td class="checkTd">
              <div><label><input type="checkbox" checked="checked" class="currently_in_progress">現在実施中のもの</label></div>
              <div>
                <input type="checkbox" class="inputActive">
                <input type="text" class="camp_start_date datepicker dateInput" disabled>
                <span>～</span>
                <input type="text" class="camp_end_date datepicker1 dateInput" disabled>の間に実施中のもの
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="5" class="btnTd">
              <button type="reset" class="reset-btn"><i class="fa fa-refresh"></i>条件クリア</button>
              <button type="button" class="submit" id="searchCampainProduct">検索</button>
            </td>
          </tr>
        </table>
      </div>
      <div class="table-wrapper">
        
        <div>
            <div class="info_page">{total_page}ページ中ページ{currentPage}を表示中</div>
            <div class="btn-wrapper"><button id="S04-add-Open" onclick="{s04AddModal}">キャンペーンを追加</button></div>
        </div>
        <table class="blue-table">
          <thead>
            <tr>
              <th>メーカー名</th>
              <th>件名</th>
              <th>説明</th>
              <th>開始日<span class="sorting" sort_field="camp_start_date"></span></th>
              <th>終了日<span class="sorting" sort_field="camp_end_date"></span></th>
              <th style="width:10%">URL</th>
              <th>カスタマ</th>
              <th>商品<br/>分類</th>
              <th>公開<br/>ステータス</th>
              <th if={ecUserInfo.member_type === 0 || ecUserInfo.member_type === '0'}>非公開<br/>販売店</th>
              <th width="55px"></th>
              <th width="55px"></th>
            </tr>
          </thead>
          <tbody>
            <tr each="{campainProduct,index in campainProducts}">
              <td>{campainProduct.comp_name}</td>
              <td>{campainProduct.camp_name}</td>
              <td class="campainProductDescription">{campainProduct.description}</td>
              <td>{campainProduct.camp_start_date.substr(0, 10)}</td>
              <td>{campainProduct.camp_end_date.substr(0, 10)}</td>
              <td><span class="word-wrap">{campainProduct.url}</span></td>
              <td>{campainProduct.customer_co_cd ? campainProduct.customer_co_name : '全カスタマ対象'}</td>
              <td><virtual each={classification in productClassification} if={classification.value == campainProduct.product_classification}>
                 {classification.label}
              </virtual></td>
              <td>
              <div if={campainProduct.member_type != 0}>
                <virtual each={status in publicStatuses} if={status.value == campainProduct.is_hidden}>
                   {status.label}
                </virtual>
              </div>
              <div if={campainProduct.member_type == 0}>
                <span if={!checkHiddenDealerCoCd(campainProduct.hidden_dealer_co_cd)}>公開</span>
                <span if={checkHiddenDealerCoCd(campainProduct.hidden_dealer_co_cd)}>非公開</span>
              </div>
              </td>
              <td if={ecUserInfo.member_type === 0 || ecUserInfo.member_type === '0'}>
                <button onclick="{openPopupListHiddenCompName}" if={campainProduct.hidden_dealer_co_cd.length > 0}>詳細</button>
                <span if={!campainProduct.hidden_dealer_co_cd}>なし</span>
              </td>
              <td>
                <button class="S04-edit-Open" onclick="{s04EditModal}"><span if={ecUserInfo.member_type == 0 || campainProduct.dealer_co_code == ecUserInfo.kikan_code && campainProduct.member_type != 0}>編集</span><span if={ecUserInfo.member_type != 0 && campainProduct.member_type == 0}>公開・非公開</span></button>
              </td>
              <td>
                <button if={(campainProduct.member_type == 0 && ecUserInfo.member_type == 0) || (ecUserInfo.kikan_code == campainProduct.dealer_co_code && campainProduct.member_type != 0 && ecUserInfo.member_type != 0)} class="S04-delete" onclick="{deleteCampaign}" seq="{campainProduct.seq}">削除</button>
              </td>
            </tr>
          </tbody>
        </table>
        <div id="paging" class="text-center">
          <ul class="pagination" id="pagination_campain_product"></ul>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-wrapper">
    <div class="o_modal" id="S04-add">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="S04-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 class="div-wraper-autocompleter"><input type="text" class="companies_manufacture_name"></div>
                  
                      <input type="hidden" class="companies_manufacture_code">
                  </td>
                </tr>
                <tr>
                  <th>件名</th>
                  <td><input type="text" class="camp_name"></td>
                </tr>
                <tr>
                  <th>説明</th>
                  <td><textarea class="camp_description"></textarea></td>
                </tr>
                <tr>
                  <th>開始日</th>
                  <td><input type="text" class="camp_start_date datepicker"></td>
                </tr>
                <tr>
                  <th>終了日</th>
                  <td><input type="text" class="camp_end_date datepicker1"></td>
                </tr>
                <tr>
                  <th>URL</th>
                  <td><input type="text" class="url_camp"></td>
                  <!-- <td><input type="text" class="image_url"></td> -->
                </tr>
                <tr>
                  <th>カスタマ</th>
                  <!-- <td><div class="div-wraper-autocompleter"><input type="text" class="camp_customer_co_name"></div></td> -->
                  <td>
                    <select id="camp_customer_co_name_add" class="camp_customer_co_name" style="width: 100%;">
                      <option value="default">---選択してください---</option>
                      <option value="all" selected="selected">全カスタマ対象</option>
                      <option if={ecUserInfo.member_type > 0} each="{dealer in listDealerCompName}" value="{dealer.comp_code}"}>{dealer.value}</option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>画像</th>
                  <td>
                    <input type="file" id="camp_image_add" name="camp_image_add">
                    <div  style="font-size: 11px;">
                      <p>3MBまでファイルをアップロード可能です</p>
                      <p>ファイルタイプ：.jpg、.jpeg、.png、.gif</p>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>商品分類</th>
                  <td>
                    <select class="product_classification">
                        <option each="{classification in productClassification}" value="{classification.value}">{classification.label}</option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>公開ステータス</th>
                  <td>
                    <select class="publicStatus">
                      <option each="{status in publicStatuses}" value="{status.value}">{status.label}</option>
                    </select>
                  </td>
                </tr>
                <tr if={ecUserInfo.member_type === 0 || ecUserInfo.member_type === '0'}>
                  <th>非公開販売店名</th>
                  <td>
                    <label for="hidden_dealer_co_cd_checkbox">あり</label> <input type="checkbox" name="hidden_dealer_co_cd_checkbox" class="hidden_dealer_co_cd_checkbox" id="hidden_dealer_co_cd_checkbox_add" onchange="{hiddenDealerCoCdCheckbox}" />
                    <div class="list_hidden_dealer_co_cd" if={list_hidden_dealer_co_cd_select.length > 0}>
                      <select id="hidden_dealer_co_cd_select" onchange="{pickHiddenDealerCoCd}">
                        <option value="">--選択してください--</option>
                        <option each="{item,index in list_hidden_dealer_co_cd_select}" value="{item.comp_code}">{item.comp_name}</option>
                      </select>
                    </div>
                    <div class="list_hidden_dealer_co_cd_selected" if={list_hidden_dealer_co_cd_selected.length > 0}>
                      <ul class="item">
                        <li each={item,index in list_hidden_dealer_co_cd_selected}>{item.comp_name} <span class="item_remove" comp_code={item.comp_code} onclick="{removeHiddenDealerCoCd}">☓削除</span></li>
                      </ul>
                    </div>
                  </td>
                </tr>
              </table>
              <div class="btn-wrapper">
                <button type="reset" class="reset-btn"><i class="fa fa-refresh"></i>条件クリア</button>
                <button type="button" class="submit" onclick="{addCampaign}">登録</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="o_modal" id="S04-edit">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="S04-edit-Close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title" if={visibleCampaignTrue}>キャンペーン更新</h3>
            <h3 class="modal-title" if={visibleCampaignFalse}>公開・非公開</h3>
            <div class="modal-form-box">
              <table if={visibleCampaignTrue}>
                <tr>
                  <th>メーカー名</th>
                  <td>
                    <div class="div-wraper-autocompleter">
                      <input type="text" class="companies_manufacture_name" value="{campainProduct.comp_name}">
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>件名</th>
                  <td><input type="text" value="{campainProduct.camp_name}" class="camp_name"></td>
                </tr>
                <tr>
                  <th>説明</th>
                  <td><textarea class="camp_description">{campainProduct.description}</textarea></td>
                </tr>
                <tr>
                  <th>開始日</th>
                  <td><input type="text" value="{campainProduct.camp_start_date}" class="camp_start_date datepicker"></td>
                </tr>
                <tr>
                  <th>終了日</th>
                  <td><input type="text" value="{campainProduct.camp_end_date}" class="camp_end_date datepicker1"></td>
                </tr>
                <tr>
                  <th>URL</th>
                  <td><input type="text" value="{campainProduct.url}" class="url_camp"></td>
                  <!-- <td><input type="text" value="{campainProduct.image_url}" class="image_url"></td> -->
                </tr>
                <tr>
                  <th>カスタマ</th>
                  <td>
                    <select id="camp_customer_co_name_edit" class="camp_customer_co_name" style="width: 100%;">
                      <option value="default">---選択してください---</option>
                      <option value="all" selected="{!campainProduct.customer_co_cd ? 'selected' : ''}">全カスタマ対象</option>
                      <option if={ecUserInfo.member_type > 0} each="{dealer in listDealerCompName}" value="{dealer.comp_code}" selected="{dealer.comp_code == campainProduct.customer_co_cd ? 'selected' : ''}">{dealer.value}</option>
                    </select>
                    <!-- <div class="div-wraper-autocompleter"><input type="text" class="camp_customer_co_name" value="{campainProduct.customer_co_name}"></div> -->
                  </td>
                </tr>
                <tr>
                  <th>画像</th>
                  <td>
                    <input type="file" id="camp_image_edit" name="camp_image_edit" accept=".png,.jpg,.jpeg,.gif">
                    <div  style="font-size: 11px;">
                      <p>3MBまでファイルをアップロード可能です</p>
                      <p>ファイルタイプ：.jpg、.jpeg、.png、.gif</p>
                    </div>
                    <img src="{campainProduct.image_url}" style="max-width: 500px; max-height: 300px;">
                  </td>
                </tr>
                <tr>
                  <th>商品分類</th>
                  <td>
                    <select class="product_classification">
                        <option each="{classification in productClassification}" selected="{campainProduct.product_classification == classification.value}"  value="{classification.value}">{classification.label}</option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th>公開ステータス</th>
                  <td>
                    <select class="publicStatus">
                        <option each="{status in publicStatuses}" selected="{campainProduct.is_hidden == status.value}"  value="{status.value}">{status.label}</option>
                    </select>
                  </td>
                </tr>
                <tr if={ecUserInfo.member_type === 0 || ecUserInfo.member_type === '0'}>
                  <th>非公開販売店名</th>
                  <td>
                    <label for="hidden_dealer_co_cd_checkbox">あり</label> <input type="checkbox" name="hidden_dealer_co_cd_checkbox" class="hidden_dealer_co_cd_checkbox" id="hidden_dealer_co_cd_checkbox_edit" onchange="{hiddenDealerCoCdCheckbox}" checked={hidden_dealer_co_cd.length > 0 ? 'checked' : ''}/>
                    <div class="list_hidden_dealer_co_cd" if={list_hidden_dealer_co_cd_select.length > 0}>
                      <select id="hidden_dealer_co_cd_select" onchange="{pickHiddenDealerCoCd}">
                        <option>--選択してください--</option>
                        <option each="{item,index in list_hidden_dealer_co_cd_select}" value="{item.comp_code}">{item.comp_name}</option>
                      </select>
                    </div>
                    <div class="list_hidden_dealer_co_cd_selected" if={list_hidden_dealer_co_cd_selected.length > 0}>
                      <ul class="item">
                        <li each={item,index in list_hidden_dealer_co_cd_selected}>{item.comp_name} <span class="item_remove" comp_code={item.comp_code} onclick="{removeHiddenDealerCoCd}">☓削除</span></li>
                      </ul>
                    </div>
                  </td>
                </tr>
              </table>
              <table if={visibleCampaignFalse}>
                <th>公開ステータス</th>
                <td>
                  <select class="hiddenDealerSelect">
                      <!-- <option each="{status in publicStatuses}" selected="{campainProduct.is_hidden == status.value ? 'selected' : ''}"  value="{status.value}">{status.label}</option> -->
                      <option selected="{checkHiddenDealerCoCd(campainProduct.hidden_dealer_co_cd) ? 'selected' : ''}" value="1">非公開</option>
                      <option selected="{!checkHiddenDealerCoCd(campainProduct.hidden_dealer_co_cd) ? 'selected' : ''}" value="0">公開</option>
                  </select>
                </td>
              </table>
              <div class="btn-wrapper">
                <button type="button" class="submit" onclick="{editCampaign}">更新</button>
                <input type="hidden" class="campainProductSeq" value="{campainProduct.seq}" >
                <input type="hidden" class="companies_manufacture_code" value="{campainProduct.comp_code}" >
                <input type="hidden" class="campainProductDealerCoCode" value="{campainProduct.dealer_co_code}" >
                <input type="hidden" class="campainProductMemberType" value="{campainProduct.member_type}" >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="o_modal" id="popup-hidden-dealer-list">
      <div class="o_modal_box">
        <div class="o_modal_head">
          <a id="popup-hidden-dealer-list-Close"><i class="fa fa-times"></i></a>
        </div>
        <div class="o_modal_body">
          <div class="o_modal_main">
            <h3 class="modal-title">非公開販売店名</h3>
            <div class="modal-form-box">
              <table>
                <tbody>
                  <tr each={item,index in list_hidden_dealer_co_cd_popup}>
                    <td>{index + 1}</td>
                    <td>{item.comp_name}</td>
                  </tr>
                </tbody>
              </table>
              <div class="btn-wrapper">
                <!-- <button type="button" class="submit">更新</button> -->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script>
    /* global $ */
    this.ecUserInfo = JSON.parse(localStorage.getItem('EcUserInfo'));
    this.supplierList = opts.supplierList;
    this.publicStatuses = opts.publicStatuses;
    this.productClassification = opts.productClassification;
    this.listDealerCompName = opts.listDealerCompName;
    this.campainProducts = [];
    this.currentPage = 1;
    this.editItem = {};
    this.sort_field = 'camp_end_date';
    this.sort_value = 'ASC';
    this.total_page = 0;
    this.customer_co_cd = '';
    this.list_hidden_dealer_co_cd_select = [];
    this.list_hidden_dealer_co_cd_selected = [];
    this.list_hidden_dealer_co_cd_popup = [];
    this.visibleCampaignTrue = false;
    this.visibleCampaignFalse = false;
    thisTag = this;
    $(function(){
      /*↓↓↓new add↓↓↓*/
      $('.inputActive').on('click',function(){
        if($(this).is(':checked')){
          $('.dateInput').prop('disabled',false);
        }else{
          $('.dateInput').prop('disabled',true);
          $('.dateInput').val('');
        }
      });
      /*↑↑↑new add↑↑↑*/
    
      $('.info_page').hide();
      $('#companies_supplier').autocompleter({ limit:10000,highlightMatches:true, source: opts.supplierList,
          callback: function(value, index){
              $('#s04_search .companies_manufacture_code').val(opts.supplierList[index].comp_code);
          }
        });
      $('#S04-add .companies_manufacture_name').autocompleter({ limit:10000,highlightMatches:true, source: opts.supplierList, 
          // callback: function (value, index) {
          //   console.log(opts.supplierList[index].comp_code);
          //   console.log(opts.supplierList[index].label);
          //   
          //   $('#S04-add .companies_manufacture_name').val(opts.supplierList[index].label);
          // }
          // select: function( event, ui ) {
          //   $('#S04-add .companies_manufacture_code').val(opts.supplierList[index].comp_code);
          //   $('#S04-add .companies_manufacture_name').val(opts.supplierList[index].label);
          // }
    
        });
      
      $('#S04-edit .companies_manufacture_name').autocompleter({ limit:10000,highlightMatches:true, source: opts.supplierList, 
          // callback: function (value, index) {
          //   $('#S04-edit .companies_manufacture_code').val(opts.supplierList[index].comp_code);
          //   $('#S04-edit .companies_manufacture_name').val(opts.supplierList[index].label);
          // }
          // select: function( event, ui ) {
          //   $('#S04-add .companies_manufacture_code').val(opts.supplierList[index].comp_code);
          //   $('#S04-add .companies_manufacture_name').val(opts.supplierList[index].label);
          // }
        });
        $('.camp_customer_co_name').autocompleter({ limit:10000,highlightMatches:true, source: thisTag.listDealerCompName });
        $('.camp_customer_co_name').on('change',function(e){

            var value = $(this).val();
            
            $.each(thisTag.listDealerCompName, function(k,v){
              
            if(v['value'].indexOf(value) !== -1 && value != ''){
              thisTag.customer_co_cd = v['comp_code'];
              return false;
            }  else {
              thisTag.customer_co_cd = '';
            }
          });
        });
//       /*S04-add*/
// //      $('#S04-add-Open').on('click',function(){
// //        $('#S04-add').fadeIn();
// //      });
//       $('#S04-add-Close').on('click',function(){
//         thisTag.customer_co_cd = '';
//         thisTag.resetAllHiddenDealerSelect();
//         $('#S04-add').fadeOut();
//       });
      
//       /*S04-edit*/
// //      $(document).on('click','.S04-edit-Open',function(){
// //        $('#S04-edit').fadeIn();
// //      });
//       $('#S04-edit-Close').on('click',function(){
//         thisTag.customer_co_cd = '';
//         thisTag.resetAllHiddenDealerSelect();
//         $('#S04-edit').fadeOut();
//       });

      $('#popup-hidden-dealer-list-Close').on('click',function(){
        $('#popup-hidden-dealer-list').fadeOut();
        thisTag.list_hidden_dealer_co_cd_popup = [];
        thisTag.update(thisTag.list_hidden_dealer_co_cd_popup);
      });
      
        /*$('#s04_search .camp_start_date').datetimepicker({
        format: 'Y-m-d',
        onShow:function( ct ){
         this.setOptions({
          maxDate:$('#s04_search .camp_end_date').val()?$('#s04_search .camp_end_date').val():false
         })
        },
        
        timepicker:false
       });
       $('#s04_search .camp_end_date').datetimepicker({
        format: 'Y-m-d', //Y-m-d H:i:s
        onShow:function( ct ){
         this.setOptions({
          minDate:$('#s04_search .camp_start_date').val()?$('#s04_search .camp_start_date').val():false
         })
        },
        
        timepicker:false
       });
        
        $('#S04-add .camp_start_date').datetimepicker({
        format: 'Y-m-d',
        onShow:function( ct ){
         this.setOptions({
          maxDate:$('#S04-add .camp_end_date').val()?$('#S04-add .camp_end_date').val():false
         })
        },
        timepicker:false
       });
       $('#S04-add .camp_end_date').datetimepicker({
        format: 'Y-m-d',
        onShow:function( ct ){
         this.setOptions({
          minDate:$('#S04-add .camp_start_date').val()?$('#S04-add .camp_start_date').val():false
         })
        },
        
        timepicker:false
       });
       
       $('#S04-edit .camp_start_date').datetimepicker({
        format: 'Y-m-d',
        onShow:function( ct ){
         this.setOptions({
          maxDate:$('#S04-edit .camp_end_date').val()?$('#S04-edit .camp_end_date').val():false
         })
        },
        
        timepicker:false
       });
       $('#S04-edit .camp_end_date').datetimepicker({
        format: 'Y-m-d',
        onShow:function( ct ){
         this.setOptions({
          minDate:$('#S04-edit .camp_start_date').val()?$('#S04-edit .camp_start_date').val():false
         })
        },
        
        timepicker:false
       });*/
       
        
        
        
        $('#searchCampainProduct').click(function(){
            var page = 1;
//            thisTag.sort_field = 'camp_end_date';
//            thisTag.sort_value = 'DESC';
            searchCampainProduct(page);
        });

        $("#searchCampainProduct").trigger("click");
        
        var cnt = 0;
        $('.sorting').click(function(){
            cnt++;
            if(cnt%2==0){
                    $('.sorting').removeClass('sorting_asc');
                    $(this).addClass('sorting_desc');
                    $(this).attr('sort_value','DESC');
            }else{
                    $('.sorting').removeClass('sorting_desc');
                    $(this).addClass('sorting_asc');
                    $(this).attr('sort_value','ASC');
            }
//                sortData(that);
            sort_field = $(this).attr('sort_field');
            sort_value = $(this).attr('sort_value');
            thisTag.sort_field = sort_field;
            thisTag.sort_value = sort_value;
            var page = 1;
            searchCampainProduct(page);
        });
        
        thisTag.actionClear();
//        $('#S04-edit .reset-btn').click(function(){
//            console.log(3333);
//            console.log(thisTag.editItem);
//            thisTag.update();
//        });
    });
    
    this.actionClear = function() {
      $('#S04-add-Close').on('click',function(){
        thisTag.customer_co_cd = '';
        thisTag.resetAllHiddenDealerSelect();
        $('#S04-add').fadeOut();
      });
      $('#S04-edit-Close').on('click',function(){
        thisTag.customer_co_cd = '';
        thisTag.resetAllHiddenDealerSelect();
        $('#S04-edit').fadeOut();
      });
      $('#s04_search .reset-btn').click(function(){
          $('#s04_search .companies_manufacture_code').val('');
          $('#s04_search #companies_supplier').val('');
          $('#s04_search .camp_start_date').val('');
          $('#s04_search .camp_end_date').val('');
          $('#s04_search .publicStatus').prop('checked', true);
      });
      $('#S04-add .reset-btn').click(function(){
          $('#S04-add .companies_manufacture_name').val('');
          $('#S04-add .companies_manufacture_code').val('');
          $('#S04-add .camp_start_date').val('');
          $('#S04-add .camp_end_date').val('');
          $('#S04-add .camp_description').val('');
          $('#S04-add .url_camp').val('');
          $('#S04-add .camp_name').val('');
          $('#S04-add .publicStatus').val(0);
          $('#S04-add .product_classification').val(null);
          $('#S04-add .image_url').val('');
          $('#S04-add #camp_image_add').val('');
      });
    }
    function searchCampainProduct(page){
        thisTag.currentPage = page;
        var supplier_name = $('#s04_search #companies_supplier').val();
        var supplier_code = $('#s04_search .companies_manufacture_code').val();
        var publicStatus = '';
        
        var camp_start_date =  $('#s04_search .camp_start_date').val();
        var camp_end_date =  $('#s04_search .camp_end_date').val();
        
        var query = [];
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
            query.push('token=' + accessTokenCognito);
            query.push('page='+page);
            query.push('sort_field='+thisTag.sort_field);
            query.push('sort_value='+thisTag.sort_value);
            query.push('limit=' +   LIMIT_ON_PAGE);
        var url = URL_API + '/api/campaign/get';
        
//        var url = 'http://ec-webapi.local/api/campaign/get';
        
        url += '?' + query.join('&');
        
        for(var k in opts.supplierList ){
             var supplier = opts.supplierList[k];
             if(supplier.comp_code == supplier_code){
                 if(supplier.value != supplier_name){
                     supplier_code = '';
                 }
             }
         }

        var data = {};
        var public_statuses = [0, 1];
        var inputActive = 0;
         if($('#s04_search .inputActive').prop( "checked" )){
             inputActive = 1;
         }
        if($('#s04_search .currently_in_progress').prop( "checked" )){
            camp_currently_in_progress = 1;
            data = {
                comp_name: supplier_name,
                comp_code: supplier_code,
                camp_currently_in_progress: (camp_currently_in_progress == '')? null: camp_currently_in_progress,
                is_hidden: public_statuses,
                inputActive: inputActive,
                camp_start_date: camp_start_date,
                camp_end_date: camp_end_date,
                screen: 's04'
            };
        }else{
           data = {
                comp_name: supplier_name,
                comp_code: supplier_code,
                is_hidden: public_statuses,
                inputActive: inputActive,
                camp_start_date: camp_start_date,
                camp_end_date: camp_end_date,
                screen: 's04'
            };
        }
        
        
        
        $.ajax({
            url: url,
            type: 'GET',
            timeout: 60000,
            data: {
                campaign_info: data
            },
            success: function (res) {
                if(res.status == 100){
                    riot.mount('app','maintain',{ messege:res.messege });
                    return false;
                }
                if(res.message == 'success'){
                    $('.info_page').show();
                     var data = res;
                     thisTag.campainProducts = data.campaign_info;
                     $.each(thisTag.campainProducts, function(index, element){
                      if(element.hidden_dealer_co_cd) {
                        thisTag.campainProducts[index].hidden_dealer_co_cd = thisTag.campainProducts[index].hidden_dealer_co_cd.split(',');
                      }
                    })
                    var totalPages = Math.ceil(data.total/LIMIT_ON_PAGE);
                        thisTag.total_page = totalPages;
                    var visiblePages = 1;
                    if(totalPages != 0){
                        visiblePages =  5;
                    } 
                    var $pagination = $('#pagination_campain_product');
                    $pagination.twbsPagination('destroy');
                    $pagination.twbsPagination({
                        totalPages: totalPages,
                        visiblePages: visiblePages,
                        startPage: thisTag.currentPage,
                        initiateStartPageClick: false,
                        onPageClick: function (event, page) {

                            searchCampainProduct(page);
                        }
                    });

                    thisTag.update(thisTag.campainProducts);
                    $('.campainProductDescription').each(function(index, value){
                        $(this).html($(this).text());
                    }) ;
                   
                    thisTag.resetAllHiddenDealerSelect();
                }
            },
            error: function (xhr, stt, err) {
                alert('error');
            }
        });
         
        
    }
    resetS04Edit(e){
        var editItem = thisTag.editItem;
        thisTag.editItem = [];
        thisTag.update(thisTag.editItem);
        thisTag.editItem = editItem;
        thisTag.update(thisTag.editItem);
    };
    
    s04AddModal(e){
        thisTag.customer_co_cd = '';
        $('#S04-add').fadeIn();
        $('#S04-add .reset-btn').trigger('click');
    };
    s04EditModal(e){
         $('#S04-edit').fadeIn();
         thisTag.customer_co_cd = '';
         thisTag.editItem = [];
         thisTag.update(thisTag.editItem);
         var item = e.item;
         item.campainProduct.description = item.campainProduct.description.replace(/<br>/g,'\n');
         if(item.campainProduct.hidden_dealer_co_cd && item.campainProduct.hidden_dealer_co_cd.length > 0) {
          $("#hidden_dealer_co_cd_checkbox_edit").prop("checked", true);
          thisTag.getCompanies(function() {
            thisTag.checkedOldValueEdit(item.campainProduct.hidden_dealer_co_cd);
          });
         }
         thisTag.editItem = item;
         thisTag.customer_co_cd = thisTag.editItem.campainProduct.customer_co_cd;
         thisTag.update(thisTag.editItem);
         thisTag.update(thisTag.customer_co_cd);
        thisTag.visibleCampaignTrue = thisTag.checkCampaignEditTrue(thisTag.editItem.campainProduct.dealer_co_code, thisTag.editItem.campainProduct.member_type);
        thisTag.visibleCampaignFalse = thisTag.checkCampaignEditFalse(thisTag.editItem.campainProduct.member_type);
        thisTag.update(thisTag.visibleCampaignTrue);
        thisTag.update(thisTag.visibleCampaignFalse);
    };
    this.addCampaign = function(e){
        var supplier_name = $('#S04-add .companies_manufacture_name').val();
        var supplier_code = '';//$('#S04-add .companies_manufacture_code').val();
        var camp_name = $('#S04-add .camp_name').val();
        var publicStatus = $('#S04-add .publicStatus').val();
        var camp_start_date =  $('#S04-add .camp_start_date').val();
        var camp_end_date =  $('#S04-add .camp_end_date').val();
        var camp_description = $('#S04-add .camp_description').val();
            camp_description = camp_description.replace(/\n/g, "<br>");
        var url_camp = $('#S04-add .url_camp').val();
        
        var image_url = $('#S04-add .image_url').val();
        var product_classification = $('#S04-add .product_classification').val();
        var customer_co_cd = $("#camp_customer_co_name_add option:selected").val();
        var hidden_dealer_co_cd = Array.from(thisTag.list_hidden_dealer_co_cd_selected, function(element) {
          return element.comp_code;
        });

        if(!supplier_name) {
          alert("メーカー名は入力必須です。");
          return false;
        }

        if(!camp_name) {
          alert("件名は入力必須です。");
          return false;
        }

        if(camp_name) {
          if(camp_name.length > 255) {
            alert("件名を255文字以内で入力してください。");
            return false;
          } 
        }
        
        if(!camp_start_date) {
          alert("開始日は選択必須です。");
          return false;
        }

        if(!camp_end_date) {
          alert("終了日は選択必須です。");
          return false;
        }

        if(url_camp) {
          if(url_camp.length > 255) {
            alert("ページURLは255文字以内で入力してください。");
            return false;
          }
        }
        
        if(!thisTag.validateExtensionUploadImage('#camp_image_add')) {
          alert("ファイルタイプ：.jpg、.jpeg、.png、.gif のみアップロード可能です");
          return false;
        }
        if($("#camp_image_add")[0].files.length > 0 && !thisTag.validateSizeUploadImage('#camp_image_add')) {
          alert("3MBまでファイルをアップロードしてください");
          return false;
        }

        // if( $("#camp_image_add")[0].files.length == 0 ){
        //   alert("アップロードファイルを選択してください。");
        //   return false;
        // }

        var formData = new FormData();
        formData.append('file',$("#camp_image_add")[0].files[0]);

        if(customer_co_cd == 'default'){
          alert("カストマーを選択してください");
          return false;
        } else if(customer_co_cd == 'all') {
          customer_co_cd = null;
        }
        for(var k in opts.supplierList ){
            var supplier = opts.supplierList[k];
           if(supplier.value == supplier_name){
               supplier_code = supplier.comp_code;
           }
        }    
        // if(supplier_code == ''){
        //     alert('メーカー名は入力必須です。');
        //     return false;
        // }
                 
        var querySuggest = [];
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        querySuggest.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/campaign/saveCampainProducts';
        
//            var url = 'http://ec-webapi.local/api/campaign/saveCampainProducts';

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

        var data = [];
        data.push({
            comp_code: supplier_code,
            comp_name: supplier_name,
            camp_name: camp_name,
            is_hidden: publicStatus,
            camp_start_date: camp_start_date,
            camp_end_date: camp_end_date,
            description: camp_description,
            url: url_camp,
            // image_url: image_url,
            product_classification: product_classification,
            // customer_co_cd: thisTag.customer_co_cd
            customer_co_cd: customer_co_cd,
            hidden_dealer_co_cd: hidden_dealer_co_cd,
            member_type: thisTag.ecUserInfo.member_type,
            action: 'add',
        });
        formData.append('campaign_info', JSON.stringify(data));
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'JSON',
            timeout: 60000,
            data: formData,
            mimeType: "multipart/form-data",
            contentType: false,
            cache : false,
            processData: false,
            success: function (res) {
                if(res.status == 100){
                    riot.mount('app','maintain',{ messege:res.messege });
                    return false;
                }
                if(res.message == 'success'){
                    alert('登録しました。');
                    // thisTag.resetAllHiddenDealerSelect();
                    thisTag.actionClear();
                    $( "#S04-add-Close" ).trigger( "click" );
                    $('#S04-add .reset-btn').trigger( "click" );
                    searchCampainProduct(thisTag.currentPage);
                }else if(res.message == 'errors'){
                    var errors = res.errors[0];
                    var msg = [];
                    for( var k in errors){
                        for(var h in errors[k]){
                            msg.push(errors[k][h]);
                        }
                    }
                    alert(msg.join("\n "));
                }
            },
            error: function (xhr, stt, err) {
                alert('error');
            }
        });
         
    }
    this.editCampaign = function(e){
        var seq = $('#S04-edit .campainProductSeq').val();
        console.log(seq);
        var dealer_co_code = $('#S04-edit .campainProductDealerCoCode').val();
        var member_type = $('#S04-edit .campainProductMemberType').val();
        var supplier_name = $('#S04-edit .companies_manufacture_name').val();
        var supplier_code = '';//$('#S04-edit .companies_manufacture_code').val();
        var camp_name = $('#S04-edit .camp_name').val();
        var publicStatus = $('#S04-edit .publicStatus').val();
        var hiddenDealerSelect = $('#S04-edit .hiddenDealerSelect').val();
        var camp_start_date =  $('#S04-edit .camp_start_date').val();
        var camp_end_date =  $('#S04-edit .camp_end_date').val();
        var camp_description = $('#S04-edit .camp_description').val();
            if(camp_description) {
              camp_description = camp_description.replace(/\n/g, "<br>");
              $('#S04-edit .camp_description').val(camp_description);
            }
        var url_camp = $('#S04-edit .url_camp').val();
        var image_url = $('#S04-edit .image_url').val();
        var product_classification = $('#S04-edit .product_classification').val();
        var customer_co_cd = $("#camp_customer_co_name_edit option:selected").val();
        var hidden_dealer_co_cd = Array.from(thisTag.list_hidden_dealer_co_cd_selected, function(element) {
          return element.comp_code;
        });

        var querySuggest = [];
        var accessTokenCognito = localStorage.getItem('accessTokenCognito');
        querySuggest.push('token=' + accessTokenCognito);
        var url = URL_API + '/api/campaign/saveCampainProducts';
                
        url += '?' + querySuggest.join('&');

        var data = [];
        var formData = new FormData();

        if(thisTag.ecUserInfo.member_type == 0 || dealer_co_code == thisTag.ecUserInfo.kikan_code && member_type != 0) {
          if(!thisTag.validateExtensionUploadImage('#camp_image_edit')) {
            alert("ファイルタイプ：.jpg、.jpeg、.png、.gif のみアップロード可能です");
            return false;
          }
          if($("#camp_image_add")[0].files.length > 0 && !thisTag.validateSizeUploadImage('#camp_image_edit')) {
            alert("3MBまでファイルをアップロードしてください");
            return false;
          }
          formData.append('file',$("#camp_image_edit")[0].files[0]);

          if(customer_co_cd == 'default'){
            alert("カストマーを選択してください");
            return false;
          } else if(customer_co_cd == 'all') {
            customer_co_cd = null;
          }
          for(var k in opts.supplierList ){
              var supplier = opts.supplierList[k];
             if(supplier.value == supplier_name){
                 supplier_code = supplier.comp_code;
             }
          }    
          if(supplier_code == ''){
              alert('メーカー名は入力必須です。');
              return false;
          }
          data.push({
              seq: seq,
              comp_code: supplier_code,
              comp_name: supplier_name,
              camp_name: camp_name,
              is_hidden: publicStatus,
              camp_start_date: camp_start_date,
              camp_end_date: camp_end_date,
              description: camp_description,
              url: url_camp,
              // image_url: image_url,
              product_classification: product_classification,
              // customer_co_cd: thisTag.customer_co_cd
              customer_co_cd: customer_co_cd,
              member_type: thisTag.ecUserInfo.member_type,
              hidden_dealer_co_cd: hidden_dealer_co_cd.length > 0 ? hidden_dealer_co_cd : null
          });
        } else {
          if(hidden_dealer_co_cd) {
            var index_hidden = $.inArray(thisTag.ecUserInfo.kikan_code, hidden_dealer_co_cd);
            if(hiddenDealerSelect > 0) {
              if (index_hidden == -1) {
                hidden_dealer_co_cd.push(thisTag.ecUserInfo.kikan_code);
              }
            } else {
              if (index_hidden != -1) {
                  hidden_dealer_co_cd.splice(index_hidden, 1);
              }
            }
          } else {
            hidden_dealer_co_cd.push(thisTag.ecUserInfo.kikan_code);
          }
          data.push({
            seq: seq,
            hidden_dealer_co_cd: hidden_dealer_co_cd.length > 0 ? hidden_dealer_co_cd : null
          });
        }

        formData.append('campaign_info', JSON.stringify(data));
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'JSON',
            timeout: 60000,
            data: formData,
            mimeType: "multipart/form-data",
            contentType: false,
            cache : false,
            processData: false,
            success: function (res) {
                if(res.status == 100){
                    riot.mount('app','maintain',{ messege:res.messege });
                    return false;
                }
                if(res.message == 'success'){
                    alert('更新しました。');
                    $( "#S04-edit-Close" ).trigger( "click" );
                    $("#camp_image_edit").val('');
                   searchCampainProduct(thisTag.currentPage);
                }else if(res.message == 'errors'){
                    var errors = res.errors[0];
                    var msg = [];
                    for( var k in errors){
                        for(var h in errors[k]){
                            msg.push(errors[k][h]);
                        }
                    }
                    alert(msg.join("\n "));
                }
            },
            error: function (xhr, stt, err) {
                alert('error');
            }
        });
        
    };
    this.deleteCampaign = function(e){
      var seq = $(e.target).attr('seq');

      if(!confirm("削除します。よろしいですか？")) {
        return false;
      }
      var seqs = [seq];
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
      var url = URL_API + '/api/campaign/deleteCampainProducts';
              
      $.ajax({
          url: url,
          type: 'GET',
          dataType: 'JSON',
          timeout: 60000,
          data: {
            token: accessTokenCognito,
            seqs: seqs
          },
          success: function (res) {
              if(res.status == 100){
                  riot.mount('app','maintain',{ messege:res.messege });
                  return false;
              }

              alert('削除しました。');
              searchCampainProduct(1);
          },
          error: function (xhr, stt, err) {
              alert('error');
          }
      });
    }
    this.getCompanies = function(callback) {
      var query = [];
      var accessTokenCognito = localStorage.getItem('accessTokenCognito');
          query.push('token=' + accessTokenCognito);

      var url = URL_API + '/api/s04/getSuggestionBySupplierFlg';

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

      $.ajax({
        url: url,
        method: 'GET',
        timeout: 60000,
        data: {
          dealer_flg: 1
        },
        success: function(res) {
          thisTag.list_hidden_dealer_co_cd_select = res.companies_list;
          thisTag.update(thisTag.list_hidden_dealer_co_cd_select);
          callback();
        }, 
        error: function(err) {

        }
      });
    } 

    this.pickHiddenDealerCoCd = function(e) {
      var comp_code = $(e.target).children("option:selected").val();
      var comp_name = $(e.target).children("option:selected").text();
      var selected = {comp_code: comp_code, comp_name: comp_name};

      if(!comp_code || !comp_name) {
        return false;
      }

      if(thisTag.list_hidden_dealer_co_cd_selected.length > 0) {
        if(!thisTag.checkHiddenDealerCoCdSelectedExist(selected)) {
          return false;
        }

        thisTag.list_hidden_dealer_co_cd_selected.push(selected);
        thisTag.update(thisTag.list_hidden_dealer_co_cd_selected);
      } else {
        thisTag.list_hidden_dealer_co_cd_selected.push(selected);
        thisTag.update(thisTag.list_hidden_dealer_co_cd_selected);
      }
    } 

    this.checkHiddenDealerCoCdSelectedExist = function(selected) {
      for (var i = thisTag.list_hidden_dealer_co_cd_selected.length - 1; i >= 0; i--) {
        if(thisTag.list_hidden_dealer_co_cd_selected[i].comp_code == selected.comp_code) {
          return false;
        }
      }
      return true;
    }

    this.removeHiddenDealerCoCd = function(e) {
      var comp_code = $(e.target).attr('comp_code');
      thisTag.list_hidden_dealer_co_cd_selected = $.grep(thisTag.list_hidden_dealer_co_cd_selected, function(element, index) {
        return element.comp_code != comp_code;
      })
      thisTag.update(thisTag.list_hidden_dealer_co_cd_selected);
    }

    this.resetAllHiddenDealerSelect = function() {
      $(".hidden_dealer_co_cd_checkbox").prop("checked", false);
      thisTag.list_hidden_dealer_co_cd_select = [];
      thisTag.list_hidden_dealer_co_cd_selected = [];
      thisTag.update(thisTag.list_hidden_dealer_co_cd_select);
      thisTag.update(thisTag.list_hidden_dealer_co_cd_selected);
    }

    this.hiddenDealerCoCdCheckbox = function(e) {
      if($(e.target).is(":checked")){
        thisTag.getCompanies(function(){

        });
      } else {
        thisTag.resetAllHiddenDealerSelect();
      }
    }

    this.checkedOldValueEdit = function(hidden_dealer_co_cd) {
      for (var i = thisTag.list_hidden_dealer_co_cd_select.length - 1; i >= 0; i--) {
        for (var j = hidden_dealer_co_cd.length - 1; j >= 0; j--) {
          if(hidden_dealer_co_cd[j] == thisTag.list_hidden_dealer_co_cd_select[i].comp_code) {
            thisTag.list_hidden_dealer_co_cd_selected.push(thisTag.list_hidden_dealer_co_cd_select[i]);
          }
        }
      }
      thisTag.update(thisTag.list_hidden_dealer_co_cd_selected);
    }

    this.openPopupListHiddenCompName = function(e) {
      var index = e.item.index;
      var comp_code_list = thisTag.campainProducts[index].hidden_dealer_co_cd;
      var query = [];

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

      var url = URL_API + '/api/s04/getCompNameHiddenDealerS04';

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

      $.ajax({
        url: url,
        method: 'POST',
        timeout: 60000,
        data: {
          comp_code: comp_code_list
        },
        success: function(res) {
          thisTag.list_hidden_dealer_co_cd_popup = res.customers;
          thisTag.update(thisTag.list_hidden_dealer_co_cd_popup);
          $('#popup-hidden-dealer-list').fadeIn();
        },
        error: function(err) {

        }
      });
    }
    this.validateExtensionUploadImage = function(className) {
      // validate extension
      var extension = $(className).val().replace(/^.*\./, '');
      if (extension == $(className).val()) {
          extension = '';
      } else {
          extension = extension.toLowerCase();
      }

      if($.inArray(extension, ['jpeg', 'jpg', 'png', 'gif', '']) == -1) {
        return false;
      }
      return true;
    }
    this.validateSizeUploadImage = function(className) {
      if(!className) {
        return false;
      }
      var size = $(className)[0].files[0].size;
      if(size > 3145728) {
        return false;
      }
      return true;
    }
    this.checkCampaignEditTrue = function(dealer_co_code, member_type) {
      if(thisTag.ecUserInfo.member_type == 0 || dealer_co_code == thisTag.ecUserInfo.kikan_code && member_type != 0) {
        return true;
      }
      return false;
    }
    this.checkCampaignEditFalse = function(member_type) {
      if(parseInt(thisTag.ecUserInfo.member_type) > 0 && member_type == 0) {
        return true;
      }
      return false;
    }
    this.checkHiddenDealerCoCd = function(hidden_dealer_co_cd) {
      if($.inArray(thisTag.ecUserInfo.kikan_code, hidden_dealer_co_cd) != -1) {
        return true;
      }
      return false;
    }
  </script>
  <script>
  DatepickerIntialize();
  </script>

</campaign-config>
