;
(function () {
    'use strict';

    const
        lodash = require('lodash'),
        event = require('myevents'),
        path = require('path'),
        EventEmitter = require('myevents'),
        apiService = require('app-service'),
        downManager = require('downmanager'),
        cache = require('app-cache'),
        uploadManager = require('uploadmanager');

    angular.module('app.controllers')
        .controller('m_shareFileCtr', m_shareFileCtr);
        m_shareFileCtr.$inject = ['$scope', '$mdDialog', 'files'];          
    return;


    //文件分享
    function m_shareFileCtr($scope, $mdDialog, files) {
        var vm = $scope;
        let file_count = files.length;
        vm.share_name = `${files[0].name}` + (file_count === 1 ? '' : `等${file_count}个文件`);
        var share_name = vm.share_name;

        vm.close = $mdDialog.cancel;
        vm.ok = () => {
            let nodes = $.fn.zTree.getZTreeObj("treeDemo").getNodes();
            let users = [],
                depts = [],
                share_file = {};

            share_selest(nodes, depts, users);

            console.error(users);
            console.error(depts);


            if (Object.keys(users).length == 0 && Object.keys(depts).length == 0) {
                layer.msg('请选择部门或者用户！');
                return;
            }

            //判断分享人数
            let sharePerson = judgePersonData(users,depts);

            sharePerson.then(data =>{
                if(data && data >= cache.share_config.limitShareData ){
                    layer.msg(`分享失败，人数超过${cache.share_config.limitShareData}个用户！`);
                    return;
                }
            });

            share_file = {
                name: vm.share_name,
                item_ids: files.map(v => v._id),
                ext:files.length === 1 ? files[0].ext :'rar' //rar
            };

            layer.load(1);
            apiService.share_file(share_file, users, depts).then((d) => {
                layer.closeAll('loading');
                if (d.ret) {
                    layer.msg('分享成功！');
                    $mdDialog.cancel(d);
                    return;
                }
                layer.msg(d.msg + '，分享失败！');
            });
        }
        EventEmitter.on('m_shareFileCtrComplete', onComplete);

        $scope.$on('$destroy', () => {
            EventEmitter.removeAllListeners('m_shareFileCtrComplete');
        });
    }

    function judgePersonData(users,depts) {
        let total = 0;
        let userLength = Object.keys(users).length;
        let deptId =[],deptIdStr='',
            deptsLength = 0;
        depts.forEach((currentValue, index, array) =>{
            deptId.push(currentValue.id);
        });
        deptIdStr = deptId.toString();
        return apiService.branchUserData(deptIdStr).then( d =>{
            if(d.success === 1){
                total = userLength + d.data.data;
                return total;
            }
            return false;
        });
    }

    function share_selest(node, depts, users) {
        node.forEach((n) => {
            if (!n.checked) {
                return;
            }
            let data = {
                id: n.id,
                name: n.name
            };
            if (n.check_Child_State == -1 || n.check_Child_State == 2) {
                n.isParent ? (depts.push(data)) : (users.push(data) );
                return;
            }
            if (n.check_Child_State == 1) {
                share_selest(n.children, depts, users);
            }
        });
    }

    function onComplete() {
        var setting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: (event, id, node) => {
                    if (node.loading || (node.children && node.children.length > 0)) {
                        return;
                    } 
                    node.loading = true;
                    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                    TransfBranch(node.id, node.checked).then((d) => treeObj.addNodes(node, d));
                },
                beforeExpand: function () {

                }
            }
        };
        var zNodes = [];
        TransfBranch(0).then(function (d) {
            zNodes = d;
            var treeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);

        });
    }

    function TransfBranch(pid, checked = false) {
        let branchs = [];
        return apiService.branchs(pid).then(function (d) {
            d = d.data;
            d.forEach((v, idx) => {
                branchs.push({
                    name: v.branchName,
                    id: v.id,
                    isParent: true,
                    checked: checked
                });
            });
            return apiService.branchUser(pid);
        }).then((d) => {
            let user = d.data;
            user.forEach((v, idx) => {
                branchs.push({
                    name: v.displayName,
                    id: v.id,
                    checked: checked
                });
            });
            return branchs;
        }).catch(() => {

        });
    }

})();
