
layui.config({
    base: '../../lib/layui/lay/mymodules/'
    ,version: '101100'
}).use('eleTree');
layui.extend({
    admin: '{/}../../static/js/admin'
});
layui.use(['jquery','eleTree','table','laypage','form','admin'], function(){
    var $= layui.jquery,
        eleTree	= layui.eleTree,
        laypage	= layui.laypage,
        form = layui.form,
        table	= layui.table;
    var addTemplateHtml = '../../pages/admin/addrecordTemplate.html';
    var updateRecordTemplate = '../../pages/admin/updateRecordTemplate.html';
    /*
	 * @todo 重新计算iframe高度
	 */
    FrameWH();
    function FrameWH() {
        var h = $(window).height()-36-46-40;
        var h1 = $(window).height()-36-25;
        $(".weIframe").css("height", h + "px");
        $(".left").css("height",h1 +"px");
        $(".right_main").css("height",h1 -20+ "px");
    }
    $(window).resize(function() {
        FrameWH();
    });
    var belpID = 'root';
    sessionStorage.setItem("ztreeDepid",'root');
    delpFun();
    function delpFun(){
        sessionStorage.setItem("departmentId",'root');
        $.ajax({
            url:'http://apptest.jieweizhineng.com/api/section/getlist',
            method:'get',
            dataType: 'json',
            success:function (res) {
                if(res.code === 0){
                    var data = [res.data];
                    eleTree.render({
                        elem: '.ele1',
                        data:data ,
                        defaultExpandAll:true,
                        // showCheckbox: true,
                    });
                    eleTree.on("nodeClick(data)",function(d) {
                        belpID =  d.data.currentData.id;
                        sessionStorage.setItem("departmentId",d.data.currentData.id);
                        sessionStorage.setItem("ztreeDepid",d.data.currentData.id);
                        $('.stetaName').val("");
                        var info={
                            statusContent: '',
                            departmentId: d.data.currentData.id,
                            deleteStatus: 'false',
                            pageNumber: '1',
                            pageSize: '1',
                        };
                        getStateList(info);
                    })
                }else{
                    layer.msg('请检查网路', {icon: 2});
                }
            },
            error:function (err) {
                layer.msg('请检查网路', {icon: 2});
            }
        })
    }
    var info={
        templateName: $('.stetaName').val(),
        departmentId: 'root',
        deleteStatus: 'false',
        pageNumber: '1',
        pageSize: '1',
    };
    getStateList(info);
    function getStateList(res) {
        $.ajax({
            url: 'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/getRecordTemplateList',
            method: 'get',
            dataType: 'json',
            data: res,
            success: function (data) {
                laypage.render({
                    elem: 'pageItem',
                    count: data.count,
                    limit: 10,
                    layout: ['count', 'prev', 'page', 'next', 'skip'],
                    jump: function(obj, first) {
                        var index = layer.load(2);
                        table.render({
                            elem: '#stateRemind',
                            url: 'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/getRecordTemplateList',
                            id: 'recordTemplateID',
                            method: 'get',
                            loading: true,
                            cols: [[
                                {field: 'templateName', title: '模版名称', align: 'center'}
                                , {field: 'createDate', title: '创建日期', align: 'center'}
                                , {title: ' 操作', align: 'center', toolbar: '#barDemo'}
                            ]],
                            where: {
                                templateName: res.statusContent,
                                departmentId: res.departmentId,
                                deleteStatus: res.deleteStatus,
                                pageNumber: obj.curr,
                                pageSize: obj.limit,
                            },

                            response: {
                                statusName: 'code'
                                , statusCode: 200,
                                countName: 'count',
                                dataName: 'data'
                            },
                            done: function (res, curr, count) {
                                layer.close(index);
                                if (res.code === '200') {
                                    $('.fr').html('共有数据：'+res.count+' 条')
                                }
                            }
                        });
                    }
                })
            }
        });
    }
    // 查询
    $(".seachSteta").click(function () {
        var checkbox = $("#checkboxT").prop('checked'),
            root='',
            info;
        if(checkbox == true){
            root = '';
            info={
                statusContent: $('.stetaName').val(),
                departmentId: root,
                deleteStatus: 'false',
                pageNumber: '1',
                pageSize: '1',
            };
        }else {
            info={
                statusContent: $('.stetaName').val(),
                departmentId: belpID,
                deleteStatus: 'false',
                pageNumber: '1',
                pageSize: '1',
            };
        }
        getStateList(info)
    });
    // 监听状态table
    table.on('tool(recordTemplateID)', function(obj) {
        if( obj.event === "move"){
            sessionStorage.setItem("statusId",obj.data.id);
            moveDep('选择部门信息','http://apptest.jieweizhineng.com/api/swagger/api/template/v1/moveRecordTemplate/','400','500',table,'recordTemplateID');
        } else if (obj.event === "copy"){
            var content ={
                _method:'put'
            };
            layer.alert('确认要复制记录模板吗？',{icon: 8}, function(index){
                $.ajax({
                    url: 'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/copyRecordTemplate/'+obj.data.id,
                    method: 'post',
                    dataType: 'json',
                    data: content,
                    success: function (res) {
                        if (res.code === '200'){
                            layer.msg('复制成功', {icon: 1});
                            table.reload('recordTemplateID');
                        } else{
                            layer.msg('复制失败', {icon: 2});
                            table.reload('recordTemplateID');
                        }
                        layer.close(index);
                    },
                    error:function () {
                        layer.msg('请检查网络', {icon: 2});
                        layer.close(index);
                    }
                });
            });
        } else if (obj.event === "edit"){
            layer.open({
                type: 2,
                id: 'updateTemplate',
                title:'修改记录模版',
                shadeClose: true,
                scrollbar:true,
                shade: 0.3,
                maxmin: true,
                skin: 'oaBtn',
                btn: ['确认', '取消'],
                area: ['1000px', '600px'],
                content: updateRecordTemplate,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    body.find('#stetaName').val(obj.data.statusContent);
                    var iframeWindow = window['layui-layer-iframe'+ index];
                    var selectVal =[];
                    iframeWindow.layui.form.render();
                    $.ajax({
                        url: 'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/getRecordTemplate/'+obj.data.id,
                        method: 'get',
                        dataType: 'json',
                        success: function (res) {
                            body.find(".TemplateName").val(res.data.templateName);
                            body.find(".Templatereamk").val(res.data.remark);
                            // body.find(".inputCheckbox").attr("checked",'checked')
                            if (res.data.statusContent == ''&& res.data.statusName == ''){
                                body.find(".changeSteta").attr("checked",'checked');
                                body.find(".textSteta").removeAttr('checked');
                                body.find('.a_inputs').show();
                                body.find(".a_text").addClass("a_hide");
                                body.find(".layui-input-block1").removeClass("a_hide");
                            }else {
                                body.find(".changeSteta").removeAttr("checked");
                                body.find(".textSteta").attr('checked','checked');
                                body.find('.a_inputs').hide();
                                body.find(".a_text").removeClass("a_hide");
                                body.find(".layui-input-block1").addClass("a_hide");
                                body.find(".textContent").val(res.data.statusContent);
                                body.find(".textName").val(res.data.statusName);
                            }
                            // 记录状态
                            if (res.data.recordStatusList !=null) {
                                sessionStorage.setItem('groudBool','false');
                                sessionStorage.setItem("addgroudBool",'false');
                                for (var i = 0; i < res.data.recordStatusList.length; i++) {
                                    if (res.data.recordStatusList[i].isEchart == false) {
                                        var str =`
                                     <div class="a_input" inputState-id="${res.data.recordStatusList[i].id}" deleteFlag="false">
                                         <input type="text" value="${res.data.recordStatusList[i].statusContent}" state-id="${res.data.recordStatusList[i].statusId}" style="width: 80%;" placeholder="请输入状态名称" checkbox-boole="${res.data.recordStatusList[i].isEchart}" name="number" autocomplete="off" class="layui-input a_stateName">
                                         <div class="operation_trem">
                                             <input type="checkbox" title="统计标识" class="inputCheckbox" lay-filter="inputCheckbox"">
                                             <i class="layui-icon layui-icon-delete delete_state"></i>
                                         </div>
                                     </div>`;
                                        body.find('.a_inputs').append(str);
                                    }else {
                                        var str =`
                                     <div class="a_input" inputState-id="${res.data.recordStatusList[i].id}" deleteFlag="false">
                                         <input type="text" value="${res.data.recordStatusList[i].statusContent}" state-id="${res.data.recordStatusList[i].statusId}" style="width: 80%;" placeholder="请输入状态名称" checkbox-boole="${res.data.recordStatusList[i].isEchart}" name="number" autocomplete="off" class="layui-input a_stateName">
                                         <div class="operation_trem">
                                             <input type="checkbox" title="统计标识" checked="${res.data.recordStatusList[i].isEchart}" class="inputCheckbox" lay-filter="inputCheckbox"">
                                             <i class="layui-icon layui-icon-delete delete_state"></i>
                                         </div>
                                     </div>`;
                                        body.find('.a_inputs').append(str);
                                    }
                                }
                            }else {
                                sessionStorage.setItem('groudBool','true');
                                sessionStorage.setItem("addgroudBool",'true');
                            }
                            // 特殊记录项和记录项
                            var num =0;
                            for (var j = 0; j < res.data.inputList.length; j++) {
                                if(res.data.inputList[j].special == true){
                                    body.find(".specialName").val(res.data.inputList[j].inputName);
                                    body.find(".specialRemarks").val(res.data.inputList[j].remark);
                                    body.find(".specialSelect").val(res.data.inputList[j].inputType);
                                    body.find(".T_recordterm").attr("recordterm-id",res.data.inputList[j].id);
                                }else {
                                    selectVal.push(res.data.inputList[j].inputType);
                                    var json = JSON.stringify(res.data.inputList[j].inputItemList);
                                    var str =`
                                        <div class="record_term border_t_n" record-id="${res.data.inputList[j].id}" deleteFlag="false">
                                             <div class="a_T a_checkbox1" style="width: ${res.data.inputList[j].inputType == "photo"?"10%":"11%"}">
                                                 ${res.data.inputList[j].isOptional== false?
                                                 "<input type=\"checkbox\" title=\"必选\" class=\"mandatory\" lay-filter=\"mandatory\" checkbox-mandatory=\"false\">\n"
                                                 :
                                                 "<input type=\"checkbox\" title=\"必选\" class=\"mandatory\" checked lay-filter=\"mandatory\" checkbox-mandatory=\"true\">\n"
                                                 } 
                                             </div>
                                             <div class="a_T record_term_name" style="width:${res.data.inputList[j].inputType == "photo"?"17%":"20%"}">
                                                 <input type="text" placeholder="请输入字段名称" class="layui-input fieldName ${j == 0?'fieldName1' : ""}" value="${res.data.inputList[j].inputName}">
                                             </div>
                                             <div class="a_T record_term_remarks" style="width: ${res.data.inputList[j].inputType == "photo"?"17%":"20%"}">
                                                 <input type="text" placeholder="请输入字段备注" class="layui-input fieldType"value="${res.data.inputList[j].remark}">
                                             </div>
                                             <div class="a_T record_term_select" style="width: ${res.data.inputList[j].inputType == "photo"?"13%":"15%"}">
                                                <select name="inputType" class="select-box select-box${num++} ${j ==0?"select-boxsa":""}" " lay-filter="inputType">
                                                    <option value="">--请选择--</option>    
                                                </select>
                                             </div>
                                             <div class="a_T record_term_select1 ${res.data.inputList[j].inputType == "photo"?"":"a_hide"}" style="width: 10%">
                                                 <select name="interest" lay-filter="photo" class="businessType">
                                                 ${res.data.inputList[j].businessType == "remote"?
                                                  "<option value=\"\">--请选择--</option>"+"<option value=\"local\">本地</option>"+" <option value=\"remote\" selected>拍照</option>"
                                                  :
                                                  "<option value=\"\">--请选择--</option>"+"<option value=\"local\" selected>本地</option>"+" <option value=\"remote\">拍照</option>"
                                                 }
                                                 </select>
                                             </div>
                                             <div class="a_T a_checkbox" style="width: 15%">
                                                 ${res.data.inputList[j].isEchart == false ?
                                                 "<input type=\"checkbox\" title=\"统计标识\" class=\"isEchart\" lay-filter=\"isEchart\" checkbox-isEchart=\"false\">\n"
                                                 :
                                                 "<input type=\"checkbox\" title=\"统计标识\" class=\"isEchart\" checked lay-filter=\"isEchart\" checkbox-isEchart=\"true\">\n"
                                                 }
                                             </div>
                                             <div class="a_T a_operation" style="width: 15%">
                                                 <span class="moveUp">上移</span>
                                                 <span class="moveDown">下移</span>
                                                 <span class="edit_record ${res.data.inputList[j].inputType == "checkbox" || res.data.inputList[j].inputType == "radio"? "" : "a_hide"}">编辑</span>
                                                 <span class="delete_record_term">删除</span>
                                             </div>
                                             <!--<input type="text" class="inputJson" style="display: none;" value="${json}">-->
                                             <span class="inputJson" style="display: none;">${json}</span>
                                        </div>
                                     `;
                                    body.find(".record_terms").append(str);
                                    // if (res.data.inputList[j].inputType == "checkbox") {
                                    //     sessionStorage.setItem("inputItemList",JSON.stringify(res.data.inputList[j].inputItemList))
                                    // }
                                }
                            };
                            // 检查项
                            var selectNum = 0;
                            for (var r = 0; r < res.data.checkItemList.length; r++) {
                                var str = `
                                        <div class="inspect_terms">
                                             <div class="inspect_term border_t_n">
                                                 <div class="a_T inspect_term_name border_t_n" style="width: 70%;">
                                                     <textarea name="desc" placeholder="请输入分组名称" class="layui-textarea term_nameTextarea" style="resize:none">${res.data.checkItemList[r].group.groupName}</textarea>
                                                 </div>
                                                 <div class="a_T inspect_term_select border_t_n" style="width: 30%">                                                                                                    
                                                     <select name="interest" class="inspect_select" lay-filter="inspect_select"> 
                                                     ${res.data.checkItemList[r].group.checkType=="checkbox"?
                                                      "<option value=\"checkbox\" selected=\"selected\">多选</option>"+"<option value=\"radio\">单选</option>"
                                                      :"<option value=\"checkbox\">多选</option>"+"<option value=\"radio\" selected=\"selected\">单选</option>"}
                                                     </select>                                         
                                                 </div>
                                             </div>
                                             <div class="inspect_term_infos inspect_term_infoss${selectNum++} border_t_n">                   
                                                 <div class="inspect_term_info" inspect-id="${res.data.checkItemList[r].checkItemList[0].id}" deleteFlag="false">                                                  
                                                     <div class="inspect_term_input border_t_n" style="width: 70%;">
                                                         <input type="text" class="layui-input inspectInfo" placeholder="请输入检查项信息" value="${res.data.checkItemList[r].checkItemList[0].itemValue}">
                                                     </div>
                                                     <div class="inspect_term_operation border_t_n" style="width: 30%">
                                                         <span class="add_inspectInfo">添加</span>
                                                     </div>
                                                </div>
                                             </div>
                                         </div>`;

                                body.find(".inspect_termList").append(str);
                                var arrSlice = res.data.checkItemList[r].checkItemList.slice(1);
                                for (var q=0;q<arrSlice.length; q++){
                                    var html =`<div class="inspect_term_info" inspect-id="${arrSlice[q].id}" deleteFlag="false">                                                  
                                                     <div class="inspect_term_input border_t_n" style="width: 70%;">
                                                         <input type="text" class="layui-input inspectInfo" placeholder="请输入检查项信息" value="${arrSlice[q].itemValue}">
                                                     </div>
                                                     <div class="inspect_term_operation border_t_n" style="width: 30%">
                                                         <span class="add_inspectInfo">添加</span>
                                                         <span class="delete_inspectInfo">删除</span>
                                                </div>
                                          </div>`;
                                    body.find(".inspect_term_infoss"+r).append(html);
                                }
                            }
                            getInputType(body,iframeWindow,selectVal);
                            iframeWindow.layui.form.render();
                        },
                        error:function () {
                            layer.msg('请检查网络', {icon: 2});
                        }
                    });
                },
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var reg = /\S/;
                    if (!reg.test(body.find(".TemplateName").val())) {
                        layer.msg('请输入模版名称', {icon: 8});
                        return false;
                    }
                    if (sessionStorage.getItem("groudBool") == 'true' && !reg.test(body.find(".textContent").val())&&!reg.test(body.find(".textName").val())) {
                        layer.msg('请输入文本状态', {icon: 8});
                        return false;
                    }else if (sessionStorage.getItem("addgroudBool") == 'false' && !reg.test(body.find(".a_stateName1").val())) {
                        layer.msg('请选择状态组', {icon: 8});
                        return false;
                    }
                    if (!reg.test(body.find(".fieldName1").val())|| body.find('.select-boxsa').val() == "") {
                        layer.msg('请填写记录项字段或类型', {icon: 8});
                        return false;
                    }
                    var inputs = body.find('.a_inputs .a_input');
                    // 记录状态
                    var stateIDArray = [],
                        valArray = [],
                        cheackboxBoolArray = [],
                        recordStatusList = [],
                        inputStateID =[],
                        deleteFlagBool = [],
                        deleteStateGroup = body.find(".deleteStateGroup").val(),
                        recordStatusObj ={isEchart:"",statusContent:'',statusId:'',id:'',deleteFlag:''};
                    if (deleteStateGroup != "") {
                        var deleteStateGroups=JSON.parse(deleteStateGroup);
                        for (var o =0;o<deleteStateGroups.length;o++) {
                            recordStatusList.push(deleteStateGroups[o])
                        }
                    }
                    inputs.each(function () {
                        var value = $(this).find('input').val(),
                            stateId = $(this).find("input").attr("state-id"),
                            cheackboxBool = $(this).find("input").attr("checkbox-boole"),
                            id = $(this).attr("inputState-id"),
                            deleteFlag = $(this).attr("deleteFlag");
                        valArray.push(value);
                        stateIDArray.push(stateId);
                        cheackboxBoolArray.push(cheackboxBool);
                        inputStateID.push(id);
                        deleteFlagBool.push(deleteFlag);
                    });
                    if (sessionStorage.getItem("groudBool") == 'true') {
                        for (var i = 0; i < inputs.length; i++) {
                            recordStatusObj = {};
                            recordStatusObj.isEchart = cheackboxBoolArray[i];
                            recordStatusObj.statusContent = valArray[i];
                            recordStatusObj.statusId = stateIDArray[i];
                            recordStatusObj.id = inputStateID[i];
                            recordStatusObj.deleteFlag = true;
                            recordStatusList.push(recordStatusObj)
                        }
                    }else {
                        for (var i = 0; i < inputs.length; i++) {
                            recordStatusObj = {};
                            if (reg.test(valArray[i])){
                                recordStatusObj.isEchart = cheackboxBoolArray[i];
                                recordStatusObj.statusContent = valArray[i];
                                recordStatusObj.statusId = stateIDArray[i];
                                recordStatusObj.id = inputStateID[i];
                                recordStatusObj.deleteFlag = deleteFlagBool[i];
                                recordStatusList.push(recordStatusObj)
                            }
                        }
                    }
                    // 记录项
                    var inputList = {businessType:'',inputItems:[],inputName:'',inputType:'',isEchart:'',isOptional:'',remark:'',special:'',zIndex:'',id:'',deleteFlag:''},
                        value,fieldType,inputItems,mandatory,isEchart,inputType,businessType,id,deleteFlag;
                    var record_term = body.find(".record_term");
                    var recordArray =[];
                    var n;
                    // 特殊记录项
                    var specialObj= {businessType:'',inputItems:[],inputName:"",inputType:'',isEchart:'false',isOptional:'false',remark:'',special:'true',zIndex:1,id:'',deleteFlag:'false'};
                    var specialName = body.find(".specialName").val(),specialRemarks = body.find(".specialRemarks").val(),specialSelect = body.find(".specialSelect").val(),specialID= body.find(".T_recordterm").attr("recordterm-id");
                    if (specialName != "" && specialRemarks != "" && specialSelect != "") {
                        specialObj.inputName = specialName;
                        specialObj.remark = specialRemarks;
                        specialObj.inputType = specialSelect;
                        specialObj.id = specialID;
                        recordArray.push(specialObj);
                        n= 1;
                    }else {
                        n= 0;
                    }
                    record_term.each(function () {
                        inputList = {};
                        value = $(this).find(".fieldName").val();
                        fieldType = $(this).find(".fieldType").val();
                        mandatory = $(this).find(".mandatory").attr("checkbox-mandatory");
                        isEchart = $(this).find(".isEchart").attr("checkbox-isEchart");
                        inputType = $(this).find(".select-box").val();
                        businessType = $(this).find(".businessType").val();
                        id = $(this).attr("record-id");
                        deleteFlag = $(this).attr("deleteFlag");
                        if (inputType == 'checkbox' || inputType == 'radio') {
                            inputItems = $(this).find(".inputJson").val();

                        }else {
                            inputItems =[]
                        }
                        if (reg.test(value) && inputType !="") {
                            inputList.businessType = businessType == undefined ? "" : businessType;
                            inputList.inputItems = inputItems == "" ? [] : JSON.parse(inputItems);
                            inputList.inputName = value;
                            inputList.inputType = inputType;
                            inputList.isEchart = isEchart;
                            inputList.isOptional = mandatory;
                            inputList.remark = fieldType;
                            inputList.special = 'false';
                            inputList.id = id;
                            inputList.zIndex = n++ +1;
                            inputList.deleteFlag = deleteFlag;
                            recordArray.push(inputList)
                        }
                    });
                    if (recordArray == "") {
                        layer.msg('至少填写一个记录状态', {icon: 8});
                        return false;
                    }
                    var deleteRecords = body.find(".deleteRecord").val();
                    if (deleteRecords != "") {
                        var deleteRecordsJ = JSON.parse(deleteRecords);
                        for (var w = 0; w < deleteRecordsJ.length; w++) {
                            recordArray.push(deleteRecordsJ[w])
                        }
                    }
                    // 检查项
                    var inspect_terms = body.find(".inspect_terms");
                    var term_nameTextarea,inspect_select,inspectInfo,checkItemArray=[],id,deleteFlag;
                    var checkItemList = {checkType:'',groupName:'',itemValue:'',zIndex:'',id:'',deleteFlag:''};
                    var inspect_term_info = body.find(".inspect_term_info");
                    var num = 0;
                    var deletecheckItemArray = body.find(".deletecheckItemArray").val();
                    if (deletecheckItemArray != "") {
                        var deletecheckItemArrays= JSON.parse(deletecheckItemArray);
                        for (var r = 0; r < deletecheckItemArrays.length; r++) {
                            checkItemArray.push(deletecheckItemArrays[r])
                        }
                    }
                    inspect_term_info.each(function () {
                        checkItemList = {};
                        term_nameTextarea = $(this).parent().parent().find('.term_nameTextarea').val();
                        inspect_select = $(this).parent().parent().find('.inspect_select').val();
                        inspectInfo = $(this).find('.inspectInfo').val();
                        if (reg.test(inspectInfo)) {
                            id =  $(this).attr("inspect-id");
                            deleteFlag = $(this).attr('deleteFlag');
                            checkItemList.checkType = inspect_select;
                            checkItemList.groupName = term_nameTextarea;
                            checkItemList.itemValue = inspectInfo;
                            checkItemList.id = id;
                            checkItemList.deleteFlag = deleteFlag;
                            checkItemList.zIndex = num++ +1;
                            checkItemArray.push(checkItemList)
                        }
                    });
                    var updateStetaInfo = {
                        templateName:body.find(".TemplateName").val(),
                        remark:body.find(".Templatereamk").val() == ""? " ":body.find(".Templatereamk").val(),
                        statusContent:sessionStorage.getItem("groudBool") == 'true'?body.find(".textContent").val():"",
                        statusName:sessionStorage.getItem("groudBool") == 'true'?body.find(".textName").val():"",
                        departmentId:belpID,
                        checkItemList:checkItemArray,
                        inputList:recordArray,
                        recordStatusList:recordStatusList,
                        _method:'put',
                        id:obj.data.id

                    };
                    $.ajax({
                        url:'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/updateRecordTemplate',
                        method:'POST',
                        dataType: 'json',
                        data: updateStetaInfo,
                        success:function (res) {
                            if(res.code === '200'){
                                layer.msg('修改成功', {icon: 1});
                                table.reload('recordTemplateID');
                                layer.close(index);
                            }else if (res.code === '438') {
                                layer.msg(res.msg, {icon: 2});
                                table.reload('recordTemplateID')
                            }else if (res.code === '422') {
                                layer.msg(res.data[0].error, {icon: 2});
                                table.reload('recordTemplateID')
                            }else {
                                layer.msg("添加失败，请检查信息", {icon: 2});
                                table.reload('recordTemplateID')
                            }
                        },
                        error:function (err) {
                            layer.close(index);
                        }
                    })
                }
            })
        } else if (obj.event === "delete"){
            var content ={
                _method:'DELETE'
            };
            layer.alert('确认要删除吗？',{icon: 8}, function(index){
                $.ajax({
                    url: 'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/reomveRecordTemplate/'+obj.data.id,
                    method: 'post',
                    dataType: 'json',
                    data: content,
                    success: function (res) {
                        if (res.code === '200'){
                            layer.msg('删除成功', {icon: 1});
                            table.reload('recordTemplateID');
                        } else{
                            layer.msg('删除失败', {icon: 2});
                            table.reload('recordTemplateID');
                        }
                        layer.close(index);
                    },
                    error:function () {
                        layer.msg('请检查网络', {icon: 2});
                    }
                });
            });
        }
    });
    // 添加记录模版
    // 打开添加弹窗
    $(".addState").click(function () {
        layer.open({
            type: 2,
            id: 'addTemplate',
            title:'添加记录模版',
            shadeClose: true,
            scrollbar:true,
            shade: 0.3,
            maxmin: true,
            skin: 'oaBtn',
            btn: ['确认', '取消'],
            area: ['1000px', '600px'],
            content: addTemplateHtml,
            success: function (layero, index) {
                var body = layer.getChildFrame('body', index);
                sessionStorage.setItem("addgroudBool",'false');
                sessionStorage.setItem('groudBool','false');
            },
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var reg = /\S/;
                if (!reg.test(body.find(".TemplateName").val())) {
                    layer.msg('请输入模版名称', {icon: 8});
                    return false;
                }
                if (sessionStorage.getItem("groudBool") == 'true' && !reg.test(body.find(".textContent").val())&&!reg.test(body.find(".textName").val())) {
                    layer.msg('请输入文本状态', {icon: 8});
                    return false;
                }else if (sessionStorage.getItem("addgroudBool") == 'false' && !reg.test(body.find(".a_stateName1").val())) {
                    layer.msg('请选择状态组', {icon: 8});
                    return false;
                }
                if (!reg.test(body.find(".fieldName1").val())|| body.find('.select-boxsa').val() == "") {
                    layer.msg('请填写记录项字段或类型', {icon: 8});
                    return false;
                }
                var inputs = body.find('.a_inputs .a_input');
                // 记录状态
                var stateIDArray = [],
                    valArray = [],
                    cheackboxBoolArray = [],
                    recordStatusList = [],
                    recordStatusObj ={isEchart:"",statusContent:'',statusId:''};
                inputs.each(function () {
                    var value = $(this).find('input').val(),
                        stateId = $(this).find("input").attr("state-id"),
                        cheackboxBool = $(this).find("input").attr("checkbox-boole");
                        valArray.push(value);
                        stateIDArray.push(stateId);
                        cheackboxBoolArray.push(cheackboxBool);
                });
                for (var i = 0; i < inputs.length; i++) {
                    recordStatusObj = {};
                    if (valArray[i] != "") {
                        recordStatusObj.isEchart = cheackboxBoolArray[i];
                        recordStatusObj.statusContent = valArray[i];
                        recordStatusObj.statusId = stateIDArray[i];
                        recordStatusList.push(recordStatusObj)
                    }
                };
                if (sessionStorage.getItem("addgroudBool") == 'true') {
                    recordStatusList = [];

                }else {
                    if (recordStatusList == "") {
                        layer.msg('至少填写一个记录状态', {icon: 8});
                        return false;
                    }
                }
                // 记录项
                var inputList = {businessType:'',inputItems:[],inputName:'',inputType:'',isEchart:'',isOptional:'',remark:'',special:'',zIndex:''},
                value,fieldType,inputItems,mandatory,isEchart,inputType,businessType;
                var record_term = body.find(".record_term");
                var recordArray =[];
                var n;
                // 特殊记录项
                var specialObj= {businessType:'',inputItems:[],inputName:"",inputType:'',isEchart:'false',isOptional:'false',remark:'',special:'true',zIndex:1};
                var specialName = body.find(".specialName").val(),specialRemarks = body.find(".specialRemarks").val(),specialSelect = body.find(".specialSelect").val();
                if (specialName != "" && specialRemarks != "" && specialSelect != "") {
                    specialObj.inputName = specialName;
                    specialObj.remark = specialRemarks;
                    specialObj.inputType = specialSelect;
                    recordArray.push(specialObj)
                    n= 1;
                }else {
                    n= 0;
                }
                // if (recordArray == "") {
                //     layer.msg('至少填写一个记录项', {icon: 8});
                //     return false;
                // }else {
                //
                // }
                record_term.each(function () {
                    inputList = {};
                    value = $(this).find(".fieldName").val();
                    fieldType = $(this).find(".fieldType").val();
                    mandatory = $(this).find(".mandatory").attr("checkbox-mandatory");
                    isEchart = $(this).find(".isEchart").attr("checkbox-isEchart");
                    inputType = $(this).find(".select-box").val();
                    businessType = $(this).find(".businessType").val();
                    if (inputType == 'checkbox' || inputType == 'radio') {
                        inputItems = $(this).find(".inputJson").val();

                    }else {
                        inputItems = []
                    }
                    if (reg.test(value) && inputType != "") {
                        inputList.businessType = businessType == undefined ? "" : businessType;
                        inputList.inputItems = inputItems == ""? [] : JSON.parse(inputItems);
                        inputList.inputName = value;
                        inputList.inputType = inputType;
                        inputList.isEchart = isEchart;
                        inputList.isOptional = mandatory;
                        inputList.remark = fieldType;
                        inputList.special = 'false';
                        inputList.zIndex = n++ +1;
                        recordArray.push(inputList)
                    }
                });
                if (recordArray == "") {
                    layer.msg('至少填写一个记录项', {icon: 8});
                    return false;
                }
                // 检查项
                var inspect_terms = body.find(".inspect_terms");
                var term_nameTextarea,inspect_select,inspectInfo,checkItemArray=[];
                var checkItemList = {checkType:'',groupName:'',itemValue:'',zIndex:''};
                var inspect_term_info = body.find(".inspect_term_info");
                var num = 0;
                inspect_term_info.each(function () {
                    checkItemList = {};
                    term_nameTextarea = $(this).parent().parent().find('.term_nameTextarea').val();
                    inspect_select = $(this).parent().parent().find('.inspect_select').val();
                    inspectInfo = $(this).find('.inspectInfo').val();
                    if (reg.test(inspectInfo)) {
                        checkItemList.checkType = inspect_select;
                        checkItemList.groupName = term_nameTextarea;
                        checkItemList.itemValue = inspectInfo;
                        checkItemList.zIndex = num++ +1;
                        checkItemArray.push(checkItemList)
                    }
                });
                if (sessionStorage.getItem("addgroudBool") == 'true') {
                    recordStatusList = [];
                }
                var addStetaInfo = {
                    templateName:body.find(".TemplateName").val() == ""? "":body.find(".TemplateName").val(),
                    remark:body.find(".Templatereamk").val() == "" ? "":body.find(".Templatereamk").val(),
                    statusContent:sessionStorage.getItem("addgroudBool") == 'true'? body.find(".textContent").val() :"",
                    statusName:sessionStorage.getItem("addgroudBool") == 'true'? body.find(".textName").val() :"",
                    departmentId:belpID,
                    checkItemList:checkItemArray,
                    inputList:recordArray,
                    recordStatusList:recordStatusList,
                };
                $.ajax({
                    method:'post',
                    url:'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/addRecordTemplate',
                    data:addStetaInfo,
                    dataType:'json',
                    success:function (res) {
                        if(res.code === '200'){
                            layer.msg('添加成功', {icon: 1});
                            table.reload('recordTemplateID');
                            layer.close(index);
                        }else if (res.code === '438') {
                            layer.msg(res.code.msg, {icon: 2});
                            table.reload('recordTemplateID')
                        }else {
                            layer.msg("添加失败，请检查信息", {icon: 2});
                            table.reload('recordTemplateID')
                        }
                    },
                    error:function (err) {
                        layer.msg('网络错误', {icon: 2});
                    }
                })
            }
        })
    });
    // 记录类型
    function getInputType(body,iframeWin,arr){
        // select-box
        $.ajax({
            method:'get',
            url:'http://apptest.jieweizhineng.com/api/swagger/api/template/v1/getInputTypeList',
            data:'',
            dataType:'json',
            success:function (res) {
                if (res.code === '200') {
                    var str;
                    for (key in res.data){
                        for (var k = 0; k < arr.length; k++) {
                            if (key == arr[k]) {
                                str = `<option value="${key}" selected>${res.data[key]}</option>`;
                            }else {
                                str = `<option value="${key}">${res.data[key]}</option>`;
                            }
                            body.find(".select-box"+k).append(str);
                        }
                    }
                    iframeWin.layui.form.render();
                }
            },
            error:function (err) {

            }
        })
    }
});