<!DOCTYPE html>
<!--[if IE 8]>
<html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]>
<html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html>
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
    <base href="#springUrl('/assets/adminlte/')"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>工作台</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.5 -->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="plugins/font-awesome/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="plugins/ionicons/css/ionicons.min.css">

    <!-- DataTables -->
    <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">

    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
         folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
    <!-- iCheck -->
    <link rel="stylesheet" href="plugins/iCheck/flat/blue.css">
    <!-- Date Picker -->
    <link rel="stylesheet" href="plugins/datepicker/datepicker3.css">
    <!-- Daterange picker -->
    <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker-bs3.css">
    <!-- bootstrap wysihtml5 - text editor -->
    <link rel="stylesheet" href="plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
    <!--validate css-->
    <link rel="stylesheet" href="plugins/jquery-validation/css/validate.css">

    <!--fileinput css-->
    <link rel="stylesheet" href="plugins/bootstrap-fileinput/bootstrap-fileinput.css">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
        td {
            padding: 5px;
        }
        .title-pan{
            font-weight: bold;padding-top:10px;border-top: #cccccc dashed 1px;
            margin-top:5px;
            clear: both;
        }
        .radio{
          margin-top:0px !important;
          margin-left:5px;
          float: left;
        }
        .borderRed{
            border: red 1px solid;
        }
        .grantTable textarea{
            width: 95%;
        }
    </style>
</head>
<!-- END HEAD -->
<body class="hold-transition skin-blue sidebar-mini">

<div class="wrapper">
    <div class="content-wrapper" style="margin-left:0;">

        <section class="content-header">
            <h1>
                促销品申请单管理
                <small>促销品申请单</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i>首页</a></li>
                <li><a class="active">促销品申请单</a></li>
            </ol>
        </section>


        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-xs-12">
                    <!-- general form elements disabled -->
                    <div class="box box-primary">
                        <form role="form" id="myForm">
                            <div class="box-body">
                                <input name="form-id" style="display: none;" value="$!{data.id}">
                                <p class="title-pan">基本信息：</p>
                                <table id="form-table" style="width: 100%;">
                                    <tr>
                                        <!--<td style="display: none;">所属单据</td>-->
                                        <!--<td><input style="display: none;" type="text" class="form-control"-->
                                        <!--name="typeformName" readonly value="$!{data.typeformName}"></td>-->
                                        <td>申请人</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-name" readonly value="$!{data.name}"></td>
                                        <td>职能部门</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-departmentName" readonly value="$!{data.dname}">
                                        </td>
                                        <td>申请用途</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-departmentName" readonly value="$!{data.uname}">
                                        </td>

                                    </tr>
                                    <tr>
                                        <td>申请单号</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-number" readonly value="$!{data.number}"></td>
                                        <td>申请时间</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-appTime" readonly
                                                   value="$!date.format('yyyy-MM-dd HH:mm',$!data.createTime)"></td>
                                        <td>审批人</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-appTime" readonly
                                                   value="$!{data.aname}"></td>


                                    </tr>
                                    <tr>
                                        <td>审批状态</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-status" readonly value="$!{data.statusName}"></td>
                                        <td>发放状态</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-issuingStateName" readonly
                                                   value="$!{data.issuingStateName}"></td>
                                        <td>申请人ORG</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-appTime" readonly
                                                   value="$!{data.org}"></td>

                                    </tr>
                                    <tr>
                                        <td>成本中心</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-costCenter" readonly value="$!{data.costCenter}"></td>
                                        <td>收货信息</td>
                                        <td><input type="text" class="form-control"
                                                   name="form-address" readonly
                                                   value="$!{data.address}"></td>
                                        <td class="showManager">是否有退库</td>
                                        <td class="showManager">
                                            #if($data.isCancel == '0')
                                            #set($isCancelName ='否')
                                            #else
                                            #set($isCancelName ='是')
                                            #end
                                            <input type="text" class="form-control"
                                                   name="form-isCancel" readonly
                                                   value="${isCancelName}">
                                        </td>
                                    </tr>
                                </table>
                                <p class="title-pan">发货渠道：</p>
                                <div id="grantSourceName"></div>
                                <div class="form-group" id="grantSource">
                                    <div class="radio">
                                        <label>
                                            <input type="radio" name="optionsRadios" id="optionsRadios1" value="0"
                                                   checked
                                            >
                                            仅供应商
                                        </label>
                                    </div>
                                    <div class="radio">
                                        <label>
                                            <input type="radio" name="optionsRadios" id="optionsRadios2" value="1"
                                            >
                                            仅管理员
                                        </label>
                                    </div>
                                    <div class="radio">
                                        <label>
                                            <input type="radio" name="optionsRadios" id="optionsRadios3" value="2"
                                            >
                                            管理员+供应商
                                        </label>
                                    </div>
                                </div>
                                <p class="title-pan" >促销品明细：</p>
                                <table id="appitems" style="border: #d2d6de 1px solid;width: 100%;">
                                    <thead style="    background: #F0F0F0;border-bottom: #d2d6de solid 1px;font-weight: bold;">
                                    <td width="20%">物品名称</td>
                                    <td width="20%">物品规格</td>
                                    <td width="5%">申请数量</td>
                                    <td width="5%">单价</td>
                                    <td width="5%" class="showManager">管理员剩余库存</td>
                                    <td width="5%">供应商剩余货量</td>
                                    <td width="10%">实际发货数量</td>
                                    <td width="15%" class="managerGrantCount" style="display: none;">管理员发货数量</td>
                                    <td width="15%" class="disGrantCount">供应商发货数量</td>
                                    </thead>
                                    <tbody>
                                    #foreach( $item in $items )
                                    <tr style='border-bottom: #d2d6de solid 1px;'
                                        data-price='${item.price}'
                                        data-id='${item.id}'
                                        data-appitem='${item.appitem}'
                                        data-num="${item.appCount}"
                                        data-itemname="${item.itemname}"
                                        data-authenticStock="${item.authenticStock}"
                                        data-disStock = "${item.disStock}"
                                    >
                                        <td>${item.itemname}</td>
                                        <td>${item.specifications}</td>
                                        <td>${item.appCount}</td>
                                        <td>${item.price}</td>
                                        <td class="showManager">${item.authenticStock}</td>
                                        <td>${item.disStock}</td>
<!--                                        #set($fund=${item.authenticStock} + ${item.disStock})-->
                                        <td><input  class='form-control sumGrantCount' value="$!{item.realityGrantCount}" onblur="fun.countBlur(this,1)"  type="number"  min="0"/></td>
                                        <td style="display: none;" class="managerGrantCount">
                                            <input class='form-control managerGrantCountInput' value="$!{item.managerGrantCount}" onblur="fun.countBlur(this,2)" type="number" min="0"/>
                                        </td>
                                        <td class="disGrantCount">
                                            <input class='form-control disGrantCountInput' value="$!{item.disGrantCount}" readonly="true"/>
                                        </td>
                                    </tr>
                                    #end
                                    </tbody>
                                </table>
                                <p class="title-pan" >管理员录入备注：</p>
                                <textarea placeholder="录入发货量备注" id="managerSubmitRemarks"
                                          style="width: 50%;margin-top: 15px;">$!{data.managerSubmitRemarks}</textarea>
                            </div>
                            <div class="box-footer">
                                #if($type == 0)
                                <a href="javascript:void(0)"  onclick="grantSubmit()" class="btn btn-primary">提交</a>
                                #end
                                <a href="#springUrl('/a/typeAppForm/list')" class="btn btn-default">取消</a>
                            </div>
                        </form>
                        <!-- /.box-body -->
                    </div><!-- /.box -->


                </div><!-- /.col -->
            </div><!-- /.row -->
        </section><!-- /.content -->
    </div><!-- /.content-wrapper -->


    <!-- Add the sidebar's background. This div must be placed
         immediately after the control sidebar -->
    <div class="control-sidebar-bg"></div>
</div><!-- ./wrapper -->

<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- DataTables -->
<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables/extensions/i18n/lanauage_ch.js"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js"></script>
<!-- SlimScroll -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="plugins/fastclick/fastclick.min.js"></script>
<!--fileinput js-->
<script src="plugins/bootstrap-fileinput/bootstrap-fileinput.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/app.min.js"></script>
<script src="plugins/bootstrap-maxlength/bootstrap-maxlength.min.js" type="text/javascript"></script>
<script src="plugins/security/sha256.js" type="text/javascript"></script>
<script src="plugins/jquery-validation/js/jquery.validate.min.js"></script>
<script src="js/jquery.form.min.js"></script>
<script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="plugins/ueditor-min-1.4.3/lang/zh-cn/zh-cn.js"></script>
<script src="common/js/cfapp.js"></script>
<script type="text/javascript" charset="utf-8" src="plugins/jquery-validation/js/localization/messages_zh.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<script>
    var csrfheader = {name: '_csrf_header', value: '${_csrf.headerName}'};
    var csrftoken = {name: '_csrf', value: '${_csrf.token}'};
</script>
<script>
    var items = eval(${data.items});

    var grantSource = "0"; //默认仅供应商
    $().ready(function () {
        Cfapp.init();
        recdTypeAdd.init();





        /**
         * 控制选择发货渠道时，联动效果
         */
        $("input[name='optionsRadios']").change(function(){
            grantSource = $(this).val();
            $(".sumGrantCount").val('');
            $(".managerGrantCountInput").val('');
            $(".disGrantCountInput").val('');
            if(grantSource=='1'){//仅管理员,不需要显示供应商发货数量
                $(".disGrantCount").hide();//隐藏供应商发货量列
                $(".managerGrantCount").show();//显示管理员发货量列
                $(".managerGrantCount input").attr("readonly","readonly");
            }else if(grantSource=='0'){//仅供应商
                $(".managerGrantCount").hide();//隐藏管理员发货量列
                $(".disGrantCount").show();//显示供应商发货列
                $(".disGrantCount input").attr("readonly","readonly");
            }else{//管理员+供应商
                $(".managerGrantCount").show();
                $(".disGrantCount").show();
                $(".managerGrantCount input").removeAttr("readonly");
            }
        })
    });

    var fun = {
        /**
         * 控制发货量失去焦点时，计算各渠道发货量
         * @param obj
         * @param type
         */
        countBlur:function(obj,type){
            $("input").removeClass("borderRed");
            var val = $(obj).val();
            var tdObject =  $(obj).parent();
            if(!StringUtils.isNotBlank(val)){
                return false;
            }
            //行对象
            var trObject = tdObject.parent();
            //管理员库存数量
            var authenticStock =  trObject.attr("data-authenticStock");
            //供应商供应商货量
            var disStock = trObject.attr("data-disStock");
            //计算总库存量
            var sumStock = 0;
            switch (grantSource) {
                case "1": //仅管理员
                    tdObject.siblings("td").find(".managerGrantCountInput").val(val);
                    break;
                case "0": //仅供应商
                    tdObject.siblings("td").find(".disGrantCountInput").val(val);
                    break;
                case "2": //管理员+供应商,计算得出供应商发货量
                    sumStock = parseInt(authenticStock)+parseInt(disStock);
                    if(type==1){//总计失去焦点回调
                        var managerGrantCountValue =  tdObject.siblings("td").find(".managerGrantCountInput").val();//输入的管理员发货量
                        if(StringUtils.isNotBlank(managerGrantCountValue)){
                            var disGrantCount = parseInt(val)-parseInt(managerGrantCountValue);
                            tdObject.siblings("td").find(".disGrantCountInput").val(disGrantCount);
                        }else{
                            return false;
                        }
                    }else{ //管理员数量失去焦点回调
                        //获取总计发放数量是否已经填写，没填写，无法计算，return false
                        var sumGrantCount =  tdObject.siblings("td").find(".sumGrantCount").val();
                        if(StringUtils.isNotBlank(sumGrantCount)){
                            var disGrantCount = parseInt(sumGrantCount)-parseInt(val)
                            tdObject.siblings("td").find(".disGrantCountInput").val(disGrantCount);
                        }else{
                            return false;
                        }
                    }
                    break;
            }
        },
        customAlert:function(content){
            Cfapp.alert({
                message: content,
                btntext: "确定",
                success: function () {
                }
            });
        },addBorderClass:function(obj){
            obj.addClass("borderRed");
        }
    }

    var StringUtils = {
        isNotBlank:function(value){
            if(value && value!=null && value!='' && value!='undefined'){
                return true;
            }
            return false;
        }
    }




    function grantSubmit() {
        var obj = $("#appitems tbody tr");
        var formData = {
            _csrf_header: csrfheader.value,
            _csrf: csrftoken.value,
            id: $("input[name='form-id']").val(),
            managerSubmitRemarks: $("#managerSubmitRemarks").val(),
            grantSource:$("input[name='optionsRadios']:checked").val()
        }

        const ILLEGAL_SUM_GRANT_COUNT_STR = "存在不合法的实际发放数量，请检查数据!";
        const ILLEGAL_MANAGER_GRANT_COUNT_STR = "存在不合法的管理员发放数量，请检查数据!";
        const ILLEGAL_DIS_GRANT_COUNT_STR = "存在不合法的供应商发放数量，请检查数据";

        var array = [];

        outer:for (let i = 0; i < obj.length; i++) {
            for (let k = 0; k < items.length; k++) {
                if (items[k].id == $(obj[i]).attr("data-appitem")) {
                    let o =items[k];
                    let tdObj = $(obj[i]);
                    let stock = tdObj.attr("data-authenticStock");//管理员库存
                    let disStock = tdObj.attr("data-disStock"); //供应商库存
                    let appCount = tdObj.attr("data-num");
                    let sumStock = parseInt(stock)+parseInt(disStock);
                    o.grantCount = tdObj.find(".sumGrantCount").val();//发放数量
                    o.realityGrantCount = tdObj.find(".sumGrantCount").val();//实际发放数量
                    let managerGrantCount=null;
                    let disGrantCount=null;
                    switch (grantSource) {
                        case "1": //仅管理员
                            if(!StringUtils.isNotBlank(o.grantCount) || parseInt(o.grantCount)>parseInt(stock) || parseInt(o.grantCount)>parseInt(appCount)){
                                fun.customAlert(ILLEGAL_SUM_GRANT_COUNT_STR);
                                fun.addBorderClass(tdObj.find(".sumGrantCount"));
                                return false;
                            }
                            managerGrantCount=tdObj.find(".managerGrantCountInput").val();
                            break;
                        case "0": //仅供应商
                            if(!StringUtils.isNotBlank(o.grantCount) || parseInt(o.grantCount)>parseInt(disStock)){
                                fun.customAlert(ILLEGAL_SUM_GRANT_COUNT_STR);
                                fun.addBorderClass(tdObj.find(".sumGrantCount"));
                                return false;
                            }
                            disGrantCount=tdObj.find(".disGrantCountInput").val();
                            break;
                        case "2": //管理员+供应商,计算得出供应商发货量
                            sumStock = parseInt(stock)+parseInt(disStock);//总库存
                            managerGrantCount=tdObj.find(".managerGrantCountInput").val();//管理员发货量
                            disGrantCount=tdObj.find(".disGrantCountInput").val();//供应商发货量
                            if(!StringUtils.isNotBlank(o.grantCount)){
                                fun.customAlert(ILLEGAL_SUM_GRANT_COUNT_STR);
                                fun.addBorderClass(tdObj.find(".sumGrantCount"));
                                return false;
                            }
                            if(!StringUtils.isNotBlank(managerGrantCount)){
                                fun.customAlert(ILLEGAL_MANAGER_GRANT_COUNT_STR);
                                fun.addBorderClass(tdObj.find(".managerGrantCountInput"));
                                return false;
                            }
                            if(parseInt(o.grantCount) > sumStock){
                                fun.customAlert(ILLEGAL_SUM_GRANT_COUNT_STR);
                                fun.addBorderClass(tdObj.find(".sumGrantCount"));
                                return false;
                            }
                            if(parseInt(managerGrantCount) > parseInt(stock)){
                                fun.customAlert(ILLEGAL_MANAGER_GRANT_COUNT_STR);
                                fun.addBorderClass(tdObj.find(".managerGrantCountInput"));
                                return false;
                            }
                            if(parseInt(disGrantCount) > parseInt(disGrantCount)){
                                fun.customAlert(ILLEGAL_DIS_GRANT_COUNT_STR);
                                fun.addBorderClass(tdObj.find(".disGrantCountInput"));
                                return false;
                            }

                            break;
                    }
                    o.managerGrantCount = managerGrantCount;//管理员发货数量
                    o.disGrantCount = disGrantCount;//供应商发货数量
                    if(!o.managerGrantCount || o.managerGrantCount ==null || o.managerGrantCount==""){
                        o.managerGrantCount=0;
                    }
                    if(!o.disGrantCount || o.disGrantCount ==null || o.disGrantCount==""){
                        o.disGrantCount=0;
                    }
                    o.grantId = $(obj[i]).attr("data-id");
                    formData["grantitems[" + i + "].id"] = $(obj[i]).attr("data-id");
                    formData["grantitems[" + i + "].price"] = o.price;
                    formData["grantitems[" + i + "].grantCount"] = o.grantCount;
                    formData["grantitems[" + i + "].appitem"] = o.id;
                    formData["grantitems[" + i + "].realityGrantCount"] = o.realityGrantCount;
                    formData["grantitems[" + i + "].managerGrantCount"] = managerGrantCount;
                    formData["grantitems[" + i + "].disGrantCount"] = disGrantCount;
                    array.push(o);
                }
            }
        }
        formData.items = JSON.stringify(array);
        $.ajax({
            type: "post",
            url: "#springUrl('/a/typeAppForm/submitGrantCount')",
            data: formData,
            dataType: "json",
            success: function (data) {
                if (data.errorNo == 0) {
                    Cfapp.alert({
                        message: "发放成功",
                        btntext: "确定",
                        success: function () {
                            location.href = "#springUrl('/a/typeAppForm/list')";
                        }
                    });
                }
            },
            error: function () {
            }
        })
    }


    var recdTypeAdd = function () {
        var initForm = function () {
            var initFormCtrl = function () {
                bindEvent();
            };
            var bindEvent = function () {

                $("#myForm").validate({
                    rules: {},
                    messages: {},
                    submitHandler: function (form) {
                        $("#save").attr("disabled", true);
                        $.getJSON("#springUrl('/a/typeAppForm/formData')", $("#myForm").serialize(), function (returnobj) {
                            $("#save").attr("disabled", false);
                            if (returnobj.errorNo == 2) {  //保存成功
                                Cfapp.confirm({
                                    message: "添加成功",
                                    btnoktext: "继续添加",
                                    btncanceltext: "关闭",
                                    success: function () {
                                        location.href = "#springUrl('/a/typeAppForm/form')";
                                    },
                                    cancel: function () {
                                        location.href = "#springUrl('/a/typeAppForm/list')";
                                    }
                                });
                            } else if (returnobj.errorNo == 0) {  //修改成功
                                Cfapp.alert({
                                    message: "更新成功",
                                    btntext: "确定",
                                    success: function () {
                                        location.href = "#springUrl('/a/typeAppForm/list')";
                                    }
                                });
                            } else {
                                Cfapp.alert({
                                    message: "创建失败",
                                    btntext: "确定",
                                    success: function () {
                                        location.href = "#springUrl('/a/typeAppForm/list')";
                                    }
                                });
                            }
                        });
                    }
                })
            }
            initFormCtrl();
        }
        return {

            //main function to initiate the module
            init: function () {
                initForm();
            }

        };
    }();
</script>
</body>
<!-- END BODY -->
</html>
