
//var myScroll;
var recordTimeObj = recordTimeObj(); // 录音倒计时
var userInfo = JSON.parse(localStorage.getItem(agentName));
var ct_id;
var pb_id=0;
var type = 0;
var quesNum = 1;
var quesArray=[]; //用于上一题的访问
var MIN_SOUND_TIME = 500;
var startTimestamp = null;
var recordTimer = null;
var realStartTime = 0;


$(function(){

    getPermission();
    getWechatInfo();

    $('.questionnaire-list').delegate('.questionnaire-box input[type="radio"]', 'click', function(){
        quesNum ++;
        var dc_answer = [$(this).val()];
        var pb_id = quesArray[quesArray.length-1];
        submitQuestion(pb_id, dc_answer);
    });

    $('#prev_question').on('click',function(){
        quesNum --;
        getQuestion('prev')
    });

    $('#next_question').on('click',function(){
        quesNum ++;
        var $inputs = $('.questionnaire-box input[name="question"]:checked');
        if($inputs.length < 1){
            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'未选择答案'}).show();
        }else{
            var dc_answer = [];
            $.each($inputs, function(i,input){
               dc_answer.push($(input).val());
            });
            var pb_id = quesArray[quesArray.length-1];
            //getQuestion();
            submitQuestion(pb_id, dc_answer);
        }

    });

    $('.btn-more-questionnaire').on('click', function(){
        // 展开更多检测
        //$('.questionnaire-more').hide();
        $('.questionnaire-more-box').show();
    });
    

    $('#btnRecord').on('click', function(){
        // 显示录音界面
        resetRecordSeconds();
        $('.record-dialog').addClass('fadeIn');
        setTimeout(function() {
            $('.record-dialog').removeClass('hidden');
        }, 0);
        setTimeout(function() {
            $('.record-dialog').removeClass('fadeIn');
        }, 800);
    });

    $('.record-btn').find('.back').on('click', function(){
        // 关闭录音界面
        closeRecord();
    });

    $('.record-btn').find('.start').on('click', function(){
        // 开始录音
        var that = $(this);
        startTimestamp = new Date().getTime();
        recordTimer = setTimeout(function(){
            wx.startRecord({
                success: function(){
                    realStartTime = new Date().getTime();
                    that.hide();
                    $('.record-btn').find('.stop').show();
                    //中间秒数的样式
                    recordTimeObj.recordTime('start', function(){
                    });
                },
                fail: function(){
                    dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'录音失败！请重试'}).show();
                }
            });
            wx.onVoiceRecordEnd({
                // 录音时间超过15秒没有停止的时候会执行 complete 回调
                complete: function (res) {
                    serverId = res.localId;
                    $('.record-result').show();
                },
                fail: function(){
                    dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'录音失败！请重试'}).show();
                }
            });
        },MIN_SOUND_TIME);
        stopRecordTimer = setTimeout(function(){
            wx.stopRecord({
                success: function (res) {
                    serverId = res.localId;
                    recordTimeObj.recordTime('stop');
                    $('.record-result').show();
                },
                fail: function(){
                    dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'录音失败！请重试'}).show();
                    //重置样式
                    resetRecordSeconds();
                }
            });
        },15500)
    });

    $('.record-btn').find('.stop').on('click', function(){
        // 停止录音
        var that = $(this);
        stopRecordTimer && clearTimeout(stopRecordTimer);
        var endTimestamp = new Date().getTime();

        var times = endTimestamp - startTimestamp;
        var realTimes = endTimestamp - realStartTime;
        if(times < MIN_SOUND_TIME || realTimes < MIN_SOUND_TIME){
            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'录音时间太短！'}).show();
            //重置样式
            resetRecordSeconds();
            startTimestamp = 0;
            realStartTime = 0;
            //小于300ms，不录音
            recordTimer && clearTimeout(recordTimer);
            wx.stopRecord({
                success: function (res) {
                },
                fail: function(){}
            });
        }else{
            wx.stopRecord({
                success: function (res) {
                    serverId = res.localId;
                    recordTimeObj.recordTime('stop');
                    $('.record-result').show();
                },
                fail: function(){
                    dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'录音失败！请重试'}).show();
                    //重置样式
                    resetRecordSeconds();
                }
            });
        }

    });

    $('.record-result-btn').find('.cancel').on('click', function(){
        // 重新录音
        $('.record-result').hide();
        resetRecordSeconds();
        //如果录音是在播放的状态，停止播放
        if($('.record-result-btn').find('.btn-action').hasClass('pause')){
            wx.stopVoice({
                localId: serverId // 需要停止的音频的本地ID，由stopRecord接口获得
            });
        }
        
    });

    $('.record-result-btn').find('.ok').on('click', function(){
        // 确认录音
        var st = $('.record-time .time').find('span').html();
        var st1 = st.split('.')[0];
        var st2 = st.split('.')[1];
        var et1 = 14 - st1;
        var et2 = 10 - st2;
        var t = et2 < 10 ? ( et1 + '.0' + et2 ) : ( (et1 + 1) + '.00' );
        closeRecord();
        setTimeout(function() {
            $('.record-result').hide();
        }, 10);
        
        // 录音展示
        $('#recordContent').find('.seconds').html(t);
        $('#recordContent').find('.upload').hide();
        $('#recordContent').find('.file').show();

        //如果录音在播放状态下，停止播放
        if($('.record-result-btn').find('.btn-action').hasClass('pause')){
            wx.stopVoice({
                localId: serverId // 需要停止的音频的本地ID，由stopRecord接口获得
            });
        }
    });
    //播放录音
    $('.record-result-btn').find('.btn-action').on('click', function(){
        var that = $(this);
        if(that.hasClass('play')){//播放
           that.removeClass('play').addClass('pause');
           wx.playVoice({
               localId: serverId // 需要播放的音频的本地ID，由stopRecord接口获得
           });

        }else if(that.hasClass('pause')){
           that.removeClass('pause').addClass('play');
           wx.pauseVoice({//暂停
               localId: serverId  // 需要暂停的音频的本地ID，由stopRecord接口获得
           });
       }
        //录音播放完毕
        wx.onVoicePlayEnd({
            success: function (res) {
                var localId = res.localId; // 返回音频的本地ID
                that.removeClass('pause').addClass('play');
            }
        });
    });

    $('.questionnaire-more-box').on('click', '.remove', function(){
        // 删除文件，重新上传
        var  that = $(this);
        var pObj = that.parents('.file');
        var loadBox = pObj.siblings('.upload');
        pObj.find('img').attr('src', ' ');
        pObj.find('img').attr('data-src', ' ');
        pObj.hide();
        loadBox.show();
    });

    $('#uploadFace').on('change', function(){
        // 面部图片上传
        var that = $(this);
        $('.btn-bar').addClass('hidden');
        clip_photo(that, 1);
    });

    $('#uploadTongue').on('change', function(){
        // 舌部图片上传
        var that = $(this);
        $('.btn-bar').addClass('hidden');
        clip_photo(that, 2);
    });

    //点击提交,提交录音
    $('#btn_submit').on('click',function(){
        wx.uploadVoice({
            localId: serverId, // 需要上传的音频的本地ID，由stopRecord接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
                var wechatServerId = res.serverId; // 返回音频的服务器端ID
                submitVoice(wechatServerId);
            }
        });
    });
});


function closeRecord(){
    // 关闭录音界面
    $('.record-dialog').addClass('bounceOutRight');
    setTimeout(function() {
        $('.record-dialog').addClass('hidden');
        $('.record-dialog').removeClass('bounceOutRight');
    }, 800);
}

function resetRecordSeconds(){
    // 重置倒计时样式
    $('.record-time .time').find('span').html('15.00');
    $('.record-time').find('.pie').attr('style', '');
    $('.record-btn').find('.stop').hide();
    $('.record-btn').find('.start').show();
}

//剪切图片
function clip_photo(obj, type){
    $('#wrapper').addClass('hidden');
    var photo = obj[0];
    var code = userInfo.uid;
    lrz(photo.files[0]).then(function (rst) {
        var url = rst.base64;
        new AlloyCrop({
            image_src: url,
            width: document.documentElement.clientWidth - 100,
            height: document.documentElement.clientWidth - 100,
            ok_text: "保存",
            cancel_text: "取消",
            output: 1,
            ok: function (base64, canvas) {
                $("#wrapper").removeClass("hidden");
                setTimeout(function(){
                    $('.btn-bar').removeClass('hidden')
                },0);
                var data=base64.split(',')[1];
                data=window.atob(data);
                var ia = new Uint8Array(data.length);
                for (var i = 0; i < data.length; i++) {
                    ia[i] = data.charCodeAt(i);
                }
                var blob=new Blob([ia],{type:"image/png",endings:'transparent'});
                var fd=new FormData();
                fd.append('ct_id',ct_id);
                fd.append('type',type);
                fd.append('patientCode',code);
                fd.append('file',blob,'image.png');
                var new_url = URL.createObjectURL(blob);
                appendFile(new_url, obj);
                obj.val('');
                 $.ajax(server_jm+'/medicine/physicalExamination/dillphoneimgdata', {
                    data: fd,
                    dataType: 'json',
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function(request) {
                        //request.setRequestHeader("userAgent", userAgent);
                    },
                    type: 'post',
                    error: function(res) {
                        dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'图片上传失败！'}).show();
                        if(res.status == 999 || res.status == 998 || res.status == 997){
                            loginUrl(res.status);
                            return;
                        }
                        clickCount = 0;
                    },
                    success: function(res) {
                        if(res.status == 999 || res.status == 998 || res.status == 997){
                            loginUrl(res.status);
                            return;
                        }
                        var params = {};
                        params.photo = res.urls;
                        var patientUrl = res.urls;
                        clickCount = 0;
                    }
                });
            },
            cancel: function () {
                $("#wrapper").removeClass("hidden");
                obj.val('');
                setTimeout(function(){
                    $('.btn-bar').removeClass('hidden')
                },0);
                return;
            }
        });
    })
    .catch(function (err){
        // 处理失败会执行
        //console.log(err)
          dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:err}).show();
    });
    
}

function appendFile(p, obj) {
    var pObj = obj.parents('.upload');
    var fileBox = pObj.siblings('.file');
    pObj.hide();
    fileBox.show();
    fileBox.find('img').attr('src', p);
    fileBox.find('img').attr("data-src",p);
    //iscrollRefresh();
}

//验证权限
function getPermission(){
    var code = userInfo.uid;
//判断是否有访问权限,若有,则进入答题页面
    var loading = dialog({contentType:'load', skin:'bk-popup'});
    loading.show();
    sendPost(server_jm+"/medicine/physicalExamination/insertslip", {patientCode: code}, "json", "get", function(){

    }, function(data){
        loading.close();
        if(data.isSignJM==2){//已签约的集美市民---->>进入第一题试题
            ct_id = data.recordset.ct_id;//咨询编号 ,需要保存下来,之后接口有用到
            //获取题目
            getQuestion();

        }else if(data.isSignJM==0 || data.isSignJM==3){ //未签约集美,且非厦门居民--->>跳转到敬请期待页面
            // window.location.href='./expectancy-page.html';
        }else{//跳转到签约说明页面  data.isSignJM==1
            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'只有与集美区进行家庭医生签约的用户才可享受此签约特色服务'}).show();
            //window.location.href='http://www.xmtyw.cn/wlyy/wx/html/qygl/html/signing-share2.html';
        }
    });


}

function getQuestion(quesType){
    var code = userInfo.uid;
    var pbId = pb_id;
    if(quesType == 'prev'){
        if(quesArray.length<=2){
            pbId = 0;
        }else{
            pbId = quesArray[quesArray.length-3];
        }
    }
    if(quesNum >= 2 && $('#prev_question').hasClass('hidden')){
        $('#prev_question').removeClass('hidden');
    }else if(quesNum < 2){
        $('#prev_question').addClass('hidden');
    }
    var loading = dialog({contentType:'load', skin:'bk-popup'});
    loading .show();
    var width = parseFloat($('.questionnaire-progress').css('width'));
    var left = parseFloat($('.progress-box').css('left'));
    sendPost(server_jm+"/medicine/physicalExamination/findQuestion", {
        pb_id:pbId,
        ct_id:ct_id,
        patientCode:code
    }, "json", "get", function(){
    }, function(data){
        loading.close();
        if(data.status==200){
            var question = data.recordset;//这边还需要判断是否是最后一题   最后一题会返回空对象 {}     返回空对象,跳转到面部等检查页面
            var pb_code = question.pb_id;    //查找  第一题的题目pb_id为0   ,但是提交第一题的答案是提交这个pb_code
            if(pb_code){
                pb_id = pb_code;

                if(quesType == 'prev'){
                    quesArray.pop();
                    var minLeft = -parseFloat($('.progress-box').css('margin-left'));
                    if(quesNum>1 && left > minLeft+30){
                        left -= 30;
                        $('.progress-box').css('left',left+'px');
                    }else if(quesNum == 1){
                        $('.progress-box').css('left',minLeft+'px');
                    }
                }else{
                    if(quesNum>1 && left < width-30){
                        left += 30;
                        $('.progress-box').css('left',left+'px');
                    }
                    quesArray.push(pb_code);
                }
                $('#questionnaire_list').html('');
                var choice = question.pb_alternative.split(/\r+|\s+/);
                var title = question.pb_title;
                var cHtml = '';
                var ctype = '';
                var className = '';
                if(question.i_multiselect == '1'){
                    cHtml = '（单选）';
                    ctype = 'radio';
                    className = 'single-choice';
                }else{
                    cHtml = '（多选）';
                    ctype = 'checkbox';
                    className = 'multi-choice';
                    type = 1;
                }
                if(choice && choice.length>0){
                    var sHtml = '';
                    $.each(choice, function(i, item){
                        sHtml += '<li>'
                                    +'<label>'
                                    +'<input value="'+item+'" type="'+ctype+'" name="question">'
                                    +'<span></span>'
                                    +item
                                    +'</label>'
                                  +'</li>'
                    })
                }
                var html = '<div class="questionnaire-box '+className+'">'
                            +'<div class="title">'
                            +quesNum+'.'+title+'<span>'+cHtml+'</span><font>*</font>'
                            +'</div>'
                            +'<div class="answer">'
                            +'<ul>'
                            +sHtml
                            +'</ul>'
                            +'</div>'
                            +'</div>';
                $('#questionnaire_list').append(html);
            }else{//不是最后一题
                //dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'最后一题了！'}).show();
                $('#questionnaire_list').html('');
                $('.btn-bar').removeClass('hidden');
                $('.bottom-btn').addClass('hidden');
                $('.questionnaire-more-box').show();
                $('.progress-box').css('left',width+'px');
            }

        }else{
            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:data.msg}).show();
        }

    });
}
//提交试卷
function submitQuestion(pb_id, dc_answer, quesType){
    var code = userInfo.uid;
    sendPost(server_jm+"/medicine/physicalExamination/handleExam", {
      ct_id: ct_id,
      pb_id: pb_id,
      type: type,
      dc_answer: JSON.stringify(dc_answer),
      patientCode: code
    }, "json", "get", function(){

    }, function(data){
        if(data.status==200){
            getQuestion(quesType);
        }else{
            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'提交失败！'+data.msg}).show();
        }
    });
}
//提交录音
function submitVoice(mediaId){
    var code = userInfo.uid;
    var loading = dialog({contentType:'load', skin:'bk-popup'});
    loading .show();
    sendPost(server_jm+"/medicine/physicalExamination/dealVoice", {
        mediaId: mediaId,
        ct_id: ct_id,
        patientCode: code,
        type: 3
    }, "json", "get", function(){

    }, function(data){
        loading.close();
        if(data.status==200){
            window.location.href='./medical-examination-result.html?ctId='+ct_id;
        }else{
            window.location.href='./submit-fail.html';
            dialog({contentType:'tipsbox',bottom:true, skin:'bk-popup' , content:'提交失败！'+data.msg}).show();
        }
    });
}

function getWechatInfo(){
    //从后台那边获取签名等信息
    var params = {};
    var url1 = window.location.href;
    params.pageUrl = url1;
    $.ajax("/wlyy/weixin/getSign", {
        data: params,
        dataType: "json",
        type: "post",
        success: function(res){
            if (res.status == 200) {
                var t = res.data.timestamp;
                var noncestr = res.data.noncestr;
                var signature = res.data.signature;
                wx.config({
                    appId: appId, // 必填，公众号的唯一标识
                    timestamp: t, // 必填，生成签名的时间戳
                    nonceStr: noncestr, // 必填，生成签名的随机串
                    signature: signature,// 必填，签名，见附录1
                    jsApiList: [
                        'chooseImage',
                        'uploadImage',
                        'startRecord',
                        'stopRecord',
                        'onVoiceRecordEnd',
                        'playVoice',
                        'pauseVoice',
                        'stopVoice',
                        'onVoicePlayEnd',
                        'uploadVoice',
                        'getNetworkType'
                    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });

                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                wx.ready(function(){
                    wx.getNetworkType({
                        success: function (res) {
                            networkStatus = res.networkType; // 返回网络类型2g，3g，4g，wifi
                        }
                    });
                });
            }
        }
    });
}

