$(function () {
    let storeId = getQueryString("storeId");
    let orderBizType = 10;
    // let payStatus = '0';
    // let orderStatus = '0';
    let url = '../face/orderList?1';
    if (storeId) {
        url += '&storeId=' + storeId;
    }
    if (orderBizType) {
        url += '&orderBizType=' + orderBizType;
    }
    // if (payStatus) {
    //     url += '&payStatus=' + payStatus;
    // }
    // if (orderStatus) {
    //     url += '&orderStatus=' + orderStatus;
    // }
    $("#jqGrid").jqGrid({
        url: url,
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '所属门店', name: 'storeName', index: 'storeName',align: 'center', width: 70},
            {label: '订单号', name: 'orderSn', index: 'order_sn', align: 'center',width: 100},
            {label: '会员', name: 'userName', index: 'user_name', align: 'center',width: 50},
            // {label: '商户订单号', name: 'merchOrderSn', index: 'merchOrderSn',align: 'center', width: 80},
            {
                label: '订单业务类型', name: 'orderBizType', index: 'order_biz_type',align: 'center', width: 60,
                formatter: function (value) {
                    if (value == '00') {
                        return '保税备货';
                    } else if (value == '02') {
                        return '保税展示补货';
                    } else if (value == '10') {
                        return '保税展示跨境';
                    } else if (value == '11') {
                        return '普通货物';
                    }
                    return '-';
                }
            },
            {
                label: '订单状态', name: 'orderStatus', index: 'order_status',align: 'center', width: 80,
                formatter: function (value) {
                    if (value == '0') {
                        return '订单创建成功等待付款';
                    } else if (value == '100') {
                        return '订单付款中';
                    } else if (value == '101') {
                        return '订单已取消';
                    } else if (value == '102') {
                        return '订单已删除';
                    } else if (value == '201') {
                        return '订单已付款，等待发货';
                    } else if (value == '300') {
                        return '订单已发货';
                    } else if (value == '301') {
                        return '用户确认收货';
                    } else if (value == '401') {
                        return '没有发货，退款';
                    } else if (value == '402') {
                        return '已收货，退款退货';
                    }
                    return value;
                }
            },
            // {
            //     label: '订付人核验', name: 'buyerPayCheck', index: 'buyer_pay_check',align: 'center', width: 60,
            //     formatter: function (value) {//订购人支付人校验，0:未知，1:一致，2:不一致,3:校验异常
            //         if (value == '0') {
            //             return '未知';
            //         } else if (value == '1') {
            //             return '一致';
            //         } else if (value == '2') {
            //             return '不一致';
            //         }
            //         return "-";
            //     }
            // },
            {
                label: '付款状态', name: 'payStatus', index: 'pay_status',align: 'center', width: 50,
                formatter: function (value) {
                    if (value == '0') {
                        return '未付款';
                    } else if (value == '1') {
                        return '付款中';
                    } else if (value == '2') {
                        return '已付款';
                    } else if (value == '3') {
                        return '退款中';
                    } else if (value == '4') {
                        return '退款';
                    }
                    return value;
                }
            },
            // {label: '实际支付', name: 'actualPrice', index: 'actual_price', align: 'center',width: 50},
            {label: '订单总价', name: 'orderPrice', index: 'order_price', align: 'center',width: 50},
            {
                label: '下单时间', name: 'addTime', index: 'add_time',align: 'center', width: 95,
                formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }
            },
            {label: '是否人脸认证', name: 'isFaceCheck', index: 'isFaceCheck', align: 'center',width: 65,
                formatter: function (value) {
                    if (value == '0') {
                        return '否';
                    } else if (value == '1') {
                        return '是';
                    }else{
                        return '-';
                    }
                    return value;
                }
            },
            {label: '是否模板通知', name: 'isTempNoti', index: 'isTempNoti', align: 'center',width: 65,
                formatter: function (value) {
                    if (value == '0') {
                        return '否';
                    } else if (value == '1') {
                        return '是';
                    }else{
                        return '-';
                    }
                    return value;
                }
            },
            {label: '人脸识别返回信息', name: 'recognitionReturnMsg', index: 'recognitionReturnMsg', align: 'center',width: 100},
            {label: '模板通知返回信息', name: 'tempNotiMsg', index: 'tempNotiMsg', align: 'center',width: 90},
            {label: '核验操作类型', name: 'checkOperatorType', index: 'checkOperatorType', align: 'center',width: 65,
                formatter: function (value) {
                    if (value == '1') {
                        return '人脸活体识别';
                    } else if (value == '2') {
                        return '按钮审核身份';
                    }else{
                        return '-';
                    }
                    return value;
                }},
            {
                label: '操作', width: 200, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    let htmlStr = '';
                    // if (hasPermission('face:checkLivenessRecognition')) {
                    //isDateLast 该订单是否在可验证人脸时间内
                    if((row.isFaceCheck==0 || row.isFaceCheck == null) && row.isDateLast=='true' && row.payStatus==0 && row.orderStatus==0){
                        htmlStr +='<button class="btn btn-outline btn-danger" onclick="vm.startCheckFace(' +
                            row.id + ','+row.userId+','+row.thirdIsFaceCheck+')">人脸识别</button>&nbsp;';
                    }
                    // }
                    if((row.isFaceCheck==0 || row.isFaceCheck == null) && row.failCount >= 3 && row.payStatus==0 && row.orderStatus==0){
                        htmlStr +='<button class="btn btn-outline btn-danger" onclick="vm.manualCheckFace(' +
                            row.id + ','+row.thirdIsFaceCheck+')">审核人脸通过</button>&nbsp;';
                    }
                    if(row.isFaceCheck == 1 && row.failCount >= 3){
                        htmlStr +='<button class="btn btn-outline btn-danger" onclick="vm.getCheckDetail(' +
                            row.faceLivenessId + ','+row.thirdIsFaceCheck+')">审核明细</button>&nbsp;';
                    }
                    if((row.isFaceCheck==0 || row.isFaceCheck == null) && row.isDateLast=='false' && row.payStatus==0 && row.orderStatus==0){
                        htmlStr +='<span style="color: red">该订单用户在\n'+row.addSecondTime+'时间前\n可不再进行人脸识别</span>';
                    }
                    if(row.isFaceCheck == 1 && row.isTempNoti == 0 && row.payStatus==0 && row.orderStatus==0){
                        htmlStr +='<button class="btn btn-outline btn-danger" onclick="vm.sendWxTemp(' +
                            row.id +','+row.thirdIsFaceCheck+')">发起微信待支付模板通知</button>&nbsp;';
                    }
                    return htmlStr==''?'-':htmlStr;
                }
            }],
        viewrecords: true,
        height: 645,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: 0,
        title: null,
        faceLivenessRecognition: {},
        checkFaceOperator: {},
        ruleValidate: {
            // approvalRemark: [
            // {required: true, message: '审核备注不能为空', trigger: 'blur'}
            // ]
        },
        q: {
            orderSn: ''
        },
        video: null,
        mediaStream: null
    },
    methods: {
        query: function () {
            vm.reload();
        },
        sendWxTemp: function(rowId,thirdIsFaceCheck){
            if(thirdIsFaceCheck==1){
                let url = '../face/sendWxTemp/';
                confirm('是否确认发起微信待支付模板通知？', function () {
                    $.get(url + rowId, function (r) {
                        if (r.code === 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    });
                });
            }else {
                alert('请检查第三方商户需开放是否核验人脸开关');
            }
        },
        startCheckFace: function(rowId,userId,thirdIsFaceCheck) {
            if(thirdIsFaceCheck==1){
                vm.showList = 2;
                vm.title = "活体人脸核身";
                $.get('../user/info/' + userId, function (r) {
                    let userInfo = r.user;
                    vm.faceLivenessRecognition = {
                        idCard: userInfo.idNo,
                        name: userInfo.username,
                        // videoBase64: '1',
                        orderId: rowId
                    };
                    vm.startVideo();
                });
            }else {
                alert('请检查第三方商户需开放是否核验人脸开关');
            }
        },
        startVideo: function(){
            var that = this;
            let lodingMsg = that.$Message.loading('视频加载中....', 6000);
            $('#startBtn').attr('disabled', true);
            $('#stopBtn').attr('disabled', true);
            $('#ppBtn').attr('disabled', true);
            $("#outVideo-div").html('');
            //判断浏览器
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
            var constraints = { audio: true, video: { width: 480, height: 320 } };
            var aa = '' ; //防止两次上传
            //调用摄像头  成功后获取视频流：mediaStream
            navigator.mediaDevices.getUserMedia(constraints)
                .then(function(mediaStream) {
                    vm.mediaStream = mediaStream;
                    var video = document.querySelector('video');
                    // 赋值 video 并开始播放
                    video.srcObject = mediaStream;
                    video.onloadedmetadata = function(e) {
                        video.play();
                        $('#startBtn').attr('disabled', false);
                        setTimeout(lodingMsg, 0);
                        that.$Message.loading('视频已加载成功', 0);
                    };
                    //录像api的调用
                    var mediaRecorder = new MediaStreamRecorder(mediaStream);
                    mediaRecorder.mimeType = 'video/webm';
                    //  停止录像以后的回调函数
                    mediaRecorder.ondataavailable = function (blob) {
                        //  停止以后调用上传
                        if(aa == ""){
                            uploadToPHPServer(blob);
                            aa = blob;
                        }
                    };
                    $("#startBtn").click(function(){
                        vm.showTime(4);
                        $('#commentDiv').html('活体人脸识别音频开始录制...录制3秒后自动上传转为base64，录制倒计时：');
                        $('#startBtn').attr('disabled',true);
                        $('#ppBtn').attr('disabled',true);
                        $('#stopBtn').attr('disabled',true);
                        //开始录像
                        mediaRecorder.start();
                        setTimeout(function(){
                            //停止录像
                            mediaRecorder.stop();
                        },4000);
                    });
                    //停止录像
                    $("#stopBtn").click(function(){
                        $('#commentDiv').html('');
                        mediaRecorder.stop();
                    });
                    //重新开始录像
                    $("#ppBtn").click(function(){
                        if(aa !== ""){
                            vm.showTime(4);
                            $('#commentDiv').html('活体人脸识别音频开始录制...录制3秒后自动上传转为base64，录制倒计时：');
                            // $('#startBtn').attr('disabled',false);
                            $('#stopBtn').attr('disabled',true);
                            $('#ppBtn').attr('disabled',true);
                            aa = "";
                            mediaRecorder.start();
                            setTimeout(function(){
                                //  4秒后停止录像
                                mediaRecorder.stop();
                            },4000);
                        }
                    });
                    // 上传
                    function uploadToPHPServer(blob) {
                        var file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
                            type: 'video/webm'
                        });
                        var formData = new FormData();
                        formData.append('videoFilename', file.name);
                        formData.append('file', file);
                        console.log(formData.get("file"));
                        alert("录像结束",function () {
                            $("#outVideo-div").html('');
                            $.ajax({
                                url:'../sys/oss/uploadAndBase64',
                                dataType:'json',
                                type:'POST',
                                async: false,
                                data: formData,
                                processData : false, // 使数据不做处理
                                contentType : false, // 不要设置Content-Type请求头
                                success: function(data){
                                    console.log(data);
                                    if(data.code==0){
                                        var objURL = vm.getObjectURL(formData.get("file"));//这里的objURL就是file的真实路径
                                        // var src = data.url;
                                        var video = '<video id="outVideo" controls="" autoplay="" name="media" style="width: 480px !important;height: 320px !important;">\n' +
                                            '<source src=\"' + objURL +
                                            '\"></video>';
                                        $("#outVideo-div").html(video);

                                        $('#ppBtn').attr('disabled', false);
                                        $('#commentDiv').html('');

                                        vm.faceLivenessRecognition.videoBase64 = data.base64EncoderImg;
                                    }else{
                                        alert(data.msg);
                                        $('#ppBtn').attr('disabled', false);
                                    }
                                },
                                error:function(response){
                                    console.log(response);
                                }
                            });
                        });
                    }
                    //  上传结束
                }).catch(function(err) {
                console.log(err.name + ": " + err.message);
            });
        },
        getObjectURL:function(file) {
            var url = null;
            if (window.createObjcectURL != undefined) {
                url = window.createOjcectURL(file);
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        },
        // 计时开始
        startTimer(){
            let self = this;
            this.si = setInterval(function () {
                self.timer++;
            }, 1000);
        },
        // 比赛结束，停止计时
        stopTimer(){
            let self = this;
            clearInterval(self.si);
        },
        //显示倒数秒数
        showTime(countdown){
            let self = this;
            self.isShareCount = true;
            self.isShowBtn = false;
            self.isShowFalseBtn = true;
            document.getElementById('showtimes').innerHTML = countdown;
            if (countdown == 0) {
                self.isShareCount = false;
                self.isShowTimer = true;
                self.isShowFalseBtn = false;
                document.getElementById('showtimes').innerHTML = "";
                // 计时器开始计时
                self.startTimer();
            } else {
                countdown -= 1;
                setTimeout(function () {
                    self.showTime(countdown);
                }, 1000);
            }
        },
        //访问用户媒体设备的兼容方法
        getUserMedia: function(constraints, success, error) {
            if (navigator.mediaDevices.getUserMedia) {
                //最新的标准API
                navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
            } else if (navigator.webkitGetUserMedia) {
                //webkit核心浏览器
                navigator.webkitGetUserMedia(constraints,success, error)
            } else if (navigator.mozGetUserMedia) {
                //firfox浏览器
                navigator.mozGetUserMedia(constraints, success, error);
            } else if (navigator.getUserMedia) {
                //旧版API
                navigator.getUserMedia(constraints, success, error);
            }
        },
        videoSuccess: function(mediaStream) {
            //兼容webkit核心浏览器
            let CompatibleURL = window.URL || window.webkitURL;
            try{
                vm.video.src = CompatibleURL.createObjectURL(mediaStream);
            }catch(e){
                vm.video.srcObject = mediaStream;
            }
            vm.video.onloadedmetadata = function(e) {
                vm.video.play();
            };
        },
        videoError: function(error) {
            console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
            alert(`访问用户媒体设备失败${error.name}, ${error.message}`);
        },
        manualCheckFace: function(rowId,thirdIsFaceCheck) {
            if(thirdIsFaceCheck==1){
                confirm('该订单人脸核身核验失败次数超过或等于3次，请您自行核验该会员身份信息，确认是本人后点击确定', function () {
                    $.get("../face/manualCheckFace/" + rowId, function (r) {
                        if (r.code === 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    });
                });
            }else {
                alert('请检查第三方商户需开放是否核验人脸开关');
            }
        },
        getCheckDetail: function(faceLivenessId, thirdIsFaceCheck) {
            if(thirdIsFaceCheck==1){
                vm.showList = 3;
                vm.title = "审核人脸身份操作人信息";
                $.get("../face/get/" + faceLivenessId, function (r) {
                    console.log(r)
                    if (r.code === 0) {
                        vm.checkFaceOperator = {
                            checkOperatorType: r.faceLiveness.checkOperatorType,
                            checkOperatorSn: r.faceLiveness.checkOperatorSn,
                            // videoBase64: '1',
                            checkOperatorTime: r.faceLiveness.checkOperatorTime
                        };
                    }
                });
            }else {
                alert('请检查第三方商户需开放是否核验人脸开关');
            }
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        saveOrUpdate: function (event) {
            var that = this;
            let lodingMsg = that.$Message.loading('人脸验证中....');

            $('#sub').attr('disabled', true);
            let url = '../face/checkLivenessRecognition';
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.faceLivenessRecognition),
                success: function (r) {
                    if (r.code === 0) {
                        setTimeout(lodingMsg, 0);
                        // that.$Message.loading('视频已加载成功', 0);
                        alert(r.msg, function (index) {
                            vm.reload();
                            $('#sub').attr('disabled', false);
                        });
                    } else {
                        alert('请重新录像！活体人脸核身验证失败，失败原因：'+r.msg);
                        $('#ppBtn').attr('disabled', false);
                        $('#sub').attr('disabled', false);
                    }
                }
            });
        },
        reloadSearch: function() {
            vm.q = {
                orderSn: ''
            }
            vm.reload();
        },
        reload: function (event) {
            if(vm.mediaStream){
                vm.mediaStream.stop();
            }
            vm.showList = 0;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'orderSn': vm.q.orderSn},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});
