{% load i18n static %}
{% load common %}
<div id="tab_{{ model_name }}">
  <div id="calculation-container" 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="calculation-tree-container" class="layui-card">
        <div  id="calculation-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="calculation_tree" class="ztree ztree-pure" style="overflow-y: auto"></ul>
        </div>
        </div>
      </div>
      <div class="layui-tab-item">
        <div id="calculation-tree-container" class="layui-card">
        <div  id="calculation-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="calculation_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="calculation-emp" action="" class="layui-form fixed-search-form att-caculation-emp-form">
            {% csrf_token %}
            <div class="layui-form-item">
              <div class="layui-inline emp-query" style="margin-right:0px">
                <label for="" class="layui-form-label">{% trans 'emp_field_employeeCode' %}</label>
                <div class="layui-input-inline">
                  <input type="text" name="emp_code" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline emp-query" style="margin-right:0px">
                <label for="" class="layui-form-label">{% trans 'emp_field_firstName' %}</label>
                <div class="layui-input-inline">
                  <input type="text" name="first_name" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline" title="{% trans 'calculation_page_empSearch' %}">
                <div class="button-3d" lay-submit="" lay-filter="employee-search">
                  <i class="fa fa-fw fa-search fa-2x"></i>
                </div>
              </div>
              <div class="layui-inline" style="margin-right:0px">
                <label for="" class="layui-form-label">{% trans 'payroll_calculation_page_endDate' %}</label>
                <div class="layui-input-inline">
                  <input id="id_calculationEndDate" type="text" name="end_date" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline" title="{% trans 'menu_payroll_salary_report_calculator' %}">
                <div class="button-3d" lay-submit="" lay-filter="calculation">
                  <button type="button" value="calculation" id="calculate_btn" class="btn btn-md" style="background:#7ac143;">calculate</button>
                </div>
              </div>
              <div id="id_calculation_emp" class="layui-hide"></div>
              <div id="id_calculation_dept" class="layui-hide"></div>
            </div>
          </form>
        </div>
        <div class="layui-card-body">
          <table class="layui-hide" id="emp-frame" lay-filter="test"></table>
        </div>
      </div>
    </div>
  </div>
  <script>
    var gloable_pm_codes = new Array();// 勾选的pm_code集合
    var table_data = new Array();// 表格数据缓存
    layui.use(['table', 'form', 'laydate', 'tablePlug'], function () {
      var table = layui.table, form = layui.form, laydate = layui.laydate, tablePlug = layui.tablePlug;
      tablePlug.smartReload.enable(true);
      var date = new Date();
      var endDate = null;
      endDate = laydate.render({
        elem: '#id_calculationEndDate',
        type: 'month',
        value: date.getFullYear() + '-' + leftInsertZero(date.getMonth()+1)
      });
      form.render();
      var tb = table.render({
        id: "emp-frame"
        , elem: "#emp-frame"
        , defaultToolbar: []
        , cellMinWidth: 80
        , height: 'full-200'
        , loading: true
        , page: {
          layout: ['refresh', 'limit', 'prev', 'page', 'next', 'count', 'skip'],
          curr: 1
        }
        , smartReloadModel: false
        , done: function (res, curr, count) {
          //this.where = {};
          var height = $("#calculation-container div.layui-table-view").height();
          $("#calculation_form").height(height - 15);
          $("#calculation_tree").height(height - 15);
          $("#calculation_tree_area").height(height - 15);
          // 设置换页勾选之前的
            table_data = res.data;
            //在缓存中找到emp_code ,然后设置data表格中的选中状态
            //循环所有数据，找出对应关系，设置checkbox选中状态
            for(var i=0;i<res.data.length;i++){
                for(var j=0;j<gloable_pm_codes.length;j++){
                    if(res.data[i].id==gloable_pm_codes[j]){
                        //这里才是真正的有效勾选
                        res.data[i]["LAY_CHECKED"]='true';
                        //找到对应数据改变勾选样式，呈现出选中效果
                        var index= res.data[i]['LAY_TABLE_INDEX'];
                        $('#calculation-container .layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                        $('#calculation-container .layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                }
            }
            //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
            var checkStatus = table.checkStatus('test');
            if(checkStatus.isAll){
                $(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
            }
        }
        , limits: [5, 20, 50, 80, 100, 200]
        , limit: 50
        , request: {
          pageName: 'page',
          limitName: 'page_size'
        }
        , cols: [[
          {field: 'id', type: "checkbox"}
          , {field: 'emp_code', title: "{% trans 'emp_field_employeeCode' %}"}
          , {field: 'first_name', title: "{% trans 'emp_field_firstName' %}"}
          , {field: 'last_name', title: "{% trans 'emp_field_lastName' %}"}
          , {field: 'hire_date', title: "{% trans 'emp_field_hireDate' %}"}
          , {field: 'dept_name', title: "{% trans 'employee_field_department' %}"}
          , {field: 'position_name', title: "{% trans 'employee_field_position' %}"}
        ]]
        , url: "/personnel/api/employee/filter_by_enable_att/"
        , method: 'get'
        , text: {
          none: gettext('none_data')
        }
      });

      table.on('checkbox(test)', function (obj) {   //人员table中的选择
       if(obj.checked==true){
           if(obj.type=='one'){
               if (!gloable_pm_codes.includes(obj.data.id))
                    gloable_pm_codes.push(obj.data.id);
          }else{
               for(var i=0;i<table_data.length;i++){
                   if (!gloable_pm_codes.includes(table_data[i].id))
                        gloable_pm_codes.push(table_data[i].id);
               }
           }
       }else{
           if(obj.type=='one'){
               for(var i=0;i<gloable_pm_codes.length;i++){
                  if(gloable_pm_codes[i]==obj.data.id){
                       gloable_pm_codes.remove(i);
                   }
              }
           }else{
               for(var j=0;j<table_data.length;j++){
                    for(var i=0;i<gloable_pm_codes.length;i++){
                        if(gloable_pm_codes[i]==table_data[j].id){
                            gloable_pm_codes.remove(i);
                            break;
                        }
                    }
                }
           }
       }
    });

    //删除数组自定义函数
    Array.prototype.remove=function(dx)
    {
        if(isNaN(dx)||dx>this.length){return false;}
        for(var i=0,n=0;i<this.length;i++)
        {
            if(this[i]!=this[dx])
            {
                this[n++]=this[i]
            }
        }
        this.length-=1
    };

      var zTree = null;
      function refreshEmployee() {
        var nodes = zTree.getCheckedNodes(true);
        var deptID = [];
        nodes.forEach(function (item) {
          deptID.push(item.id);
        });
         var c = {departments:""};
        //if (deptID.length > 0 && zTree.getCheckedNodes(false).length > 0) {
        //  ext = {where: {departments: deptID.join(',')}};
        //}

        $("#calculation-emp").find('div.emp-query input').each(function () {
          var n = $(this).attr('name');
          var val = $(this).val();
          if (val) {
            ext['c'][n] = val;
          }
          else{
             ext['c'][n] = "";
          }
        });
      table.reload(tb.config.id, {where: c,page:{curr:1}});
      }

      var zTree_area = null;
      function refreshEmployeeByArea(){
        var nodes = zTree_area.getCheckedNodes(true);
        var deptID = [];
        nodes.forEach(function (item) {
          deptID.push(item.id);
        });
         var c = {areas:""};
        //if (deptID.length > 0 && zTree.getCheckedNodes(false).length > 0) {
        //  ext = {where: {departments: deptID.join(',')}};
        //}

        $("#calculation-emp").find('div.emp-query input').each(function () {
          var n = $(this).attr('name');
          var val = $(this).val();
          if (val) {
            ext['c'][n] = val;
          }
          else{
             ext['c'][n] = "";
          }
        });
      table.reload(tb.config.id, {where: c,page:{curr:1}});
      }
      function onClick(event, treeId, treeNode) {
        if(treeId == "calculation_tree") {
            zTree.checkNode(treeNode, !treeNode.checked, false, false);
            refreshEmployee();
        }else{
            zTree_area.checkNode(treeNode, !treeNode.checked, false, false);
            refreshEmployeeByArea();
        }

      }

      function onCheck(event, treeId, treeNode) {
        if(treeId == "calculation_tree") {
            refreshEmployee();
        }else{
            refreshEmployeeByArea();
        }
      }

      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($("#calculation_tree"), setting, nodes);
          }
        });
        $.ajax({
          url: "{% url 'biotime:personnel_area_tree_nodes' %}",
          type: "GET",
          dataType: "json",
          success: function (nodes) {
            zTree_area = $.fn.zTree.init($("#calculation_tree_area"), setting, nodes);
          }
        });
      }
      department_tree();
      $("#calculation_show_all").click(function () {
        table.reload(tb.config.id, {where: {}});
        department_tree();
      });
      var dataQuery = function () {
        var c = {departments:""};
        $("#calculation-emp").find('div.emp-query input').each(function () {
          var n = $(this).attr('name');
          var val = $(this).val();
          if (val) {
            c[n] = val;
          }
          else{
             c[n] = "";
          }
        });
        table.reload(tb.config.id, {where: c,page:{curr:1}});
        gloable_pm_codes = [];
      };
      $("#calculation-emp").find('div.emp-query input').each(function () {
        $(this).keypress(function (event) {
          if (event.keyCode === 13) {
            dataQuery();
          }
        });
      });
      form.on('submit(employee-search)', function (data) {  //人员search
        dataQuery();
      });
      form.on('submit(calculation)', function (data) {    // 计算器
        $("#id_calculation_emp").empty();
        $("#id_calculation_dept").empty();
        gloable_pm_codes.forEach(function (item) {
          $("#id_calculation_emp").append('<input name="emp" value="' + item + '"/>');
        });
        if(gloable_pm_codes.length == 0){
          var nodes = zTree.getCheckedNodes(true);
          nodes.forEach(function (item) {
            $("#id_calculation_dept").append('<input name="dept" value="' + item.id + '"/>');
          });
        }
        var loadIndex = layer.load(2);
        $("#calculation-emp").ajaxSubmit({
          url: "payroll/reportcalculator/",
          type: "POST",
          dataType: "json",
          success: function (callback) {
            if (callback.code < 0) {
              layer.msg(callback.msg, {icon: 5, time: 0, closeBtn: 2});
            } else {
              layer.msg(callback.msg, {icon: 1});
            }
            layer.close(loadIndex);
          },
          error: function () {
            layer.close(loadIndex);
          }
        });
      });
      $("#calculation-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);
              refreshEmployee();
            }
          } 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);
              refreshEmployee();
            }
          } else if (name == 'mul') {
            zTree.setting.check.chkStyle = 'checkbox';
          } else if (name == "sub") {
            zTree.setting.check.chkboxType = {"Y": "s", "N": "s"};
          }
        }
        zTree.refresh();
      });
      $("#calculation-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);
              refreshEmployeeByArea();
            }
          } 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);
              refreshEmployeeByArea();
            }
          } 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();
      });
    });
  </script>
</div>