//全局的页面遮盖
let loadingMsg;
var startWorkFiles = {};
var upload;
var id;
var formData;
let form;
var outsidenum=1;
layui.use(['form', 'table', 'upload', 'laydate'], function () {
    form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
    form.render();
    upload = layui.upload;
    var laydate = layui.laydate;
	
    laydate.render({
        elem: '#dataTime'
      });
	  
	initProList();
    uploadFile();

	//训次的点击事件
	$(".patrolBatch").click(function(){
		$(".patrolBatch").removeClass("patrolNumDivClick");
		$(this).addClass("patrolNumDivClick");
		if($(this).attr("id")=="one"){
			outsidenum=1;
		}else{
			outsidenum=2;
		}
		
	})
	
    form.on('submit(formDemo)', function (data) {
		$("#hideUpload").trigger("click");
    });
	form.on('select(proId)', function(data){
		console.log(data);
		initGtList(data.value);
	})
	
});
function initProList(){
	$.ajax({//id获取详情打开弹窗传值子页面
	    type: 'post',
	    url: PATH_URL + "/makeInfo/getProList",
	    dataType: 'json',
		async:false,
	    data: {
	    },
	    success: function (res) {
			console.log(res,"getProList");
			 $("#proId").empty();
			 var html="<option value='' selected>请选择</option>";
			 for(var i=0;i<res.data.length;i++){
				 html+="<option value='"+res.data[i].proId+"'>"+ res.data[i].proName +"</option>";
			 }
			 $("#proId").append(html);
			form.render();
	    },
		error:function(e){
		}
	})
}
function initGtList(proId){
	$.ajax({//id获取详情打开弹窗传值子页面
	    type: 'post',
	    url: PATH_URL + "/makeInfo/getGtList",
	    dataType: 'json',
		async:false,
	    data: {
	       proId:proId,userId:localStorage.getItem("resultUserId")
	    },
	    success: function (res) {
			console.log(res,"getGtList");
			$("#gtId").empty();
			var html="<option value='' selected>请选择</option>";
			for(var i=0;i<res.data.length;i++){
				html+="<option value='"+res.data[i].gtId+"'>"+ res.data[i].gtName +"</option>";
			}
			$("#gtId").append(html);
			form.render();
	    },
		error:function(e){
		}
	})
}
var url="";
var ysurl="";
function uploadFile(){
    var uploadcom = upload.render({
        elem: '#test',
        url: PATH_URL + "/makeInfo/upload", //改成您自己的上传接口
        multiple: true,   //是否允许多文件上传，默认未false
        dataType: "json",
        // data: {"pickId": id},
        exts: 'jpg|png',
        //acceptMime: 'image/jpg,image/png,image/jpeg,file/pdf,file/xlsx',
        auto: false,  //是否自动上传 ，默认为true
        number: 9,  //最大上传数量
        // size: 1024*5, //最大文件大小，单位k
        bindAction: '#hideUpload', //绑定的按钮
        field: 'file', //传到后台的字段名,默认file
        choose: function (obj) {
            flag = false;
            var suffixType = ''; //后缀类型
            uploadcom.config.elem.next()[0].value = '';
            obj.files = obj.pushFile();
            startWorkFiles = obj.pushFile();
            obj.preview(function (index, file, result) {
                console.log(index); //得到文件索引
                console.log(file.name); //得到文件对象
                var files = $('#demo img')
                if(files.length <= 2){
                    $('#demo').append(
                        '<div id="prove_' + index + '" style="display: inline-block">' +
                        '<div class="item">' +
                        '<div class="handle" style="margin-top: -28px" data-idx="prove_' + index + '">' +
                        '<i class="layui-icon layui-icon-delete" style="position: relative;top: 30px;left: 72px; font-size: 20px;color: red"  data-idx="prove_' + index + '" ></i>' +
                        '</div>' +
                        '<img src="' + result + '" alt="' + file.name + '" title="' + file.name + '" data-index="prove_' + index + '" data-name="' + file.name + '" style="height: 100px;width: 100px;margin-right: 10px" class="layui-upload-img ">' +
                        '<div><span>' + (file.name.length > 8 ? (file.name.substr(0, 8) + "..") : file.name) + '</span></div>' +
                        '</div>'+
                        '</div>'
                    );
                }else{
                    layer.msg('最多上传2张照片',{icon:2})
                }
                addDelete(startWorkFiles);
            });
        },
        before: function (obj) {
            this.data = {
               uploadType:"one",photoType:"hxy"
            };
        },
        done: function (data) {
			url=data.data.url;
			ysurl=data.data.ysUrl;
        },
        allDone: function (data) {
			insertOutside();
			var iframeWindow = parent.window['layui-layer-iframe' + localStorage.getItem("resultindex")];
			iframeWindow.reloadData();
			var index = parent.layer.getFrameIndex(window.name); //先得到当前 iframe层的索引
			parent.layer.close(index);
        },
        error: function (e) {
            //请求异常回调
            console.log(e)
        }
    });
}

function insertOutside(){
	if(url.length == 0){
		layer.msg('请上传文件', {icon: 2});
		return;
	}
	$.ajax({
	     type:"post",
	     url : PATH_URL + "/makeInfo/insertMakeGt", 
		 async:false,
	     data:{
			"gtId": $("#gtId").val(),
			userId:localStorage.getItem("resultUserId"),
			makeMonth:localStorage.getItem("resultMakeMonth"),
			proId:localStorage.getItem("resultProId"),
			makeTime:$("#dataTime").val(),
			sFilePath:ysurl,
			filePath:url,
			makeType:1,
			numTimes:outsidenum
	     },
	     dataType:"json",
	     success:function(res){
				console.log(res,"res")
				if(res.code==500){
					parent.layer.msg(res.msg)
					return;
				}
	     },
	     error:function(data){
	     }
	 });
}

var deletePhoto = [];
function delPhoto(i,id) {
    var parentcolor = document.getElementById("demo" + i);
    var childcolor = document.getElementById(id + "");
    var path = childcolor.name;
    deletePhoto.push(path);
    parentcolor.removeChild(childcolor);
    var photoNum = $("#demo" + i).children().length;
    if (photoNum == 0) {
        $("#preview" + i).css("display", "none");
    }
}
function addDelete(arr) {
    $('#demo').click(function (e) {
        var target = $(e.target)
        if (target.hasClass('handle') || target.hasClass('layui-icon')) {
            var dataIdx = target.attr('data-idx')
            var filePath = $('#' + dataIdx).children().children().next().attr('file')
            delete arr[dataIdx]; // 通过获取绑定在标签上的index，删除files对象中对应的key属性即可
            target.parents('.item').remove() // 页面文件标签也删除
        }
    });
}
//设置弹窗关闭
function reloading() {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前 iframe层的索引
    parent.layer.close(index); //再执行关闭
    window.parent.location.reload();
}


