define(function(require, exports, module) {
  var global = require("../../js/global");
  var community = window.require('../../common/js/community');
  var maccRequest = window.require('../../common/js/maccRequest');
  var jsUtil = window.require('../../common/js/jsUtil');
  // var co = require('co');
  // var util = require('util');


  function init() {
    var self = this;
    var user = global.userMgrIns.getUserInfo();
    var maccHost = global.jsUtil.getPkgInfo().spec.info.maccHost;
    var groupId = 0;
    maccRequest.setConfig(maccHost, user.userName, user.password);
    $(".unitItem").change(function(){
      $(this).removeClass("error");
    })
    $(".textareaImport .placeholder, .unitItem").click(function(event) {
      $(".textareaImport .placeholder").hide();
    });
    $(".textareaImport .placeholder").click(function(event) {
      $(".textareaImport .unitItem").focus();
    });
    $(".unitItem").blur(function(){
      if($(".textareaImport .unitItem").val() === ''){
        $(".textareaImport .placeholder").show();
      }
    })
    var params = {
      "maccHost": maccHost,
      "userName":user.userName,
      "password": user.password
    }
    community.getToken(params,function(err,res) { //生成access_token
      if (err != null) {
        console.log(res,"错误");
        return;
      }
      res.token = res.access_token;

      var setting = {
        async: {
				  enable: true,
  				// url: "http://macc1.ruijie.com.cn/service/api/group/0?groupType=BUILDING&access_token="+res.access_token,
          url: getAsyncUrl,
  				autoParam:["id", "name=n", "level=lv"],
  				dataFilter: filter,
          type:"get"
  			},
        view: {
          expandSpeed:"",
          selectedMulti: false
  			},
        edit: {
          enable: false //单独设置为true时，可加载修改、删除图标
  			},
  			data: {
          key: {
            children: "nodes"
          },
  				simpleData: {
  					enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: null
  				}
  			},
        callback:{
          onClick: zTreeOnClick
        }
      };

      function zTreeOnClick(event, treeId, treeNode) {
        if($(event.target).parent('a').find(".customBtn").length == 0) {
          $(".customBtn").remove(); //先全部移除增删改按钮，在给当前的节点添加增删改按钮
          var nametext = $(event.target).parent('a').children('span').eq(1).text(); //节点名称
          var type = ''; //要添加的节点类型
          var canImport = false //判断右侧 导入小区单元 按钮是否可以点击
          if(treeNode.pId == null){ //当前为根节点(我的网络节点)
            type = 'LOCATION';
            canImport = false;
            $(".unitItem").attr("disabled", true);
          }
          else if(treeNode.type == 'LOCATION' && treeNode.level == 1) { //当前为小区节点
            type = 'LOCATION';
            canImport = false;
            $(".unitItem").attr("disabled", true);
          }
          else if(treeNode.type == 'LOCATION' && treeNode.level == 2) { //当前为楼层节点
            type = 'BUILDING';
            canImport = true;
            $(".unitItem").attr("disabled", false);
          }
          if(canImport) {
            $(".btnImport").removeAttr('disabled').removeClass('disabled');
            var communityName = $(event.target).closest('ul').prev('a').children("span").eq(1).text();//获取小区名称
            $(".importUnint .name").text(communityName+'/'+nametext);
          } else {
            $(".btnImport").prop("disabled","disabled").addClass('disabled');
            $(".importUnint .name").text('');
            $(".unitItem").attr("disabled", true);
          }
          // var hasCommunity = false; //判断是否已经创建小区，（只能有一个小区）
          // if((treeNode.pId == null) && ($(event.target).parent('a').siblings('ul').children('li').length>0)) {
          //   hasCommunity = true;
          // } else {
          //   hasCommunity = false;
          // }
          var addDOM = (type == '') ? '' : '<span class="customBtn button add" data-groupid="'+treeNode.id+'" data-type="'+(treeNode.type || "ROOT")+'" id="addBtn"  title="添加" onfocus="this.blur(); style="margin-left:5px"></span>' ; //是否有添加按钮， 只有小区和楼层才有添加按钮，单元没有
          var editDOM = '<span class="customBtn button edit" data-groupid="'+treeNode.id+'" data-type="'+(treeNode.type || "ROOT")+'" id="editBtn" title="编辑" style="margin-left:5px"></span>';
          var delDOM = treeNode.pId ? '<span class="customBtn button remove" data-groupid="'+treeNode.id+'" data-type="'+(treeNode.type|| "ROOT")+'" id="delBtn" title="删除" style="margin-left:5px"></span>' : '';
          $(event.target).parent('a').append(addDOM+editDOM+delDOM);
          $(".communityTree").undelegate();
          //添加节点
          addGroup(res, type, treeNode);
          //编辑节点
          editGroup(res, type, treeNode);
          // 删除节点
          delGroup(res, type, treeNode);
          //导入单元
          importUnit(res, 'BUILDING', treeNode);
        }
      }
      function getAsyncUrl (treeId, treeNode) {
        var groupId = (treeNode&&treeNode.id) ? treeNode.id : 0;
        return maccHost+"/service/api/group/"+groupId+"?depth=BUILDING&access_token="+res.access_token;
      };
      function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        childNodes.groups.id = childNodes.groups.groupId;
        var data = [];
        if(childNodes.rootGroupId === childNodes.groups.groupId) { //构造根节点
          var rootName = childNodes.groups.name === 'ROOT' ? '我的网络': childNodes.groups.name;
          var root = {'name':rootName,'id':childNodes.groups.id, pId:null, 'open': true};
          if(childNodes.groups.subGroups && childNodes.groups.subGroups.length>0) {
             root.isParent = true;
          }
          data.push(root);
        }
        if(childNodes.groups.subGroups && childNodes.groups.subGroups.length>0) {
          childNodes.groups.subGroups.forEach(function(item){
            item.id = item.groupId;
            item.pId = childNodes.groups.id;
            if(item.subGroups&&item.subGroups.length>0){
              item.isParent= true;
            }
            data.push(item);
          })
        }
        return data;
  		};
      $(document).ready(function(){
  			$.fn.zTree.init($("#treeDemo"), setting);
  		});
    })
    function addGroup(res, type, treeNode){
      $(".communityTree").delegate('#addBtn', 'click', function(event) {
        event.stopPropagation();
        switch (treeNode.level) {
          case 0:
              $("#addCommunityModal .modal-title").text("添加小区");
              $("#groupName").attr("placeholder","小区名称");
            break;
          case 1:
              $("#addCommunityModal .modal-title").text("添加楼号");
              $("#groupName").attr("placeholder","楼号名称");
              break;
          case 2:
              $("#addCommunityModal .modal-title").text("添加单元");
              $("#groupName").attr("placeholder","单元号");
              break;
          default:
              $("#addCommunityModal .modal-title").text("添加");
              $("#groupName").attr("placeholder","");
        }
        var pGroupId = $(this).data("groupid");
        $("#addCommunityModal").modal('show');
        $('#addCommunityModal').on('shown.bs.modal', function() {
          $("#groupName").val("");
        });
        $('#addCommunityModal').on('hidden.bs.modal', function() {
          $("#addCommunityModal .btn-ok").unbind();
        });
        $("#addCommunityModal .btn-ok").unbind();
        $("#addCommunityModal .btn-ok").click(function(e) {
            e.stopPropagation();
            e.preventDefault();
            var name = $("#groupName").val();
            if(name == '' || name == null) {
              $("#groupName").addClass('error');
              return;
            }
            var params = {
              "pGroupId":pGroupId,
              "name": name,
              "info": res
            }
            console.log(type,"AAAAAAAAAAAAAAAAAAA");
            if(type == 'BUILDING') {
              community.addQuickGroup(params, function (err, res) { //addQuickGroup 快速建网，会默认创建一个ssid模板
                if (err != null) {
                  console.log(res,"错误");
                  alert(undefined, res);
                  return;
                }
                var result = (typeof(res) === 'object') ? res : JSON.parse(res);
                console.log(result,"BBBBBBBBBBBBBBBBBBBBBB");
                if (result.code == 0) {
                  var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                  console.log(result,"CCCCCCCCCCCCCCC");
                  var newNode = {};
                  // console.log(result,"CCCCCCCCCCCCCCC");
                  newNode.id = result.groupId;
                  newNode.pId = pGroupId;
                  newNode.name = name;
                  zTree.addNodes(treeNode, newNode, false);
                  $("#addCommunityModal").modal('hide');
                } else {
                  alert(undefined, result.msg);
                }
              })
            } else {
              params.type = type;
              community.addGroup(params, function (err, res) {
                if (err != null) {
                  console.log(res,"错误");
                  alert(undefined, res);
                  return;
                }
                var result = (typeof(res) === 'object') ? res : JSON.parse(res);
                if (result.code == 0) {
                  var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                  var newNode = res.group;
                  newNode.id = newNode.groupId;
                  zTree.addNodes(treeNode, newNode, false);
                  $("#addCommunityModal").modal('hide');
                }
              })
            }
        })
      });

    }
    function editGroup(res, type, treeNode){
      $(".communityTree").delegate('#editBtn', 'click', function(event) {
        event.stopPropagation();
        switch (treeNode.level) {
          case 1:
              $("#addCommunityModal .modal-title").text("编辑小区名");
              $("#groupName").attr("placeholder","小区名称");
              break;
          case 2:
              $("#addCommunityModal .modal-title").text("编辑楼层名");
              $("#groupName").attr("placeholder","楼层名称");
              break;
          case 3:
              $("#addCommunityModal .modal-title").text("编辑单元名");
              $("#groupName").attr("placeholder","单元名称");
              break;
          default:
              $("#addCommunityModal .modal-title").text("编辑");
              $("#groupName").attr("placeholder","");
        }
        var pGroupId = $(this).data("groupid");
        var oldName = $(event.target).parent('a').children('span').eq(1).text();
        $("#addCommunityModal").modal('show');
        $('#addCommunityModal').on('shown.bs.modal', function() {
          $("#groupName").val(oldName);
        });
        $('#addCommunityModal').on('hidden.bs.modal', function() {
          $("#addCommunityModal .btn-ok").unbind();
          $("#groupName").val("");
        });
        $("#addCommunityModal .btn-ok").unbind();
        $("#addCommunityModal .btn-ok").click(function(e) {
          e.preventDefault();
          e.stopPropagation();
          var newName = $("#groupName").val();
          var params = {
            groupId: pGroupId,
            name: newName,
            info: res
          }
          community.editGroup(params, function(err, res){
            if (err != null) {
              console.log(res,"错误");
              alert(undefined, res);
              return;
            }
            var result = (typeof(res) === 'object') ? res : JSON.parse(res);
            if(result.code == 0) {
              var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
              treeNode.name = newName;
              $("#addCommunityModal").modal('hide');
              treeObj.updateNode(treeNode);
            } else {
              alert(undefined, res.msg);
            }
          })
        })
      });
    }
    function delGroup(res, type, treeNode){
      $(".communityTree").delegate('#delBtn', 'click', function(event) {
        var self = this;
        var pGroupId = $(this).data("groupid");
        var params = {
          "groupId":pGroupId,
          "info": res
        }
        community.delGroup(params, function(err, res) {
          if (err != null) {
            console.log(res,"错误");
            alert(undefined, res);
            return;
          }
          var result = (typeof(res) === 'object') ? res : JSON.parse(res);
          if(result.code == 0) {
            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
            treeObj.removeNode(treeNode);
          } else {
            alert(undefined, res.msg);
          }
        })
      });
    }
    function importUnit(tokenRes, type, treeNode){
      var parentNode = treeNode;
      $(".btnImport").unbind();
      $(".btnImport").click(function(event) {
          var list = $(".unitItem").val().replace(/\n/g, '');
          if(!(/^[\u4E00-\u9FA5a-zA-Z0-9]+$/.test(list))) {
            alert(undefined, "导入的小区单元，格式不对");
            return
          }
          var unitItem = $(".unitItem").val().split("\n");
          if(unitItem[unitItem.length - 1] == ''){//有可能最后是一个空字符串
            unitItem.splice(unitItem.length-1,1);
          }

          if(!unitItem || unitItem.length == 0 ){
            alert(undefined,"请填写导入单元")
            return
          }
          $(".importShadow").show();
          var time = 0;
          var errArray = []; //上传错误Item;
          var successArray =[]; //保存添加成功的数据
          synchronousAdd(time,tokenRes,treeNode, type)
          function synchronousAdd(index,tokenRes,treeNode, type) { //同步一条条添加单元
            if (index <= unitItem.length -1) {
              var pGroupId = treeNode.id;
              var params = {
                "pGroupId":pGroupId,
                "name": unitItem[index],
                // "type": type,
                "info": tokenRes
              }
              community.addQuickGroup(params, function (err, res) { //addQuickGroup 快速建网接口，默认会创建ssid模板
                if (err != null) {
                  console.log(res,"错误");
                  errArray.push(unitItem[index]);
                } else {
                  var result = (typeof(res) === 'object') ? res : JSON.parse(res);
                  if (result.code == 0) {
                    var newNode = res;
                    newNode.id = newNode.groupId;
                    newNode.name = unitItem[index];
                    successArray.push(newNode);
                  } else {
                    errArray.push(unitItem[index]);
                  }
                }
                time +=1;
                synchronousAdd(time, tokenRes,treeNode,'BUILDING');
              })
            } else { // 全部单元调用接口完成
              $(".importShadow").hide();
              var zTree = $.fn.zTree.getZTreeObj("treeDemo");
              if(successArray.length > 0) {
                zTree.addNodes(treeNode, successArray, true);
              }
              if(errArray.length > 0) {
                $(".unitItem").val(errArray.join(",")+"导入失败");
                $(".unitItem").addClass('error');
              } else {
                $(".unitItem").val("");
                $(".unitItem").removeClass('error');
                alert(undefined,"导入成功");
              }
            }
          }
          // unitItem.forEach(function(item) {
          //   var pGroupId = treeNode.id;
          //   (function(){
          //     var params = {
          //       "pGroupId":pGroupId,
          //       "name": item,
          //       "type": type,
          //       "info": res
          //     }
          //     community.addGroup(params, function (err, res) {
          //         time +=1;
          //         if (err != null) {
          //           console.log(res,"错误");
          //           errArray.push(item);
          //           return;
          //         }
          //         var result = (typeof(res) === 'object') ? res : JSON.parse(res);
          //         if (result.code == 0) {
          //           var newNode = res.group;
          //           newNode.id = newNode.groupId;
          //           successArray.push(newNode);
          //         } else {
          //           errArray.push(item);
          //         }
          //         if(time ===unitItem.length) { //表示循环调用添加接口结束
          //           $(".importShadow").hide();
          //           var zTree = $.fn.zTree.getZTreeObj("treeDemo");
          //
          //           if(successArray.length>0){
          //             zTree.addNodes(treeNode, successArray, true);
          //           }
          //           if(errArray.length > 0) {
          //             $(".unitItem").val(errArray.join(",")+"导入失败");
          //             $(".unitItem").addClass('error');
          //           } else {
          //             $(".unitItem").val("");
          //             $(".unitItem").removeClass('error');
          //             alert(undefined,"导入成功");
          //           }
          //         }
          //       })
          //   }())
          // })
      });
    }
  }
  exports.init = init;
})
