;(function () {
    const
        request = require('request'),
        transfer = require('transfer'),
        app_cache = require('app-cache'),
        EventEmitter = require('myevents'),
        { api: apiURL, server_id,sso} = require('sys-config');

    class api {
        constructor() {}

        user_info(access_token){
           return csRrequest('get',`/api/oauth/profile?token=${access_token}`,sso.host)
        }
        item_list(pid, key = '', ext = '') {
            if (!pid) {
                pid = '0';
            }
            return baseRequest('get', `/v2/api/item?pid=${pid}&key=${encodeURI(key)}&ext=${ext}`);
        }
        page_list(pid, key = '', ext = '', limit = 100, page = 1) {
            if (!pid) {
                pid = '0';
            }
            return baseRequest('get', `/v2/api/item_pagination?pid=${pid}&key=${encodeURI(key)}&ext=${ext}&limit=${limit}&page=${page}`);
        }
        item_detail(id) {
            return baseRequest('get', `/v2/api/item/${id}/detail`);
        }
        // recycle() {
        //     return baseRequest('get', `/v2/api/item/recycle`);
        // }
        recycle(page, limit) {
            return baseRequest('get', `/v2/api/item/recycle_pagination?page=${page}&limit=${limit}`);
        }
        recovery(_ids, same_files) {
            return baseRequest('post', `/v2/api/item/recovery`, { item_ids: _ids, same_files: same_files });
        }
        check_recovery(_ids) {
            return baseRequest('post', `/v2/api/item/check_recovery`, { item_ids: _ids });
        }
        add_item(d) {
            return baseRequest('post', '/v2/api/item', d);
        }
        update_item(d) {
            return baseRequest('put', '/v2/api/item', d);
        }
        rename(new_name, item_id) {
            return baseRequest('post', `/v2/api/item/rename`, { name: new_name, _id: item_id });
        }
        check_rename(item) {
            return baseRequest('post', `/v2/api/item/check_rename`, item);
        }
        delete_item(_ids, is_remove = 1) { //is_remove 0 彻底删除 、1丢到垃圾桶
            return baseRequest('post', `/v2/api/item/delete`, { item_ids: _ids, is_remove: is_remove });
        }
        recycleClear() {
            return baseRequest('post', `/v2/api/recycle/clear`);
        }
        folder(pid, _ids) {
            if (!pid) {
                pid = '0';
            }
            return baseRequest('post', `/v2/api/item/${pid}/folder`, { item_ids: _ids });
        }
        branchs(pid = '83000001') {
            return baseRequest('get', `/v2/api/branchs/${server_id}/${pid}`);
        }
        branchUser(branch_id) {
            return baseRequest('get', `/v2/api/user/${server_id}/${branch_id}`);
        }
        branchUserData(branch_id){
            return baseRequest('get', `/v2/api/share/userTotal?serverID=${server_id}&branchIDs=${branch_id}`);
        }
        share_file(files, users, depts) {
            return baseRequest('post', `/v2/api/share`, {
                share_file: files,
                users: users,
                depts: depts
            });
        }
        share_package_files(share_id) {
            return baseRequest('get', `/v2/api/share/package/${share_id}`);
        }
        cancel_share(share_id) {
            return baseRequest('delete', `/v2/api/${share_id}/share`);
        }
        user_share_files() {
            return baseRequest('get', `/v2/api/share`);
        }
        share_to_me(type = 'all') {
            return baseRequest('get', `/v2/api/share/to/me?type=${type}`);
        }
        move_file(file_ids, pid, is_copy = false) {
            return baseRequest('post', !is_copy ? `/v2/api/item/move_file/to/${pid}` : `/v2/api/item/copy_file/to/${pid}`, { item_ids: file_ids, is_copy: is_copy });
        }
        analysis_add(share_file, item_id = '', type = 'down') {
            return baseRequest('post', `/v2/api/shareAnalysis`, {
                file_name: share_file.name,
                share_id: share_file._id,
                share_user: share_file.user,
                item_id: item_id,
                type: type,
                user: {
                    name: app_cache.cur_user.displayName,
                    id: app_cache.cur_user.id,
                    login_name: app_cache.cur_user.loginName
                }
            });
        }
        use_space() {
            return baseRequest('get', `/v2/api/use_space`);
        }
        login(username, password) {
            return Q((resolve, reject) => {

                request.post({
                    'url': apiURL + `/v2/api/login`,
                    json: {
                        username: username,
                        password: password,
                        server_id: server_id
                    }
                }, function (err, d) {
                    if (err || d.statusCode != 200) {
                        resolve({
                            ret: -1,
                            msg: '网络错误'
                        });
                    } else {
                        typeof d.body == 'string' ? resolve(JSON.parse(d.body)) : resolve((d.body));
                    }
                }).on('error', function (err) {

                    EventEmitter.emit('ajax_errorx');
                });
            });
        }

    }
    let csRrequest = (method, url, apiHost) => {
        let base = request.defaults({
           headers: {
               'content-type': 'application/json'
           }
        });
        url = apiHost + url;
        console.log(url);

        return  Q((resolve,reject) => {
            base[method](url,success).on('error',function (...err) {
                EventEmitter.emit('ajax_errorx', err);
                resolve({
                    ret: 0,
                    net: -1,
                    msg: '网络错误'
                });
            })
            function success(err, d) {
                if(err || d.statusCode != 200){
                    EventEmitter.emit('ajax_errorx', err, d);
                    resolve({
                        ret: 0,
                        msg: '网络错误'
                    });
                }else{
                    let data = typeof d.body == 'string' ? (JSON.parse(d.body)) : ((d.body));
                    data.ret = 1;
                    resolve(data);
                }
            }

        })

    }


    let baseRequest = (method, url, data) => {
        if (!app_cache.cur_user) {
            //未登录 
            return;
        }

        let base = request.defaults({
            headers: {
                'authorization': `Basic ${app_cache.cur_user.authorization}`,
                'content-type': 'application/json'
            }
        });

        return Q((resolve, reject) => {

            if (url != '/v2/api/item' && url != '/v2/api/use_space') { //批量上传造成一直有个加载框
                // EventEmitter.emit('ajax_before');
            }
            url = apiURL + url;
            console.error(url);
            if (!data)
                base[method](url, success).on('error', function (...err) {
                    EventEmitter.emit('ajax_errorx', err);
                    resolve({
                        ret: 0,
                        net: -1,
                        msg: '网络错误'
                    });
                });

            else
                base[method]({
                    'url': url,
                    json: data
                }, success).on('error', function (err) {

                    resolve({
                        ret: 0,
                        net: -1,
                        msg: '网络错误'
                    });
                    //  EventEmitter.emit('ajax_error');
                });

            function success(err, d) {
                //   EventEmitter.emit('ajax_complete');
                // if (d.statusCode == 401) {
                //     resolve({
                //         ret: 0,
                //         msg: '身份验证失败'
                //     });
                //     return;
                // }console.log(err, d);

                if (err || d.statusCode != 200) {

                    EventEmitter.emit('ajax_errorx', err, d);
                    resolve({
                        ret: 0,
                        msg: '网络错误'
                    });
                } else {
                    let data = typeof d.body == 'string' ? (JSON.parse(d.body)) : ((d.body));
                    data.ret = 1;
                    resolve(data);
                }
            }
        });
    }

    let Q = (caller) => {
        let promise = new Promise(function (resolve, reject) {
            caller(resolve, reject);
        });
        promise.catch(() => {
            //  EventEmitter.emit('ajax_complete');
            //  EventEmitter.emit('ajax_error');
        });
        return promise;
    }

    transfer.api = new api();

}());