
$(function(){
    let user=JSON.parse(localStorage.getItem("user"));
    let  user_id=user.id;
    $.ajax({
        　　type:"get",
        　　url:"http://xd.cbeid.cn/api/5e8bd9e0141d5",	
        　　data:{
            user_id,
        },
        headers: {
            "access-token":localStorage.getItem("token")//此处放置请求到的用户token
          },
        　　success:function(res){
            var str = '<select class="form-control">';
            var data=res.data;
            for(var i = 0 ; i <data.length ; i ++){
                var id=data[i].id;
                str += ` <option value=${id}>${data[i].name}</option>`
            }
            str += " </select>"
            str += " <div class='flex-center'>"
            str += '  <button type="button" class="btn btn-primary" id="selectOk">确定</button>'
             str +=' </div>'
            $(".selectMould").append(str);
        }
    })
})
$("body").on("click", "#selectOk", function () {
    let user=JSON.parse(localStorage.getItem("user"));
    let  user_id=user.id;
    let type_id=$('.selectMould>select').val();
    $.ajax({
        　　type:"get",
        　　url:"http://xd.cbeid.cn/api/5e8bdbc9e286b",	
        　　data:{
            user_id,
            type_id
        },
        headers: {
            "access-token":localStorage.getItem("token")//此处放置请求到的用户token
          },
        　　success:function(res){
            $('.selectMould').css("display","none")
            $('.container-fluid').css("display","block")
           
            var list1=''
            　　var item= JSON.parse(res.data.type);
             console.log(item)

            for(var i = 0 ; i < item.length ; i ++){
              var type=item[i].type;
             var str;
            switch (type) {
                // 单文本
                case "text":
            str = '<!--具体的表单控件 文本框-->';
            str += `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice}  data-limit=${item[i].limit}  data-limiterror=${item[i].limiterror} data-placeholder=${item[i].placeholder} data-isdel=${item[i].isdel}> `;
            //'<!--表单控件的头部-->';
            str += '<div class="questionnaireItemHead">';
            //'<!--表单控件的名称-->';
            if(item[i].choice=="true"){
                str += `<div class="required">*</div><div class="questionnaireItemName">${item[i].name}</div>`;
            }else{
                str += `<div class="required"></div><div class="questionnaireItemName">${item[i].name}</div>`;
            }
            //'<!--表单控件的功能按钮-->';
            str += '<div class="questionnaireItemGroupButton">'
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
           
            str += '</div></div>';
            //'<!--控件-->';
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
            str += `<input type="text" class="form-control formVal" name="text" placeholder=${item[i].placeholder}>`;
            str += '</div><div class="errorMain"></div></div></div></div>';
                    break;
                //多行文本
                case "multiple":
                       //<!--具体的表单控件 多行文本框-->
            var str = `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice} data-height=${item[i].height} data-placeholder=${item[i].placeholder}> `;
            //<!--表单控件的头部-->
            str += '<div class="questionnaireItemHead">';
            //<!--表单控件的名称-->
            str += '<div class="required">*</div><div class="questionnaireItemName">多行文本框</div>';
            //<!--表单控件的功能按钮-->
            str += '<div class="questionnaireItemGroupButton">';
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
            str += '</div></div>';
            //<!--控件-->
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
            var height=Number(item[i].height)+14;
            str += `<textarea name="" class="form-control formVal" cols="30" rows="5" style="resize: none;height:${height}px"  placeholder=${item[i].placeholder}></textarea>`;
            str += '</div><div class="errorMain"></div></div></div></div>';
                    break;
                // 时间框
                case "date":
            //<!--具体的表单控件 时间框-->
            var str = `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice} data-placeholder=${item[i].placeholder}>`;
            //<!--表单控件的头部-->
            str += '<div class="questionnaireItemHead">';
            //<!--表单控件的名称-->
            if(item[i].choice=="true"){
                str += `<div class="required">*</div><div class="questionnaireItemName">${item[i].name}</div>`;
            }else{
                str += `<div class="required"></div><div class="questionnaireItemName">${item[i].name}</div>`;
            }
            //<!--表单控件的功能按钮-->
            str += '<div class="questionnaireItemGroupButton">';
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
            str += '</div></div>';
            //<!--控件-->
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
            str += `<input type="date" class="form-control formVal" name="" placeholder=${item[i].placeholder}>`;
            str += '</div><div class="errorMain"></div></div></div></div>';
                    break;
                // 单选框
                case "radio":
                        //<!--具体的表单控件 单选框-->
            var str = `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice} data-content=${item[i].content}>`;
            //<!--表单控件的头部-->
            str += '<div class="questionnaireItemHead">';
            //<!--表单控件的名称-->
            if(item[i].choice=="true"){
                str += `<div class="required">*</div><div class="questionnaireItemName">${item[i].name}</div>`;
            }else{
                str += `<div class="required"></div><div class="questionnaireItemName">${item[i].name}</div>`;
            }
            //<!--表单控件的功能按钮-->
            str += '<div class="questionnaireItemGroupButton">';
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
            str += '</div></div>';
            //<!--控件-->
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
            var content=item[i].content.split(",");
            for(let i = 0 ; i < content.length ; i ++){
                str += '<div class="form-check">';
            str += '<label class="form-check-label">';
            str += `<input type="radio" class="form-check-input checkMargin" name="selectName" value="${content[i]}">${content[i]}</label></div>`;
            }
            str += '</div><div class="errorMain"></div></div></div></div>';
                    break;
                //多选框
                case "checkbox":
                     //<!--具体的表单控件 复选框-->
            var str = `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice} data-content=${item[i].content}>`;
            //<!--表单控件的头部-->
            str += '<div class="questionnaireItemHead">';
            //<!--表单控件的名称-->
            if(item[i].choice=="true"){
                str += `<div class="required">*</div><div class="questionnaireItemName">${item[i].name}</div>`;
            }else{
                str += `<div class="required"></div><div class="questionnaireItemName">${item[i].name}</div>`;
            }
            //<!--表单控件的功能按钮-->
            str += '<div class="questionnaireItemGroupButton">';
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
            str += '</div></div>';
            //<!--控件-->
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
                var content=item[i].content.split(",");
            for(let i = 0 ; i < content.length ; i ++){
                str += '<div class="form-check">';
            str += '<label class="form-check-label">';
            str += `<input type="checkbox" class="form-check-input checkMargin" name="selectName" value="${content[i]}">${content[i]}</label></div>`;
            }
            
            str += '</div><div class="errorMain"></div></div></div></div>';
                    break;
                //下拉框
                case "dropdown":
                    //<!--具体的表单控件 下拉框-->
            var str = `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice} data-content=${item[i].content}>`;
            //<!--表单控件的头部-->
            str += '<div class="questionnaireItemHead">';
            //<!--表单控件的名称-->
            if(item[i].choice=="true"){
                str += `<div class="required">*</div><div class="questionnaireItemName">${item[i].name}</div>`;
            }else{
                str += `<div class="required"></div><div class="questionnaireItemName">${item[i].name}</div>`;
            }
            //<!--表单控件的功能按钮-->
            str += '<div class="questionnaireItemGroupButton">';
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
            str += '</div></div>';
            //<!--控件-->
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
            str += '<select class="form-control select">';
                var content=item[i].content.split(",");
            for(let i = 0 ; i < content.length ; i ++){
                str += `<option value=${content[i]}>${content[i]}</option>`;
            }
        
            str += '</select>';
            str += '</div><div class="errorMain"></div></div></div></div>';
                    break;
                case "textdropdown":
                    str = getTextDropdown();
                    break;
                //上传图片
                case "img":
                var str = `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice} data-num=${item[i].num}>`;
            //<!--表单控件的头部-->
            str += '<div class="questionnaireItemHead">';
            //<!--表单控件的名称-->
            if(item[i].choice=="true"){
                str += `<div class="required">*</div><div class="questionnaireItemName">${item[i].name}</div>`;
            }else{
                str += `<div class="required"></div><div class="questionnaireItemName">${item[i].name}</div>`;
            }
            //<!--表单控件的功能按钮-->
            str += '<div class="questionnaireItemGroupButton">';
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
            str += '</div></div>';
            //<!--控件-->
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
            str += '<div class="img-box full">';
            str += '<section class="img-section">';
            str += '<div class="z_photo upimg-div clear">';
            str += '<section class="z_file fl">';
            str += '<div class="z_fileImgDel">删除</div>';
            str += '<img src="../images/a11.png" class="add-img" />';
            str += '<input type="file" name="file" class="file imgFile" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" leipiplugins="imgupload" title="图片上传" />';
            str += '</section></div></section>';
            str += '<div class="imgExplain">支持jpg、jpeg、png、bmp等图片格式</div>';
            str += '<div class="errerClass imgErrer"></div>';
            str += '</div>';
            str += '</div><div class="errorMain"></div></div></div></div>';
            
                    break;
                case "file":
                //上传文件
                var str = `<div class="row"><div class="questionnaireItem" data-name=${item[i].name} data-type=${item[i].type} data-choice=${item[i].choice} data-num=${item[i].num} >`;
            //<!--表单控件的头部-->
            str += '<div class="questionnaireItemHead">';
            //<!--表单控件的名称-->
            if(item[i].choice=="true"){
                str += `<div class="required">*</div><div class="questionnaireItemName">${item[i].name}</div>`;
            }else{
                str += `<div class="required"></div><div class="questionnaireItemName">${item[i].name}</div>`;
            }
            //<!--表单控件的功能按钮-->
            str += '<div class="questionnaireItemGroupButton">';
            if(item[i].isdel=="true"){
                str += '<button type="button" class="btn btn-primary controlMove">移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete">删除</button>';
            }else{
                str += '<button type="button" class="btn btn-primary controlMove" disabled>移动</button>';
                str += '<button type="button" class="btn btn-primary controlDelete" disabled>删除</button>';
            }
            str += '</div></div>';
            //<!--控件-->
            str += '<div class="questionnaireItemContent">';
            str += '<div class="form-group hidMargin">';
            str += '<div class="message">';
            str += '<div class="messagedel">删除</div>';
            str += '<input type="text" name="txt" class="input fileUpload form-control" value="" disabled="disabled" />';
            str += '<input type="button" value="上传文件" size="30" class="liulan fileUploadBtn">';
            str += '<input type="file" name="f" style="height:26px;" class="files leipiplugins fileUploadReal" size="1" leipiplugins="uploadfile" title="文件上传" hidefocus></div>';
            str += '<div class="fileTips">';
            str += '<p>1.上传文档不超过100MB</p>';
            str += '<p>2.为了保证文档能正常使用，我们支持以下格式的文档上传：</p>';
            str += '<p>MS Office文档： doc,docx,ppt,pptx,xls,xlsx,vsd,pot,pps,rtf</p>';
            str += '<p>压缩文档： rar,zip,tar,gz,tgz</p>';
            str += '<p>图片： jpg,jpeg,gif,bmp,png</p>';
            str += '<p>WPS office系列： wps,et,dps</p>';
            str += '<p>PDF： pdf</p>';
            str += '<p>纯文本： txt</p>';
            str += '<p>EPUB： epub</p></div>';
            str += '<div class="errerClass FileErrer"></div>';
            str += '</div><div class="errorMain"></div></div></div></div>';
                    break;
                default :
                    str = ""; 
                    break;
            }
             list1+=str;
            }
            $(".questionnaireSubjectForm").append(list1);
        },
        error:function(res){
            alert("提交失败")
        　　}
    })

});

    //关闭预览界面
$("body").on("click", ".btnNo", function () {
    $(".previewMain").hide();
    $(".container-fluid").css("display", "block");
});
$("body").on("click", ".btnNo", function () {
    $(".previewMain").hide();
    $(".container-fluid").css("display", "block");
});
$("body").on("click", ".btnOk", function () {
    let name=$("#formname").val();
    if(!name){
            alert("请输入表单模版名称")
            return;
    }
    let user=JSON.parse(localStorage.getItem("user"));
    let  user_id=user.id;
    let  agency_id=user.default_agency_id
    let list = [];
    $(".questionnaireSubjectForm>.row>.questionnaireItem").each(function (index, item) {
        var formFile = new FormData();
        let text={};
        let type=$(this).attr("data-type"),
        name=$(this).attr("data-name"),
        isdel=$(this).attr("data-isdel"),
        choice=$(this).attr("data-choice");
        text.type=type;
        text.choice=choice;
        text.isdel=isdel;
        if (type == "text") {
            var limit = $(this).attr("data-limit"),
                limiterror = $(this).attr("data-limiterror")
            placeholder = $(this).attr("data-placeholder");
            text.name = name || "文本框";
            text.limit = limit || "undefined";
            text.limiterror = limiterror || "undefined";
            text.placeholder = placeholder || "无";
            // console.log(type, name, choice, limit, limiterror, placeholder);
        } else if (type == "multiple") {
            var placeholder = $(this).attr("data-placeholder"),
                height = $(this).attr("data-height");
            text.name = name || "多行文本框";
            text.placeholder = placeholder || "无";
            text.height = height;
            // console.log(type, name, choice, placeholder, height);
        } else if (type == "date") {
            text.name = name || "时间框";
            var placeholder = $(this).attr("data-placeholder");
            text.placeholder = placeholder || "无";
            // console.log(type, name, choice, placeholder);
        } else if (type == "radio") {
            text.name = name || "单选框";
            var content = $(this).attr("data-content")|| "选项一,选项二";
            content= dump(content);
            text.content = content;
            // console.log(type, name, choice, content);
        } else if (type == "checkbox") {
            text.name = name || "复选框";
            var content = $(this).attr("data-content")|| "选项一,选项二,选项三";
            content= dump(content);
            text.content = content;
            // console.log(type, name, choice, content);
        } else if (type == "dropdown") {
            text.name = name || "下拉框";
           var content = $(this).attr("data-content")|| "选项一,选项二,选项三";
           content= dump(content);
            text.content = content;
            // console.log(type, name, choice, content);
        } else if (type == "img") {
            text.name = name || "图片上传";
            let num = $(this).attr("data-num");
            text.num = num;
            // console.log(type, name, choice, num);
        } else if (type == "file") {
            text.name = name || "文件上传";
            let num = $(this).attr("data-num");
            text.num = num;
            // console.log(type, name, choice, num);
        }
        list.push(text);
    });
    list.sort(compare('isdel'))
    var jsonString = JSON.stringify(list)  //将JS对象转换为JSON字符串
    $.ajax({
        　　type:"post",
        　　url:"http://xd.cbeid.cn/api/5e8414b29bae0",	
        　　data:{
            user_id,
            agency_id,
            name,
            template:jsonString
        },
   
        headers: {
            "access-token":localStorage.getItem("token")//此处放置请求到的用户token
          },
        　　success:function(res){
                // $(".previewMain").hide();
                // $(".container-fluid").css("display", "block");
                // $(".questionnaireSubjectForm>.row").remove();
                alert("提交成功")
               window.top.location.href="http://xd.cbeid.cn/#/formlist"
        　　},
        　　error:function(res){
            alert("提交失败")
        　　}
        });
});

//显示属性框的方法
function AttributeShow(object){
    var attribute = $(".questionnaireAttribute");
    for(var i = 0 ; i < attribute.length ; i ++){
        if(attribute.eq(i).data("type") == object.data("type")&&object.data("isdel")==true){
            attribute.eq(i).show();
            //显示控件名称
            $(".controlAttributeName").eq(i).val(object.find(".questionnaireItemName").text());
            //显示默认值
            if(object.data("type") == "text" || object.data("type") == "multiple" || object.data("type") == "date" ){
                // let val=object.find(".formVal").val();
                // if(!object.find(".formVal").val()){
                //     attribute.eq(i).find(".textDetailsName").val(object.data("placeholder"));
                // }else{
                //     attribute.eq(i).find(".textDetailsName").val(val);
                // }
                attribute.eq(i).find(".textDetailsName").val(object.data("placeholder"));
            }
            if(object.data("type") == "multiple" ){
                attribute.eq(i).find(".multipleHeight").val(object.data("height"));
            }
            //显示限制条件
            if(object.data("type") == "text"){
                var limit = object.data("limit");
       
                var optionss = attribute.eq(i).find(".limitSelect option");
 
                var auto = true;//自定义正则表达式
                for(var k = 0 ; k < optionss.length ; k ++){
                    var op = optionss.eq(k).val();  
                    if(op == limit){
                        optionss.eq(k).prop("selected","selected");
                        auto = false;
                    }else{
                        optionss.eq(k).prop("selected",false);
                    }
                }
                //是自定义表达式
                if(auto){
                    optionss.eq(optionss.length - 1).prop("selected","selected");
                    $(".textRegularCustom").show().text(limit);
                }else{
                    $(".textRegularCustom").hide().text("");
                }
            }
            //显示文件可上传数量
            if(object.data("type") == "img" || object.data("type") == "file"){
                attribute.eq(i).find(".uploadNum").val(object.data("num"));
            }
            //显示下拉框值
            if(object.data("type") == "radio" || object.data("type") == "checkbox" ){
                var inputs = object.find("input");
                var inputval = "";
                for(var j = 0 ; j < inputs.length ; j ++){
                    inputval += inputs.eq(j).val() + "\n";
                }
                attribute.eq(i).find(".selectAttr").val(inputval);
            }else if(object.data("type") == "dropdown"){
                var inputs = object.find("option");
                var inputval = "";
                for(var j = 0 ; j < inputs.length ; j ++){
                    inputval += inputs.eq(j).val() + "\n";
                }
                attribute.eq(i).find(".selectAttr").val(inputval);
            }else if(object.data("type") == "textdropdown"){
                var inputs = object.find(".form-group").find("p");
                var inputval = "";
                for(var j = 0 ; j < inputs.length ; j ++){
                    inputval += inputs.eq(j).text() + "\n";
                }
                attribute.eq(i).find(".selectAttr").val(inputval);
            }
            //显示是否必选
            if(object.data("choice") == true){
                attribute.eq(i).find("input[name='ChoiceRadio']").eq(0).prop("checked","checked");
                object.find(".required").removeClass("requiredHiddle");
            }else{
                attribute.eq(i).find("input[name='ChoiceRadio']").eq(1).prop("checked","checked");
                object.find(".required").addClass("requiredHiddle");
            }
            //显示是否能删除
            if(object.data("isdel") == true){
                attribute.eq(i).find("input[name='ChoiceDel']").eq(0).prop("checked","checked");
            }else{
                attribute.eq(i).find("input[name='ChoiceDel']").eq(1).prop("checked","checked");
            }
        }else{
            attribute.eq(i).hide();
        }
    }
}