(function () {
    'use strict';

    const
        lodash = require('lodash'),
        path = require('path'),
        myStorage = require('local-storage'),
        EventEmitter = require('myevents'),
        apiService = require('app-service'),
        downManager = require('downmanager'),
        fs = require('fs'),
        downFiles = require('down-folder'),
        appCache = require('app-cache'),
        { down: downURL } = require('sys-config'),
        uploadManager = require('uploadmanager');

    angular
        .module("app.factory")
        .factory('fileTool', file_tool);

    file_tool.$inject = ['$mdDialog'];
    function file_tool($mdDialog) {
        let service = {
            downFile: function () {
                let self = this;
                let local_config = appCache.local_config();
                return function (files) {

                    if (local_config.down_setting.default) {
                        downFiles(local_config.down_setting.path, files);
                        service._addCart(files);
                        return Promise.resolve(true);
                    }

                    return $mdDialog.show({
                        controller: 'm_downFileCtr',
                        templateUrl: './app/widgets/download/down.html',
                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        fullscreen: false,
                        multiple: true,
                        locals: {
                            files: files
                        }
                    }).then(function () {
                        $('body').off('change', '#openFolder');
                        service._addCart(files);
                        appCache.task_panel = 'download';
                        appCache.task_controller = 'task.downList';
                    }, function () {
                        $('body').off('change', '#openFolder');
                    });
                }
            },
            downshareFile: function () {
                let self = this;
                return function (share_files) {

                    let save_path = myStorage.get('save_path');

                    if (!!save_path) {
                        share_files.forEach((file) => {
                            let file_path = path.join(save_path, file.name);
                            apiService.share_package_files(file._id).then((v) => {
                                return d.data;
                            }).then(files => {
                                downFiles(save_path, files);
                            });
                        });
                        service._addCart(share_files);
                        return;
                    }
                    share_files.share = true;
                    return $mdDialog.show({
                        controller: 'm_downFileCtr',
                        templateUrl: './app/widgets/download/down.html',
                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        fullscreen: false,
                        multiple: true,
                        locals: {
                            files: share_files
                        }
                    }).then(function () {
                        $('body').off('change', '#openFolder');
                        service._addCart(share_files);
                        appCache.task_panel = 'download';
                        appCache.task_controller = 'task.downList';

                        share_files.forEach(v => {
                            return apiService.analysis_add(v).then(function (d) {
                            });
                        });

                    }, function () {
                        $('body').off('change', '#openFolder');
                    });
                }
            },
            shareFile: function () {
                return (files) => {
                    $mdDialog.show({
                        controller: 'm_shareFileCtr',
                        templateUrl: 'shareFile.html',
                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        fullscreen: false, multiple: true,
                        onComplete: function () {
                            EventEmitter.emit('m_shareFileCtrComplete');
                        },
                        locals: {
                            files: files
                        }
                    })
                }
            },

            deleteFile: function (files) {
                var confirm;
                confirm = {
                    controller: 'm_deleteFileCtr',
                    templateUrl: `./app/widgets/alert/alert.html`,
                    parent: angular.element(document.body),
                    clickOutsideToClose: false,
                    fullscreen: false,
                    multiple: true,
                    locals: {
                        files: files
                    }
                }
                return $mdDialog.show(confirm)
                    .then(function () {
                        let tip_loading = layer.load(1);
                        return apiService.delete_item(files.map(v => v._id)).then(function (d) {
                            EventEmitter.emit('fileListRefresh');
                            layer.close(tip_loading)
                            return d;
                        });
                    }, function () { });
            },

            moveFile: function (files, is_copy) {
                return $mdDialog.show({
                    controller: 'm_moveFileCtr',
                    template: `
                                <div class="dialog" style="width: 400px;">
                                                            <div class="dialog-head">{{title}}<span class="dialog-close" ng-click="close()" title="关闭" role="button" tabindex="0">
                                        <svg class="icon" aria-hidden="true">
                                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-close"></use>
                                        </svg>
                                    </span></div>
                                    <div class="dialog-center z-Tree" >
                                        <div style="" class="ztree" id="treeDemo"></div>
                                    </div>
                                    <div class="dialog-footer">
                                      <md-button class="md-raised md-primary"  ng-click="ok()">确定</md-button>
                                      <md-button class="md-raised "    ng-click="close()">取消</md-button>
                                      
                                    </div>
                                </div>
                            `,
                    parent: angular.element(document.body),
                    clickOutsideToClose: false,
                    fullscreen: false, multiple: true,
                    onComplete: function () {
                        EventEmitter.emit('m_moveFileCtronComplete', files, is_copy);
                    },
                    locals: {
                        files: files,
                        is_copy: is_copy
                    }
                }).then(function () { }, function () { });
            },
            saveFile: function (files) {
                return $mdDialog.show({
                    controller: 'm_saveFileCtr',
                    template: `
                                <div class="dialog" style="width: 400px;">
                                    <div class="dialog-head">{{title}}<span class="dialog-close" ng-click="close()" title="关闭" role="button" tabindex="0">
                                        <svg class="icon" aria-hidden="true">
                                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-close"></use>
                                        </svg>
                                    </span></div>
                                    <div class="dialog-center z-Tree" >
                                        <div style="" class="ztree" id="treeDemo"></div>
                                    </div>
                                    <div class="dialog-footer">
                                        <a class="btn" ng-click="close()">取消</a>
                                        <a class="btn" ng-click="ok()">确定</a>
                                    </div>
                                </div>
                            `,
                    parent: angular.element(document.body),
                    clickOutsideToClose: false,
                    fullscreen: false, multiple: true,
                    onComplete: function () {
                        EventEmitter.emit('m_saveFileCtronComplete', files);
                    },
                    locals: {
                        files: files
                    }
                });
            },
            newFile: function () {
                return $mdDialog.show({
                    controller: 'm_newFileCtr',
                    template: `
                                    <div class="dialog" style="width: 400px;">
                                        <form name="m_newFileForm" ng-submit="ok()">
                                            <div class="dialog-head">新建文件夹<span class="dialog-close" ng-click="close()" title="关闭" role="button" tabindex="0">
                                                <svg class="icon" aria-hidden="true">
                                                    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-close"></use>
                                                </svg>
                                            </span></div>
                                            <div class="dialog-center"> 
                                                 <input   name="newFileName" ng-model="fileName" 
                                                    ng-maxlength="50"  
                                                   required 
                                                  id="newName" placeholder="请输入文件名"> 
                                            </div> 
                                            <div class="dialog-footer"> 
                                             <button type="submit" class="md-raised md-primary md-button md-ink-ripple"
                                                     ng-disabled="m_newFileForm.$invalid">
                                                 创&nbsp;建
                                               </button>
                                                <md-button class="md-raised "    ng-click="close()">取消</md-button>
                                            </div>
                                        </form>
                                    </div>          
                                 `,
                    parent: angular.element(document.body),
                    clickOutsideToClose: false,
                    fullscreen: false, multiple: true
                }).then((result) => {
                    EventEmitter.emit('fileListRefresh');
                    return result;
                });
            },
            rename: function (item) {
                return (() => {
                    return $mdDialog.show({
                        controller: 'm_renameCtr',
                        template: `
                                <div class="dialog" style="width: 400px;">  
                                    <form name="m_renameFileForm" ng-submit="rename()">
                                        <div class="dialog-head">重命名<span class="dialog-close" ng-click="close()" title="关闭" role="button" tabindex="0">
                                            <svg class="icon" aria-hidden="true">
                                                <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-close"></use>
                                            </svg>
                                        </span></div>
                                        <div class="dialog-center">
                                            <input type="text" ng-model="fileName"  ng-maxlength="50"  required  placeholder="请输入新的文件名" id="newName">
                                            <p ng-if="error" class="error_txt">文件名已经存在</p>
                                        </div> 
                                        <div class="dialog-footer"> 
                                             <button type="submit" class="md-raised md-primary md-button md-ink-ripple"
                                                     ng-disabled="m_renameFileForm.$invalid">
                                                 重命名
                                               </button>
                                            <md-button class="md-raised "  ng-click="close()">取消</md-button> 
                                        </div>
                                    </form>
                                </div>          
                                 `,
                        parent: angular.element(document.body),
                        clickOutsideToClose: false,
                        fullscreen: false, multiple: true,
                        locals: {
                            item: item
                        }
                    }).then((result) => {

                    });
                })()
            },
            cancelShareFile: function (files) {
                var confirm = {
                    controller: 'm_cancelShareCtr',
                    templateUrl: `./app/widgets/alert/alert.html`,
                    parent: angular.element(document.body),
                    clickOutsideToClose: false,
                    fullscreen: false,
                    multiple: true,
                    locals: {
                        'files': files
                    }
                }
                return $mdDialog.show(confirm).then(function (d) {
                    EventEmitter.emit('shareListRefresh');
                    return d;
                });
            },
            alert: function (content, title) {
                var confirm = {
                    controller: 'm_alertCtr',
                    templateUrl: `./app/widgets/alert/alert.html`,
                    parent: angular.element(document.body),
                    clickOutsideToClose: false,
                    fullscreen: false,
                    multiple: true,
                    locals: {
                        content: content,
                        title: title
                    }
                }
                return $mdDialog.show(confirm).then(function () {
                    return true;
                }, function () {
                    return false;
                });
            },
            attribute: function (file) {
                var confirm = {
                    controller: 'm_attributeFileCtr',
                    template: `
                        <div class="dialog" style="width: 400px;">
                            <div class="dialog-head">
                                文件属性
                                <span class="dialog-close" ng-click="ok()" title="关闭" role="button" tabindex="0">
                                    <svg class="icon" aria-hidden="true">
                                        <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-close"></use>
                                    </svg>
                                </span>
                            </div>
                            <div class="dialog-center">
                                <div class="fileAttr">
                                    <div class="first cf" title="{{file.name}}">
                                        <span class="tabs" style="">
                                            <span class="imgs list-list">
                                                <span class="ico ico-{{file.ext||'file'}}"></span>
                                            </span>
                                        </span>
                                            {{file.name}}                        
                                    </div>
                                    <div class="content">
                                        <div><label>类型：</label>{{file.ext}}文件</div>
                                        <div title="{{file.path}}"><label>位置：</label>我的云盘{{file.path||"我的云盘"}}</div>
                                        <div><label>大小：</label>{{file.size| formByteLength}}</div>
                                        <div><label>修改时间：</label>{{file.server_ctime | date: 'yyyy-MM-dd HH:mm' }}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="dialog-footer">
                               <md-button class="md-raised md-primary"  ng-click="ok()">关闭</md-button>   
                            </div>
                        </div>
                    `,
                    parent: angular.element(document.body),
                    clickOutsideToClose: false,
                    fullscreen: false,
                    multiple: true,
                    locals: {
                        file: file
                    }
                };
                $mdDialog.show(confirm);
            },
            _addCart: function (files) {

                var ends = $('#end').offset();
                let icon = files[0].ext || "folder";
                var flyer = $(`<div class="u-flyer ico-list"><div class="u-flyer ico ico-${icon}" style="background-size: cover;width:100%;height:100% "></div></div>`);

                var fileSet = $('.' + files[0]._id).offset();
                flyer.fly({
                    start: {
                        left: fileSet.left,
                        top: fileSet.top
                    },
                    end: {
                        left: ends.left + 50,
                        top: ends.top + 50,
                        width: 0,
                        height: 0
                    },
                    onEnd: function () {
                        flyer.remove();
                    }
                });
            }
        }
        return service;
    }

})();
