// 设备列表
$(function () {
  var ERROK = 200;
  var contextPath = $("#contextPath").val()
  var table;
  template.config("escape", false);
  var orgId = $("#orgId").attr('org__id');
  var tpl = {
    "addTpl": '<div class="dialog-wp">\
    <div class="mask"></div>\
    <div class="dialog dialog-account-con">\
      <div class="title-wp">\
        <span>新增企业类型</span>\
        <span class="close-btn"></button>\
      </div>\
      <div class="dialog-account-wp ">\
         <div class="account-list">\
          <%if(isAdmin == "true"){%>\
            <div class="account-item required clearfloat">\
              <div class="item-tip"><span class="red">*</span>校区：</div>\
              <div class="item-con">\
                <div class="layui-input-inline">\
                <input class="pop-select orgId layui-input" name="orgId" id="orgId" autocomplete="off" placeholder="请选择校区" />\
                <span class="select_wrap _hide"></span>\
              </div>\
            </div>\
            </div>\
          <%}%>\
          <%if(isAdmin  == "false"){%>\
            <input class="pop-select orgId layui-input" name="orgId" id="orgId" autocomplete="off" type="hidden" value="<%=orgId%>" org__id="<%=orgId%>"/>\
          <%}%>\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>企业类型名称：</div>\
            <div class="item-con">\
              <input  type="text" class="item-input companyType" placeholder="请输入企业类型名称">\
            </div>\
          </div>\
          <div class="account-item required clearfloat heiAu">\
            <div class="item-tip"><span class="red">*</span>功能权限：</div>\
            <div class="item-con" id="funcApply">\
              <%for(var j=0;j<funcList.length;j++){%>\
                <div class="checkbox-wp">\
                  <span class="checkbox-input">\
                    <input type="checkbox" id="wx-<%=j%>" class="check-item staple-food" data-id="<%=funcList[j].id%>"/>\
                    <span class="checkbox-inner"></span>\
                  </span>		\
                  <label class="checkbox-con" for="wx-<%=j%>"><%=funcList[j].name%></label>\
                </div>\
              <%}%>\
            </div>\
          </div>\
         </div>\
          <div class="dialog-btns">\
            <button class="sure-add-btn btn-red">确定</button>\
          </div>\
         </div>\
      </div>\
    </div>\
  </div>	',
    "modifyTpl": '<div class="dialog-wp">\
    <div class="mask"></div>\
    <div class="dialog dialog-account-con">\
      <div class="title-wp">\
        <span>修改企业类型</span>\
        <span class="close-btn"></button>\
      </div>\
      <div class="dialog-account-wp ">\
         <div class="account-list">\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>校区：</div>\
            <div class="item-con">\
              <div class="layui-input-inline">\
                <input class="pop-select orgId layui-input disabled" name="orgId" id="orgId" autocomplete="off" org__id="<%=orgId%>" value="<%=orgName%>" disabled/>\
              </div>\
            </div>\
          </div>\
          <div class="account-item required clearfloat">\
            <div class="item-tip"><span class="red">*</span>企业类型名称：</div>\
            <div class="item-con">\
              <input type="text" class="item-input companyType" value="<%=name%>" placeholder="请输入企业类型名称">\
            </div>\
          </div>\
          <div class="account-item required clearfloat heiAu">\
            <div class="item-tip"><span class="red">*</span>功能权限：</div>\
            <div class="item-con" id="funcApply">\
              <%for(var j=0;j<funcList.length;j++){%>\
                <div class="checkbox-wp">\
                  <span class="checkbox-input">\
                    <input type="checkbox" id="wx-<%=j%>" class="check-item staple-food" data-id="<%=funcList[j].id%>" <%if(funcList[j].checked){%>checked<%}%>/>\
                    <span class="checkbox-inner"></span>\
                  </span>		\
                  <label class="checkbox-con" for="wx-<%=j%>"><%=funcList[j].name%></label>\
                </div>\
              <%}%>\
            </div>\
          </div>\
          <div class="dialog-btns">\
            <button class="sure-add-btn btn-red">确定</button>\
          </div>\
         </div>\
      </div>\
    </div>\
  </div>',
  'delete': '<div class="account-item required clearfloat">\
      <div class="item-tip"><span class="red">*</span>通行权限：</div>\
      <div class="item-con">\
        <%for(var j=0;j<funcList.length;j++){%>\
          <div class="checkbox-wp">\
            <span class="checkbox-input">\
              <input type="checkbox" id="wx-<%=j%>" class="check-item staple-food" data-id="<%=funcList[j].id%>"/>\
              <span class="checkbox-inner"></span>\
            </span>		\
            <label class="checkbox-con" for="wx-<%=j%>"><%=funcList[j].itemname%></label>\
          </div>\
        <%}%>\
      </div>\
    </div>\
    <div class="account-item required clearfloat">\
    <div class="item-tip"><span class="red">*</span>所有校区通用：</div>\
      <div class="item-con">\
        <div class="radio-wp">\
          <span class="radio-input">\
            <input type="radio" id="zu" class="radio-item user-type" data-status="2" name="userType" checked/>\
            <span class="radio-inner"></span>\
          </span>		\
          <label class="radio-con" for="zu">个人账号</label>\
        </div>\
        <div class="radio-wp">\
          <span class="radio-input">\
            <input type="radio" id="zu1" class="radio-item user-type" data-status="1" name="userType"/>\
            <span class="radio-inner"></span>\
          </span>		\
          <label class="radio-con" for="zu1">管理员</label>\
        </div>\
      </div>\
    </div>\
    </div>'

  };
  var api = {
    init: function () {
      this.render();
      this.bindEvent();
    },
    render: function () {
      this.rendertable();
    },
    bindEvent: function () {
      var _this = this;
      //重置
      $(".set-btn").on("click", function () {
        var $orgId = $("#conditionform  .single-orgid");
        var $dom = $("#conditionform input,#conditionform select")
        if($orgId.length){
          $dom.val("").removeAttr('dep__id')
        }else{
          $dom.val("").removeAttr('org__id')
        }
        _this.againRenderTable({type:1});
      });
      //新增
      $(".add-ele-btn").on("click", function () {
        let funcList = []
        let orgId = $("#conditionform #orgId").attr('org__id')
        let isAdmin = $("#isAdmin").val()
        if(isAdmin == "false") {
          _this.getFuncList(orgId,function (data) {
            $("body").append(template.render(tpl.addTpl)({
              isAdmin: $("#isAdmin").val(),
              orgId: orgId,
              funcList: data
            }));
             //关闭弹窗
            $(".close-btn,.cancel-add-btn").on("click", function () {
              $(".dialog-wp").remove();
            });
            //确认添加
            $(".sure-add-btn").on("click", function () {
              let serviceId = ''
              let arr = []
              if (!$(".dialog-wp #orgId").attr('org__id')) {
                layer.msg("请选择校区");
                return false;
              }
              if (!$(".dialog-wp .companyType").val()) {
                layer.msg("请输入企业类型名称");
                return false;
              }
              $.each($('#funcApply input:checkbox:checked'),function(){
                arr.push($(this).attr('data-id'))
              });
              serviceId = arr.join(';')
              if (arr.length == 0) {
                layer.msg("请选择功能权限");
                return false;
              }
              _this.submitAdd(function () {
                $(".dialog-wp").remove();
                _this.againRenderTable();
              },serviceId);
            });
          })
        }else{
          $("body").append(template.render(tpl.addTpl)({
            isAdmin: $("#isAdmin").val(),
            orgId: orgId,
            funcList: funcList
          }));
           //关闭弹窗
            $(".close-btn,.cancel-add-btn").on("click", function () {
              $(".dialog-wp").remove();
            });
            //确认添加
            $(".sure-add-btn").on("click", function () {
              let serviceId = ''
              let arr = []
              if (!$(".dialog-wp #orgId").attr('org__id')) {
                layer.msg("请选择校区");
                return false;
              }
              if (!$(".dialog-wp .companyType").val()) {
                layer.msg("请输入企业类型名称");
                return false;
              }
              $.each($('#funcApply input:checkbox:checked'),function(){
                arr.push($(this).attr('data-id'))
              });
              serviceId = arr.join(';')
              if (arr.length == 0) {
                layer.msg("请选择功能权限");
                return false;
              }
              _this.submitAdd(function () {
                $(".dialog-wp").remove();
                _this.againRenderTable();
              },serviceId);
            });
        }
       
      });
      // 模糊搜索
      _this.search_fuzzy()
    },
    // 模糊搜索校区
    search_fuzzy: function(){
      var _this = this
      var default_option = {
        org_attrName:'org__id',
        com_attrName:'com__id',
        dep_attrName:'dep__id',
        org_spanName:'org__span',
        com_spanName:'com__span',
        dep_spanName:'dep__span',
        org_path:'/admin/templ/getOrgListByName',
        com_path:'/admin/templ/getVirList',
        dep_path:'/admin/templ/getDept',
        contextPath:$("#contextPath").val()
      }
      var option_1 = $.extend(true,{},default_option,{
        org_target:'.default-select#orgId'
      });
      var option_2 = $.extend(true,{},default_option,{
        org_target:'.pop-select#orgId'
      });
      
      function eve(option_,otherOption){
        var obj = $.extend(true, {}, option_, otherOption);
        var type = obj.type
        var _path, _target, _attrName, _spanName
        if(type == 1){
          _path = obj.org_path
          _target = obj.org_target
          _attrName = obj.org_attrName
          _spanName = obj.org_spanName
        }else if(type == 2){
          _path = obj.com_path
          _target = obj.com_target
          _attrName = obj.com_attrName
          _spanName = obj.com_spanName
        }else if(type == 3){
          _path = obj.dep_path
          _target = obj.dep_target
          _attrName = obj.dep_attrName
          _spanName = obj.dep_spanName
        }
        $('body').on("input",_target,function(event){
          var _this = $(this)
          var obj_input = $.extend(true,{}, obj,{"_this":_this});
          cjqt.search_fuzzy.event_input(_this,_attrName,_spanName,contextPath,_path,obj_input)
        });
        $('body').on("focus",_target,function(event){
          var _this = $(this)
          var obj_focus = $.extend(true,{},obj,{"_this":_this});
          cjqt.search_fuzzy.event_focus(_this,_attrName,_spanName,contextPath,_path,obj_focus)
        });
        $('body').on('blur',_target,function(event) {
          var _this = $(this)
          var obj_blur = $.extend(true,{},obj,{"_this":_this});
          cjqt.search_fuzzy.event_blur(_this,_attrName,obj_blur)
        });
        $('body').on('click',_target+'~.select_wrap>.'+_spanName, function(event) {
          event.preventDefault();
          event.stopPropagation();
          /* Act on the event */
          var _this = $(this)
          var obj_click = $.extend(true,{},obj,{"_this":_this});
          cjqt.search_fuzzy.event_click(_this,_attrName,_target,obj_click)
        });

      }
      // 搜索联动
      eve(option_1,{type:1})
      // 新增、修改联动
       eve(option_2,{
        type:1,
        click_callback:function(){
          console.log('change')
          var orgId = $('.pop-select#orgId').attr('org__id')
          _this.getFuncList(orgId,function(data){
            let html = ''
            for(let i=0; i<data.length; i++){
              html += "<div class='checkbox-wp'><span class='checkbox-input'><input type='checkbox' id='wx-"+i+"' class='check-item staple-food' data-id='"+data[i].id+
              "'/><span class='checkbox-inner'></span></span><label class='checkbox-con' for='wx-"+i+"'>"+data[i].name+"</label></div>"
            }
            $("#funcApply").html(html)
          })
        }
      })
    },

    rendertable: function () {
      var _this = this;
      layui.use(['table', 'laydate', 'form'], function () {
        table = layui.table;
        var form = layui.form,
          layer = layui.layer,
          laydate = layui.laydate;
        //日期
        laydate.render({
          elem: '#date1'
        });
        //方法级渲染
        table.render({
          elem: '#LAY_table_user',
          url: $("#contextPath").val() + "/admin/virPerm/virPermList",
          method: "post",
          where: {
            orgId: $("#conditionform #orgId").attr('org__id'),
            permType: '0',
            virPermName: ''
          },
          skin: 'nob' //行边框风格
            ,
          even: true //开启隔行背景
            ,
          size: 'lg' //小尺寸的表格
            ,
          cols: [
            [{
              field: 'index',
              title: '序号',
              width: '80',
              templet: '#indexTpl'
            }, {
              field: 'orgName',
              title: '校区',
              width: 200
            }, {
              field: 'permName',
              title: '企业类型名称',
              minWidth: 200
            }, {
              field: 'funcListStr',
              title: '功能权限',
              minWidth: 200
            }, {
              field: 'userName',
              title: '创建人',
              minWidth: 120
            }, {
              field: 'createTime',
              title: '创建时间',
              width: 200
            }, {
              title: '操作',
              fixed: 'right',
              width: 120,
              align: 'center',
              templet: function (data) {
                var str = "<div class='operate'>";
                str += "<span class='op_edit_btn' lay-event='edit' data-id='"+data.id+"'><i class='edit'></i><i class='op_hover'>修改</i></span>";
                str += "<span class='op_del_btn' lay-event='del' data-id='"+data.id+"'><i class='delete'></i><i class='op_hover'>删除</i></span>";
                str += "</div>";
                return str;
              }
            }]
          ],
          id: 'testReload',
          page: true,
          response: {
            statusName: 'code' //数据状态的字段名称，默认：code
              ,
            statusCode: 200 //成功的状态码，默认：0
              ,
            countName: "count" //数据总数的字段名称，默认：count
              ,
            dataName: "data" //数据列表的字段名称，默认：data
          },
          request: {
            pageName: 'pageNo' //页码的参数名称，默认：page
              ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
          },
          done: function (res, curr, count) {
            $(".edit,.delete").mouseover(function(){
              $(this).next().show();
            })
            $(".edit,.delete").mouseout(function(){
              $(this).next().hide();
            })
            //如果是异步请求数据方式，res即为你接口返回的信息。
            //删除
            $(".op_del_btn").on("click", function () {
              var id = $(this).data("id");
              _this.ajaxDelTemp(id, function () {
                _this.againRenderTable();
              })
            });
            //修改
            $(".op_edit_btn").on("click", function () {
              var id = $(this).data("id");
              _this.ajaxDetail(id, function (data) {
                $("body").append(template.render(tpl.modifyTpl)(data));
                //关闭弹窗
                $(".close-btn,.cancel-add-btn").on("click", function () {
                  $(".dialog-wp").remove();
                });
                //确认添加
                $(".sure-add-btn").on("click", function () {
                  let serviceId = ''
                  let arr = []
                  if (!$(".dialog-wp .companyType").val()) {
                    layer.msg("请输入企业类型名称");
                    return false;
                  }
                  $.each($('#funcApply input:checkbox:checked'),function(){
                    arr.push($(this).attr('data-id'))
                  });
                  serviceId = arr.join(';')
                  if (arr.length == 0) {
                    layer.msg("请选择功能权限");
                    return false;
                  }
                  _this.submitAdd(function () {
                    $(".dialog-wp").remove();
                    layer.msg("修改成功！");
                    _this.againRenderTable();
                  }, serviceId, id);
                })
              });
            });
          }
        });
        //查询
        $('.search-btn').on('click', function () {
          _this.againRenderTable();
        });
      });
    },
    /**
     * 删除模板
     * @param id 模板id
     * @param callback
     */
    ajaxDelTemp: function (id, callback) {
      var str = "确认删除?";
      layer.confirm(str, {
        btn: ['确定', '取消']
      }, function (index, layero) {
        layer.close(index); //如果设定了yes回调，需进行手工关闭
        $.ajax({
          type: "post",
          url: $("#contextPath").val() + "/admin/virPerm/delVirPerm",
          data: {
            id: id
          },
          success: function (data) {
            if (data.code == 200) {
              callback();
            } else {
              layer.msg(data.msg)
            }
          },
          error: function () {
            // layer.msg('系统繁忙...')
          }
        });
      }, function (index) {

      });
    },

    /*重新渲染table*/
    againRenderTable: function (option) {
      var obj = $.extend(true, {}, option);
      var type =  obj.type || ''
      if(type == 1){
        table.reload('testReload', {
          where: {
            orgId: '',
            virPermName: '',
            permType: '0'
          },
          page: {
            curr: 1 //重新从第 1 页开始
          }
        });
      }else{
        table.reload('testReload', {
          where: {
            orgId: $("#conditionform #orgId").attr("org__id"),
            virPermName: $("#conditionform #virPermName").val(),
            permType: '0'
          },
          page: {
            curr: 1 //重新从第 1 页开始
          }
        });
      }
    },
    /**
     * 请求详情
     * @param id
     * @param callback
     */
    ajaxDetail: function (id, callback) {
      var _this = this;
      $.ajax({
        type: "post",
        url: contextPath + "/admin/virPerm/virPermInfo",
        data: {
          virPermId: id
        },
        success: function (data) {
          if (data.code == ERROK) {
            callback(data.data)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    /**
     * 新增或修改
     * @param callback
     * @param id
     */
    submitAdd: function (callback, serviceId, id) {
      var _this = this;
      $.ajax({
        type: "post",
        url: $("#contextPath").val() + "/admin/virPerm/addUpdateVirPerm",
        data: {
          id: id,
          serviceId: serviceId,
          virPermName: $(".dialog-wp .companyType").val(),
          permType: '0',
          orgId: $(".dialog-wp #orgId").attr('org__id')
        },
        dataType: "json",
        success: function (data) {
          if (data.code == 200) {
            callback();
          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
    },
    /**
     * 获取校区开启的功能权限列表
     * @param callback
     * @param orgId
     */
    getFuncList: function (orgId,callback) {
      $.ajax({
        type: "post",
        url: contextPath + "/admin/virPerm/openedFunctionPermissionList",
        data: {
          orgId: orgId
        },
        success: function (data) {
          if (data.code == ERROK) {
            console.log(data.data,'功能权限')
            callback(data.data)
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    }
  };
  api.init();
})