let gridManager = null;
//页面控制标识
let control = {
    isInitiator: false,//是否为审核人
    isDistribute: false,//是否已分发
}

$(document).ready(function () {
    initializate()
    loadGrid();
    // initAssistantGrid();
    loadRejectReasonBox();
})


function initializate() {
    //页面控制
    $("#businessPersonnelList").hide();
    
    switch ($("#active").val()) {
        case '0'://已分发未完成
            if ($("#deptCode").val() === "system") {
                $("#auditForm").show();
            } else {
                $("#buttonBox").show();
            }
            break;
        case '1'://完成/审核
            // $("#auditForm").show();
            break;
        case '2'://保存未分发
            $("#buttonBox").show();
            break;
        case '3'://被驳回
            showRejectCauseBox();
            $("#buttonBox").show();
            break;
        default://其他/详情
            $("#buttonBox").show();
            break;
    }

    // let isInitiator = ($("#isInitiator").val() === "true");
    // if (isInitiator) {
    //     //创建或审核人
    //     $("#buttonBox").remove();
    // }else{
    //     //审核人
    //     $("#auditForm").remove();
    // }


    // $('input[name="maintenanceType"]').change(function () {
    //     if ($(this).is(':checked')) {
    //         console.log($(this).val()); // 输出选中的值
    //         switch ($(this).val()) {
    //             case 'new':
    //                 if ($("#mtart").val() == "ZMPN") {
    //                     UICtrl.enable($("#matnr"));
    //                 } else {
    //                     UICtrl.disable($("#matnr"));
    //                 }
    //                 UICtrl.disable($("#lvorm"));
    //                 UICtrl.enable($("#mtart"));
    //                 UICtrl.enable($("#matkl"));
    //                 UICtrl.enable($("#spart"));
    //                 break;
    //             case 'modify':
    //                 UICtrl.enable($("#lvorm"))
    //                 UICtrl.disable($("#mtart"));
    //                 UICtrl.disable($("#matkl"));
    //                 UICtrl.disable($("#spart"));
    //                 break;
    //             case 'extend':
    //                 UICtrl.enable($("#lvorm"))
    //                 UICtrl.disable($("#mtart"));
    //                 UICtrl.disable($("#matkl"));
    //                 UICtrl.disable($("#spart"));
    //                 break;
    //         }
    //     }
    // });
    //
    // $('input[name="businessUsage"]').change(function () {
    //     if ($(this).is(":checked")) {
    //         console.log($(this).val()); // 输出选中的值
    //     }
    // });

}


/**
 * 初始化对应的分发部门
 */
function loadGrid() {
   // alert($("#businessCode").val());
    $("#genericName").attr("disabled",true);
    $("#applicableStandard").attr("disabled",true);
    $("#baseUnit").attr("disabled",true);
    $("#size").attr("disabled",true);
    $("#material").attr("disabled",true);
    $("#design").attr("disabled",true);
    $("#brand").attr("disabled",true);
    $("#specifications").attr("disabled",true);
    $("#materialUsage").attr("disabled",true);

    UICtrl.disable($("#werksName"));
    UICtrl.disable($("#materialUsage"));
    UICtrl.disable($("#baseUnit"));
    UICtrl.disable($("#itemAttributes"));
    //let coRowNum = $("#businessUsage").val().replace(/,/g, '') + 1;
    // let length = dept.length;
    // let dept=$("#businessUsage").val().split(",");
    // let a=(dept.length+1)*37.5;
    gridManager = UICtrl.grid("#businessPersonnelListGrid", {
        columns: [
            {display: "部门", name: "deptName", width: 200, minWidth: 60, type: "string", align: "left"},
            {  display: "部门人员", name: "userName", width: 200, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: 'tree',
                    required: true,
                    data: {
                        name: 'org',
                        filter: 'psm',
                        minWidth: 250
                    },
                    textField: 'userName',
                    valueField: 'userCode'
                }
                // editor: {
                //     required: true, type: "select",
                //     data: {
                //         type: 'system',
                //         name: "testUser",
                //         back: {
                //             id: "userName",
                //             userCode: "userCode"
                //         },
                //         getParam: function (data) {
                //             return {deptCode: data.deptCode}
                //         },
                //     },
                // }
            },
            {  display: "人员Id", name: "userCode", width: 260, minWidth: 60, type: "string", align: "left",
                editor: {
                    type: 'text',
                    required: true
                }
            },
        ],
        dataAction: "server",
        url: web_app.name + '/sapNonProdApplyNext/slicedDeptList.ajax',
        parms: {dept: $("#businessUsage").val(),deptId: $("#applyDeptId").val(),id:$("#id").val()},
        pageSize: 20,
        usePager: false,
        enabledEdit: true,
        width: "100%",
        height: "90%",//coRowNum * 37.5,
        heightDiff: -8,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
    });
    UICtrl.setSearchAreaToggle(gridManager);
}


/**
 * 表单提交
 * @returns {boolean}
 */
function saveForm(status) {
   // $("#active").val(status)
    //alert($("#businessCode").val());
    let extendedData = getExtendedData();
    if (!extendedData) return false;
    var _self = this;
    $('#submitForm').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/saveSapNonProdApplyDept.ajax?opstatus='+status,
        param: extendedData,
        success: function (data) {
            $("#applyDeptId").val(data.applyDeptId);
            if (data.result==""){
                Public.successTip("保存成功！");
            } else {
                Public.tip(data.result);
            }
           // _self.close();
            if (status==1) {
                $("#buttonBox").remove();
            }
            UICtrl.reloadTabById('homepage');
        }
    });
}

//撤销
function  clearForm() {
    // $("#saleForm").formClean();
    $("#kzdkz").val("");
    $("#art").val("");
    $("#aktiv").val("");
    $("#insmk").val("");
    $("#ppl").val("");
    $("#app").val("");
    $("#mer").val("");
    $("#dyn").val("");


}
/**
 * 分发表单到各个部门
 */
function distributeForm() {
    if (control.isDistribute) {
        Public.successTip("已分发");
        return false;
    }
    let extendedData = getExtendedData();
    if (!extendedData) return false;
    $('#submitForm').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/distributeSapNonProdApplyDept.ajax',
        param: extendedData,
        success: function (data) {
            Public.successTip("分发成功！");
            control.isDistribute = true;
            _self.close();
        }
    });
}




function getExtendedData() {

    
    let msg = "[";
    let isUndefined = false
    let deptStaffResult = DataUtil.getGridData({
        gridManager: gridManager,
        isAllData: true,
        onCheck: function (data) {
            if (typeof data.userCode === 'undefined') {
                msg += `${data.deptName}、`;
                isUndefined = true;
            }
            return true;
        }
    });

    /*if (isUndefined) {
        Public.tip(`${msg.slice(0, -1)}]未选择对应分发人员`);
        return false
    }*/
    let extendedData = {};
    extendedData.deptStaff = Public.encodeJSONURI(deptStaffResult);
    return extendedData;
}


function rejectForm() {
    
    $('#auditForm').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/rejectNonProdApplyDept.ajax',
        param: {meId:getMeId()},
        success: function (data) {
            Public.successTip("已驳回！");
            _self.close();
        }
    });

}

function checkThrough(){
    $('#exPass').ajaxSubmit({
        url: web_app.name + '/sapNonProdApplyNext/rejectNonProdApplyDept.ajax',
        param: {meId:getMeId()},
        success: function (data) {
            Public.successTip("检查通过！");
            _self.close();
        }
    });
}


/**
 * 根据选择的驳回的部门生成输入框
 */
function loadRejectReasonBox() {
    $('input[name="auditDept"]').change(function () {
            let val = $(this).val()
            let textData = $(this).parent().text().trim()
            if (this.checked) {
                if ($(`#id_${val}`).length) {
                    // 元素存在
                    $(`#id_${val}`).show();
                } else {
                    // 元素不存在
                    let box = `<div id="id_${val}">
                            <div class="col-xs-4 col-sm-2" style="height:60px;">
                                <label class="hg-form-label" name="${val}" title="[${textData}]驳回原因">[${textData}]驳回原因&nbsp;:</label>
                             </div>
                             <div class="col-xs-8 col-sm-10 col-warp col-white-bg" style="height:60px;">
                                <textarea name="${val}"  label="[${textData}]驳回原因" id="text_${val}"></textarea>
                             </div>
                        </div>`;
                    $("#rejectReasonBox").append(box)
                }
                $(window).scrollTop($(document).height());
            } else {
                $(`#id_${val}`).hide();
            }
        }
    );
}

/**
 *根据驳回信息生成驳回信息展示栏
 */
function showRejectCauseBox() {
    Public.ajax(web_app.name + '/sapNonProdApplyNext/slicedRejectCauseList.ajax', {meId: getMeId()}, function (data) {
        const generateCauseHTML = (item, newCause) => {
            const { rectifyDate, rejectMsg, bsnExecuteId, rejectDate } = item;
            return `
    <div class="hg-form-row">
      <div class="col-xs-4 col-sm-1" style="height:56px;">
        <label class="hg-form-label" title="驳回原因">驳回原因${newCause}&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-11 col-warp col-gray-bg" style="height:56px;">
        <textarea rows="2" label="驳回原因" readonly="readonly">${rejectMsg}</textarea>
      </div>
    </div>
    <div class="hg-form-row">
      <div class="col-xs-4 col-sm-1">
        <label class="hg-form-label" title="驳回人">驳回人&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-3 col-warp col-gray-bg">
        <input type="text" value="${bsnExecuteId}" readonly="readonly" label="驳回人">
      </div>
      <div class="col-xs-4 col-sm-1">
        <label class="hg-form-label" title="驳回时间">驳回时间&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-3 col-warp col-gray-bg">
        <input type="text" value="${rejectDate}" readonly="readonly" label="驳回时间">
      </div>
      <div class="col-xs-4 col-sm-1">
        <label class="hg-form-label" title="处理时间">处理时间&nbsp;:</label>
      </div>
      <div class="col-xs-8 col-sm-3 col-warp col-gray-bg">
        <input type="text" value="${rectifyDate}" readonly="readonly" label="处理时间">
      </div>
    </div>
  `;
        };
        let newCause = `<span style="color:red;">new</span>`;
        const ahtml = data
            .map((item) => {
                const cause = item.rectifyDate === '' ? `[${newCause}]` : '';
                return generateCauseHTML(item, cause);
            })
            .join('');

        $("#cause-details-box").html(ahtml);
        $("#causeBox").show();
    })

}

function getMeId() {
    return $("#meId").val() || '';
}