$(function () {
    // 时间
    new Rolldate({
        el: '#datePickerStart',
        format: 'YYYY-MM-DD hh:mm',
        beginYear: new Date().getFullYear(), // 开始时间
        endYear: 2021, //结束时间
        confirm: function (val) {
            console.log(val); // 获取值
        }
    })
    new Rolldate({
        el: '#datePickerEnd',
        format: 'YYYY-MM-DD hh:mm',
        beginYear: new Date().getFullYear(), // 开始时间
        endYear: 2021, //结束时间
        confirm: function (val) {
            console.log(val); // 获取值
        }
    })
})

// 上传图片
$(function () {
        $gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
    $uploaderInput = $("#uploaderInput"),
    $uploaderFiles = $("#uploaderFiles");
    $uploaderInput.on("change", function (e) {
        let src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
        for (let i = 0, len = files.length; i < len; ++i) {
            let file = files[i];

            if (url) {
                src = url.createObjectURL(file);
            } else {
                src = e.target.result;
            }           
            upload_image(file)
          
        }     
    });
    $uploaderInput.on("click", function (e) {
        let pic_limitnum = $uploaderFiles.find('li').length
        if(pic_limitnum>4){
            $uploaderInput.attr('disabled',true)
        }
    })
    $('body').on('click','.clean_pic_btn',function(){
       let url = $(this).parents().attr('data-url')
       let this_=$(this)
       let data={}
       data['image'] = url
       layer.open({
            content:'是否删除这张图片',
            btn: ['是','否'],
            yes:function(){
                post_json(data)
                this_.parents('li').remove()
                $('.pic_limit_num').text( $('#uploaderFiles li').length)
            }
        })  
     
    })
    $uploaderFiles.on("click", "li", function () {
        $galleryImg.attr("style", this.getAttribute("style"));
        $gallery.fadeIn(100);
    });
    $gallery.on("click", function () {
        $gallery.fadeOut(100);
    });
})


$(function(){
    //底部拟态框
    let $iosActionsheet = $('#iosActionsheet');
    let $iosMask = $('#iosMask');
    function hideActionSheet() {
        $iosActionsheet.removeClass('weui-actionsheet_toggle');
        $iosMask.fadeOut(200);
    }
    $iosMask.on('click', hideActionSheet);
    $('#iosActionsheetCancel').on('click', hideActionSheet);
    $(".contestant-list .more").on("click", function () {
        $iosActionsheet.addClass('weui-actionsheet_toggle');
        $iosMask.fadeIn(200);

        $iosActionsheet.attr('data-id',$(this).parents('.contestant-list').index())
        if($(this).parents('.contestant-list').find('input[name=locking]').val()==0){
            $('.locking_btn').text('解锁候选人')
        }else{
            $('.locking_btn').text('锁定候选人')
        }
       
    });

    //底部拟态框
    function hidemoreinfo_active(){
        $('#moreinfo_active').removeClass('weui-actionsheet_toggle');
        $('#moreinfo_model').fadeOut(200);
   }
   $('#moreinfo_model_cancel').on('click',hidemoreinfo_active)

   //详细
    $('.vote_info_btn').on('click',function(){
        hideActionSheet()
        $('#moreinfo_active').addClass('weui-actionsheet_toggle');
        $('#moreinfo_model').fadeIn(200);
        getcanddigest($('.contestant-list').eq($iosActionsheet.attr('data-id')).find('input[name=queue]').val())
    })
    let getcanddigest = (queue) =>{
        let data={}
        data['queue'] = queue
        data['getcanddigest'] = 'getcanddigest'
        $.ajax({
            url:"",
            type: "GET",
            data: data,
            dataType: "json",
            success:function(data){      
                let html='<textarea class="weui-textarea" name="canddigest"  value="'+data.result+'" rows="3" placeholder="详细描述">'+data.result+'</textarea>'
                $('#moreinfo_active .weui-actionsheet__title-text').text('编辑候选项描述('+$('.contestant-list').eq($iosActionsheet.attr('data-id')).find('input[name=queue]').val()+'号 新增的候选项)')
                $('#moreinfo_active .weui-actionsheet__menu .weui-cell').html(html)
            },
            error:function(data){
                layer.open({
                    content:'业务繁忙',
                    time: 2
                })  
            }
         
        })
    }
    $('body').on('click','.change_btn',function(){
        let canddigest = $(this).parents('#moreinfo_active').find('textarea[name=canddigest]').val()
        let  votefalse = $(this).parents('#moreinfo_active').find('input[name=votefalse]').val()
        let data= {}
        let staus=0
        if(canddigest){
            data['ue'] = 'ue'
            data['canddigest'] = canddigest
            data['queue'] = $('.contestant-list').eq( $iosActionsheet.attr('data-id')).find('input[name=queue]').val()
        }
        if(votefalse){
            data['editvotes'] = 'editvotes'
            data['votefalse'] = votefalse
            data['queue'] = $('.contestant-list').eq( $iosActionsheet.attr('data-id')).find('input[name=queue]').val()
            staus = 3
        }
        
       if(data){     
            post_json(data,staus)         
       }
       hidemoreinfo_active()
    })
    //修改投票数
    $('.vote_editnum_btn').on('click',function(){
        hideActionSheet()
        $('#moreinfo_active').addClass('weui-actionsheet_toggle');
        $('#moreinfo_model').fadeIn(200);
        let html='<input class="weui-input" name="votefalse" placeholder="请输入虚拟票数" type="number" oninput="if(value>9999999999)value=9999999999;if(value<0)value=0" value=0>'
        $('#moreinfo_active .weui-actionsheet__title-text').text('虚拟票数')
        $('#moreinfo_active .weui-actionsheet__menu .weui-cell').html(html)
    })
    
    let id =$('#candid').val()
    let queue_old =[]
    $('.contestant-list').each(function(){
        queue_old[$(this).index()] = $(this).find('input[name=queue]').val()
    })

    //修改参数
    $('body').on('change','form textarea,input',function(){      
        console.log(1);
           
        let name =$(this).attr('name')     
        let value = $(this).val()
        let status = 0
        let data = {}
        switch(name){
            case 'digest':
                data['ue_'] ='ue_'
                data[name] = value
            break
            case 'title':
                if(value){          
                    if(id){
                        data['id'] = id
                    }else{
                        data['action'] = 'add'
                        status = 1     
                    }
                    data[name] = value
                                                   
                }else{
                    layer.open({
                        content:'标题不能为空',
                        time: 1
                    })
                }
            break
            case 'queue':
                data['id'] = id
                data[name] = value
                data['index'] = $(this).parents('.contestant-list').index()
                data['queue_old'] = queue_old[$(this).parents('.contestant-list').index()]        
            break
            case 'candtitle': 
                data['id'] = id
                data[name] = value
                data['index'] = $(this).parents('.contestant-list').index()
                data['queue'] = $(this).parents('.contestant-list').find('input[name=queue]').val()
            break
            case 'candtitles': 
            data['id'] = id
            data[name] = value
            data['queue'] = $(this).parents('.contestant-list').find('input[name=queue]').val()
            break
            case 'canddigest':
                data['ue'] = 'ue'
                data[name] = value
                data['queue'] = $(this).parents('.contestant-list').find('input[name=queue]').val()
            default:
            break
        }

        if(data.length>0){
            post_json(data,status)        
        }   
    })
    //下一步     
    $('.vote_list .weui-navbar__item').on('click',function(){         
        if(id){
            $('.vote_list .active').removeClass('active')
            $(this).addClass('active')
            $('.weui-form .weui-form__control-area').addClass('hide')
            $('.weui-form .weui-form__control-area').eq($(this).index()).removeClass('hide')
            if($(this).index()==3){
                $('.save_btn').text('完成')
            }else{
                $('.save_btn').text('下一步')
            }
        }else{
            if($(this).index()!=0){
                layer.open({
                    content:'请填写投票标题',
                    time: 1
                })
            }      
        }
    })
    $('.save_btn').on('click',function(){  
        let i = $('.vote_list .active').index();               
       if(i<3){
            $('.vote_list .weui-navbar__item').eq(i+1).click()     
       } 
       if(i==3){
           window.location.href ='center_nav_mobile'
       }     
    })

    //锁定候选人
    $('.locking_btn').on('click',function(){
        let index = $(this).parents('#iosActionsheet').attr('data-id')    
        let locking = $('.contestant-list').eq(index).find('input[name=locking]').val()
        let html=''
        let data={}
        data['state'] = 'state'     
        data['queue'] = $('.contestant-list').eq(index).find('input[name=queue]').val()
        if(locking==0){
            $('.contestant-list').eq(index).find('input[name=locking]').val(1)
            html = '<span class="text-success">正常</span>'
            data['locking'] = 1
           
        }else{
            $('.contestant-list').eq(index).find('input[name=locking]').val(0)
            html = '<span class="text-warm">已锁定</span>'
            data['locking'] = 0
        }
        layer.open({
            content:'是否'+$(this).text(),
            btn:['是','否'],
            yes:function(i){       
                $('.contestant-list').eq(index).find('.locking_text span').remove()              
                $('.contestant-list').eq(index).find('.locking_text').append(html)
                hideActionSheet()
                layer.close(i)                
                post_json(data)    
            }
        })
    })
    //添加候选人
    $('.add_btn').on('click',function(){
        let data={}
        data['addplayer'] = 'addplayer'     
        layer.open({
            content:'是否'+$(this).text(),
            btn:['是','否'],
            yes:function(i){       
                hideActionSheet()
                layer.close(i)                
                post_json(data,3)    
            }
        })
    })
    //删除候选人
    $('.delete_btn').on('click',function(){
        let index = $(this).parents('#iosActionsheet').attr('data-id')    
        let data={}
        data['delete'] = 'delete'     
        data['queue'] = $('.contestant-list').eq(index).find('input[name=queue]').val() 
        layer.open({
            content:'是否'+$(this).text(),
            btn:['是','否'],
            yes:function(i){       
                hideActionSheet()
                layer.close(i)                
                post_json(data,3)    
            }
        })
    })
    //上传图片
    let new_url=$(".current-btn img").attr("src");
	$("body").on("click", ".current-btn", function () {
		let this_ = $(this);
		if (this_.attr("current") == false) {
			let img_ = $(this).find("img");
			$(this).siblings('input[type=file]').trigger("click");
			$(this).siblings('input[type=file]').off("change").on('change', function () {
				upload($(this), img_, this_,new_url);

			});
		} else {
			let img_ = this_.parents(".contestant-list").find(".upload-box img");
			this_.parents(".contestant-list").find(".upload-box input[type=file]").trigger("click");
			this_.parents(".contestant-list").find(".upload-box input[type=file]").off("change").on('change', function () {
				upload($(this), img_, this_);
			});
		}
    })

})
// 封面图片上传函数
function upload(e, img, this_,new_url) {
	let file = e.prop('files')[0];
	let formData = new FormData();
	if (file) {
		let reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onloadend = function (even) {
			let loading = layer.open({ type: 3, shadeClose: false, icon: 2, }); // 初始化loading
			// 必须项,不可修改
			formData.append("action", "upload");
			// 图片数据'file'为必须的命名不可更改,第二个参数为图片数据
			formData.append("file", file);  // 添加自定义属性(name)
			// formData.append("file", this_[0].files[0]);
			// 图片存放路径,第一个参数'dir'不可更改,第二个为upload文件夹下的文件夹名称,没有的话自动创建
			formData.append("dir", "vote_sys")
			// 图片保存名称,可有,没有则按年月日命名
			// formData.append("filename", "my_file_name")
			$.ajax({
				scriptCharset: 'UTF-8',
				type: 'POST', // 请求方式
				// 必须的请求路径
				url: '/api/admin_process', // 请求路径
				data:formData, // 参数
				cache: false,
				processData: false,
				contentType: false,
				dataType: 'json', // 数据类型
				success: function (data) {  // 请求成功后的回调函
					// 失败
					if (data.state == "FAILURE"){
						// 打印错误信息
                        layer.open({
                            content:data.msg,
                            time: 2
                        })
					// 成功
					// 	# 成功时返回url/新的文件-名/文件大小M/文件类型后缀{{'state': 'SUCCESS', 'url':
 					// '/upload/up_file/file/201909/190902161609.zip',
					// 'filename': '190902161609.zip', 'size': 0.1, 'type': '.zip', 'loginid': ''}
					}else{
						this_.addClass("on");
						// this_.attr("img-data", even.currentTarget.result);
						img.attr("src", data.url); // 图片赋值
						img.attr("style", ''); // 删除旧样式重新加载新样式
						// layer.msg('上传成功', { time: 1000 });
						if(new_url!=data.url){
							// let loading = layer.open({ type: 3, shadeClose: false, icon: 2, }); // 初始化loading
							$.ajax({
								url:"",
								type: "POST",
								data: {
									"photo": data.url,
									"queue": this_.parents("tr").find("input[name='queue']").val()
								},
								dataType: "json",
								success:function(data){
									if (data.code!="0"){
                                        layer.open({
                                            content:data.msg,
                                            time: 2
                                        })
										
									}
								},
								error:function(data){
                                    layer.open({
                                        content:'错误',
                                        time: 2
                                    })
								}
							})
						}
					}
				},
				// error: function (XMLHttpRequest, textStatus, errorThrown) { // 请求失败后的回调函数
                error: function () { // 请求失败后的回调函数
                    layer.open({
                        content:'上传失败',
                        time: 2
                    })
				},
				complete: function () {  // 结束执行
					layer.close(loading); // 关闭loading
				},
			})
		}
	}
}

let post_json = (data,status=0) =>{
    $.ajax({
        url:"",
        type: "POST",
        data: data,
        dataType: "json",
        success:function(data){
            layer.open({
                content:data.msg,
                time: 2
            })
            if(status==1&&data.code==1){
                window.location.href =  "release_vote_mobile?edit=" + data.candid;
            } 
            if(status==3&&data.code==1){
                window.location.reload()
            } 
        },
        error:function(data){
            layer.open({
                content:'业务繁忙',
                time: 2
            })        
        }
     
    })
}

let get_josn = (data) =>{
    $.ajax({
        url:"",
        type: "GET",
        data: data,
        dataType: "json",
        success:function(data){      
            return data.result
        },
        error:function(data){
            layer.open({
                content:'业务繁忙',
                time: 2
            })  
            return false
        }
     
    })
}


//上传轮播图
function upload_image(file){ //e:$('img')
    let formData = new FormData();
    // 必须项,不可修改
    formData.append("action", "upload");
    // 图片数据'file'为必须的命名不可更改,第二个参数为图片数据
    formData.append("file", file);  // 添加自定义属性(name)
    // formData.append("file", this_[0].files[0]);
    // 图片存放路径,第一个参数'dir'不可更改,第二个为upload文件夹下的文件夹名称,没有的话自动创建
    formData.append("dir", 'vote_sys');
    // 图片保存名称,可有,没有则按年月日命名
    // formData.append("filename", "my_file_name");
    console.log(file);
    console.log(formData);
    
    $.ajax({
        scriptCharset: 'UTF-8',
        type: 'POST', // 请求方式
        url: '/api/admin_process', // 必须的请求路径
        data: formData, // 参数
        cache: false,
        async: false,
        processData: false,
        contentType: false,
        dataType: 'json', // 数据类型
        success: function (data) {  // 请求成功后的回调函            
            if(data['state']=="SUCCESS"){
                let formdata ={}
                formdata['add'] = 'add'
                formdata['image'] = data['url']
                $('.pic_limit_num').text( $('#uploaderFiles li').length)
                let tmpl = `<li class="weui-uploader__file" style="background-image:url(`+data.url+`);position: relative;"  data-url="`+data.url+`">	
                <span class="weui-badge clean_pic_btn" style="position: absolute; top: -0.4em; right: -0.4em;">X</span></li>`
                $('.pic_limit_num').text( $('#uploaderFiles li').length)
                $('#uploaderFiles').append(tmpl);
                $('.pic_limit_num').text( $('#uploaderFiles li').length)
                $.ajax({
                    url:"",
                    type: "POST",
                    data: formdata,
                    dataType: "json",
                    success:function(data){
                        layer.open({
                            content:data.msg,
                            time: 2
                        })    
                       
                    },
                    error:function(data){
                        layer.open({
                            content:'业务繁忙',
                            time: 2
                        })        
                    }
                 
                })
            }    
        },error: function(){
            console.log('业务繁忙');
            
        }
    })
}
        
   