;
(function() {
    'use strict';

    const
        PATH = require('path'),
        lodash = require('lodash'),
        event = require('myevents'),
        downFiles = require('down-folder'), 
        EventEmitter = require('myevents'),
        apiService = require('app-service'),
        downManager = require('downmanager'),
        logicaldisk = require('logicaldisk'),
        uploadManager = require('uploadmanager') ;
    const app_cache = require('app-cache'),
     local_storage = require('local-storage');

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

    function m_downFileCtr($scope, $timeout, $mdDialog, files, fileTool) {

        let vm = $scope;
        let disk_infos;
        vm.downCheck = false;
        vm.file = files[0];
        vm.filesName = files.map(v => v.name).join('/');

        let local_config = app_cache.local_config()  ;

        var _addCart = fileTool._addCart;
        vm.folderTxt  =  local_config.down_setting.path ; 
        
        logicaldisk().then((d) => {
            disk_infos = d;
            let disk_id = PATH.parse( vm.folderTxt  ).root[0] + ':';
            vm.disk_info = disk_infos[disk_id];
        }).then(() => {
            $('body').on('change', '#openFolder', function() {
                let path = $(this).val();

                let disk_id = PATH.parse(path).root[0] + ':';

                $timeout(() => {
                    vm.folderTxt = path;
                    vm.disk_info = disk_infos[disk_id];
                }, 10);
            });
        });
        
        vm.download = function() {

            if (!vm.folderTxt) {
                layer.alert('请选择下载目录')
                return;
            }
            
            local_config.down_setting={
                default:vm.downCheck ,
                path:vm.folderTxt
            }; 
            local_storage.set('local_config' , local_config );
            if (!files.share) {
                downFiles(vm.folderTxt, files);
            } else {
                delete files.share;
                files.forEach((file) => {
                    let file_path = PATH.join(vm.folderTxt, file.name);
                    apiService.share_package_files(file._id).then((v) => {
                        return downFiles(file_path, v.data);
                    });
                });
            }


            $mdDialog.hide();
        }

        vm.close = $mdDialog.cancel;
        $scope.$on('$destroy', () => {
            $('body').off('change', '#openFolder')
        });

    }
})();
