;
(function () {
    'use strict';

    const
        lodash = require('lodash'),
        event = require('myevents'),
        path = require('path'),
        EventEmitter = require('myevents'),
        apiService = require('app-service');
    var checkNode;
    angular.module('app.controllers')
        .controller('m_moveFileCtr', m_moveFileCtr);
    m_moveFileCtr.$inject = ['$scope', '$mdDialog', 'files', 'is_copy'];
    return;

    //文件移动
    function m_moveFileCtr($scope, $mdDialog, files, is_copy) {
        var vm = $scope;
        vm.close = $mdDialog.cancel;
        vm.is_copy = is_copy;
        vm.title = is_copy ? "文件复制到" : "文件移动到";
        vm.ok = () => {
            if (!checkNode) {
                layer.msg('请选择文件夹');
                return;
            }
            let tip_loading = layer.load(1);
            apiService.move_file(files.map(v => v._id), checkNode.id, is_copy).then((d) => {
                layer.close(tip_loading);
                if (d.ret) {
                    event.emit('fileListRefresh');
                    EventEmitter.emit('getUserSpace');
                    $mdDialog.cancel();
                    return;
                }
                layer.msg(is_copy ? "复制失败" : '移动失败');
            });
        }

        EventEmitter.on('m_moveFileCtronComplete', onComplete);

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

    }
    //文件移动数据遍历
    function getFolder(pid, _id) {
        let folders = [];
        return apiService.folder(pid, _id).then(function (d) {

            d.data.forEach((v, idx) => {
                folders.push({
                    name: v.name,
                    id: v._id,
                    isParent: true
                });
            });
            return folders;
        });
    }

    function onComplete(files, is_copy) {
        var setting = {
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: (event, id, node) => {
                    if (node.isloading || (node.children && node.children.length > 0)) {
                        return;
                    }
                    node.isloading = true;
                    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                    getFolder(node.id)
                        .then((d) => treeObj.addNodes(node, d));
                },
                onClick: function (event, id, node) {
                    checkNode = node;
                }
            }
        };
        var zNodes = [{
            name: "根目录",
            id: '0',
            open: true,
            children: []
        }];

        getFolder('0', files.filter(v => v.isdir === 1).map(v => v._id)).then(function (d) { //is_copy?[]:
            zNodes[0].children = d;

            var treeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        });
    }

})();
