import somes from 'somes';
import path from 'somes/path';
import * as React from 'react';
import { ViewController } from './ctr';
import './utils.css';
import access from './auth';
import Loading from './loading';
const qiniu = require('qiniu-js');
var uploadUrl = '/service-api/utils/uploadFile';
var qiniuUptoken = async function () {
    return {
        token: '',
        domain: '',
    };
};
export function setConfig(uptoken, upload_url) {
    qiniuUptoken = uptoken;
    uploadUrl = upload_url;
}
export async function uploadFile(file, params) {
    var url = uploadUrl;
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    fd.append('file', file);
    for (var i in params) {
        fd.append(i, params[i]);
    }
    xhr.open('POST', url, true);
    xhr.responseType = 'json';
    var sign = access.signer.sign(url);
    for (var i in sign) {
        xhr.setRequestHeader(i, sign[i]);
    }
    return new Promise((resolve, reject) => {
        xhr.onload = (e) => {
            var res = xhr.response;
            if (res.code === 0) {
                resolve(res.data);
            }
            else {
                reject(Error.new(res, res.code));
            }
        };
        xhr.onerror = (e) => {
            reject(Error.new('网络异常，请稍后重试'));
        };
        xhr.upload.onprogress = (e) => {
            if (e.lengthComputable) {
                var percent = (e.loaded / e.total - 0.01) || 0;
            }
        };
        xhr.send(fd);
    });
}
export async function uploadQiniu(file, params = {}) {
    var uptoken = await qiniuUptoken();
    var url = await new Promise((resolve, reject) => {
        var extname = path.extname(file.name);
        var key = `${new Date().toString('yyyyMMdd')}/${somes.random()}${somes.random()}${extname}`;
        var subscription = qiniu.upload(file, key, uptoken.token, {
            fname: '',
            params: params,
            mimeType: null,
        }, {
            useCdnDomain: true,
            region: qiniu.region.z0,
        }).subscribe((r) => {
        }, (e) => {
            reject(e);
        }, async (e) => {
            resolve(uptoken.domain + '/' + e.key);
        });
    });
    return url;
}
export default class Upload extends ViewController {
    constructor() {
        super(...arguments);
        this.state = { src: '' };
        this.m_id = '';
        this.m_handle_change = async (e) => {
            var file = e.target.files[0];
            if (!file)
                return;
            var name = file.name;
            this.m_onStartUpload(file);
            Loading.show('上传中..', this.m_id);
            try {
                var src = await uploadQiniu(file);
            }
            finally {
                Loading.close(this.m_id);
            }
            this.m_onChange(src, this.value);
            this.setState({ src });
        };
    }
    m_onChange(src, raw) {
        if (this.props.onChange) {
            this.props.onChange(src, raw);
        }
    }
    m_onStartUpload(file) {
        if (this.props.onStartUpload) {
            this.props.onStartUpload(file);
        }
    }
    m_onError(err) {
        if (this.props.onError) {
            this.props.onError(err);
        }
    }
    get value() {
        return this.state.src || this.props.src || this.props.value || '';
    }
    triggerLoad() {
        this.m_id = `upload_${somes.getId()}`;
        this.setState({ src: this.props.src || this.props.value || '' });
    }
    render() {
        var cls = this.props.className || this.props.class;
        var src = this.value;
        var accept = this.props.accept || 'image/*';
        var style = {};
        var defaultImage = '';
        if (src && !/\.(jpeg|jpg|png|gif)$/i.test(src)) {
            src = '';
            defaultImage = 'defaultImage';
        }
        if (!this.props.noShow) {
            var size = this.props.size ?
                `?imageMogr/auto-orient/thumbnail/${this.props.size}` : '';
            style = {
                ...(src ? { backgroundImage: `url(${src}${size})` } : {}),
                backgroundSize: '100%',
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'center',
            };
        }
        return (React.createElement("div", { className: `g_upload ${cls} ${defaultImage}`, style: style },
            React.createElement("input", { accept: accept, type: "file", onChange: this.m_handle_change, style: {
                    width: '100%',
                    height: '100%',
                    opacity: 0.01,
                } }),
            React.createElement("div", { className: "upload_icon" })));
    }
}
