;
(function () {

    const
        path = require('path')
        , lodash = require('lodash')
        , EventEmitter = require('myevents')
        , apiService = require('app-service')
        , appCache = require('app-cache')
        , uploadManager = require('uploadManager')
        , dbServer = require('db-server')
        , fs = require('fs')
        , PATH = require('path')
        , readdir = require('readdir')
        ;
    var curSortName,
        curDesc;
    angular.module('app.controllers')
        .controller('index_Controller', index_Controller);
    index_Controller.$inject = ['$scope', '$timeout', '$mdDialog', 'fileTool', '$document', '$stateParams', 'files'];
    return;

    /*页面控制层*/
    function index_Controller($scope, $timeout, $mdDialog, fileTool, $document, $stateParams, files) {
        let vm = $scope;
        let click_item_flag = false;
        vm.files = files.result;
        vm.pagerFiles = files;
        vm.cur_id = "storage";
        vm.breadcrumbs = appCache.breadcrumbs;


        vm.pager = {
            page: 1,
            limit: 200
        }

        vm.$parent.allow_search = true;
        vm.crumb_change = (idx) => {
            vm.pager.page = 1;
            return crumbClk(idx);
        };
        vm.contextmenu = contextmenu;

        vm.item_click = (item) => {
            let i = vm.breadcrumbs.findIndex(v => v.id === item._id);
            i === -1 && (i = vm.breadcrumbs.push({ id: item._id, text: item.name }) - 1);
            vm.pager.page = 1;
            crumbClk(i);
            click_item_flag = true;
            return
        };

        var historyCrumbs = lodash.last(vm.breadcrumbs);

        EventEmitter.on('fileListRefresh', (v) => {
            // disableMenu();

            if (!v) {
                $timeout(() => {
                    crumbClk(-1);
                });
                return;
            }
            let last = lodash.last(vm.breadcrumbs);
            if (last.id == v.pid || (last.id == '' && v.pid == '0')) {
                $timeout(() => {
                    vm.files.unshift(v);
                    vm.sortClick(curSortName, curDesc);
                });
            }
        }); /*刷新文件*/

        EventEmitter.on('crumbClk', (...arg) => {
            vm.pager.page = 1;
            crumbClk(...arg);
        });



        let disable_menu = ['downloadFile', 'shareFile', 'deleteFile'];
        //  设置主页面的 下载 分享 删除按钮不可点击
        function disableMenu(file_length) {
            let bol = file_length === 0;
            $scope.$parent.menuBtn[0].ifDisable = bol;
            $scope.$parent.menuBtn[1].ifDisable = bol;
            $scope.$parent.menuBtn[2].ifDisable = bol;

            $scope.$parent.menuBtn[3].ifDisable = false;
        }

        vm.sortClick = function (sortName, desc) {
            curSortName = sortName, curDesc = desc;
            let asc = desc == 0 ? 1 : -1;
            if (sortName == 'name') {
                vm.files.sort((a, b) => {
                    return a.name.localeCompare(b.name) * asc;
                });
                vm.files.sort((a, b) => {
                    if (a.isdir == b.isdir) return 0;
                    if (a.isdir == 1) return -1;
                    if (b.isdir == 1) return 1;
                    return 0
                });
                return;
            }
            if (sortName == 'size')
                return vm.files.sort((a, b) => {
                    return (a.size - b.size) * asc;
                });
            if (sortName == 'time')
                return vm.files.sort((a, b) => {
                    return a.server_ctime - (b.server_ctime) * asc;
                });
        };
        //排序初始化
        vm.sortClick('name','desc');

        vm.OnItemClick = function (num, files,e) {

            if(click_item_flag && files && files[0]){
                $timeout(() => {
                    // $scope.$emit("toFooter", files.length, true);
                    disableMenu(0);
                });
                click_item_flag = false;
                return false;
            }
            $timeout(() => {
                // $scope.$emit("toFooter", files.length, true);
                disableMenu(files.length);
            });
            return false;
        };

        vm.OnCheckAll = function (is_all, files) {
            $timeout(() => {
                //$scope.$emit("toFooter", files.length, true);
                disableMenu(files.length);
            });
            return false;
        };

        vm.OnContextmenu = function (ev, files) {
            $timeout(() => {
                contextmenu(ev, files, $scope, fileTool, $mdDialog);
                disableMenu(files.length);
            });
            return false;
        };

        vm.on_pager = (idx = 1) => {
            vm.pager.page = idx;
            crumbClk(-1);
        };

        $('#J-fileList').on('contextmenu', function (ev) {
            ev.preventDefault();
            moreContextmenu(ev, fileTool, vm);
        });


        disableMenu(0);
        $scope.$on('$destroy', () => {
            EventEmitter.removeAllListeners('fileListRefresh');
            EventEmitter.removeAllListeners('crumbClk');
            $(document).off('contextmenu', '#J-fileList');
            $('#fileDialog').off('change');
            $('#folderDialog').off('change');
            appCache.breadcrumbs = [{
                id: '0',
                text: "我的云盘"
            }];
        });
        $timeout(() => { uploadFile(vm) }, 1000);
        return;

        /*加载文件*/
        function getFiles(pid, key, ext) {
            curSortName = '', curDesc = '';
            apiService.page_list(pid, key, ext, vm.pager.limit, vm.pager.page).then((d) => {
                vm.$apply(function () {
                    vm.files = d.data.result;
                    vm.pagerFiles = d.data;
                    vm.sortClick(curSortName, curDesc);
                });
            });
        }

        /*
        idx:索引项（索引号） 
         key:input搜索文件值  
        ext:文件类型归类显示 
         text: 归类类型     
          cur_id:归类类型点击显示样式做判断的样式
        */
        //面包屑的展示事件
        function crumbClk(idx, key, ext, text, cur_id) {
            if (key) {
                vm.cur_id = "storage";
                vm.breadcrumbs = [{
                    id: '0',
                    text: "我的云盘"
                }, {
                    id: '',
                    text: `“${key}“的搜素结果`,
                    key: key
                }];
                idx = 1;
            }
            if ([0, 1, 2, 3,4].indexOf(ext) >= 0 && text) {
                vm.breadcrumbs = [{
                    id: '0',
                    text: "我的云盘"
                }, {
                    id: '',
                    text: `${text}`,
                    ext: ext
                }];
                idx = 1;
            }

            appCache.breadcrumbs = vm.breadcrumbs;
            var cur_item = vm.breadcrumbs[idx],
                len = vm.breadcrumbs.length - idx - 1;
            !cur_item ? cur_item = lodash.last(vm.breadcrumbs) : vm.breadcrumbs.splice(idx + 1, len);
            !!cur_id && (vm.cur_id = cur_id);
            getFiles(cur_item.id, cur_item.key, cur_item.ext);
            //排序初始化
            vm.sortClick('name','desc');
            EventEmitter.emit('more');

        }

    }

    /*上传文件*/
    function uploadFile(vm) {
        $('#fileDialog').on('change', function (evt) {
            let last = appCache.breadcrumbs.length;
            if (!this.value) {
                return;
            }
            let stat = fs.statSync(this.value);

            dbServer.upload.add({
                name: PATH.basename(this.value),
                extname: PATH.extname(this.value),
                size: stat.size,
                mtime: stat.mtime,
                path: this.value,
                pid: appCache.breadcrumbs[last - 1].id || '0',
                status: 0,
                end_len: 0,
                md5: '',
                url: ''
            }).then(e => {
                readdir();
            });
            document.querySelector('#fileDialog').value = '';
        });

        $('#folderDialog').on('change', function (evt) {
            let last = appCache.breadcrumbs.length;
            dbServer.folder.add(this.value, appCache.breadcrumbs[last - 1].id).then(e => {
                readdir();
            });
            document.querySelector('#folderDialog').value = '';
        });

    }

    function moreContextmenu(ev, fileTool, scope, $timeout) {
        let menu = new nw.Menu();

        menu.append(new nw.MenuItem({
            label: '    上传               ',
            click: () => {
                document.querySelector('#fileDialog').click();
            }
        }));

        menu.append(new nw.MenuItem({
            label: '    新建文件夹                ',
            click: () => {
                fileTool.newFile();
            }
        }));
        menu.append(new nw.MenuItem({ type: 'separator' }));
        menu.append(new nw.MenuItem({
            label: '    刷新                  ',
            click: () => {
                EventEmitter.emit('fileListRefresh');
            }
        }));
        var submenu = new nw.Menu();


        let icon = nw.__dirname + '/web_content/assets/imgs/select.png';

        submenu.append(new nw.MenuItem({
            label: '    文件名                ',
            icon: curSortName === 'name' ? icon : '',
            click: () => {
                document.querySelector('#J-sortName').click();
            }
        }));

        submenu.append(new nw.MenuItem({
            label: '    文件大小                  ',
            icon: curSortName === 'size' ? icon : '',
            click: () => {
                document.querySelector('#J-sortSize').click();
            }
        }));

        submenu.append(new nw.MenuItem({
            label: '    修改时间                  ',
            icon: curSortName === 'time' ? icon : '',
            click: () => {
                document.querySelector('#J-sortTime').click();
            }
        }));

        menu.append(new nw.MenuItem({
            label: '    排序方式                   ',
            submenu: submenu
        }));

        menu.popup(ev.clientX, ev.clientY);
    }

    function contextmenu(ev, files, scope, fileTool, $mdDialog) {

        let menu = new nw.Menu();

        menu.append(new nw.MenuItem({
            label: ' 打开                  ',
            enabled: files.length === 1 && files[0].isdir,
            click: function () {
                let item = files[0];
                if (!item.isdir) {
                    return;
                }
                scope.item_click(item);
            }
        }));

        menu.append(new nw.MenuItem({ type: 'separator' }));
        menu.append(new nw.MenuItem({
            label: ' 下载              ',
            click: () => {
                fileTool.downFile()(files);
            }
        }));

        menu.append(new nw.MenuItem({ type: 'separator' }));

        menu.append(new nw.MenuItem({
            label: ' 删除               ',
            click: () => {
                fileTool.deleteFile(files);
            }
        }));
        menu.append(new nw.MenuItem({
            label: ' 重命名              ',
            enabled: files.length === 1,
            click: () => {
                fileTool.rename(files[0]);
            }
        }));
        menu.append(new nw.MenuItem({
            label: ' 移动到              ',
            click: () => {
                fileTool.moveFile(files);
            }
        }));
        menu.append(new nw.MenuItem({
            label: ' 复制到             ',
            click: function () {
                fileTool.moveFile(files, true);
            }
        }));

        menu.append(new nw.MenuItem({ type: 'separator' }));
        menu.append(new nw.MenuItem({
            label: ' 分享              ',
            click: () => {
                fileTool.shareFile($mdDialog)(files);
            }
        }));
        menu.append(new nw.MenuItem({ type: 'separator' }));
        menu.append(new nw.MenuItem({
            label: ' 属性              ',
            enabled: files.length === 1,
            click: () => {
                let file = files[0];
                fileTool.attribute(file);
            }
        }));
        menu.popup(ev.clientX, ev.clientY);

    }


})();
