<%--
  Created by IntelliJ IDEA.
  User: yangzi
  Date: 2023/2/21
  Time: 10:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/webpage/include/taglib.jsp" %>
<div id="toolbar">
    <a class="btn btn-primary btn-sm pull-left" onclick="addDetail('#detail_table')" title="新增"><i class="fa fa-plus"></i> 新增</a>
</div>
<table id="detail_table" data-toolbar="#toolbar"></table>
<script>
    console.log(${fns:toJson(goods)})
    
    var selector = "#detail_table";
    function initTable(){
        var data = ${fns:toJson(goods.goodsInfoList)};
        if(data.length){
            data = data.map(function(item){
                item.delFlag = 0;
                return item;
            })
        }

        $(selector).bootstrapTable({
            data: data,
            columns:[
                {
                    field: 'no',
                    title: '序号',
                    align: 'center',
                    width: 60,
                    formatter: function (value, row, index){
                        var tpl = $("#hideTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, "");
                        var html = Mustache.render(tpl, {
                            idx: index,
                            row: row
                        })

                        return html + '<span>'+(index+1)+'</span>'
                    }
                },
                // {
                //     field: 'type.name',
                //     title: '品名',
                //     formatter: function (value,row,index){
                //         return Mustache.render($("#nameTpl").html(),{
                //             row: row,
                //             idx: index
                //         })
                //     }
                // },
                {
                    field: 'type.name',
                    title: '品名',
                    formatter: function (value,row,index){
                        return Mustache.render($("#typeNameTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'type.code',
                    title: '代码',
                    formatter: function (value,row,index){
                        return Mustache.render($("#typeCodeTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'amount',
                    title: '单价',
                    formatter: function (value,row,index){
                        return Mustache.render($("#amountTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'type.unit',
                    title: '单位',
                    formatter: function (value,row,index){
                        return Mustache.render($("#unitTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'model',
                    title: '型号',
                    formatter: function (value,row,index){
                        return Mustache.render($("#modelTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'num',
                    title: '数量',
                    formatter: function (value,row,index){
                        return Mustache.render($("#numTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'infoSum',
                    title: '总价',
                    formatter: function (value,row,index){
                        return Mustache.render($("#infoSumTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: 'remarks',
                    title: '备注',
                    formatter: function (value,row,index){
                        return Mustache.render($("#remarksTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g, ""),{
                            row: row,
                            idx: index
                        })
                    }
                },
                {
                    field: '',
                    title: '操作',
                    formatter: function (value,row,index){
                        if (row.qrCode && row.qrCode.state !== '0') {
                            return '';
                        }
                        var text = row.delFlag == 1 ? '撤销删除' : '删除';
                        var result = ["<a href='javascript:void(0);' onclick=\"removeRow(" + index + ", '" + row.id + "',  '" + row.delFlag + "')\">"+text+"</a>" ]
                        return result.join('');
                    }
                }
            ]
        })
    }
    /**
     * 获取所有明细数据
     * @returns {*|jQuery}
     */
    function getTableData() {
        return $(selector).bootstrapTable('getData');
    }
    function addDetail(selector){
        var row = {
            id: '',
            delFlag: 0,
            name: '',
            type: {
                id: '',
                name: '',
                unit: '',
                code: ''
            },
            model: '',
            num: null,
            amount: null,
            remarks: '',
            infoSum: ''
        }

        $(selector).bootstrapTable('append', [
            row
        ])
    }
    function removeRow(index, rowId, rowDelFlag){
        if(rowId){
            var delFlag = rowDelFlag == 1 ? 0 : 1
            updateRow(index, {
                delFlag: delFlag
            })
        }else{
            $(selector).bootstrapTable("remove", {
                field: '$index',
                values: [index]
            })
        }
        setSumPrice();
    }
    function updateRow(index, row){
        $(selector).bootstrapTable('updateRow', {
            index: index,
            row: row
        })
    }
    function onInputChange(rowIndex, elem , field){
        var obj = {};
        obj[field] = $(elem).val();

        // 校验数量与单价
        if(field === 'num' &&  obj[field]){

            // 正则表达式验证可以带小数点的数字
            var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
            // 不是数字
            if(!reg.test(obj[field])){
                jp.warning("必须是数字");
                $(elem).val('')
                return
            }

            if (Number(obj[field]) <= 0) {
                jp.warning("数量不能小于等于0");
                $(elem).val('');
                return;
            }

            if ($("#goodsInfoList" + rowIndex + "_amount").val()) {
                obj.infoSum = new Big($("#goodsInfoList" + rowIndex + "_amount").val()).times(obj[field]).toNumber();
            }
        }

        if(field === 'amount' &&  obj[field]) {
            // 正则表达式验证可以带小数点的数字
            // 不是数字
            if(!/^(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(obj[field])) {
                jp.warning("输入正确的金额");
                $(elem).val('')
                return
            }

            if ($("#goodsInfoList" + rowIndex + "_num").val()) {
                obj.infoSum = new Big($("#goodsInfoList" + rowIndex + "_num").val()).times(obj[field]).toNumber();
            }
        }

        updateRow(rowIndex, obj);

        if((field === 'num' && obj[field]) || (field === 'amount' &&  obj[field])) {
            setSumPrice();
        }
    }

    function setSumPrice(){
       var data = $(selector).bootstrapTable('getData');
       var sum = data.reduce(function (sum, current){
           if(current.delFlag != 1 && current.amount && current.num){
               var total = new Big(current.amount).times(current.num).toNumber();
               return new Big(sum).plus(total);
           }
           return new Big(sum);
       },0)
       $("#sum").val(sum);
    }

    function onSelectType(nodes, rowIndex){
        if(Array.isArray(nodes) && nodes.length === 1){
            var node = nodes[0];
            var obj = {
                type: {
                    id: node.id,
                    name: node.text,
                    code: node.original.code,
                    unit: node.original.unit
                },
                amount: node.original.amount,
            };
            if ($("#goodsInfoList" + rowIndex + "_num").val()) {
                obj.infoSum = new Big($("#goodsInfoList" + rowIndex + "_num").val()).times(obj.amount).toNumber();
            }
            updateRow(rowIndex, obj)
        }
    }

    function delType (idName, id) {
        var name = $("#" + idName + 'Id').attr('name');
        var str1 = name.split('.')[0];
        var startNum = str1.indexOf('[') + 1;
        var str2 = str1.substring(startNum);
        var endNum = str2.length - 1;
        var num = str2.substring(0, endNum);
        var key = "#goodsInfoList" + num;
        $(key + "_typeCode").val('');
        $(key + "_amount").val('');
        $(key + "_unit").val('');
        $(key + "_infoSum").val('');
        var obj = {
            type: {
                id: '',
                name: '',
                code: '',
                unit: ''
            },
            amount: '',
            infoSum: ''
        };
        updateRow(num, obj);
        setSumPrice();
    }
</script>

<script id="hideTpl" type="text/html">
    <input id="goodsInfoList{{idx}}_id" name="goodsInfoList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
    <input id="goodsInfoList{{idx}}_delFlag" name="goodsInfoList[{{idx}}].delFlag" type="hidden" value="{{row.delFlag}}"/>
</script>

<script id="nameTpl" type="text/html">
        <input id="goodsInfoList{{idx}}_name" name="goodsInfoList[{{idx}}].name" type="text" value="{{row.name}}" onchange="onInputChange('{{idx}}', this, 'name')"   class="form-control required"/>
</script>

<script id="typeNameTpl" type="text/html">//<!--
    <sys:treeselect id="goodsInfoList{{idx}}_typeName" name="goodsInfoList[{{idx}}].type.id" value="{{row.type.id}}" labelName="goodsInfoList[{{idx}}].type.name" labelValue="{{row.type.name}}"
							title="品名代码" url="/warehouse/materialtype/materialType/treeData" notAllowSelectParent="true" cssClass="form-control required" allowClear="true" allowSearch="true" callback="onSelectType" delCallback="delType" />//-->
</script>
<script id="typeCodeTpl" type="text/html">
    <input id="goodsInfoList{{idx}}_typeCode" name="goodsInfoList[{{idx}}].type.code" type="text" value="{{row.type.code}}" readonly class="form-control required"/>
</script>
<script id="amountTpl" type="text/html">
    <input id="goodsInfoList{{idx}}_amount" name="goodsInfoList[{{idx}}].amount" type="text" value="{{row.amount}}" readonly onchange="onInputChange('{{idx}}', this, 'amount')"  class="form-control required"/>
</script>
<script id="unitTpl" type="text/html">
    <input id="goodsInfoList{{idx}}_unit" name="goodsInfoList[{{idx}}].type.unit" type="text" value="{{row.type.unit}}" readonly onchange="onInputChange('{{idx}}', this, 'type.unit')"  class="form-control required"/>
</script>
<script id="modelTpl" type="text/html">
    <input id="goodsInfoList{{idx}}_model" name="goodsInfoList[{{idx}}].model" type="text" value="{{row.model}}" onchange="onInputChange('{{idx}}', this, 'model')"    class="form-control required"/>
</script>

<script id="numTpl" type="text/html">
    <input id="goodsInfoList{{idx}}_num" name="goodsInfoList[{{idx}}].num" type="text" value="{{row.num}}" onchange="onInputChange('{{idx}}', this, 'num')"  class="form-control required"/>
</script>

<script id="infoSumTpl" type="text/html">
    <input id="goodsInfoList{{idx}}_infoSum" name="goodsInfoList[{{idx}}].infoSum" type="text" value="{{row.infoSum}}" readonly onchange="onInputChange('{{idx}}', this, 'infoSum')"  class="form-control required"/>
</script>
<script id="remarksTpl" type="text/html">
    <textarea id="goodsInfoList{{idx}}_remarks" name="goodsInfoList[{{idx}}].remarks" rows="2"  onchange="onInputChange('{{idx}}', this, 'remarks')"  class="form-control ">{{row.remarks}}</textarea>
</script>
