{% load i18n static %}
{% load common %}
<div id="{{ model_name }}_csrf_token">
  {% csrf_token %}
</div>
<div id="{{ model_name }}_fluid" class="layui-fluid">
  <div class="layui-row layui-col-space15" style="margin-bottom: 0px">
    <div class="layui-col-md2">
      <div class="layui-tab" style="padding-top: 20px;">
        <ul class="layui-tab-title">
          <li class="layui-this">{% trans 'employee_department_filter' %}</li>
          <li>{% trans 'employee_area_filter' %}</li>
        </ul>
        <div class="layui-tab-content">
          <div class="layui-tab-item layui-show">
            <div id="{{ model_name }}-tree-container" class="layui-card">
            <div  id="{{ model_name }}-dept-tree-control" class="layui-card-header " style="background-color: #f2f2f2">
            <span class="" name="all"><a href="javascript:void(0);" title="{% trans 'department_tree_selectAll' %}"><i
                class="fa fa-fw fa-check-square-o"></i></a></span>
            <span class="selected" name="mul"><a href="javascript:void(0);" title="{% trans 'department_tree_multipleSelect' %}"><i
                class="fa fa-fw fa-list"></i></a></span>
            <span name="sub"><a href="javascript:void(0);" title="{% trans 'department_tree_selectSubDepartment' %}"><i
                class="fa fa-fw fa-sitemap"></i></a></span>
            </div>
            <div class="layui-card-body">
                <ul id="{{ model_name }}-tree" class="ztree ztree-pure" style="overflow-y: auto"></ul>
            </div>
            </div>
          </div>
          <div class="layui-tab-item">
            <div id="{{ model_name }}-tree-container" class="layui-card">
              <div  id="{{ model_name }}-area-tree-control" class="layui-card-header" style="background-color: #f2f2f2">
                <span class="" name="all"><a href="javascript:void(0);" title="{% trans 'department_tree_selectAll' %}"><i
                    class="fa fa-fw fa-check-square-o"></i></a></span>
                <span class="selected" name="mul"><a href="javascript:void(0);" title="{% trans 'department_tree_multipleSelect' %}"><i
                    class="fa fa-fw fa-list"></i></a></span>
                <span name="sub"><a href="javascript:void(0);" title="{% trans 'area_tree_selectSubDepartment' %}"><i
                    class="fa fa-fw fa-sitemap"></i></a></span>
              </div>
              <div class="layui-card-body">
                <ul id="{{ model_name }}-tree-area" class="ztree ztree-pure" style="overflow-y: auto"></ul>
              </div>
            </div>
          </div>
        </div>
    </div>
    </div>
    <div class="layui-col-md10">
      <div class="layui-card">
        <div class="layui-card-header" style="background-color: #ffffff;">
          <form id="{{ model_name }}-search-form" action="" class="layui-form fixed-search-form att-report-search-form">
            {% csrf_token %}
            <div class="layui-form-item">
              <div class="layui-inline">
                <label for="" class="layui-form-label">{% trans 'report_searchField_startDate' %}</label>
                <div class="layui-input-inline">
                  <input id="{{ model_name }}-start-date" type="text" name="start_date"
                         lay-verify="required"
                         autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <label for="" class="layui-form-label">{% trans 'report_searchField_endDate' %}</label>
                <div class="layui-input-inline">
                  <input id="{{ model_name }}-end-date" type="text" name="end_date"
                         lay-verify="required"
                         autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline" id="{{ model_name }}_search_employee">
                <label for="" class="layui-form-label">{% trans 'report_searchField_employee' %}</label>
                <div class="layui-input-inline">
                  <div class="layui-form-select">
                    <div class="layui-select-title">
                      <input id="{{ model_name }}-employee" type="text" autocomplete="off" class="layui-input" readonly>
                      <i id="{{ model_name }}-employee-select" class="layui-edge"></i>
                    </div>
                  </div>
                </div>
              </div>
              <div class="layui-inline">
                <div class="button-3d" lay-submit=""
                     lay-filter="{{ model_name }}-search">
                  <i class="fa fa-fw fa-search"></i>
                </div>
              </div>
            </div>
            <div class="layui-hide"><input id="{{ model_name }}-selected-emp-container" type="hidden"></div>
            <div class="layui-hide"><input id="{{ model_name }}SelectedEmployeeDetail" type="hidden"></div>
          </form>
        </div>
        <table id="id_grid_{{ model_name }}" class="layui-hide" lay-filter="{{ model_name }}"></table>
        <script type="text/html" id="{{ model_name }}_toolbar">
          <div class="layui-btn-container grid-toolbar" style="">
            <ul class="layui-nav"></ul>
          </div>
        </script>
      </div>
    </div>
  </div>
</div>
<script>
  $(function () {
    var csrf_token= $("#{{ model_name }}_csrf_token").find("input").first().attr("value")
    var opts = {
      id: "id_grid_{{ model_name }}"
      , elem: "#id_grid_{{ model_name }}"
      , cellMinWidth: 80
      , height: 'full-180'
      , page: {
        layout: ['refresh', 'limit', 'prev', 'page', 'next', 'count', 'skip']
        , curr: 1
        , limits: [20, 50, 80, 100, 200]
        , limit: 50
      }
      , where: {
        csrfmiddlewaretoken: csrf_token
      }
      , method: 'post'
      , toolbar: '#{{ model_name }}_toolbar'
      , defaultToolbar: []
      , smartReloadModel: true
      , request: {
        pageName: 'page',
        limitName: 'page_size'
      }
      , text: {
        none: gettext("none_data")
      }
      , done: function (res, curr, count) {
        //this.where = {page:{curr:curr}};
        setTimeout(function () {
          $.fn.trigger_action_auto(opts.model, 'fit');
        }, 10);
        var height = $("#{{ model_name }}_fluid div.layui-table-view").height();
        $("#{{ model_name }}-tree-container").height(height);
        $("#{{ model_name }}-tree").height(height - 5);
        $("#{{ model_name }}-tree-area").height(height - 5);
      }
    };
    layui.use(['table', 'form', 'element', 'laydate', 'tablePlug'], function () {
      var table = layui.table, form = layui.form, laydate = layui.laydate, tablePlug = layui.tablePlug,
        element = layui.element;
      tablePlug.smartReload.enable(true);
      form.render();
      {% block search_form_init %}
      var date = new Date();
      var startDate = laydate.render({
        elem: '#{{ model_name }}-start-date',
        type: 'date',
        value: date.getFullYear() + '-' + leftInsertZero(date.getMonth() + 1) + '-01',
        done: function (value, date) {
          endDate.config.min = {
            year: date.year,
            month: date.month - 1,
            date: date.date
          };
        }
      });
      var endDate = laydate.render({
        elem: '#{{ model_name }}-end-date',
        type: 'date',
        value: date.getFullYear() + '-' + leftInsertZero(date.getMonth() + 1) + '-' + leftInsertZero(date.getDate()),
        /*done: function (value, date) {
          startDate.config.max = {
            year: date.year,
            month: date.month - 1,
            date: date.date
          };
        }*/
      });
      {% endblock %}
      {% block opts_modify %}
        $.extend(opts, {});
      {% endblock %}
      {% autoescape off %}
      var colIndex = {};
      opts.cols[0].forEach(function(col, index){
        colIndex[col.field] = index;
      });
      var hidden_fields = {{ hidden_fields }};
      var ordered_fields = {{ ordered_fields }};
      hidden_fields.forEach(function(col){
        var index = colIndex[col];
        opts.cols[0][index].hide = true;
      });
      if(ordered_fields.length > 0){
        var cols = [];
        ordered_fields.forEach(function(col){
          cols.push(opts.cols[0][colIndex[col]]);
        });
        opts.cols[0] = cols
      }
      var tb = table.render(opts);   //首次渲染？
      var zTree = null;
      var zTree_area = null;
      var url = '/payroll/api/report/{{ model_name }}/export/';
      var action_opts = {   //
        container: "#{{model_name}}_fluid",
        actionContainer: "#{{model_name}}_fluid" + " div.grid-toolbar",
        model: "{{model_name}}",
        table: table,
        tableId: "id_grid_{{model_name}}",
        form: form,
        element: element,
        curTable: tb,
        grid_opts: opts,
        actions: "",
        export_url: url,
        column_order_url:'/column_order/',
        disabled_fields_url: "/disabled_fields/",
        init_disabled_fields: hidden_fields,
        dimension: {height: "auto", width: "auto"},
        disabled_action_panel_east: ["history"],
        prefer_best_fit_op: 'best_fit',
        callback: {}
        , csrf_token: "{{ csrf_token }}"
      };
      $("#{{model_name}}_fluid" + " div.grid-toolbar").actions(action_opts);
      {% endautoescape %}
      function refreshReport(searchType) {
        //opts.page.curr = 1;
        //table.render(opts);
        var startDate = $("#{{ model_name }}-search-form input[name='start_date']").val();
        var endDate = $("#{{ model_name }}-search-form input[name='end_date']").val();
        if (startDate === "") {
          layer.msg(gettext("start_date_is_empty"));
          return false;
        }
        if (endDate === "") {
          layer.msg(gettext("end_date_is_empty"));
          return false;
        }
        if(new Date(startDate) > new Date(endDate)){
            layer.alert(gettext('end_date_can_not_greater_than_start_date'), {
                title: gettext('system_exception')
                , icon: 5
                , btn: gettext('btn_confirm')
            })
            return false;
        }
        var c = {start_date: startDate, end_date: endDate};
        if (searchType === 'd') {
          $("#{{ model_name }}-selected-emp-container").val('-1');
          $("#{{ model_name }}-employee").val("");
        }

        var nodes = zTree.getCheckedNodes(true);
        var deptID = [];
        nodes.forEach(function (item) {
          deptID.push(item.id);
        });
        if (deptID.length === 0) {
          deptID.push(-1);
        }
        c["departments"] = deptID.join(',');

        var emps = $("#{{ model_name }}-selected-emp-container").val();
        c["employees"] = emps;

        {% block columns_modify %}
        table.reload(tb.config.id, {where: c, page: {curr: 1}});
        $("#{{model_name}}_fluid" + " div.grid-toolbar").actions(action_opts);
        {% endblock %}
        form.on("submit({{ model_name }}-search)", function (data) {
          refreshReport('');
        });
      }   //freshReport

      function refreshReportByArea(searchType) {
        //opts.page.curr = 1;
        //table.render(opts);
        var startDate = $("#{{ model_name }}-search-form input[name='start_date']").val();
        var endDate = $("#{{ model_name }}-search-form input[name='end_date']").val();
        if (startDate === "") {
          layer.msg(gettext("start_date_is_empty"));
          return false;
        }
        if (endDate === "") {
          layer.msg(gettext("end_date_is_empty"));
          return false;
        }
        var c = {start_date: startDate, end_date: endDate};
        if (searchType === 'd') {
          $("#{{ model_name }}-selected-emp-container").val('-1');
          $("#{{ model_name }}-employee").val("");
        }

        var nodes = zTree_area.getCheckedNodes(true);
        var deptID = [];
        nodes.forEach(function (item) {
          deptID.push(item.id);
        });
        if (deptID.length === 0) {
          deptID.push(-1);
        }
        c["areas"] = deptID.join(',');

        var emps = $("#{{ model_name }}-selected-emp-container").val();
        c["employees"] = emps;

        {% block columns_modify1 %}
        tb = table.reload(tb.config.id, {where: c, page: {curr: 1}});
        $.extend(action_opts, {
            curTable: tb
        });
        $("#{{model_name}}_fluid" + " div.grid-toolbar").actions(action_opts);
        {% endblock %}
        form.on("submit({{ model_name }}-search)", function (data) {
          refreshReportByArea('');
        });
      }
      function onClick(event, treeId, treeNode) {
        if(treeId == "{{ model_name }}-tree") {
            zTree.checkNode(treeNode, !treeNode.checked, false, false);
            refreshReport('d');
        }else{
            zTree_area.checkNode(treeNode, !treeNode.checked, false, false);
            refreshReportByArea('d');
        }
      }

      function onCheck(event, treeId, treeNode) {
        if(treeId == "{{ model_name }}-tree") {
            refreshReport('d');
        }else{
            refreshReportByArea('d');
        }
      }


      function department_tree() {
        var setting = {
          view: {
            dblClickExpand: false,
            showIcon: false,
            showLine: true
          },
          data: {
            simpleData: {
              enable: true
            }
          },
          check: {
            enable: true,
            chkboxType: {"Y": "", "N": ""},
            chkStyle: 'checkbox',
            radioType: "all"
          },
          callback: {
            onClick: onClick
            , onCheck: onCheck
          }
        };
        $.ajax({
          url: "{% url 'biotime:personnel_department_tree_nodes' %}",
          type: "GET",
          dataType: "json",
          success: function (nodes) {
            zTree = $.fn.zTree.init($("#{{ model_name }}-tree"), setting, nodes);
          }
        });
        $.ajax({
          url: "{% url 'biotime:personnel_area_tree_nodes' %}",
          type: "GET",
          dataType: "json",
          success: function (nodes) {
            zTree_area = $.fn.zTree.init($("#{{ model_name }}-tree-area"), setting, nodes);
          }
        });
      }

      department_tree();

      $("#{{ model_name }}-employee").click(function () {
        $.ajax({
          url: "/personnel/filter_resign_employee/"
          , type: "GET"
          , dataType: "html"
          , success: function (response) {
            layer.open({
              title: gettext("employee_frame_title")
              , btn: [gettext("btn_confirm"), gettext("btn_cancel")]
              , area: ['auto', 'auto']
              , content: response
              , yes: function (index, layero) {
                var selectedEmp = $(layero).find("#employee-frame-selected-container").val();
                var selectedEmpDetail = $(layero).find("#employeeFrameSelectedDetailContainer").val();
                $("#{{ model_name }}-selected-emp-container").val(selectedEmp);
                $("#{{ model_name }}-employee").val(selectedEmpDetail);
                refreshReport('e');
                layer.close(index);
              }
            });
          }
        });
      });
      $("#{{ model_name }}-dept-tree-control span").click(function () {
        var name = $(this).attr('name');
        if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
          if (name === 'all') {
            if (zTree.setting.check.chkStyle === 'checkbox') {
              zTree.checkAllNodes(false);
              refreshReport('d');
            }
          } else if (name === 'mul') {
            var nodes = zTree.getCheckedNodes(true);
            zTree.checkAllNodes(false);
            if (nodes.length > 0) {
              zTree.checkNode(nodes[0], true, false, true);
            }
            zTree.setting.check.chkStyle = 'radio';
          } else if (name === "sub") {
            zTree.setting.check.chkboxType = {"Y": "", "N": ""};
          }
        } else {
          $(this).addClass('selected');
          if (name === 'all') {
            if (zTree.setting.check.chkStyle === 'checkbox') {
              zTree.checkAllNodes(true);
              refreshReport('d');
            }
          } else if (name === 'mul') {
            zTree.setting.check.chkStyle = 'checkbox';
          } else if (name === "sub") {
            zTree.setting.check.chkboxType = {"Y": "s", "N": "s"};
          }
        }
        zTree.refresh();
      });
      $("#{{ model_name }}-area-tree-control span").click(function () {
        var name = $(this).attr('name');
        if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
          if (name === 'all') {
            if (zTree_area.setting.check.chkStyle === 'checkbox') {
              zTree_area.checkAllNodes(false);
              refreshReportByArea('d');
            }
          } else if (name === 'mul') {
            var nodes = zTree_area.getCheckedNodes(true);
            zTree_area.checkAllNodes(false);
            if (nodes.length > 0) {
              zTree_area.checkNode(nodes[0], true, false, true);
            }
            zTree_area.setting.check.chkStyle = 'radio';
          } else if (name === "sub") {
            zTree_area.setting.check.chkboxType = {"Y": "", "N": ""};
          }
        } else {
          $(this).addClass('selected');
          if (name === 'all') {
            if (zTree_area.setting.check.chkStyle === 'checkbox') {
              zTree_area.checkAllNodes(true);
              refreshReportByArea('d');
            }
          } else if (name === 'mul') {
            zTree_area.setting.check.chkStyle = 'checkbox';
          } else if (name === "sub") {
            zTree_area.setting.check.chkboxType = {"Y": "s", "N": "s"};
          }
        }
        zTree_area.refresh();
      });
      $("#calculation_show_all").click(function () {
        table.reload(tb.config.id, {where: {}});
        department_tree();
      });
      form.on("submit({{ model_name }}-search)", function (data) {
        refreshReport('');
        refreshReportByArea('');
      });

// "#{{ model_name }}-employee"和"#{{ model_name }}-departmetn"时分别获取更新人员、部门数据点
// 点击搜索按钮时，refreshReport 执行数据获取，同时该函数里面 ‘ block columns_modify 这个标签，可在获取数据后动态修改表格
// opts表格配置项，每个子模板载 opts_modify 标签后，在var tb = table.render(opts)时第一次选择表格
// 导出渲染在后面通过action_opts渲染table中表的导出等action的url等

    });
  });
</script>