<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改工资')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-salary-edit" th:object="${salary}">
            <h4 class="form-header h4">工资信息</h4>
            <input name="salaryId" th:field="*{salaryId}" type="hidden">
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">用户：</label>
                    <div class="col-sm-8">
                        <select class="form-control" name="userId" th:with="users=${@user.getUserList()}" readonly="readonly">
                            <option value="">请选择</option>
                            <option th:each="user : ${users}" th:text="${user.userName}" th:value="${user.userId}" th:field="*{userId}"></option>
                        </select>

                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">薪水分类：</label>
                    <div class="col-sm-8">
                        <select name="salaryType" id="salaryType" class="form-control" th:with="type=${@dict.getType('subject_type')}">
                            <option value="">请选择</option>
                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{salaryType}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">工资日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="salaryDate" th:value="${#dates.format(salary.salaryDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">工资总金额：</label>
                    <div class="col-sm-8">
                        <input name="sumAmount" th:field="*{sumAmount}" class="form-control" type="text">
                    </div>
                </div>
            </div>
            <h4 class="form-header h4">工资明细信息</h4>
            <div class="row">
                <div class="col-sm-12">
<!--                    <button type="button" class="btn btn-white btn-sm" onclick="addRow()"><i class="fa fa-plus"> 增加</i></button>-->
<!--                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delRow()"><i class="fa fa-minus"> 删除</i></button>-->
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <script th:inline="javascript">
        var baseFlagDatas = [[${@dict.getType('sys_yes_no')}]];
        var prefix = ctx + "business/salary";
        $("#form-salary-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/edit", $('#form-salary-edit').serialize());
            }
        }

        $("input[name='salaryDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $(function() {
            var options = {
                data: [[${salary.salaryDetailList}]],
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                {
                    field: 'index',
                    align: 'center',
                    title: "序号",
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push($.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index)));
                        actions.push($.common.sprintf("<input class='form-control' type='hidden' name='salaryDetailList[%s].baseFlag' value='%s'>", index, row.baseFlag));
                        actions.push($.common.sprintf("<input class='form-control' type='hidden' name='salaryDetailList[%s].salarySubjectId' value='%s'>", index, row.salarySubjectId));
                        return actions.join('') + $.table.serialNumber(index);
                    }
                },
                {
                    field: 'subjectName',
                    align: 'center',
                    title: '科目名',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='salaryDetailList[%s].subjectName' value='%s'>", index, value);
                        return html;
                    }
                },
                {
                    field: 'baseFlag',
                    title: '基准标记',
                    visible: false,
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' type='text' name='salaryDetailList[%s].baseFlag' value='%s'>", index, value)
                        return html;
                    }
                },
                {
                    field: 'baseFlagName',
                    title: '基准标记',
                    formatter: function(value, row, index) {
                        return $.table.selectDictLabel(baseFlagDatas, row.baseFlag);
                    }
                },
                {
                    field: 'percent',
                    title: '占比',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' readonly='readonly' type='text' name='salaryDetailList[%s].percent' value='%s'>", index, value);
                        return html;
                    }
                },
                {
                    field: 'formula',
                    title: '公式',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control' readonly='readonly' type='text' name='salaryDetailList[%s].formula' value='%s'>", index, value);
                        return html;
                    }
                },
                {
                    field: 'amount',
                    align: 'center',
                    title: '金额',
                    formatter: function(value, row, index) {
                        var html = $.common.sprintf("<input class='form-control detail-amount' type='text' name='salaryDetailList[%s].amount' value='%s'>", index, value);
                        return html;
                    }
                }
                // {
                //     title: '操作',
                //     align: 'center',
                //     formatter: function(value, row, index) {
                //         var value = $.common.isNotEmpty(row.index) ? row.index : $.table.serialNumber(index);
                //         return '<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="sub.delRowByIndex(\'' + value + '\')"><i class="fa fa-remove"></i>删除</a>';
                //     }
                // }
                ]
            };
            $.table.init(options);
        });

        // function addRow() {
        //     var count = $("#" + table.options.id).bootstrapTable('getData').length;
        //     var row = {
        //         index: $.table.serialNumber(count),
        //         salarySubjectId: "",
        //         subjectName: "",
        //         amount: "",
        //         delFlag: "",
        //         createBy: "",
        //         createTime: "",
        //         updateBy: "",
        //         updateTime: "",
        //     }
        //     sub.addRow(row);
        // }

        $(document).on("blur", "input[type='text'].detail-amount", function () {
            let name = $(this).attr("name");
            const index = name.split('[')[1].split(']')[0];

            $("#" + table.options.id).bootstrapTable('updateRow', {
                index: index, // 你想修改哪行，0表示第一行
                row: {
                    index: $.table.serialNumber(index + 1),
                    salarySubjectId: $("#" + table.options.id).bootstrapTable('getData')[index].salarySubjectId,
                    subjectName: $("#" + table.options.id).bootstrapTable('getData')[index].subjectName,
                    baseFlag: $("#" + table.options.id).bootstrapTable('getData')[index].baseFlag,
                    percent: $("#" + table.options.id).bootstrapTable('getData')[index].percent,
                    formula: $("#" + table.options.id).bootstrapTable('getData')[index].formula,
                    amount: $(this).val(),
                }
            })

            let allData = $("#" + table.options.id).bootstrapTable('getData');
            let changeRow = allData[index];
            let sumAmt = 0;

            if (changeRow.baseFlag === "Y") {
                let baseValue = parseFloat(changeRow.amount);
                sumAmt = sumAmt + baseValue;
                for (let i = 0; i < allData.length; i++) {
                    if (i != index) {
                        let curRow = allData[i];
                        let curAmt = 0;
                        if ($.common.isEmpty(curRow.formula)) {
                            // 使用percent计算
                            let curPercent = parseFloat(curRow.percent) || 0;
                            curAmt = (baseValue * curPercent / 100).toFixed(2);
                        } else {
                            // 使用formula计算
                            curAmt = eval(curRow.formula).toFixed(2);
                        }
                        sumAmt = sumAmt + parseFloat(curAmt);
                        $("#" + table.options.id).bootstrapTable('updateRow', {
                            index: i, // 你想修改哪行，0表示第一行
                            row: {
                                index: $.table.serialNumber(i+1),
                                salarySubjectId: curRow.salarySubjectId,
                                subjectName: curRow.subjectName,
                                baseFlag: curRow.baseFlag,
                                percent: curRow.percent,
                                formula: curRow.formula,
                                amount: curAmt,
                            }
                        })
                    }
                }
            }
            $("#sumAmount").val(sumAmt);
        });

        // $("#salaryType").blur(function(){
        //
        //     $("#" + table.options.id).bootstrapTable('removeAll');
        //
        //     $.ajax({
        //         url: ctx + "business/subject/getlist/" + $("#salaryType").val(),
        //         type: "get",
        //         processData: false,
        //         contentType: false,
        //         beforeSend: function () {
        //             $.modal.loading("正在处理中，请稍后...");
        //             $.modal.disable();
        //         },
        //         success: function (result) {
        //             if (result.code === web_status.SUCCESS) {
        //                 console.log(result.rows);
        //                 if (result.rows.length > 0) {
        //                     for (var i = 0; i < result.rows.length; i++) {
        //                         var count = $("#" + table.options.id).bootstrapTable('getData').length;
        //
        //                         var row = {
        //                             index: $.table.serialNumber(count),
        //                             salarySubjectId: result.rows[i].salarySubjectId,
        //                             subjectName: result.rows[i].subjectName,
        //                             baseFlag: result.rows[i].baseFlag,
        //                             percent: result.rows[i].percent,
        //                             formula: result.rows[i].formula,
        //                             amount: "0",
        //                         }
        //                         console.log(row);
        //                         sub.addRow(row);
        //                     }
        //                 }
        //
        //                 // $.modal.alertSuccess(result.msg)
        //             } else if (result.code === web_status.WARNING) {
        //                 $.modal.alertWarning(result.msg)
        //             } else {
        //                 $.modal.alertError(result.msg);
        //             }
        //             $.modal.closeLoading();
        //             $.modal.enable();
        //         }
        //     })
        //
        // });

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