$(document).on('turbolinks:load', function () {
  if ($('body.admins-multiple-school-reports-index-page').length > 0) {
    var baseOptions = {
      autoclose: true,
      language: 'zh-CN',
      format: 'yyyy-mm-dd',
      startDate: '2017-04-01',
      endDate: '-1d'
    }

    var defineDateRangeSelect = function (element) {
      $(element).datepicker(baseOptions);
    };

    defineDateRangeSelect("#begin_at");
    defineDateRangeSelect("#end_at");

    $('.export-action').on('click', function () {
      var form = $(".multiple-school-report-list-form .search-form")
      var exportLink = $(this);
      var school = form.find("[name='school']").val();
      var begin_at = form.find("input[name='begin_at']").val();
      var end_at = form.find("input[name='end_at']").val();
      var search_type = form.find("[name='search_type']").val();

      var url = exportLink.data("url").split('?')[0] + "?school=" + school + "&begin_at=" + begin_at + "&end_at=" + end_at + "&search_type=" + search_type;
      window.open(url);
    });


    $("#school").select2({
      placeholder: '请选择学校',
      allowClear: true,
       ajax: {
         url: "/admins/multiple_school_reports/school",
         dataType: 'json',
         delay: 500,
         data: function (params) {
           return {
             q: params.term, // search term
             page: params.page
           };
         },
         processResults: function (data, params) {
           params.page = params.page || 1;

           return {
             results: data.items,
             pagination: {
               more: (params.page * 10) < data.total_count
             }
           };
         },
         cache: true
       },
       escapeMarkup: function (markup) {
         return markup;
       }, 
       minimumInputLength: 1,
       templateResult: formatRepoProvince,
       templateSelection: formatRepoProvince 
     });

    function formatRepoProvince(repo) {
      return repo.name || repo.text;
    }
  }
})