<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<!DOCTYPE HTML>
<html>
<head>
    <meta name="decorator" content="base"/>
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="${ctxPlugin}/static/css/reset.css">
    <link rel="stylesheet" href="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/dist/viewer.css" media="all">
    <style>html {background-color: #fff;padding-bottom: 50px;}td, th {text-align: center !important;} .xm-body .scroll-body{max-height: 110px !important;}</style>
</head>

<body>
<div class="layui-form">
    <div class="layui-card">
        <div class="layui-col-xs12 mb-10 pr-30">
            <div class="layui-inline layui-col-xs6">
                <label class="layui-form-label w-130"><i class="red">*</i>产品编号：</label>
                <div class="layui-input-block">
                    <select name="projectId" id="projectId" lay-verify="required" >
                        <option value="">请选择</option>
                        <c:forEach items="${project}" var="ject">
                            <option value="${ject.columns.id}" ${apply.columns.project_id eq ject.columns.id? 'selected': ''} title="${ject.columns.name}">${ject.columns.code}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
            <div class="layui-inline layui-col-xs6">
                <label class="layui-form-label w-130"><i class="red">*</i>入库仓库：</label>
                <div class="layui-input-block">
                    <select name="inWarehouseId" lay-verify="required">
                        <option value="">请选择</option>
                        <c:forEach items="${wares}" var="warehouse">
                            <option value="${warehouse.columns.id}"
                                ${apply.columns.in_warehouse_id eq warehouse.columns.id? 'selected': ''}
                                ${wares.size() == 1 ? 'selected': ''}>${warehouse.columns.name}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 mb-10 pr-30">
            <div class="layui-inline layui-col-md3 layui-col-sm3">
                <label class="layui-form-label w-130"><i class="red">*</i>省：</label>
                <div class="layui-input-block">
                    <select name="province" id="province" lay-verify="required" lay-filter="province" lay-search >
                        <option value=""></option>
                        <c:forEach items="${province}" var="pro">
                            <option value="${pro.columns.ProvinceName}" <c:if test="${apply.columns.province eq pro.columns.ProvinceName}"> selected</c:if> title="${pro.columns.ProvinceID }">${pro.columns.ProvinceName}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
            <div class="layui-inline layui-col-md3 layui-col-sm3">
                <label class="layui-form-label w-130"><i class="red">*</i>市：</label>
                <div class="layui-input-block">
                    <select name="city" id="city" lay-verify="required" lay-filter="city" lay-search >
                        <option value="">请选择</option>
                        <c:forEach items="${faccitys}" var="city">
                            <option value="${city.columns.CityName}" <c:if test="${apply.columns.city eq city.columns.CityName}">selected</c:if> title="${city.columns.CityID}">${city.columns.CityName}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
            <div class="layui-inline layui-col-md3 layui-col-sm3">
                <label class="layui-form-label w-130"><i class="red">*</i>区县：</label>
                <div class="layui-input-block">
                    <select name="area" id="area" lay-verify="required" lay-search >
                        <option value="">请选择</option>
                        <c:forEach items="${areas}" var="area">
                            <option value="${area.columns.DistrictName}" <c:if test="${apply.columns.area eq area.columns.DistrictName}">selected</c:if> title="${area.columns.DistrictID}">${area.columns.DistrictName}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label w-130">仓库地址：</label>
                <div class="layui-input-block ">
                    <input type="text" autocomplete="off" id="address" name="address" class="layui-input " value="${apply.columns.address}">
                </div>
            </div>

        </div>
        <div class="layui-col-xs12 mb-10 pr-30">
            <div class="layui-form-item">
                <label class="layui-form-label w-130">订单备注：</label>
                <div class="layui-input-block ">
                    <textarea name="remark" class="layui-textarea">${apply.columns.remark}</textarea>
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 mb-10 pr-30">
            <div class="layui-inline layui-col-xs6">
                <label class="layui-form-label">代码：</label>
                <div class="layui-input-block">
                    <div id="code"></div>
                </div>
            </div>
            <div class="layui-inline layui-col-xs6">
                <label class="layui-form-label">描述：</label>
                <div class="layui-input-block">
                    <div id="desc"></div>
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 mb-10 pr-30 pl-30">
            <table class="layui-table">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>物料/BOM代码</th>
                    <th>物料/BOM类型</th>
                    <th>物料组</th>
                    <th>物料/BOM描述</th>
                    <th>申请数量</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="materialBody">
                    <c:forEach items="${applyDetails}" var="detail" varStatus="vs">
                        <tr>
                            <td data-id="${detail.columns.target_id}" data-type="${detail.columns.type}">${vs.count}</td>
                            <td>${detail.columns.code}</td>
                            <td>${detail.columns.materialTypeName}</td>
                            <td>${detail.columns.materialGroupName}</td>
                            <td>${detail.columns.remarks}</td>
                            <td><input type="text" class="layui-input" value="${detail.columns.amount}" name="amount" lay-verify="required"/></td>
                            <td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
    <div class="operate-footer">
        <c:if test="${empty id}">
            <input type="button" lay-submit lay-filter="save" id="save" class="layui-btn " value="保存">
        </c:if>
        <c:if test="${not empty id}">
            <input type="button" lay-submit lay-filter="save" id="save" class="layui-btn " value="重新提交">
        </c:if>
        <input type="button" value="取消" class="layui-btn layui-btn-primary " onclick="closeDiv();">
    </div>
</div>

<script src="${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/layui/layui.js"></script>
<script src="${ctxPlugin}/lib/xm-select.js"></script>
<script type="text/javascript">
    //初始数据
    var $form;
    var form;
    var $;
    var imgs = '';
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    layui.config({
        base: '${ctxPlugin}/lib/layuiAdmin/dist/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['form', 'layedit', 'laydate', 'jquery', 'layer'], function () {
        $ = layui.jquery;
        form = layui.form;
        $form = $('form');

        var codeXm = xmSelect.render({
            el: '#code',
            name: 'code',
            radio: true,
            tips: '请输入查询',
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod: function (val, cb, show) {
                searchVal(val, cb, {
                    code: val
                }, 'code');
            },
            on: function (data) {
                if (data.isAdd && data.arr.length > 0) {
                    appendTr(data);
                }
            }
        });

        var descXm = xmSelect.render({
            el: '#desc',
            name: 'desc',
            radio: true,
            tips: '请输入查询',
            clickClose: true,
            filterable: true,
            remoteSearch: true,
            remoteMethod: function (val, cb, show) {
                searchVal(val, cb, {
                    desc: val
                }, 'remarks');
            },
            on: function (data) {
                if (data.isAdd && data.arr.length > 0) {
                    appendTr(data);
                }
            }
        });

        function appendTr(data) {
            var d = data.arr[0].origin;
            var html = '<tr>'
                + '<td data-id="' + d.id + '" data-type="' + d.type + '"></td>'
                + '<td>' + d.code + '</td>'
                + '<td>' + d.material_type + '</td>'
                + '<td>' + d.material_group + '</td>'
                + '<td>' + d.remarks + '</td>'
                + '<td><input type="text" class="layui-input" name="amount" lay-verify="required"/></td>'
                + '<td><button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="del(this)">删除</button></td>'
                + '</tr>';
            var $trs = $('#materialBody>tr');
            var exist = false;
            for (var i = 0; i < $trs.length; i++) {
                var $tr = $trs.eq(i);
                var id = $tr.find('td:first').data('id');
                if (id === d.id) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                $('#materialBody').append(html);
            } else {
                layer.msg('物料/BOM已存在');
            }
            appendSort();
            data.arr.length = 0;
            codeXm.reset();
            descXm.reset();
        }

        window.del = function(obj){
            $(obj).closest('tr').remove();
        }

        function searchVal(val, cb, searchData, filed) {
            if (!isBlank(val)) {
                $.ajax({
                    type: 'post',
                    url: '${ctx}/material/apply/findCanApplyMaterials',
                    data: searchData,
                    async: false,
                    dataType: 'json',
                    success: function (d) {
                        var arr = [];
                        for (var i = 0; i < d.length; i++) {
                            var data = {};
                            data.name = d[i][filed];
                            data.value = d[i].id;
                            data.origin = d[i];
                            arr.push(data);
                        }
                        cb(arr);
                    }
                });
            } else {
                cb([]);
            }
        }

        function appendSort() {
            $('#materialBody>tr').each(function (i) {
                $(this).find('td:first').html(i + 1);
            });
        }

        form.on('select(inWarehouseId)',function(data){
            var value = $(data.elem).find("option:selected").val();
            if(isBlank(value)){
                return
            }
            var that_ = $(this);

            $.ajax({
                url:"${ctx}/material/apply/findWarehouseById",
                type:"POST",
                data:{
                    id:value
                }
                ,success:function (result) {

                    if(result.code =="200"){
                        var _data = result.data;
                        $("#person_in_charge").val(_data.personInCharge);
                        $("#mobile").val(_data.mobile);
                        $("#province").val(_data.province);
                        provinceOrder(_data.province,_data.city);
                        /*   $("#city").val(_data.city);
                           $("#area").val(_data.area);*/
                        cityOrder(_data.city,_data.area);
                        $("#address").val(_data.address);
                    }
                }
            })

        })



        form.on('submit(save)', function (data) {
            var $trs = $('#materialBody>tr');
            if ($trs.length === 0) {
                layer.msg('请添加物料/BOM');
                return;
            }
            var arr = [];
            for (var i = 0; i < $trs.length; i++) {
                var obj = {};
                var $tr = $trs.eq(i);
                var $fisrtTd = $tr.find('td:first');
                obj.targetId = $fisrtTd.data('id');
                obj.type = $fisrtTd.data('type');
                obj.amount = $tr.find('input[name=amount]').val();
                if (!/^\d+(\.\d{1,2})?$/.test(obj.amount)) {
                    layer.msg('第' + (i + 1) + '行申请数量格式不正确');
                    return;
                }
                arr.push(obj);
            }
            var inWarehouseId = data.field.inWarehouseId;
            $.ajax({
                url: '${ctx}/material/apply/saveApplyOrder',
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify({
                    id: '${id}',
                    inWarehouseId: inWarehouseId,
                    remark: data.field.remark,
                    projectId: data.field.projectId,
                    province: data.field.province,
                    city: data.field.city,
                    area: data.field.area,
                    address: data.field.address,
                    personInCharge:'${apply.columns.person_in_charge}',
                    mobile:'${apply.columns.mobile}',
                    details: arr
                }),
                dataType: 'JSON',
                success: function (res) {
                    if (res.code === "200") {
                        parent.layer.msg("保存成功", {time: 1000});
                        closeDiv();
                        parent.table.reload('test');
                    } else if (res.code === '501') {
                        layer.msg(res.errMsg);
                    } else {
                        layer.msg("保存失败", {time: 1000});
                    }
                },
                error: function (data) {
                }
            });
        });

        form.on('select(province)', function(data){
            var province = $(data.elem).find("option:selected").val();
            provinceOrder(province);
        });
        form.on('select(city)', function(data){
            var city = $(data.elem).find("option:selected").val();
            cityOrder(city);

        });
        function provinceOrder(province,_city){
            $("#city").empty();
            $("#area").empty();
            if(isBlank(province)){
                $("#city").append("<option value=''>请选择</option>");
                return "";
            }
            $.ajax({
                type:"POST",
                url:"${ctx}/main/redirect/getCitysByProName",
                data:{
                    province:province
                },
                success:function(result){
                    if(result =="205"){
                        layer.msg("暂无数据!")
                        return
                    }
                    var html =" <option value=''>请选择</option>";
                    for(var i=0;i<result.length;i++){
                        var city = result[i];
                        if(city.columns.CityName==_city){
                            html =html+ '<option value="'+city.columns.CityName+'" selected title="'+city.columns.CityID+'">'+city.columns.CityName+'</option>';
                        }else{
                            html =html+ '<option value="'+city.columns.CityName+'" <c:if test=""> selected</c:if> title="'+city.columns.CityID+'">'+city.columns.CityName+'</option>';
                        }
                    }
                    console.log(_city)
                    if(!isBlank(_city)){
                        $("#city").val(_city)
                    }
                    $("#city").append(html);
                    form.render('select');
                }
            });

        }

        function cityOrder(city,arean){
            $("#area").empty()
            if(isBlank(city)){
                $("#area").append("<option value=''>请选择</option>");
                return "";
            }
            $.ajax({
                type:"POST",
                url:"${ctx}/main/redirect/getAreaByCityName",
                data:{
                    city:city
                },
                success:function(result){
                    if(result =="205"){
                        layer.msg("暂无数据!")
                        return
                    }
                    var html ="<option value=''>请选择</option>";
                    for(var i=0;i<result.length;i++){
                        var area = result[i];
                        html =html+ '<option value="'+area.columns.DistrictName+'" >'+area.columns.DistrictName+'</option>';
                    }
                    $("#area").append(html);
                    if(!isBlank(arean)){
                        $("#area").val(arean)
                    }

                    form.render('select');
                }
            });

        }

    })

    function closeDiv() {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index);
    }

    function isBlank(val) {
        if (val == null || val == '' || val == undefined) {
            return true;
        }
        return false;
    }


</script>
</body>
</html>
