$(document).ready(function() {
    var notRadio = '';
    var yesRadio = '';
    var notChecked = '';
    var checked = '';
    var payResultTimer = null;
    var service_domain = location.origin+'/'
    var isPayDialog = false
    var allPostData=new Object()
    //获取服务项目具体信息
    $.ajax(service_domain +'ajax_get_ai_services', function(response) {
        // 请求成功时的回调函数
        console.log(response);
    }).fail(function(xhr, status, error) {
        // 请求失败时的回调函数
        console.log(error);
    });
    //step监听滚动位置
        $(window).scroll(function() {
            var element = $('.step_back'); 
            var element2 = $('.footer'); 
            var distanceToTop = element.offset().top - $(this).scrollTop();
            if(distanceToTop <= 64){
                element.addClass('stickyStep')
                element2.addClass('footer2')
                
            }else{
                element.removeClass('stickyStep')
                element2.removeClass('footer2')
            }
        });
    function getFormData() {
        var formData = new FormData(document.querySelector('form'));
        var data = {};
        for (var [key, value] of formData.entries()) {
            data[key] = value;
        }
        console.log(data);
    }
    //标题输入字数
    $('.inputChange').on('input', function() {
        var maxLength = $('.inputText').attr('max');
        var currentLength = $(this).val().length;
        if(currentLength > 0){
            $('.normal_recommend_title').addClass('recommend_title')
        }else{
            $('.normal_recommend_title').removeClass('recommend_title')
        }
        $('.inputText').text(currentLength + '/' + maxLength);
        if(currentLength >maxLength){
            $('.inputText').addClass('warnInputText')
        }else{
            $('.inputText').removeClass('warnInputText')
            // $('.inputText').removeClass('recommend_title')
        }
    });
    // $('.inputChange').on('blur', function() {
    //     console.log('blur----');
    //     getAiTitleList()
    // });
    // $('.right_btn').click(function(e) {
    //     if ($('.right_btn').hasClass('activebtn')) {
    //         $('.right_btn').removeClass('activebtn')
    //     }
    //     $(this).addClass('activebtn')
    // });
    function showOptArea(area){
        $('.opt-area').css('display','none');
        $('#'+area).css('display','block');
    }
    function hideOptArea(){
        $('.opt-area').css('display','none');
    }
    function getWordCountList(){
        var chkType = $('li.active_select').attr('type');
        var word_list_str = $("#word_list_str"+chkType).val();

        $('.form_essayWords').addClass('disNone');
        if(word_list_str){
            var word_list = word_list_str.split(",");
            if(word_list.length>0){
                $('.form_essayWords').removeClass('disNone');
            }
        }
    }
    $('.pay_every').click(function(e){
        if ($('.pay_every').hasClass('pay_active')) {
            $('.pay_every').removeClass('pay_active')
        }
        $(this).addClass('pay_active')
        let pay_type = $('.pay_active').attr('pay_type');
        allPostData = {...allPostData,pay_type}
        // $('#totalMoney').text('')
        payAction()
        // getPayQrcode(postData,check_flag)

    })
    $('.close_modal').on('click',function(e){
        $('.pageMask').addClass('hide');
        $('.payModal').addClass('hide');
        if(!$('.pay_detail').hasClass('hide')){
            $('.pay_detail').addClass('hide')
        }
        if($('.modal_mes').hasClass('hide')){
            $('.modal_mes').removeClass('hide')
        }
        if($('.pay_content').hasClass('hide')){
            $('.pay_content').removeClass('hide')
        }
        clearTimeout(payResultTimer);
    })
    function getPayType() {
        var paytype = $('.pay_active').attr('pay_type');
        return paytype;
    }
    function payAction(){
        let check_type = $('li.active_select').attr('type');
        let check_flag = $('li.active_select').attr('check_flag');
        let pay_type = getPayType();
        let title = $('.inputChange').val().trim();
        // goods_id 0
        // const postData = {
        //     title:'88',
        //     check_type,
        //     pay_type,
        //     get_pay_goods:'1',
        //     aiessay_wordnum:'3000',
        //     // recharge_goods_id:'0',
        //     // value_added_services:''//增值服务
        // }
        if(check_type == '') {
            alert('提交类型不合法');
            errorJump();
            return false;
        }
        const postData = {
            title,
            check_type,
            pay_type,
            get_pay_goods: '1',
        }
        if ($('.opt-advise').css('display') !== 'none') {
            if(title == ''){
                alert('提交标题不能为空');
                return;
            }
            if(check_type == '62' ||check_type == '63'){
                if(title.length >500){
                    alert('论文标题不得多于500字');
                    // errorJump();
                    $('.inputChange').val('')//重置输入框文本
                    $('.inputText').text('0/500')
                    return;
                }
            }
            if(title.length >100){
                alert('论文标题不得多于100字');
                $('.inputChange').val('')//重置输入框文本
                $('.inputText').text('0/100')
                return;
            }
        }
        if(check_type == '64'){
            title = $('.key_words_input').val().trim()
            if(title == ''){
                alert('关键词不能为空');
                return;
            }
            if(title.length >50){
                alert('关键词不得多于50字');
                $('.inputChange').val('')//重置输入框文本
                return;
            }
            postData.title = title
        }
        if(!$('.custom-select').hasClass('disNone')){
            var major = parseInt($('#project_select').find('option:selected').val());
            if (major <= 0 || !major) {
                alert("请选择您的专业");
                return;
            }
        }
        if ($('.form_essayWords').css('display') !== 'none') {
            var wordnums = parseInt($('input[type="radio"][name="wordnums"]:checked').val());
            if (wordnums <= 0 || isNaN(wordnums)) {
                alert("请选择您的字数");
                return;
            }
        }
        allPostData = {...allPostData,check_flag,recharge_goods_id:'0',...postData}

        //检验信息
        getPayQrcode(postData)
    }
    function clearhisText(){
        $('.inputChange').val('')//重置输入框文本
        $('.key_words_input').val('')//重置输入框文本
        $('.inputText').text('0/100')
        $('#project_select').val('')
        $('.coreWordCount').val('')
       if($('.normal_recommend_title').hasClass('recommend_title'))$('.normal_recommend_title').removeClass('recommend_title')
    }
    function errorJump() {
        // if(isPayDialog) {
            location.reload();
            return;
        // }
        // location.href = '/';
    }
    $('#formInputSumbtn').on('click',function(e){
        payAction()
    })
    function getPayQrcode(postData){
        
        $.ajax({
            type: "post",
            dataType:'json',
            url: service_domain + allPostData.check_flag+'/ajax_check_aisubmit',
            data: {
                ...postData
            }, 
            success: function (res) {
                if(res.data.user_not_enough_money) {
                    if(isPayDialog){
                        $('.pageMask').addClass('hide');
                        $('.payModal').addClass('hide');
                    }
                    $('.pageMask').removeClass('hide');
                    $('.payModal').removeClass('hide');
                    isPayDialog = true
                    if(postData.pay_type == 2 || postData.pay_type == 3){
                        getRechargePayUrl()
                        // getRechargeGoods(payInfo, configData);
                    }
                }
            }
        });
    }
    function getRechargePayUrl(){
        console.log(allPostData,'allPostData');
        var core_content = $('.coreWordCount').val();
        var postData1 = new Object();
        postData1.type = allPostData.check_type;
        postData1.pay_type = allPostData.pay_type;
        // postData1.value_added_services = configData.addedServicesStr;//增值服务
        // if(configData.ppt_tpl != '') postData1.ppt_tpl = configData.ppt_tpl;//ppt
        // postData1.recharge_goods_id = '0';
        postData1.title = allPostData.title;
        // postData1.core_content = core_content;
        // if(postData1.type == '63'){
        //     postData1.major = parseInt($('#project_select').find('option:selected').val());
        // }
        if(!$('.custom-select').hasClass('disNone')){
            var major = parseInt($('#project_select').find('option:selected').val());
            postData1.aiessay_major = major
        }
        if(!$('.formItem_pro').hasClass('disNone')){
            var edu = parseInt($('#educationRight').find('input[type="radio"]:checked').val());
            postData1.aiessay_edu = edu
        }
        if ($('.form_essayWords').css('display') !== 'none') {
            var wordnums = parseInt($('input[type="radio"][name="wordnums"]:checked').val());
            postData1.aiessay_wordnum = wordnums
        }
        if(postData1.type == '94'){
            postData1.core_content = $('.core_content').val().trim()//核心内容
        }
        $.ajax({
            url:service_domain+allPostData.check_flag+'/ajax_get_ai_pay_url',
            type:'post',
            dataType:'json',
            data:{...postData1},
            // data:{
            //     type: '94',
            //     pay_type: postData1.pay_type,
            //     value_added_services: '',
            //     recharge_goods_id: '0',
            //     title: '123',
            //     fuid: '',
            //     aiessay_wordnum: '3000',
            //     aiessay_edu: '2',
            //     aiessay_major: '1'
            // },
            success:function(res){
                if(res.status){
                    $('#qrcode').html('');
                    $('#qrcode').attr('tid', res.data.tid);
                    $('#qrcode').attr('paytype', postData1.pay_type);
                    $('#totalMoney').text(res.data.total_fee)
                    var qrcode = new QRCode(document.getElementById("qrcode"), {
                        text: res.data.qrcode_url,
                        width: 135,
                        height: 135,
                        colorDark : "#000000",
                        colorLight : "#ffffff",
                        correctLevel : QRCode.CorrectLevel.H
                    });
                    getRechargePayResult(res.data)
                }else{
                    alert(res.info);
                }
            },
            error:function(){
                alert('网络错误1');
            }
        });
    }
    function getRechargePayResult(payinfo){
        console.log(payinfo,'payinfo');
        clearTimeout(payResultTimer);
        if (payinfo.tid) {
            ptid = payinfo.tid;
        }
        $.ajax({
            url:service_domain+ allPostData.check_flag +'/ajax_get_ai_pay_result',
            type:'post',
            dataType:'json',
            data:{
                tid:ptid,
                pay_type:getPayType()
            },
            success:function(res){
                if(res.status){
                    if(res.data.pay_status == 'NOTPAY') {
                        payResultTimer = setTimeout(function(){
                            getRechargePayResult(payinfo);
                        }, 2000);
                        return;
                    }else if(res.data.pay_status == 'SUCCESS'){
                        if(isPayDialog){
                            // $('.pageMask').addClass('hide');
                            $('.pay_content').addClass('hide');
                            $('.modal_mes').addClass('hide');
                            $('.pay_detail').removeClass('hide');
                        }
                        payresultAction(res)
                    }
                    clearTimeout(payResultTimer);
                    return;
                }
    
                clearTimeout(payResultTimer);
                alert(res.info);
            },
            error:function(err){
                alert('网络错误2');
            }
        });
    	
    }
    payresultAction({data:{tid:'99237482378','wechat_qrcode_url':'iuyeriuweyi'}})
    function payresultAction(res) {
        var data = res.data;
        if(data.wechat_qrcode_url){
            $('#pay_succ_tid').text(data.tid)
            $('#qrcode1').attr('src', data.wechat_qrcode_url);
        }
        $('.payresultBtn2').click(function(){
            location.href = `${service_domain}report2?oid=${data.tid}`;
        });
        $('.payresultBtn1').click(function(){
            if(isPayDialog) {
                location.reload();
                return;
            }
        });
        $('#copy_tid').unbind('click');
        var clipboard2 = new ClipboardJS('#copy_tid', {
            text: function () {
                return $('#pay_succ_tid').text();
            }
        });
        clipboard2.on('success', function(e) {
            alert('复制成功')
        })

    }
    
    
    $('li').click(function(e) {
        if ($('li').hasClass('active_select')) {
            $('li').removeClass('active_select')
        }
        $(this).addClass('active_select')
        // getWordCountList();
        clearhisText()//清空记录
        var t = $('li.active_select').attr('type');
        if(t =='96'){
            location.href = location.origin+'/aippt'
            return
        }
        if(t =='94'){//字数
            $('.form_essayWords').show();
            $('.side_info').show();
            $('.step_two').show()
            $('.key_words').addClass('hide')
            $('.checkbox_wrap').show()
        } else{
            $('.checkbox_wrap').hide()
            $('.step_two').hide()
            $('.form_essayWords').hide();
            $('.side_info').hide();
            $('.key_words').removeClass('hide')
        }
        if(t == '94' || t == '82'){
            $('[step="3"]').show()
            $('[step="2"]').hide()
            $('.btn_result').show()
            $('.btn_result_now').hide()
            $('.step_two').show()
        }else{
            $('.btn_result').hide()
            $('.btn_result_now').show()
            $('.step_two').hide()
            $('[step="2"]').show()
            $('[step="3"]').hide()
        }
        if(t == '64'){
            $('.key_words').show()
            $('.key_words').show()
            if ($('.opt-advise').css('display') !== 'none') {
                // 元素是隐藏的
                $('.opt-advise').hide()
            }
        }else{
            $('.key_words').hide()
            $('.opt-advise').show()
        }
        if (['81','85'].indexOf(t) !== -1) {//
            $('.coreContent').show();
        } else{
            $('.coreContent').hide();
        }
        if(t == '62' ||t == '63'){
            $('.inputText').attr('max','500')
            $('.inputText').text('0/500')
        }else if(t=='82'){
            $('.inputText').attr('max','200')
            $('.inputText').text('0/200')
        }else{
            $('.inputText').attr('max','100')
            $('.inputText').text('0/100')
        }
        // if(t == '96'){
        //     $('.form_pptItem').show()
        // }else{
        //     $('.form_pptItem').hide()
        // }
        // $("#downdemo").attr('href', '/downreportdemo/type/'+t);
        //图表公式
        var table_formula_types = getTableFormulaTypes('support_table_formula_types');
        if (table_formula_types) {
        	if (table_formula_types.indexOf(t) !== -1) {
        		$('#paper-table_and_formulas-wrapper').parent().show();
        	} else{
                $('#paper-table_and_formulas-wrapper').parent().hide();
            }
        }
        changeLiActive(t,'support_titleMore','.normal_recommend_title')// 标题优化
        changeLiActive(t,'support_pro','.custom-select')// 专业优化
        changeLiActive(t,'support_edu','.formItem_pro')// 学历优化
        // if($('.custom-select').hasClass('disNone') && $('.opt-advise').hasClass('disNone')){}
    });

    function changeLiActive(t,attr_type,ele){
        var support_titleMore = getTableFormulaTypes(attr_type);
        if (support_titleMore) {
            if (support_titleMore.indexOf(t) !== -1) {
                $(ele).removeClass('disNone');
                // $(ele).css('display','block')
            } else{
                $(ele).addClass('disNone');
                // $(ele).css('display','none')
            }
        }
    }
    function getTableFormulaTypes(attr_type) {
    	var support_table_formula_types = $("#htmlconfig").attr(attr_type);
    	if (!support_table_formula_types) return '';

    	var support_table_formula_types_arr = support_table_formula_types.split(",");
    	return support_table_formula_types_arr;
    }
});