//全局的页面遮盖
let loadingMsg;
var startWorkFiles = {};
var upload;
var id;
var formData;


layui.use(['form', 'table', 'upload', 'laydate'], function () {
    let form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
    form.render();
    upload = layui.upload;
    var laydate = layui.laydate;
	
    laydate.render({
        elem: '#dataTime'
      });

    uploadFile();

    form.on('submit(formDemo)', function (data) {
		$("#hideUpload").trigger("click");
    });
});
var ysUrls=[];
var urls=[];
var filenum=0;
function uploadFile(){
    var uploadcom = upload.render({
        elem: '#test',
        url: PATH_URL + "/makeInfo/upload", //改成您自己的上传接口
        multiple: true,   //是否允许多文件上传，默认未false
        dataType: "json",
        // data: {"pickId": id},
        exts: 'jpg|png|mp4',
        //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) {
			 ysUrls=[];
			 urls=[];
			 filenum=0;
            this.data = {
                photoType: "hxy",makeId:localStorage.getItem("resultId"),uploadType:'special',remarks:$("#remark").val()
            };
        },
        done: function (data) {
			console.log(data,"data");
			urls.push(data.data.url);
			ysUrls.push(data.data.ysUrl);
			// insertSpecial(data);
        },
        allDone: function (data) {
			console.log(data,"data");
			filenum=data.total
			if(filenum==urls.length){
				insertSpecial();
				reloading();
			}else{
				layer.msg("传输错误，请重新上传！")
			}
			
			// top.layer.close(loadingMsg);
			// top.layer.msg(data.msg, {icon: 1});
        },
        error: function (e) {
            //请求异常回调
            console.log(e)
        }
    });
}
function insertSpecial(obj){
	if(ysUrls.length == 0){
		layer.msg('请上传文件', {icon: 2});
		return;
	}
	var urld="";
	var ysurld="";
	$.each(urls,function(index,item){
		urld=urld+item+",";
	});
	$.each(ysUrls,function(index,item){
		ysurld=ysurld+item+",";
	})
	$.ajax({
	     type:"post",
	     url : PATH_URL + "/makeInfo/insertSpecial", 
		 async:false,
	     data:{
				makeId:localStorage.getItem("resultId"),
				ysUrl:ysurld,url:urld,
				remarks:$("#remark").val(),
				makeTime:$("#dataTime").val()
	     },
	     dataType:"json",
	     success:function(res){
				
	     },
	     error:function(data){
	     }
	 });
}


function add() {
    // loadingMsg = top.layer.msg('数据上传中,请稍候...', {icon: 16, scrollbar: false, time: 0, shade: [0.8, '#393D49']});
	var files = $('#demo img')
	if(files.length == 0){
		layer.msg('请上传文件', {icon: 2});
		return;
	}
	
    $.ajax({
        type: 'POST',
        async: true, // 默认异步true,false表示同步
        url: ctxPath + '/supplyChainBlack/addBlack',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(formData.field), //获取提交的表单字段
        dataType: 'json', // 服务器返回数据类型
        success: function (data) {
            if (data.code == 200) {
				$("#hideUpload").trigger("click");
            } else {
                layer.alert(data.msg, {icon: 2});
            }
        },
        error: function (XMLHttpRequest, textStatus, e) {
            top.layer.close(loadingMsg);
            layer.msg('数据请求发生异常,请稍后重试', {icon: 16, scrollbar: false});
        }
    });
}



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();
}


