//当前节点 入库质检
var layer;
var form;
var table;
var page = 1;
var limit = 10;
var curCheckData = null;// 当前编辑数据
var curCheckItems = null;// 当前数据的检查项信息
$(function () {
    layui.use(['layer', 'laydate', 'form', 'table'], function () {
        layer = layui.layer;
        form = layui.form;
        table = layui.table;
        var laydate = layui.laydate;
        laydate.render({
            elem: '#start',
            theme: '#7b8e9f',
            value: startTime
        });
        laydate.render({
            elem: '#end',
            theme: '#7b8e9f',
            value: endTime
        });
        laydate.render({
            elem: '#foodYear',
            theme: '#7b8e9f',
            type: 'year',
        });
        // 初始化表单数据
        renderTable();
        // 监听行工具事件
        table.on('tool(tableData)', function (obj) {
            if (obj.event === 'edit') {
                //更新仓库下拉列表
                updateSelect(obj);
                //展示数据
                showDetail(obj);
            }
        });
        //监听仓库选择
        layui.form.on('select(depotId)', function (data) {
            updateFoodVariety(data.value);
        });
        //监听化验结果单填写数据,并给出提示结果
        table.on('edit(tableCheckItem)', function (obj) {
            getResult(obj);
        });
    });
    //显示入库流程
    showProgress();
    // 初始化WebSocket
    initInoutWS(deptId, bizType, progress, userId);
});
//控制流程环节显示
function showProgress() {
    if (!inoutProgress) {
        return;
    }
    if (inoutProgress.indexOf("REGISTER") == -1) {
        $("#progress-register").css("display", "none");
    }
    if (inoutProgress.indexOf("CHECK") == -1) {
        $("#progress-check").css("display", "none");
    }
    if (inoutProgress.indexOf("WEIGHT_FULL") == -1) {
        $("#progress-fullWeight").css("display", "none");
    }
    if (inoutProgress.indexOf("HANDLE") == -1) {
        $("#progress-hand").css("display", "none");
    }
    if (inoutProgress.indexOf("WEIGHT_EMPTY") == -1) {
        $("#progress-emptyWeight").css("display", "none");
    }
    if (inoutProgress.indexOf("CARD_BACK") == -1) {
        $("#progress-cardBack").css("display", "none");
    }
}
//根据填写化验数据,给出提醒是否合格
function getResult(obj) {
    var data = obj.data;
    //填写的数据值
    var setValue = data.value;
    //标准值 >= 合格
    var lower = data.lowerLimit;
    if (0 != lower) {
        if (setValue > lower) {
            data.remarks = "合格";
        } else {
            data.remarks = "不合格";
        }
    }
    //标准值 <= 合格
    var upper = data.upperLimit;
    if (0 != upper) {
        if (setValue <= upper) {
            data.remarks = "合格";
        } else {
            data.remarks = "不合格";
        }
    }
    obj.update(data);
    //根据化验结果提醒是否合格
    updateCheckResultTip();
}
//动态更换仓库下拉列表
function updateSelect(obj) {
    $('#depotId option').remove();
    var dat = obj.data;
    if (dat.progress === "RECORD") {
        for (var i = 0; i < depot.length; i++) {
            $('#depotId').append('');
        }
    } else {
        for (var j = 0; j < listInDepot.length; j++) {
            $('#depotId').append('');
        }
    }
    //重新渲染
    form.render('select');
}
//根据选择仓库显示粮食品种
function updateFoodVariety(depotId) {
    var selectDepot;
    $.each(depot, function (index, data) {
        if (data.id === depotId) {
            selectDepot = data;
            return false;
        }
    });
    if (selectDepot) {
        var nowYear = dateFormatStr();
        form.val("form-detail", {
            foodVariety: selectDepot.foodVariety,
            foodLocation: selectDepot.foodLocation,
            foodYear: nowYear
        });
        form.render();
        //仓库变化,检验重新获取
        flushCheckItem(selectDepot.foodVariety);
    }
}
function dateFormatStr() {
    var d = new Date();
    return dateFtt("yyyy", d);
}
// socket信息返回處理
function socketOnMessage(packet) {
    layer.alert(packet.data);
    window.parent.sysNotify(packet.data);
};
// 查询
function flushData() {
    var index = layer.load();
    var param = form.val("form-param");
    table.reload('tableData', {
        url: "../../basic/inout/page-check-data",
        where: param,
    });
    $("thead tr").css({
        "border-bottom": "2px solid #53adce",
        "background": "#eff4f6"
    });
    layer.close(index);
};
// 导出数据-- 跳转新页面处理
function exportData() {
    var url = "com.ld.igds.inout.ReportInoutCheck.d";
    window.parent.openTab(url, "化验结果导出", "checkDataExport");
};
// 根据模式启动开始扦样
function checkExe(type) {
    checkDto.type = type;
    var param = JSON.stringify(checkDto);
    var index = layer.load();
    $.ajax({
        type: "POST",
        url: "../../api/check/check-exe",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: param,
        success: function (result) {
            layer.close(index);
            if (result.code != "0000") {
                layer.alert(result.msg);
            } else {
                layer.msg("操作命令发送成功!");
            }
        },
        error: function () {
            layer.close(index);
            layer.alert("后台异常,操作命令发送失败!");
        }
    });
};
// 关闭扦样机器
function checkStop() {
    var param = JSON.stringify(checkDto);
    var index = layer.load();
    $.ajax({
        type: "POST",
        url: "../../api/check/stop",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: param,
        success: function (result) {
            layer.close(index);
            if (result.code != "0000") {
                layer.alert(result.msg);
            } else {
                layer.msg("操作命令发送成功!");
            }
        },
        error: function () {
            layer.close(index);
            layer.alert("后台异常,操作命令发送失败!");
        }
    });
};
// 扦样机复位
function checkReset() {
    var param = JSON.stringify(checkDto);
    var index = layer.load();
    $.ajax({
        type: "POST",
        url: "../../api/check/reset",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: param,
        success: function (result) {
            layer.close(index);
            if (result.code != "0000") {
                layer.alert(result.msg);
            } else {
                layer.msg("操作命令发送成功!");
            }
        },
        error: function () {
            layer.close(index);
            layer.alert("后台异常,操作命令发送失败!");
        }
    });
};
function showDetail(obj) {
    curCheckData = obj.data;
    curCheckData.foodYear = dateFormatStr();
    curCheckData.checkUser = checkUser;
    // 赋值
    form.val("form-detail", curCheckData);
    form.render();
    layer.open({
        type: 1,
        title: "化验单明细",
        area: ['1400px', '600px'],
        shade: 0,
        content: $('#checkDetail'),
        btnAlign: 'c',
        btn: ['保存提交', '关闭取消'],
        yes: function () {
            // 更新到页面
            var data = form.val("form-detail");
            obj.update(data);
            // 合并更新當前编辑数据
            Object.assign(curCheckData, data);
            submit();
        }, btn2: function () {
            layer.closeAll();
        },
        closeBtn: 0
    });
    // 获取化验项信息
    flushCheckItem(null);
};
/**
 * 获取化验结果,结果查询后直接覆盖现有的结果信息
 */
function getCheckResult() {
    // 调整参数
    checkDto.checkId = curCheckData.checkId;
    checkDto.recordId = curCheckData.id;
    checkDto.progress = curCheckData.progress;
    var param = JSON.stringify(checkDto);
    var index = layer.load();
    $.ajax({
        type: "POST",
        url: "../../api/check/get-check-result",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: param,
        success: function (result) {
            layer.close(index);
            if (result.code != "0000") {
                layer.msg(result.msg);
            } else {
                curCheckItems = result.data;
                renderTableCheckItem();
            }
        },
        error: function () {
            layer.close(index);
            layer.msg("后台异常,请重试或者联系管理员!!");
        }
    });
};
/**
 * 刷新化验结果项
 */
function flushCheckItem(foodVariety) {
    curCheckItems = null;
    $("#check-result-tip").text("");
    if (foodVariety) curCheckData.foodVariety = foodVariety;
    var index = layer.load();
    $.ajax({
        type: "POST",
        url: "../../basic/inout/get-check-item",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(curCheckData),
        success: function (result) {
            if (result.code != "0000") {
                layer.msg(result.msg);
            } else {
                curCheckItems = result.data;
                // 根据化验结果提醒是否合格
                updateCheckResultTip();
                // 页面渲染检测项
                renderTableCheckItem();
                layer.close(index);
            }
        },
        error: function () {
            layer.close(index);
            layer.msg("后台异常,请重试或者联系管理员!!");
        }
    });
};
// 更新化验结果提醒,只做提醒,不做自动判断
function updateCheckResultTip() {
    if (!curCheckItems || curCheckItems.length == 0) {
        return;
    }
    if (curCheckData.checkStatus != "NONE") {
        return;
    }
    var msg;
    $.each(curCheckItems, function (index, data) {
        if (!data.remarks) {
            return true;
        }
        if (data.remarks == "不合格") {
            msg = "不合格";
            return false;
        }
        if (data.remarks == "合格") {
            msg = "合格";
        }
    });
    if (msg) {
        $("#check-result-tip").text("系统判断:" + msg);
    } else {
        $("#check-result-tip").text("系统判断:");
    }
};
/**
 * 渲染表格
 */
function renderTableCheckItem() {
    // 清空数据
    $("#tableCheckItem").empty();
    table.render({
        elem: '#tableCheckItem',
        data: curCheckItems,
        page: false,
        // skin: 'line',
        even: true,
        cols: [[{
            field: 'standardName',
            title: '化验项',
            align: 'center',
            width: '20%'
        }, {
            field: 'value',
            title: '化验值',
            align: 'center',
            width: '20%',
            edit: 'text'
        }, {
            field: 'upperLimit',
            title: '标准上限',
            align: 'center',
            width: '16%'
        }, {
            field: 'lowerLimit',
            title: '标准下限',
            align: 'center',
            width: '16%'
        }, {
            field: 'unit',
            title: '单位',
            align: 'center',
            width: '10%'
        }, {
            field: 'remarks',
            title: '说明',
            align: 'center'
        }]]
    });
    $("thead tr").css({
        "border-bottom": "2px solid #53adce",
        "background": "#eff4f6"
    });
};
// 当前完成
function submit() {
    if (curCheckData.checkStatus == "NONE" || curCheckData.checkStatus == "NONE2") {
        layer.alert("请填写化验结果!!!");
        return;
    }
    if (!curCheckData.depotId) {
        layer.alert("请填写仓库信息!!");
        return;
    }
    if (!curCheckData.foodVariety) {
        layer.alert("请填写粮食品种信息!!");
        return;
    }
    if (!curCheckData.foodYear) {
        layer.alert("请填写粮食年份信息!!");
        return;
    }
    curCheckData.checkItems = curCheckItems;
    var index = layer.load();
    $.ajax({
        type: "POST",
        url: "../../basic/inout/update-check",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(curCheckData),
        success: function (result) {
            if (result.code != "0000") {
                layer.close(index);
                //layer.alert(result.msg);
                notify(result.msg, result.data);
            } else {
                layer.closeAll();
                curCheckData = null;
                //layer.alert("数据提交成功!");
                notify("数据提交成功", result.data);
                flushData();
            }
        },
        error: function () {
            layer.close(index);
            layer.alert("提交失败,请重新尝试!");
        }
    });
};
// 渲染表单数据
function renderTable() {
    var param = form.val("form-param");
    // 清空数据
    $("#tableData").empty();
    table.render({
        elem: '#tableData',
        url: '../../basic/inout/page-check-data',
        page: true,
        limit: limit,
        even: true,
        method: 'POST',
        contentType: "application/json;charset=UTF-8",
        cols: [[{
            field: 'checkId',
            title: '单据号',
            width: '13%',
            style: 'color: #f67d06;font-weight: bold'
        }, {
            field: 'plateNum',
            title: '车船号',
            width: '11%',
            style: 'font-weight: bold'
        }, {
            field: 'customerName',
            title: '往来单位',
        }, {
            field: 'foodVariety',
            title: '品种',
            width: '10%',
            templet: function (item) {
                var result = item.foodVariety;
                $.each(listFoodVariety, function (index, data) {
                    if (item.foodVariety == data.code) {
                        result = data.name;
                        return true;
                    }
                });
                return result == null ? "" : result;
            }
        }, {
            field: 'depotId',
            title: '装卸仓库',
            width: '10%',
            templet: function (item) {
                var result = item.depotId;
                $.each(listDepot, function (index, data) {
                    if (item.depotId == data.id) {
                        result = data.name;
                        return true;
                    }
                });
                return result == null ? "" : result;
            }
        }, {
            field: 'checkStatus',
            title: '是否合格',
            width: '10%',
            style: 'font-weight: bold',
            templet: function (item) {
                if (item.checkStatus == 'NONE') {
                    return "未化验";
                }
                if (item.checkStatus == 'PASS') {
                    return "合格";
                }
                if (item.checkStatus == 'UNPASS') {
                    return "不合格";
                }
                return item.checkStatus == null ? "" : item.checkStatus;
            }
        }, {
            field: 'registerTime',
            title: '登记时间',
            width: '14%'
        }, {
            field: '',
            title: '操作',
            width: '9%',
            toolbar: "#barControl"
        }]],
        where: param,
        parseData: function (res) {
            if ("0000" == res.code) {
                return {
                    "code": "0",
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.records
                }
            } else {
                return {
                    "code": "1",
                    "msg": res.msg
                }
            }
        }
    });
    $("thead tr").css({
        "border-bottom": "2px solid #53adce",
        "background": "#eff4f6"
    });
};
// 表单清空
function resetForm() {
    $("#form-param")[0].reset();
    form.render();
};
/**
 * 弹出提醒框
 * @param msg 提醒信息
 * @param data 数据信息,可能为空
 */
function notify(msg, data) {
    if (data) {
        //赋值
        $("#resultMsg").text(msg);
        $("#resultUserName").text(data.userName);
        $("#resultPlateNum").text(data.plateNum);
        if ("IN" == data.type) {
            $("#resultType").text("入库-" + INOUT_PROGRESS_MSG(data.progress));
        } else {
            $("#resultType").text("出库-" + INOUT_PROGRESS_MSG(data.progress));
        }
        $("#resultIntelCard").text(data.intelCard);
        layer.open({
            type: 1,
            offset: ['150px', '200px'],
            area: '450px;',
            shade: 0.8,
            id: 'dialog_notify_info',
            btn: ['确定'],
            content: $('#dialog-from-notify'),
            yes: function (index) {
                layer.closeAll();
            }
        });
    } else {
        layer.alert(msg, {offset: ['300px', '300px']});
    }
};
// ---------------------------往来人员操作-开始 -------------------//
// 弹出往来单位下拉框
function showCustomer() {
    var index = layer.load();
    // 渲染往来单位列表
    table.render({
        elem: '#tableCustomer',
        url: '../../basic/inout/list-in-customer',
        page: false,
        // skin : "nob",
        // size : 'sm',
        toolbar: '#toolbarCustomer',
        even: true,
        method: 'POST',
        contentType: "application/json;charset=UTF-8",
        cols: [[{
            field: 'id',
            title: '编码'
        }, {
            field: 'name',
            title: '名称',
            width: '75%'
        }]],
        // where : param,
        parseData: function (res) {
            if ("0000" == res.code) {
                return {
                    "code": "0",
                    "msg": res.msg,
                    "data": res.data
                }
            } else {
                return {
                    "code": "1",
                    "msg": res.msg
                }
            }
        },
        done: function (res) {
            layer.close(index);
        }
    });
    //双击显示选中数据
    table.on('rowDouble(tableCustomer)', function (obj) {
        var data = obj.data;
        // 赋值
        form.val("form-detail", {
            customerId: data.id,
            customerName: data.name,
            noticeId: data.noticeId
        });
        // 关闭
        layer.close(index2);
    });
    // 弹出对话框
    var index2 = layer.open({
        type: 1,
        title: "选择往来单位",
        area: ['600px', '600px'],
        shade: 0,
        content: $('#listCustomer'),
        btn: 0,
        btn: ['取消'],
        yes: function () {
            // 关闭
            layer.close(index2);
        },
        closeBtn: 0
    });
};
// 刷新往来单位数据
function flushCustomer() {
    var key = $("#key").val();
    table.reload('tableCustomer', {
        url: "../../basic/inout/list-in-customer",
        where: {
            key: key
        },
        done: function (res) {
            if (key) {
                $("#key").val(key);
            }
        }
    });
};
// ---------------------------往来人员操作 -结束 -------------------//
// ---------------------------粮食产地 -开始 -------------------//
// 弹出粮食产地下拉框
function showFoodLocation() {
    var index = layer.load();
    // 渲染往来单位列表
    table.render({
        elem: '#tableFoodLoaction',
        url: '../../basic/common/page-food-location',
        page: false,
        toolbar: '#toolbarFoodLocaton',
        even: true,
        method: 'POST',
        contentType: "application/json;charset=UTF-8",
        cols: [[{
            field: 'code',
            title: '编码',
        }, {
            field: 'simple',
            title: '简拼',
        }, {
            field: 'name',
            title: '名称',
            width: '60%'
        }]],
        where: {
            "page": 1,
            "limit": 100
        },
        parseData: function (res) {
            if ("0000" == res.code) {
                return {
                    "code": "0",
                    "msg": res.msg,
                    "count": res.data.total,
                    "data": res.data.records
                }
            } else {
                return {
                    "code": "1",
                    "msg": res.msg
                }
            }
        },
        done: function (res) {
            layer.close(index);
        }
    });
    //双击显示选中数据
    table.on('rowDouble(tableFoodLoaction)', function (obj) {
        var data = obj.data;
        // 赋值
        form.val("form-detail", {
            foodLocation: data.name,
        });
        // 关闭
        layer.close(index2);
    });
    // 弹出对话框
    var index2 = layer.open({
        type: 1,
        title: "选择粮产地",
        area: ['600px', '600px'],
        shade: 0,
        content: $('#listFoodLocation'),
        btn: 0,
        btn: ['取消'],
        yes: function () {
            // 关闭
            layer.close(index2);
        },
        closeBtn: 0
    });
};
// 刷新
function flushFoodLocation() {
    var key = $("#key2").val();
    table.reload('tableFoodLoaction', {
        url: "../../basic/common/page-food-location",
        where: {
            key: key
        },
        done: function (res) {
            if (key) {
                $("#key2").val(key);
            }
        }
    });
};
// ---------------------------粮食产地 -结束 -------------------//