import { __decorate } from "tslib";
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Http, getSessionStorage, AppServiceBase } from '@ibizstudio/runtime';
import { getCookie } from 'qx-util';
import './app-file-upload-camera.less';
let AppFileUploadCamera = class AppFileUploadCamera extends Vue {
    constructor() {
        super(...arguments);
        /**
         * 请求头
         *
         * @type {*}
         * @memberof AppImageUpload
         */
        this.headers = {};
        this.videoSelect = "";
        this.options = [];
        this._streamCopy = null;
        this.rotateDeg = 90;
        this.imgFiles = [];
        this.dialogVisible = false;
        this.dialogImageUrl = "";
    }
    /**
     * vue 生命周期
     *
     * @returns
     * @memberof AppFileUpload
     */
    mounted() {
        navigator.mediaDevices.enumerateDevices().then(this.gotDevices).then(this.getStream).catch(this.handleError);
        this.setHeaders();
    }
    /**
     * 设置请求头
     *
     * @memberof AppFileUpload
     */
    setHeaders() {
        if (AppServiceBase.getInstance().getAppEnvironment().SaaSMode) {
            let activeOrgData = getSessionStorage('activeOrgData');
            this.headers['srforgid'] = activeOrgData === null || activeOrgData === void 0 ? void 0 : activeOrgData.orgid;
            this.headers['srfsystemid'] = activeOrgData === null || activeOrgData === void 0 ? void 0 : activeOrgData.systemid;
            if (getSessionStorage("srfdynaorgid")) {
                this.headers['srfdynaorgid'] = getSessionStorage("srfdynaorgid");
            }
        }
        else {
            this.headers['srforgid'] = undefined;
            this.headers['srfsystemid'] = undefined;
            if (getSessionStorage("srfdynaorgid")) {
                this.headers['srfdynaorgid'] = getSessionStorage("srfdynaorgid");
            }
        }
        if (getCookie('ibzuaa-token')) {
            this.headers['Authorization'] = `Bearer ${getCookie('ibzuaa-token')}`;
        }
        else {
            // 第三方应用打开免登
            if (sessionStorage.getItem("srftoken")) {
                const token = sessionStorage.getItem('srftoken');
                this.headers['Authorization'] = `Bearer ${token}`;
            }
        }
    }
    gotDevices(deviceInfos) {
        this.options = [];
        for (var i = 0; i < deviceInfos.length; ++i) {
            var deviceInfo = deviceInfos[i];
            if (deviceInfo.kind === 'videoinput') {
                if (deviceInfo.label.startsWith("Integrated ")) { }
                else {
                    if (deviceInfo.label.startsWith("ZMFZL")) {
                        this.videoSelect = deviceInfo.deviceId;
                    }
                    var option = {};
                    option.value = deviceInfo.deviceId;
                    option.label = deviceInfo.label;
                    this.options.push(option);
                }
            }
        }
    }
    getStream() {
        this.closeCamera();
        var constraints = {
            audio: false,
            video: {
                optional: [
                    {
                        sourceId: this.videoSelect
                    }
                ]
            }
        };
        navigator.mediaDevices.getUserMedia(constraints).then(this.gotStream).catch(this.handleError);
    }
    handleError(error) {
        this.$info(error.name + ": " + error.message, 'handleError');
    }
    gotStream(stream) {
        this._streamCopy = stream; // make stream available to console
        var videoSource = this.$refs.videoSource;
        videoSource.srcObject = stream;
    }
    closeCamera() {
        if (this._streamCopy != null) {
            try {
                this._streamCopy.stop(); // if this method doesn't exist, the catch will be executed.
            }
            catch (e) {
                this._streamCopy.getVideoTracks()[0].stop(); // then stop the first video track of the stream
            }
        }
    }
    changeCamera(event) {
        var constraints = {
            audio: false,
            video: {
                width: 200,
                height: 100,
                optional: [
                    {
                        sourceId: event
                    }
                ]
            }
        };
        navigator.mediaDevices.getUserMedia(constraints).then(this.gotStream).catch(this.handleError);
    }
    /**
     * 左旋转
     */
    leftRotate() {
        this.rotateDeg -= 90;
        var videoSource = this.$refs.videoSource;
        videoSource.style.transform = "rotate(" + this.rotateDeg + "deg)";
    }
    /**
     * 右旋转
     */
    rightRotate() {
        this.rotateDeg += 90;
        var videoSource = this.$refs.videoSource;
        videoSource.style.transform = "rotate(" + this.rotateDeg + "deg)";
    }
    /**
     * 拍照
     */
    takePicture() {
        var videoSource = this.$refs.videoSource;
        var height = videoSource.videoHeight;
        var width = videoSource.videoWidth;
        var c = document.createElement("canvas");
        var ctx = c.getContext('2d');
        var degree = this.rotateDeg % 360;
        if (degree == 0 || degree == -0) {
            c.height = height;
            c.width = width;
            ctx === null || ctx === void 0 ? void 0 : ctx.translate(0, 0);
        }
        else if (degree == 90 || degree == -270) {
            c.height = width;
            c.width = height;
            ctx === null || ctx === void 0 ? void 0 : ctx.translate(height, 0);
        }
        else if (degree == 180 || degree == -180) {
            c.height = height;
            c.width = width;
            ctx === null || ctx === void 0 ? void 0 : ctx.translate(width, height);
        }
        else if (degree == 270 || degree == -90) {
            c.height = width;
            c.width = height;
            ctx === null || ctx === void 0 ? void 0 : ctx.translate(0, width);
        }
        ctx === null || ctx === void 0 ? void 0 : ctx.rotate(degree * Math.PI / 180);
        ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(videoSource, 0, 0, width, height);
        var preview = {};
        preview.url = c.toDataURL('image/jpeg', 1);
        this.$emit("takePicture", preview);
        this.imgFiles.push(preview);
        //抛出图片数据
    }
    /**
     * 上传图片
     */
    saveImg() {
        var params = {};
        params.images = this.imgFiles;
        Http.getInstance().post(this.uploadUrl, params).then((response) => {
            if (!response.data) {
                return;
            }
            const data = { name: response.data.name, id: response.data.id };
            this.imgFiles = [];
            this.$emit('closecamera', data);
        }).catch((response) => {
            this.$throw(response, 'saveImg');
        });
    }
    /**
 * 预览
 *
 * @param {*} file
 * @memberof AppFileUpload
 */
    handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
    }
    /**
     * 删除图片
     */
    handlePictureRemove(file, fileList) {
        this.imgFiles = fileList;
    }
    /**
     * 关闭预览
     */
    handleClose() {
        this.dialogVisible = false;
    }
    /**
     * 解析条形码
     */
    parseBarcode() {
        this.$info('开发中', 'parseBarcode');
    }
    rederImgContainer() {
        return (this.$createElement('el-upload', {
            props: {
                action: "#",
                headers: this.headers,
                "list-type": "picture-card",
                'file-list': this.imgFiles,
                'on-preview': (file) => this.handlePictureCardPreview(file),
                "on-remove": (file, fileList) => this.handlePictureRemove(file, fileList),
            }
        }));
    }
    /**
     * 绘制内容
     *
     * @param {CreateElement} h
     * @returns
     * @memberof AppFileUpload
     */
    render(h) {
        return (<div class="file-upload-camera2">
                <div class="camera-container">
                <div class="camera-select">
                    <span>{this.$t('components.camera.choose')}</span>
                    {/* <el-radio-group v-model={this.videoSelect}>
            {this.options ? this.options.map((items: any,index) => {
                return <el-radio label={items.value} on-change={(event)=>{this.getStream()}}>{items.label}</el-radio>
            }):''}
             </el-radio-group> */}
                    <el-select class="video-select" x-placement="top-start" v-model={this.videoSelect} popper-append-to-body={false} size="mini" on-change={(event) => { this.getStream(); }}>
                    {this.options ? this.options.map((items, index) => {
                return <el-option value={items.value} label={items.label}></el-option>;
            }) : ""}
                    </el-select>
                    </div>
                    <div class="video-container">
                        <video class="viedo-source" ref="videoSource" autoplay crossOrigin='Anonymous' style="transform:rotate(90deg)"></video>
                    </div>
                    <div class="action-container">
                    <div>
                    <el-button size="small" class="elBtn" type="primary" on-click={() => { this.leftRotate(); }} icon="el-icon-refresh-left">{this.$t('components.camera.left')}</el-button>
                    <el-button size="small" class="elBtn" type="primary" on-click={() => { this.rightRotate(); }} icon="el-icon-refresh-right">{this.$t('components.camera.right')}</el-button>
                    <el-button size="small" class="elBtn" type="primary" on-click={() => { this.takePicture(); }} icon="el-icon-camera-solid">{this.$t('components.camera.photo')}</el-button>
                    <el-button size="small" class="elBtn" type="primary" on-click={() => { this.saveImg(); }} icon="el-icon-document-checked">{this.$t('components.camera.save')}</el-button>
                    {/* <el-button size="small" class="elBtn" type="primary" on-click={()=>{this.parseBarcode()}}>识别条码</el-button> */}
                    </div>
                </div>
                </div>
                <div class="img-container">
                    {this.rederImgContainer()}
                </div>
                <el-dialog class="dialog-handlepicture" visible={this.dialogVisible} before-close={this.handleClose} append-to-body={true}><img src={this.dialogImageUrl} width="100%"/></el-dialog>
            </div>);
    }
};
__decorate([
    Prop({ default: '/ibizutil/upload' })
], AppFileUploadCamera.prototype, "uploadUrl", void 0);
AppFileUploadCamera = __decorate([
    Component({})
], AppFileUploadCamera);
export default AppFileUploadCamera;
