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');
  // 'use strict';
  // global.Promise = require('bluebird');
  // var co = require('co');
  // var maccRequest = require('./maccRequest');
  // var jsUtil = require('./jsUtil');
  // var path = require('path');
  // var fs = require('fs');

  function init() {
    var self = this;
    var user = global.userMgrIns.getUserInfo();
    var maccHost = global.jsUtil.getPkgInfo().spec.info.maccHost;
    maccRequest.setConfig(maccHost, user.userName, user.password);
    var params = {
      "maccHost": maccHost,
      "userName":user.userName,
      "password": user.password
    }
    community.getToken(params,function(err,res) {
      if (err != null) {
        console.log(res,"错误");
        return;
      }
      res.token = res.access_token;
      initTree(res);
      initEvent(res);
      // initTable(res);

      function initTree(res) {
        var setting = {
          async: {
            enable: true,
            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:{
            // onAsyncSuccess: zTreeOnAsyncSuccess
            onClick: zTreeOnClick
          }
        };
        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;
              }
              if(item.type == 'LOCATION') {
                item.open = true;
              }
              data.push(item);
            })
          }
          return data;
    		};
        // function zTreeOnAsyncSuccess(treeId, parentNode, childNodes) {
        //   debugger
        // }
        function zTreeOnClick(treeId, parentNode, childNodes) {
          $(".userContent .hint").hide();
          $("#ownerList ul").html("");
          if(childNodes.level == 2 || childNodes.level == 3) {
            $(".ownerSearchBtn").removeClass('disabled').removeAttr('disabled');
          }
          console.log(childNodes,"AAAAAAAAAAAAAAAAAAAA");
          if(childNodes.subGroups && childNodes.subGroups.length>0 && childNodes.level == 2) {
            self.ownerItems = childNodes.subGroups
            var unitItem = '';
             childNodes.subGroups.forEach(function(item){
               unitItem += '<li data-groupid="'+item.groupId+'">'+item.name+'</li>';
             })
             $("#ownerList ul").append(unitItem);
          } else if(childNodes.level == 3){
            var userInfo = global.userMgrIns.getUserInfo();//登录用户帐号信息
            var unitName = childNodes.name.replace(/[^0-9]/ig,""); //获取单元名中的数字
            var groupId = childNodes.groupId;
            var tokenRes = res;
            createCode(userInfo, groupId, unitName, tokenRes)
            // var unitItem = '<li data-groupid="'+childNodes.groupId+'">'+childNodes.name+'</li>';
            // $("#ownerList ul").html("");
            // $("#ownerList ul").append(unitItem);
          }else{
            self.ownerItems = []
          }
        }
        $(document).ready(function(){
    			$.fn.zTree.init($("#treeDemo"), setting);
          var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    		});
      }
      //判断是否有子帐号（有的话先删除在创建）
      function createCode (userInfo, groupId, unitName, tokenRes) {
        var params = {
              group_id: +groupId,
              page: 1,
              per_page: 10,
              info:res
            }
        community.getAccountList(params, function(err, res){
         if (err != null) {
           console.log(res,"获取账号列表错误");
           alert(undefined, res);
           return;
         }
         console.log(res, "子帐号列表");
         var result = (typeof(res) === 'object') ? res : JSON.parse(res);
         if(result.code == 0) {
           if(result.totalCount == 0) {//该分组下没有子账号(创建一个子帐号，生成二维码)
             createAccount(userInfo, groupId, unitName, tokenRes);
           } else { //该分组下有子帐号，(先删除改子账号，在重新创建一个子帐号（账号名一样）)
             var accountId = result.accountList[0].id
             var delParams = {
               accountId: accountId,
               info: tokenRes
             }
             community.delAccount(delParams, function(err, delRes){
               if (err != null) {
                 console.log(res,"删除子账号错误");
                 alert(undefined, res);
                 return;
               }
               var delResult = (typeof(delRes) === 'object') ? delRes : JSON.parse(delRes);
               if(delResult.code == 0) {
                 console.log("删除子帐号成功");
                 //创建子帐号
                 createAccount(userInfo, groupId, unitName, tokenRes);
               }
             })
           }
           $("#smallConchCode").modal('show');
        } else {
           alert(undefined, result.msg);
        }
       })
      }
      function initEvent(tokenRes) {
        $("#ownerList").delegate("li", 'click', function(event) {
          var userInfo = global.userMgrIns.getUserInfo();//登录用户帐号信息
          var unitName = $(this).text().replace(/[^0-9]/ig,""); //获取单元名中的数字
          // var accoutName = user.userName + '_' + unitName
          var groupId =  $(this).data("groupid");
          var tokenRes = res;
          console.log(userInfo, '||' ,groupId,'||' , unitName,'||' , tokenRes)
          createCode(userInfo, groupId, unitName, tokenRes);
        });
        //搜索
        $(".ownerSearchBtn").click(function(event) {
          var searchTxt = $(".searchVal").val();
          var searchResult = self.ownerItems.filter(function(item){
             return item.name.indexOf(searchTxt) != -1;
          });
          var unitItem = '';
          searchResult.forEach(function(item){
             unitItem += '<li data-groupid="'+item.groupId+'">'+item.name+'</li>';
           })
           $("#ownerList ul").html("");
           $("#ownerList ul").append(unitItem);
        });
      }

      function createAccount(userInfo, groupId, unitName, tokenRes){
        var account = userInfo.userName + "_" + groupId + "_" + unitName +'UNIT';
        var createParams = {
          account: account,
          password: 'ruijie123456',
          role:'manager',
          groupId: groupId,
          language: 'cn',
          info: tokenRes
        }
        community.createAccount(createParams, function(err, createRes){
          if (err != null) {
            console.log(res,"创建子账号错误");
            alert(undefined, res);
            return;
          }
         var createResult = (typeof(createRes) === 'object') ? createRes : JSON.parse(createRes);
         if(createRes.code == 0) {
           console.log("创建子帐号成功");
          //  alert(undefined, "创建成功");
           $('#wxCode').html('');
           $('#wxCode').qrcode({
             width:248,
             height:248,
             text: "http://macc1.ruijie.com.cn/ajtest?username="+account+"&password=ruijie123456"
           });
         }
        })
      }
      // function initTable(res) {
      //   $('#ownerTable').bootstrapTable({
      //     data: []
      //   });
      //   getAccountList();
      //   function getAccountList () {
      //     var params = {
      //       group_id: 58,
      //       page: 1,
      //       per_page: 10,
      //       info:res
      //     }
      //     community.getAccountList(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) {
      //         $('#ownerTable').bootstrapTable('load', res.accountList);
      //       }
      //     })
      //   }
      // }
    })
    // var $table = $('#ownerTable');
    // $('#ownerTable').bootstrapTable({
		// 	data: [{
    //     "uint": "1001单元",
    //     "username": "老王",
    //     "phone": "137745491366",
    //     "wx":"微信1",
    //     "operate": "重新开户"
    //   },{
    //     "uint": "1001单元",
    //     "username": "老王",
    //     "phone": "137745491366",
    //     "wx":"微信1",
    //     "operate": "重新开户"
    //   },{
    //     "uint": "1001单元",
    //     "username": "老王",
    //     "phone": "137745491366",
    //     "wx":"微信1",
    //     "operate": "重新开户"
    //   },{
    //     "uint": "1001单元",
    //     "username": "老王",
    //     "phone": "137745491366",
    //     "wx":"微信1",
    //     "operate": "重新开户"
    //   }]
		// });
  }

  exports.init = init;
})
