/**
 * 用户信息
 */
$(function () {
  var contextPath = $("#contextPath").val();
  var tree = null;
  //菜单树setting配置
  var setting1 = {
    edit: {
      enable: true,
      editNameSelectAll: true,
      showRenameBtn: true
    },
    data: {
      simpleData: {
        enable: true
      }
    }
  };
  var tpl = {
    oneTpl: '	<div class="alertAdd alert1">\
    <div class="mask"></div>\
    <div class="alert-con">\
      <div class="title-wp"><span>新增一级功能</span><span class="close-btn"></span></div>\
      <div class="dialog-email-wp">\
        <div class="d-email-wrapper-top">\
          <div class="email-item">\
            <span class="tips">功能名称</span>\
            <input type="text" class="e-item-text funcName" placeholder="请输入功能名称">\
          </div>\
          <div class="email-item">\
            <span class="tips">排 序</span>\
            <input type="text" class="e-item-text sortNum" placeholder="请输入排序">\
          </div>\
          <div class="line"></div>\
          <div class="d-email-btns">\
            <button class="cancel btn-red bt_blue_middle">取消</button>\
            <button class="certain btn-red bl_yellow_big">确认</button>\
          </div>\
        </div>\
      </div>\
    </div>\
  </div>',
    twoTpl: '	<div class="alertAdd alert2">\
    <div class="mask"></div>\
    <div class="alert-con">\
      <div class="title-wp"><span>新增二级功能</span><span class="close-btn"></span></div>\
      <div class="dialog-email-wp">\
        <div class="d-email-wrapper-top">\
          <div class="email-item">\
            <span class="tips">功能名称</span>\
            <input type="text" class="e-item-text funcName" placeholder="请输入功能名称">\
          </div>\
          <div class="email-item">\
            <span class="tips">排 序</span>\
            <input type="text" class="e-item-text sortNum" placeholder="请输入排序">\
          </div>\
          <div class="email-item">\
            <span class="tips">U R L</span>\
            <input type="text" class="e-item-text urlLink" placeholder="请输入URL">\
          </div>\
          <div class="line"></div>\
          <div class="d-email-btns">\
            <button class="cancel btn-red bt_blue_middle">取消</button>\
            <button class="certain btn-red bl_yellow_big">确认</button>\
          </div>\
        </div>\
      </div>\
    </div>\
  </div>',
    thirdTpl: '	<div class="alertAdd alert3">\
  <div class="mask"></div>\
  <div class="alert-con">\
    <div class="title-wp"><span>新增三级功能</span><span class="close-btn"></span></div>\
    <div class="dialog-email-wp">\
      <div class="d-email-wrapper-top">\
        <div class="email-item">\
          <span class="tips">功能名称</span>\
          <input type="text" class="e-item-text funcName" placeholder="请输入功能名称">\
        </div>\
        <div class="email-item">\
          <span class="tips">功能编码</span>\
          <input type="text" class="e-item-text codeNum" placeholder="请输入功能编码">\
        </div>\
        <div class="email-item">\
          <span class="tips">功能权限</span>\
          <input type="text" class="e-item-text power" placeholder="请输入功能权限">\
        </div>\
        <div class="line"></div>\
        <div class="d-email-btns">\
          <button class="cancel btn-red bt_blue_middle">取消</button>\
          <button class="certain btn-red bl_yellow_big">确认</button>\
        </div>\
      </div>\
    </div>\
  </div>\
</div>'
  }
  var isApp = "0";
  $('.listMenu').on('click', 'li', function (event) {
    isApp = $(this).data('is');
    api.getData(isApp);
    console.log(isApp);
    if (!$(this).hasClass('layui-this')) {
      $(this).addClass('layui-this').siblings().removeClass('layui-this');
    }
  })
  var param = {
    id: '',
    systemcode: '',
    functionName: '',
    url: '',
    rightType: 0,
    treecode: '',
    parentcode: 0,
    orderNumber: '',
    isApp: isApp,
    perms: ''
  };
   var perm = '';
  // 数据获取
  var api = {
    getData: function (isApp) {
      $.ajax({
        url: contextPath + "/admin/function/funcList",
        data: {
          isApp: isApp
        },
        type: "POST",
        dataType: "json",
        success: function (data) {
          //替换返回json数据中的key值 供ztree展示数据
          let jsonData = data.data;
          for (let i = 0; i < jsonData.length; i++) {
            jsonData[i]["name"] = jsonData[i]["functionName"]; //'text'是需要的字段
            jsonData[i]["pId"] = jsonData[i]["parentcode"];
            delete jsonData[i]["functionName"]; //key是要替换为'text'的字段
            delete jsonData[i]["parentcode"];
          }
          $.fn.zTree.init($("#tree"), setting1, jsonData);
          let treeObj = $.fn.zTree.getZTreeObj("tree");
          let nodes = treeObj.transformToArray(treeObj.getNodes());
          perm = nodes[0].perms;
          let dataArr = [],
            arr = [];
            // api.get_user_info_list(arr);
            // console.log(arr,777);
          $.each(nodes, function (index, value) {
            // if (index != 0) {
            if (value.rightType == 0) {
              dataArr.push(value);
            }
            // }
          })
          console.log(dataArr, 888);
          api.get_user_info_list(dataArr);
        },
        error: function (data) {
          // alert("系统繁忙,加载失败..");
        }
      });
    },
    get_user_del: function (id) {
      $.ajax({
        type: "post",
        url: contextPath + "/admin/function/deleteFuncTion",
        data: {
          id: id
        },
        type: "POST",
        dataType: "json",
        success: function (data) {
          if (data.code == '200') {
            layer.msg(data.msg)
            api.getData(isApp);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    },
    get_user_info_list: function (jsonData) {
      layui.use('table', function () {
        var table = layui.table;
        table.render({
          elem: '#table_user_info',
          size: 'lg', //小尺寸的表格
          limit: 10,
          cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
          cols: [
            [{
              field: 'name',
              width: '33.33%',
              title: '一级功能',
              templet: function (data) {
                return "<div style='float:left;padding-left: 10px' class='operate'>" + data.name +
                  " </div><div class='operate frt' style='padding-right: 10px' data-right='1'  data-parent='" + data.id +
                  "' data-id='" + data.id + "' data-rightType='" + data.rightType + "' data-parentcode='" + data.pId +
                  "'  data-treecode='" + data.treecode + "'  data-name='" + data.name + "' data-order='" + data.orderNumber + "' data-perms='" + data.perms + "'><span class='op_edit_btn'>修改</span><span class='op_del_btn'>删除</span><span class='op_add_btn edit-style'>+新增二级</span></div>"
              }
            }, {
              field: 'name',
              width: '33.33%',
              title: '二级功能',
              templet: function (data) {
                let childOne = data.children;
                let templt = " ";
                if (childOne) {
                  for (var i = 0; i < childOne.length; i++) {
                    let jsondata = [],
                      indec = 1;
                    jsondata = childOne[i].children;
                    if (jsondata) {
                      indec = jsondata.length
                    }
                    templt += "<div class='layui-table-cell laytable-cell-1-name am' style='height:" + 50 * indec +
                      "px; line-height:" + 50 * indec + "px'><div style='float:left' class='operate'>" + childOne[i].name +
                      "</div><div class='operate frt'  data-right='2'  data-parent='" + childOne[i].id +
                      "' data-id='" + childOne[i].id + "' data-rightType='" + childOne[i].rightType + "' data-parentcode='" + childOne[i].pId +
                      "' data-treecode='" + childOne[i].treecode + "'  data-name='" + childOne[i].name + "'  data-order='" + childOne[i].orderNumber +
                      "'  data-url='" + childOne[i].url + "' data-perms='" + childOne[i].perms + "'><span class='op_edit_btn' style='line-height:" + 40 * indec +
                      "px'>修改</span><span class='op_del_btn'  style='line-height:" + 40 * indec + "px'>删除</span><span class='op_add_btn'>+新增三级</span></div></div>"
                  }
                }
                return templt
              }
            }, {
              field: 'name',
              width: '33.33%',
              title: '三级功能',
              templet: function (data) {
                let childOne = data.children;
                let templt1 = " ";
                if (childOne) {
                  for (var i = 0; i < childOne.length; i++) {
                    let jsondata = [];
                    jsondata = childOne[i].children;
                    if (jsondata) {
                      for (var j = 0; j < jsondata.length; j++) {
                        templt1 += "<div class='layui-table-cell laytable-cell-1-name am' style='height:50px;line-height:50px'><div style='float:left' class='operate'>" + jsondata[j].name +
                          "</div><div class='operate frt' data-id='" + jsondata[j].id + "'  data-parent='" + jsondata[j].pId +
                          "' data-rightType='" + jsondata[j].rightType + "' data-parentcode='" + jsondata[j].pId + "' data-treecode='" + data.treecode +
                          "' data-name='" + jsondata[j].name + "' data-code='" + jsondata[j].systemcode + "' data-perms='" + jsondata[j].perms + "'><span class='op_edit_btn'>修改</span><span class='op_del_btn'>删除</span></div></div>"
                      }
                    } else {
                      templt1 += "<div class='layui-table-cell laytable-cell-1-name am' style='height:50px;line-height:50px'><div style='float:left' class='operate'></div></div>"
                    }
                  }
                }
                return templt1
              }
            }]
          ],
          data: jsonData,
          id: 'reloadData',
          page: true,
          response: {
            statusName: 'code', //数据状态的字段名称，默认：code             
            // statusCode: 200, //成功的状 态码，默认：0        
            countName: "count", //数据总数的字段名称，默认：count            
            dataName: "data" //数据列表的字段名称，默认：data
          },
          done: function (res, curr, count) {

          }
        });
        
      });
    },
    get_add_func: function (param) {
      $.ajax({
        type: "post",
        url: contextPath + "/admin/function/saveOrUpdate",
        data: {
          id: param.id,
          systemcode: param.systemcode,
          functionName: param.functionName,
          url: param.url,
          rightType: param.rightType,
          treecode: param.treecode,
          parentcode: param.parentcode,
          orderNumber: param.orderNumber,
          isApp: param.isApp,
          perms: param.perms
        },
        success: function (data) {
          if (data.code == '200') {
            $('.funcName').val('');
            $('.sortNum').val('');
            $('.urlLink').val('');
            $('.codeNum').val('');
            $('.power').val('');
            $('.alertAdd').css('display', 'none');
            layer.msg(data.msg)
            api.getData(isApp);
          } else {
            layer.msg(data.msg)
          }
        },
        error: function (error) {
          layer.msg('error')
        }
      });
    }
  }
  api.getData(isApp);
  $('.close-btn').click(function () {
    console.log('取消')
    $('.alertAdd').hide()
  })
  // 事件处理新增一级功能
  $('.btn1').click(function () {
    $('.app-func .alert1').css("display", "block");
    $('.alert1 .power').val(perm)
    $('.alert1 .certain').unbind("click").click(function () {
      let funcName = $('.funcName').val();
      let sortNum = $('.sortNum').val();
      let perms = $('.power').val();
      if (!funcName) {
        layer.msg('功能名称必填');
        return false
      }
      if (!perms) {
        layer.msg('功能权限必填');
        return false
      }
      param.id = '';
      param.treecode = '';
      param.functionName = funcName;
      param.orderNumber = sortNum;
      param.isApp = isApp;
      param.rightType = 0;
      param.parentcode = 0;
      param.perms = perms;
      api.get_add_func(param);
    })
  })
  // 取消
  $('.close-btn').click(function () {
    $('.funcName').val('');
    $('.sortNum').val('');
    $('.urlLink').val('');
    $('.codeNum').val('');
    $('.power').val('');
    $('.alertAdd').css('display', 'none');
  })
  $('.cancel').click(function () {                                                                                                                                                                                                                                                                                                                                                                                                        
    $('.funcName').val('');
    $('.sortNum').val('');
    $('.urlLink').val('');
    $('.codeNum').val('');
    $('.power').val('');
    $('.alertAdd').css('display', 'none');
  })
  // 查询                                                           
  $('#searchUser').click(function () {                                                            
    var title = $('#title').val();                                                                                              
    console.log("查询")
    // api.getData(title);
  })                                                                                                                                                        
  // 重置
  $('#resetSearch').click(function () {
    $('input[name="date1"]').val('');
  })

  $("#tables").on("click", ".op_edit_btn", function (event) { //点击修改
    event.stopPropagation();
    var target = $(event.target);
    let rightType = target.parent().data('righttype');
    let parentcode = target.parent().data('parentcode');
    let idType = target.parent().data('id');
    let treecode = target.parent().data('treecode');
    let name = target.parent().data('name');
    let order, url, code, perms;
    let $tpl;
    if (rightType == 0) {
      $('.app-func .alert1').css("display", "block");
      $tpl = $('.app-func .alert1');
      order = target.parent().data('order');
      $('.sortNum').val(order);
    } else if (rightType == 1) {
      $('.app-func .alert2').css("display", "block");
      $tpl = $('.app-func .alert2');
      order = target.parent().data('order');
      url = target.parent().data('url');
      $('.sortNum').val(order);
      $('.urlLink').val(url);
    } else if (rightType == 2) {
      $('.app-func .alert3').css("display", "block");
      $tpl = $('.app-func .alert3');
      code = target.parent().data('code');
      $('.codeNum').val(code);
    }
    perms = target.parent().data('perms');
    $('.power').val(perms)
    $('.funcName').val(name);
    // 修改
    $tpl.unbind("click").on('click', '.certain', function () {
      let funcName = $tpl.find('.funcName').val();
      let sortNum = $tpl.find('.sortNum').val();
      let systemcode = $tpl.find('.codeNum').val();
      let urlLink, perms;
      urlLink = $tpl.find('.urlLink').val();
      perms = $tpl.find('.power').val();
      if (!funcName) {
        layer.msg('功能名称必填');
        return false
      }
      if (!perms) {
        layer.msg('功能权限必填');
        return false
      }
      param.id = idType;
      param.treecode = treecode;
      param.functionName = funcName;
      param.orderNumber = sortNum;
      param.url = urlLink;
      param.isApp = isApp;
      param.rightType = rightType;
      param.parentcode = parentcode;
      param.perms = perms;
      param.systemcode = systemcode;
      api.get_add_func(param);
    })
  })
  $("#tables").on("click", ".op_del_btn", function (event) { //点击删除
    event.stopPropagation();
    var target = $(event.target);
    let id = target.parent().data('id');
    layer.confirm('确定删除？(删除之后，该角色用户都会失效)', {
      btn: ['确定', '取消'] 
    }, function(index, layero){
       layer.close(index); //如果设定了yes回调，需进行手工关闭
       api.get_user_del(id);
    }, function(index){
      
    });	

  })
  $("#tables").on("click", ".op_add_btn", function (event) { // 新增功能
    event.stopPropagation();
    var target = $(event.target);
    let rightType = target.parent().data('right');
    let parentcode = target.parent().data('parent');
    let perms = target.parent().data('perms');
    let $tpl1;
    if (rightType == 1) {
      $('.app-func .alert2').css("display", "block");
      $tpl1 = $('.app-func .alert2');
    } else if (rightType == 2) {
      $('.app-func .alert3').css("display", "block");
      $tpl1 = $('.app-func .alert3');
    }
    $('.power').val(perms)
    $tpl1.unbind("click").on('click', '.certain', function () {
      let funcName = $tpl1.find('.funcName').val();
      let sortNum = $tpl1.find('.sortNum').val();
      let urlLink, perms, systemcode;
      urlLink = $tpl1.find('.urlLink').val();
      perms = $tpl1.find('.power').val();
      systemcode = $tpl1.find('.codeNum').val();
      if (!funcName) {
        layer.msg('功能名称必填');
        return false
      }
      if (!perms) {
        layer.msg('功能权限必填');
        return false
      }
      param.id = '';
      param.treecode = '';
      param.functionName = funcName;
      param.orderNumber = sortNum;
      param.url = urlLink;
      param.isApp = isApp;
      param.rightType = rightType;
      param.parentcode = parentcode;
      param.perms = perms;
      param.systemcode = systemcode;
      api.get_add_func(param);
    })
  })
})