{% load i18n static %}
{% load common %}
<div style="width:1200px;height:400px;overflow:hidden;">
  <div class="layui-row layui-col-space5 employee-row">
    <div class="layui-col-md3" style="width: 240px">
      <div class="layui-tab" style="padding-top: 0px;">
        <ul class="layui-tab-title">
          <li class="layui-this">{% trans 'employee_department_filter' %}</li>
          <li>{% trans 'employee_area_filter' %}</li>
            <li>{% trans 'employee_position_filter' %}</li>
        </ul>
          <div class="layui-tab-content">
              <div class="layui-tab-item layui-show">
              <div id="employee-department-tree-container" class="layui-card">
                <div id="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>
                  {% trans 'Department Filter' %}
                </div>
                <div class="layui-card-body">
                  <ul id="employee-department-tree" class="ztree ztree-pure" style="overflow: scroll"></ul>
                </div>
              </div>
              </div>
              <div class="layui-tab-item">
                  <div id="employee-area-tree-container" class="layui-card">
                    <div id="area-tree-control" class="layui-card-header" style="background-color: #f2f2f2">
                        <span class="" name="all"><a href="javascript:void(0);" title="{% trans 'area_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 'area_tree_multipleSelect' %}"><i
                        class="fa fa-fw fa-list"></i></a></span>
                        <span name="sub"><a href="javascript:void(0);" title="{% trans 'area_tree_selectSubArea' %}"><i
                         class="fa fa-fw fa-sitemap"></i></a></span>
                        {% trans 'Area Filter' %}
                    </div>
                      <div class="layui-card-body">
                        <ul id="employee-area-tree" class="ztree ztree-pure" style="overflow: scroll"></ul>
                      </div>
                  </div>
              </div>
               <div class="layui-tab-item">
                  <div id="employee-position-tree-container" class="layui-card">
                    <div id="pos-tree-control" class="layui-card-header" style="background-color: #f2f2f2">
                        <span class="" name="all"><a href="javascript:void(0);" title="{% trans 'position_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 'position_tree_multipleSelect' %}"><i
                        class="fa fa-fw fa-list"></i></a></span>
                        <span name="sub"><a href="javascript:void(0);" title="{% trans 'position_tree_selectSubPosition' %}"><i
                         class="fa fa-fw fa-sitemap"></i></a></span>
                        {% trans 'Position Filter' %}
                    </div>
                      <div class="layui-card-body">
                        <ul id="employee-position-tree" class="ztree ztree-pure" style="overflow: scroll"></ul>
                      </div>
                  </div>
              </div>
          </div>
      </div>
    </div>

    <div id="id-frame-unselect-container" class="layui-col-md6" style="width: auto">
      <div class="layui-card-header" style="background-color: #f2f2f2">
        <div class="layui-form employee-frame-search-form">
          <div class="layui-form-item">
            <div class="layui-inline">
              <div class="layui-input-inline">
                <input id="frameSearch" type="text"
                       placeholder="{% trans 'employee_frame_employeeSearchPlaceholder' %}" name="frame-search"
                       autocomplete="off"
                       class="layui-input">
              </div>
            </div>
            <div class="layui-inline">
              <div class="button-3d" lay-submit="" lay-filter="emp-frame-search" style="background-color: #f2f2f2;">
                <i class="fa fa-fw fa-search"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="layui-card-body">
        <table id="id-employee-frame-unselect" class="layui-hide" lay-filter="employee-unselect"></table>
      </div>
    </div>
    <div id="id-frame-selected-container" class="layui-col-md3">
      <div class="layui-card-header" style="background-color: #f2f2f2;width: 486px">
        {% trans 'employee_frame_selectedEmployee' %}<span id="selected_count"
                                                           style="padding: 0 5px;color: #5FB878">0</span>
      </div>
      <div class="layui-card-body">
        <table id="id-employee-frame-selected" class="layui-hide" lay-filter="employee-selected"></table>
        <input type="hidden" id="employee-frame-selected-container">
        <input type="hidden" id="employeeFrameSelectedDetailContainer">
        <div id="employee_pool"></div>
      </div>
    </div>
  </div>
</div>
<script>
  $(function () {
    var global_pm_codes = [],
      table_data = [],
      pageData = [],
      unselect_opts = {
        id: "id-employee-frame-unselect"
        , elem: "#id-employee-frame-unselect"
        , cellMinWidth: 80
        , height: '340'
        , width: '460'
        , page: {
          layout: ['limit', 'count',  'prev', 'next', 'skip']
          , limits: [20, 50, 80, 100, 200]
          , limit: 50
          , curr: 1
        }
        , request: {
          limitName: "page_size"
          , pageName: "page"
        }
        , text: {
          none: gettext("none_data")
        }
        , cols: [[
          {field: 'id', width: "40", type: "checkbox"}
          , {field: 'emp_code', title: "{% trans 'emp_field_employeeCode' %}", width: "80"}
          , {field: 'first_name', title: "{% trans 'emp_field_firstName' %}", width: "120"}
          , {field: 'last_name', title: "{% trans 'emp_field_lastName' %}", width: "120"}
          , {field: 'dept_name', title: "{% trans 'employee_field_department' %}", width: "120"}
        ]]
        , url: "/personnel/api/employee/filter_by_resign_emp/"
        , smartReloadModel: true
        , done: function (res, curr, count) {
          pageData = res;
          //this.where = {};
          var height = $("#id-frame-unselect-container div.layui-table-view").height();
          $("#employee-department-tree-container").height(height);
          $("#employee-department-tree").height(height - 15);
          $("#employee-area-tree-container").height(height);
          $("#employee-area-tree").height(height - 15);

          $("#employee-position-tree-container").height(height);
          $("#employee-position-tree").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 < global_pm_codes.length; j++) {
              if (res.data[i].id === global_pm_codes[j]) {
                //这里才是真正的有效勾选
                res.data[i]["LAY_CHECKED"] = 'true';
                //找到对应数据改变勾选样式，呈现出选中效果
                var index = res.data[i]['LAY_TABLE_INDEX'],
                  checkbox = $('#id-frame-unselect-container .layui-table tr[data-index=' + index + '] input[type="checkbox"]');
                checkbox.prop('checked', true);
                checkbox.next().addClass('layui-form-checked');
              }
            }
          }
          //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
          var checkStatus = layui.table.checkStatus('employee-unselect');
          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');
          }
        }
      };
    var selected_opts = {
      id: "id-employee-frame-selected"
      , elem: "#id-employee-frame-selected"
      , cellMinWidth: 80
      , height: '340'
      , width: '485'
      , page: false
      , text: {
        none: gettext("none_data")
      }
      , cols: [[
        {field: 'id', title: "ID", width: "40", type: "checkbox"}
        , {field: 'emp_code', title: "{% trans 'emp_field_employeeCode' %}", width: "80", sort: true}
        , {field: 'first_name', title: "{% trans 'emp_field_firstName' %}", width: "120", sort: true}
        , {field: 'last_name', title: "{% trans 'emp_field_lastName' %}", width: "120", sort: true}
        , {field: 'dept_name', title: "{% trans 'employee_field_department' %}", width: "120"}
      ]]
      , data: []
      , smartReloadModel: true
      , done: function (res, curr, count) {
        // console.log('reload id-employee-frame-selected')
        // 调用reload的时候需要刷新
        global_pm_codes = [];
        for (var i = 0, n = 0; i < res.data.length; i++) {
          global_pm_codes.push(res.data[i].id)
        }
        var selected = layui.table.checkStatus('id-employee-frame-selected').data;
        $("#selected_count").html(selected.length);
        var selectedIDs = [], display = [];
        var tmp = '';
        selected.forEach(function (item, index) {
          selectedIDs.push(item.id);
          display.push(item.first_name ? item.first_name : item.emp_code);
          tmp += '<input type="hidden" name="employee" value="' + item.id + '"/>';
        });
        $("#employee_pool").html(tmp);
        $("#employee-frame-selected-container").val(selectedIDs.join(','));
        $("#employeeFrameSelectedDetailContainer").val(display.join(','));
      }
    };
    layui.use(['table', 'form', 'element', 'laydate', 'tablePlug'], function () {
      var table = layui.table, form = layui.form, laydate = layui.laydate, tablePlug = layui.tablePlug;
      var unselectTB = table.render(unselect_opts);
      var selectedTB = table.render(selected_opts);
      var zTree_dept = null;
      var zTree_area = null;
      var zTree_pos = null;
      tablePlug.smartReload.enable(true);

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

      function refreshEmployee() {
        var nodes_dept = zTree_dept.getCheckedNodes(true);
        var nodes_area = zTree_area.getCheckedNodes(true);
        var nodes_pos = zTree_pos.getCheckedNodes(true);
        var deptID = [];
        var areaID = [];
        var posID = [];
        nodes_dept.forEach(function (item) {
          deptID.push(item.id);
        });
        nodes_area.forEach(function (item) {
          areaID.push(item.id);
        });
        nodes_pos.forEach(function (item) {
          posID.push(item.id);
        });
        table.reload(unselectTB.config.id, {where: {departments: deptID.join(','), areas: areaID.join(','), positions:posID.join(',')}, page: {curr: 1}});
      }

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

        function onCheck(event, treeId, treeNode) {
          refreshEmployee();
        }

        function onClick(event, treeId, treeNode) {
          zTree_area.checkNode(treeNode, !treeNode.checked, false, false);
          refreshEmployee();
        }

        $.ajax({
          url: "{% url 'biotime:personnel_area_tree_nodes' %}",
          type: "GET",
          dataType: "json",
          success: function (nodes) {
            zTree_area = $.fn.zTree.init($("#employee-area-tree"), setting, nodes);
          }
        });
      }

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

        function onCheck(event, treeId, treeNode) {
          refreshEmployee();
        }

        function onClick(event, treeId, treeNode) {
          zTree_dept.checkNode(treeNode, !treeNode.checked, false, false);
          refreshEmployee();
        }

        $.ajax({
          url: "{% url 'biotime:personnel_department_tree_nodes' %}",
          type: "GET",
          dataType: "json",
          success: function (nodes) {
            zTree_dept = $.fn.zTree.init($("#employee-department-tree"), setting, nodes);
          }
        });
      }

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

        function onCheck(event, treeId, treeNode) {
          refreshEmployee();
        }

        function onClick(event, treeId, treeNode) {
          zTree_pos.checkNode(treeNode, !treeNode.checked, false, false);
          refreshEmployee();
        }

        $.ajax({
          url: "{% url 'biotime:personnel_position_tree_nodes' %}",
          type: "GET",
          dataType: "json",
          success: function (nodes) {
            zTree_pos = $.fn.zTree.init($("#employee-position-tree"), setting, nodes);
          }
        });
      }

      area_tree();
      department_tree();
      pos_tree();

      $("#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);
              refreshEmployee();
            }
          } else if (name === 'mul') {
            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);
              refreshEmployee();
            }
          } 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();
      });

      $("#dept-tree-control span").click(function () {
        var name = $(this).attr('name');
        if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
          if (name === 'all') {
            if (zTree_dept.setting.check.chkStyle === 'checkbox') {
              zTree_dept.checkAllNodes(false);
              refreshEmployee();
            }
          } else if (name === 'mul') {
            zTree_dept.setting.check.chkStyle = 'radio';
          } else if (name === "sub") {
            zTree_dept.setting.check.chkboxType = {"Y": "", "N": ""};
          }
        } else {
          $(this).addClass('selected');
          if (name === 'all') {
            if (zTree_dept.setting.check.chkStyle === 'checkbox') {
              zTree_dept.checkAllNodes(true);
              refreshEmployee();
            }
          } else if (name === 'mul') {
            zTree_dept.setting.check.chkStyle = 'checkbox';
          } else if (name === "sub") {
            zTree_dept.setting.check.chkboxType = {"Y": "s", "N": "s"};
          }
        }
        zTree_dept.refresh();
      });

       $("#pos-tree-control span").click(function () {
        var name = $(this).attr('name');
        if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
          if (name === 'all') {
            if (zTree_pos.setting.check.chkStyle === 'checkbox') {
              zTree_pos.checkAllNodes(false);
              refreshEmployee();
            }
          } else if (name === 'mul') {
            zTree_pos.setting.check.chkStyle = 'radio';
          } else if (name === "sub") {
            zTree_pos.setting.check.chkboxType = {"Y": "", "N": ""};
          }
        } else {
          $(this).addClass('selected');
          if (name === 'all') {
            if (zTree_pos.setting.check.chkStyle === 'checkbox') {
              zTree_pos.checkAllNodes(true);
              refreshEmployee();
            }
          } else if (name === 'mul') {
            zTree_pos.setting.check.chkStyle = 'checkbox';
          } else if (name === "sub") {
            zTree_pos.setting.check.chkboxType = {"Y": "s", "N": "s"};
          }
        }
        zTree_pos.refresh();
      });
      $("#frameSearch").keypress(function (event) {
        if (event.keyCode === 13) {
          var alias = $(this).val();
          table.reload(unselectTB.config.id, {where: {search: alias}});
        }
      });
      form.on('submit(emp-frame-search)', function (data) {
        var key_world = data.field['frame-search'];
        if (key_world && key_world.length > 0) {
          table.reload(unselectTB.config.id, {
            where: {
              search: key_world
            },
            page: {
              curr: 1
            }
          });
        } else {
          table.reload(unselectTB.config.id, {
            where: {
              search: undefined
            }
          });
        }
      });

      table.on('checkbox(employee-unselect)', function (obj) {
        var selected = table.checkStatus(selectedTB.config.id).data;
        var selectedID = [];
        selected.forEach(function (item, index) {
          selectedID.push(item.id);
        });
        var empSelectedID = [];
        var empSelected = [];
        var i;
        if (!obj.checked) {
          if (obj.type === 'one') {
            selected.splice(selectedID.indexOf(obj.data.id), 1);
            for (i = 0; i < global_pm_codes.length; i++) {
              if (global_pm_codes[i] === obj.data.id) {
                global_pm_codes.remove(i);
              }
            }
          } else if (obj.type === 'all') {
            pageData.data.forEach(function (item, index) {
              for (var i = 0; i < selected.length; i++) {
                if (selected[i].id === item.id) {
                  selected.remove(i);
                  break;
                }
              }
              {#selected.splice(selectedID.indexOf(item.id), 1);#}
            });
            for (var j = 0; j < table_data.length; j++) {
              for (i = 0; i < global_pm_codes.length; i++) {
                if (global_pm_codes[i] === table_data[j].id) {
                  global_pm_codes.remove(i);
                  break;
                }
              }
            }
          }
          selected.forEach(function (item, index) {
            empSelectedID.push(item.id);
            empSelected.push($.extend(item, {LAY_CHECKED: true}));
          });
        } else {
          selected.forEach(function (item, index) {
            if (item.id !== undefined && empSelectedID.indexOf(item.id) === -1) {
              empSelectedID.push(item.id);
              empSelected.push($.extend(item, {LAY_CHECKED: true}));
            }
          });
          var curSelect = table.checkStatus(unselectTB.config.id).data;
          curSelect.forEach(function (item, index) {
            if (item.id !== undefined && empSelectedID.indexOf(item.id) === -1) {
              empSelectedID.push(item.id);
              empSelected.push($.extend(item, {LAY_CHECKED: true}));
            }
            if (!global_pm_codes.includes(item.id)) {
              global_pm_codes.push(item.id);
            }
          });
        }
        table.reload(selectedTB.config.id, {data: empSelected, limit: empSelected.length, initSort: 'id'});
        var tmp = '', display = [];
        empSelected.forEach(function (item, index) {
          tmp += '<input type="hidden" name="employee" value="' + item.id + '"/>';
          display.push(item.first_name ? item.first_name : item.emp_code);
        });
        $("#employee_pool").html(tmp);
        $("#selected_count").html(empSelected.length);
        $("#employee-frame-selected-container").val(empSelectedID.join(','));
        $("#employeeFrameSelectedDetailContainer").val(display.join(','));
      });
      table.on('checkbox(employee-selected)', function (obj) {
        var selected = table.checkStatus(selectedTB.config.id).data;
        $("#selected_count").html(selected.length);
        var selectedIDs = [], display = [];
        var tmp = '';
        selected.forEach(function (item, index) {
          selectedIDs.push(item.id);
          display.push(item.first_name ? item.first_name : item.emp_code);
          tmp += '<input type="hidden" name="employee" value="' + item.id + '"/>';
        });
        $("#employee_pool").html(tmp);
        $("#employee-frame-selected-container").val(selectedIDs.join(','));
        $("#employeeFrameSelectedDetailContainer").val(display.join(','));
      });
    });
  });
</script>
