;
(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_saveFileCtr', m_saveFileCtr);
    m_saveFileCtr.$inject = ['$scope', '$mdDialog', 'files'];
    return;

    //文件移动
    function m_saveFileCtr($scope, $mdDialog, files) {
        var vm = $scope;
        vm.close = $mdDialog.hide;

        vm.title = "保存到网盘";
        vm.ok = () => {
            if (!checkNode) {
                layer.msg('请选择文件夹');
                return;
            }
            let tip_loading = layer.load(1);
            apiService.move_file(files.map(v => v._id), checkNode.id, true).then((d) => {
                layer.close(tip_loading)
                if (d.ret) {
                    $mdDialog.cancel();
                    if (d.data.length == 0) {
                        layer.msg('保存成功!');
                    } else {
                        layer.msg('保存成功，已跳过重复文件！');
                    }
                    return;
                }
                layer.msg('保存失败');
            });
        }

        EventEmitter.on('m_saveFileCtronComplete', onComplete);

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

    }
    //文件移动数据遍历
    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) {
        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, 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', []).then(function (d) {
            zNodes[0].children = d;

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

})();
