@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section header
    {
    <style type="text/css">
        .head {
            padding-top: 7px;
            border-bottom: 1px solid #eee !important;
        }
    </style>
}
<div class="layui-fluid">
    <!--head-->
    <header class="layui-row head layui-form" lay-filter="example">
        <div class="layui-col-sm3">
            <div class="layui-form-item">
                <label class="layui-form-label">条码信息<span class="lable-required">*</span></label>
                <div class="layui-input-inline">
                    <input type="text" name="barCode" id="barCode" lay-verify="required" onkeydown="enter(event)" autocomplete="off" placeholder="请录入条码信息" class="layui-input" />
                </div>
            </div>
        </div>
        <div class="layui-col-sm3">
            <div class="layui-form-item">
                <label class="layui-form-label">工位信息<span class="lable-required">*</span></label>
                <div class="layui-input-inline" lay-filter="stationCode">
                    <select name="stationCode" id="stationCode" lay-filter="stationCode"></select>
                </div>
            </div>
        </div>
        <div class="layui-col-sm3">
            <div class="layui-form-item">
                <label class="layui-form-label">操作时间<span class="lable-required">*</span></label>
                <div class="layui-input-inline">
                    <input name="optionTime" id="optionTime" autocomplete="off" lay-verify="required" class="layui-input layui-date" value="@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")" />
                </div>
            </div>
        </div>
    </header>
    <!--内容-->
    <div class="layui-row content">
        <div class="layui-row">
            <div class="layui-card">
                <div class="layui-card-header">
                    <b>工序信息</b><span>&nbsp;&nbsp;</span>
                    <button class="layui-btn layui-btn-sm" onclick="search(false)"><i class="layui-icon layui-icon-search"></i>获取数据</button>
                    <button class="layui-btn layui-btn-sm" onclick="resert()"><i class="layui-icon layui-icon-refresh"></i>重置</button>
                </div>
                <div class="layui-card-body">
                    <table class="layui-table" id="mainList" lay-filter="mainList"></table>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-row">
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header"><b>物料信息</b></div>
                <div class="layui-card-body">
                    <table class="layui-table" id="materialInfo" lay-filter="materialInfo"></table>
                </div>
            </div>
        </div>
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header"><b>设备信息</b></div>
                <div class="layui-card-body">
                    <table class="layui-table" id="equipmentInfo" lay-filter="equipmentInfo"></table>
                </div>
            </div>
        </div>
    </div>

    <!--按钮-->
    <footer class="layui-btn-container layui-container">
        <button id="start" class="layui-btn layui-btn-normal layui-btn-lg" onclick="start()"><i class="layui-icon layui-icon-flag"></i>工序开工</button>
        <button id="complate" class="layui-btn layui-btn-lg" onclick="complete()"><i class="layui-icon layui-icon-ok"></i>工序完工</button>
        <button id="workReport" class="layui-btn layui-btn-warm layui-btn-lg" onclick="workReport()"><i class="layui-icon layui-icon-release"></i>报工MOM</button>
    </footer>
</div>

<script type="text/html" id="MaterialUseLog">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<script type="text/html" id="EquipmentProcessTemplate">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<script type="text/html" id="stateLable">
    {{# if(d.state==0){ }}
    <span>初始化</span>
    {{# }else if(d.state==30){ }}
    <span>生产中</span>
    {{# }else if(d.state==60){ }}
    <span>运输中</span>
    {{# }else if(d.state==100){ }}
    <span>已完成</span>
    {{# }else if(d.state==100){ }}
    <span>已变更无需处理</span>
    {{# }else { }}
    <span>{{ d.state}}</span>
    {{# } }}
</script>
<script type="text/html" id="workReportLable">
    {{# if(d.workReportStatus==0){ }}
    <span>未报工</span>
    {{# }else if(d.workReportStatus==10){ }}
    <span>开工已报工</span>
    {{# }else if(d.workReportStatus==20){ }}
    <span>完工已报工</span>
    {{# }else if(d.workReportStatus==30){ }}
    <span>无需报工</span>
    {{# }else { }}
    <span>{{ d.workReportStatus}}</span>
    {{# } }}
</script>
@section Scripts
    {
    <script>
        var element, table, laydate, form, layer = null;
        //默认值
        const defaultData =
        {
            id: 0,
            headKeys: "",
            bodyKeys: "",
            workOrderInfo: [],
            materInfo: [],
            equipmentInfo: []
        };
        var allTableData = defaultData;
        layui.use(['table', 'element', 'laydate', 'form', 'layer'], function () {
            element = layui.element;
            table = layui.table;
            laydate = layui.laydate;
            form = layui.form;
            layer = layui.layer;
            laydate.render({
                elem: '#optionTime',
                type: 'datetime'
            });
            reloadTable();
        });

        //重载所有表格数据
        function reloadTable() {
            //工序信息
            table.render({
                elem: '#mainList',
                even: true,
                height: 150,
                data: allTableData.workOrderInfo,
                size: 'sm',
                cols: [[
                    { field: "id", width: 60, title: " ID" },
                    { field: "keys", width: 150, hide: true, title: "keys" },
                    { field: "bodyKeys", width: 150, hide: true, title: "bodyKeys" },
                    { field: "planCode", width: 150, title: "生产计划号" },
                    { field: "productHeaderCode", width: 150, title: "产品编号" },
                    { field: "productHeaderName", width: 150, title: "产品名称" },
                    { field: "workCenterCode", width: 150, title: "工作中心编号" },
                    { field: "lineCode", width: 150, title: "线体编号" },
                    { field: "lineName", width: 150, title: "线体名称" },
                    { field: "workOrderCode", width: 150, title: "订单编号" },
                    { field: "state", width: 150, title: "状态", templet: "#stateLable" },
                    { field: "workReportStatus", width: 150, title: "报工状态", templet: "#workReportLable" },
                    { field: "serialNumber", width: 150, title: "工序" },
                    { field: "planStartTime", width: 150, title: "计划开始时间" },
                    { field: "planEndTime", width: 150, title: "计划结束时间" },
                    { field: "actualStartTime", width: 150, title: "实际开始时间" },
                    { field: "actualEndTime", width: 150, title: "实际结束时间" },
                    { field: "createTime", width: 150, title: "创建时间" },
                ]],
                done: function (res, curr, count) {
                    var that = this.elem.next();
                    res.Result.forEach(function (item, index) {
                        if (item.id == allTableData.id) {
                            var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']");
                            tr.css("background-color", "#31BDEC");
                            tr.css("color", "white");
                        }
                    });
                }
            });

            //物料信息
            table.render({
                elem: '#materialInfo',
                even: true,
                height: 200,
                data: allTableData.materInfo,
                size: 'sm',
                cols: [[
                    { field: "id", width: 80, title: "id", hide: true },
                    { field: "key", width: 80, title: "Keys", hide: true },
                    { field: "materialCode", width: 150, title: "物料编码" },
                    { field: "materialName", width: 150, title: "物料名称" },
                    { field: "qyt", width: 80, title: "数量" },
                    { field: "crux", width: 100, title: "精追件标识", templet: function (obj) { return obj.crux == "false" ? "否" : "是" } },
                    { field: "createTime", width: 170, title: "创建时间" },
                    { field: "createBy", width: 150, title: "创建人" },
                    { field: "remarks", width: 150, title: "备注" },
                    { fixed: 'right', title: '操作', width: 70, toolbar: '#MaterialUseLog' }
                ]],
            });

            table.on(`tool(materialInfo)`, function (obj) {
                if (obj.event === "delete") {
                    layer.confirm(`你确定删除【${obj.data.materialCode}】行吗?`, function (index) {
                        var deleteItem = allTableData.materInfo.find(x => x.id == obj.data.id);
                        allTableData.materInfo.splice(allTableData.materInfo.indexOf(deleteItem), 1)
                        obj.del();
                        layer.close(index);
                    });
                }
            });

            //重载设备Table信息
            reloadEquipmentTable();

            //启用或禁用按钮
            if (allTableData.workOrderInfo.length === 0) {
                //禁用
                if (!$("#start").hasClass("layui-btn-disabled")) {
                    $("#start").addClass("layui-btn-disabled");
                }
                if (!$("#complate").hasClass("layui-btn-disabled")) {
                    $("#complate").addClass("layui-btn-disabled");
                }
                if (!$("#workReport").hasClass("layui-btn-disabled")) {
                    $("#workReport").addClass("layui-btn-disabled");
                }
            }
            else {
                //启用
                if ($("#start").hasClass("layui-btn-disabled")) {
                    $("#start").removeClass("layui-btn-disabled");
                }
                if ($("#complate").hasClass("layui-btn-disabled")) {
                    $("#complate").removeClass("layui-btn-disabled");
                }
                if ($("#workReport").hasClass("layui-btn-disabled")) {
                    $("#workReport").removeClass("layui-btn-disabled");
                }
                //当前待报工的工序
                var workOrder = allTableData.workOrderInfo.find(x => x.id == allTableData.id);
                $("#stationCode").empty();
                layui.form.render("select");
                $.ajax({
                    type: "post",
                    url: "/configure/Station/LoadStationCodeByworkCenterCode",
                    data: {
                        workCenterCode: workOrder.workCenterCode,
                        lineCode: workOrder.lineCode
                    },
                    success: function (res) {
                        var data = JSON.parse(res);
                        if (data.Status) {
                            $.each(data.Result, function (index, value) {
                                $("#stationCode").append(new Option(value.workStationName, value.workStationCode));
                            });
                            layui.form.render("select");
                        }
                        else {
                            layer.msg(data.Message, { icon: 2 });
                        }
                    },
                    error: function (err) {
                        console.log(err);
                        layer.msg(err.statusText, { icon: 2 });
                    }
                })

                ////监听工位选中事件
                form.on('select(stationCode)', function (data) {
                    var stationCode = form.val('example').stationCode;
                    var workOrder = allTableData.workOrderInfo.find(x => x.id == allTableData.id);
                    if (stationCode != null && stationCode != "") {
                        $.ajax({
                            type: "post",
                            url: "GetEquipmentInfo",
                            data: {
                                "bodyKeys": allTableData.bodyKeys,
                                "workCenterCode": workOrder.workCenterCode,
                                "stationCode": stationCode
                            },
                            success: function (res) {
                                var resultData = JSON.parse(res);
                                allTableData.equipmentInfo = resultData.Result;
                                reloadEquipmentTable();
                                if (resultData.Status) {
                                    layer.msg(resultData.Message, { icon: 1 });
                                }
                                else {
                                    layer.msg(resultData.Message, { icon: 2 });
                                }
                            },
                            error: function (ero) {
                                layer.msg(err.statusText, { icon: 2 });
                            }
                        })
                    }
                })
            }
        }

        //重载设备Table信息
        function reloadEquipmentTable() {
            table.render({
                elem: '#equipmentInfo',
                even: true,
                height: 200,
                data: allTableData.equipmentInfo,
                size: 'sm',
                cols: [[
                    { field: "id", width: 80, title: "id", hide: true },
                    { field: "key", width: 80, title: "key", hide: true },
                    { field: "device_code", width: 150, title: "设备编号" },
                    { field: "device_information", width: 150, title: "设备信息" },
                    { field: "processing_steps", width: 150, title: "加工步骤" },
                    { field: "processing_parameters", width: 150, title: "加工参数名称" },
                    { field: "processing_results", width: 150, title: "加工参数执行结果" },
                    { field: "createTime", width: 170, title: "创建时间" },
                    { field: "createBy", width: 150, title: "创建人" },
                    { field: "remarks", width: 150, title: "备注" },
                    { fixed: 'right', title: '操作', width: 70, toolbar: '#EquipmentProcessTemplate' }
                ]],
            });

            table.on(`tool(equipmentInfo)`, function (obj) {
                if (obj.event === "delete") {
                    layer.confirm(`你确定删除【${obj.data.device_information}】行吗?`, function (index) {
                        var deleteItem = allTableData.equipmentInfo.find(x => x.id == obj.data.id);
                        allTableData.equipmentInfo.splice(allTableData.equipmentInfo.indexOf(deleteItem), 1)
                        obj.del();
                        layer.close(index);
                    });
                }
            });
        }

        //根据条码获取数据
        function search(local) {
            var code = $("#barCode").val();
            $.ajax({
                type: "post",
                data: {
                    barCode: code
                },
                success: function (data) {
                    var resultData = JSON.parse(data);
                    if (resultData.Status) {
                        if (local) {
                            //只更新工序信息数据
                            allTableData.workOrderInfo = resultData.Result.workOrderInfo;
                        } else {
                            //更新所有数据
                            allTableData = resultData.Result;
                            layer.msg(resultData.Message);
                        }
                        reloadTable();
                    }
                    else {
                        layer.msg(resultData.Message, { icon: 2 });
                        allTableData = defaultData;
                        reloadTable();
                    }
                },
                error: function (err) {
                    console.log(err);
                    layer.msg(err.statusText, { icon: 2 });
                }
            });
        }

        //工序开工
        function start() {
            var stationCode = form.val('example').stationCode;
            if (stationCode == null || stationCode == "") {
                layer.msg("请选择工位信息", { icon: 2 });
                return;
            }
            var optionTime = $("#optionTime").val();
            if (optionTime == null || optionTime == "") {
                layer.msg("时间不能为空!", { icon: 2 });
                return;
            }
            $.ajax({
                type: "post",
                url: "UpdateProcess",
                data: {
                    headKeys: allTableData.headKeys,
                    bodyKeys: allTableData.bodyKeys,
                    id: allTableData.id,
                    actualStartTime: optionTime,
                    Material: allTableData.materInfo,
                    Equipment: allTableData.equipmentInfo,
                    stationCode: stationCode
                },
                success: function (data) {
                    var resultData = JSON.parse(data);
                    console.log(resultData);
                    if (resultData.Status) {
                        search(true);
                        workReport("当前工序已开工,");
                    }
                    else {
                        layer.msg(resultData.Message, { icon: 2 });
                    }
                },
                error: function (err) {
                    console.log(err);
                    layer.msg(err.statusText, { icon: 2 });
                }
            })
        }

        //工序完工
        function complete() {
            var optionTime = $("#optionTime").val();
            if (optionTime == null || optionTime == "") {
                layer.msg("时间不能为空!", { icon: 2 });
                return;
            }
            $.ajax({
                type: "post",
                url: "WorkComplete",
                data: {
                    headKeys: allTableData.headKeys,
                    id: allTableData.id,
                    actualEndTime: optionTime
                },
                success: function (data) {
                    var resultData = JSON.parse(data);
                    if (resultData.Status) {
                        search(true);
                        workReport("当前工序已完工,");
                    }
                    else {
                        layer.msg(resultData.Message, { icon: 2 });
                    }
                },
                error: function (err) {
                    console.log(err);
                    layer.msg(err.statusText, { icon: 2 });
                }
            })
        }

        //重置
        function resert() {
            $("#barCode").val("");
            allTableData = defaultData;
            reloadTable();
            $("#stationCode").empty();
            layui.form.render("select");
        }

        //条码录入回车事件
        function enter(event) {
            if (event.keyCode == 13) {
                search(false);
            }
        }

        //报工
        function workReport(title) {
            if (title == undefined) {
                title = `ID:“${allTableData.id}”,`;
            }
            layer.confirm(`${title}是否需要报工?`, { icon: 3, title: '提示' }, function (idnex) {
                $.ajax({
                    type: "post",
                    url: `WorkReport`,
                    data: { headKey: allTableData.headKeys },
                    success: function (res) {
                        var resData = JSON.parse(res);
                        if (resData.Status == false) {
                            layer.msg(resData.Message);
                        }
                        else {
                            layer.confirm(resData.Message, { icon: 3, title: '提示' }, function (index) {
                                $.ajax({
                                    type: "post",
                                    url: `WorkReport`,
                                    data: { headKey: allTableData.headKeys, IsValdate: false },
                                    success: function (result) {
                                        resData = JSON.parse(result);
                                        if (resData.Status == false) {
                                            layer.msg(resData.Message, { icon: 2 });
                                        }
                                        else {
                                            search(true);
                                            layer.msg(resData.Message, { icon: 1 });
                                        }
                                    },
                                    error: function (err) {
                                        console.log(err);
                                        layer.msg(err.statusText, { icon: 2 });
                                    }
                                });
                                layer.close(index);
                            });
                        }
                    },
                    error: function (err) {
                        console.log(err);
                        layer.msg(err.statusText, { icon: 2 });
                    }
                });
            });
        }
    </script>
}