<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>修改</title>
    <link rel="stylesheet" th:href="@{/lib/layui/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all">
    <link rel="stylesheet" th:href="@{/lib/font-awesome-4.7.0/css/font-awesome.min.css}" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>
<body>
<form class="layui-form" action="" lay-filter="formDemo">
    <div class="layui-form layuimini-form" style="padding-bottom: 100px">
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label required" style="width: 90px">报账名称</label>
            <div class="layui-input-inline" style="width: 800px">
                <!--                <input type="hidden" id="id" name="id" class="layui-input" th:value="${reimbursement.id}">-->
                <input type="text" id="mc" name="mc" class="layui-input" value="${reimbursement.mc}" readonly>
            </div>
        </div>
        <div class="layui-form-item layui-inline" style="width: 100%">
            <input type="hidden" id="fysq" name="fysq" class="layui-input" th:value="${reimbursement.fysq}">
            <label class="layui-form-label" style="width: 90px">费用类别</label>
            <div class="layui-input-inline" style="width: 380px">
                <input type="hidden" id="fylb" name="fylb" class="layui-input" th:value="${reimbursement.fylb}">
                <input type="text" id="fylbmc" name="fylbmc" class="layui-input" th:value="${reimbursement.fylbmc}"
                       readonly>
            </div>
            <label class="layui-form-label" style="width: 80px">申请金额(元)</label>
            <div class="layui-input-inline" style="width: 300px">
                <input type="number" id="sqje" name="sqje" class="layui-input" th:value="${reimbursement.sqje}"
                       readonly>
            </div>
        </div>

        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label required" style="width: 90px">报账金额(元)</label>
            <div class="layui-input-inline" style="width: 380px">
                <input type="text" id="bzje" name="bzje" class="layui-input" autocomplete="off"
                       th:value="${reimbursement.bzje}">
            </div>
            <label class="layui-form-label required" style="width: 80px">税率(%)</label>
            <input type="hidden" id="slval" name="slval" class="layui-input" th:value="${reimbursement.sl}">
            <div class="layui-input-inline" style="width: 300px">
                <select id="sl" name="sl" lay-filter="sl">
                    <option th:each="item:${dictList}" th:text="${item.name}" th:value="${item.name}"></option>
                </select>
            </div>
        </div>
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label required" style="width: 100px; margin-left: -10px">不含税金额(元)</label>
            <div class="layui-input-inline" style="width: 380px">
                <input type="number" id="bhsje" name="bhsje" class="layui-input" th:value="${reimbursement.bhsje}"
                       readonly>
            </div>
            <label class="layui-form-label required" style="width: 80px">税费(元)</label>
            <div class="layui-input-inline" style="width: 300px">
                <input type="number" id="sf" name="sf" class="layui-input" th:value="${reimbursement.sf}" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 110px">实际花费差旅费</label>
        </div>
        <div class="layui-form-item" style="margin-left: 20px; margin-right: 20px; margin-top: -30px">
            <div class="layuimini-container">
                <div class="layui-btn-group" style="margin-bottom: -8px">
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subAdd"><i
                            class="layui-icon"></i>新建
                    </button>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subEdit"><i
                            class="layui-icon"></i>编辑
                    </button>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subView"><i
                            class="layui-icon">&#xe63c;</i>查看
                    </button>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subDelete"><i
                            class="layui-icon"></i>删除
                    </button>
                </div>
                <table class="layui-hide" id="currentTableId1" name="currentTableId1" lay-filter="currentTableFilter1"
                       style="padding-top: 0px;margin-top: 0px"></table>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 70px">报销凭证</label>
        </div>
        <div class="layui-form-item" style="margin-left: 20px; margin-right: 20px; margin-top: -30px">
            <div class="layuimini-container">
                <input type="hidden" id="bxpz" name="bxpz" class="layui-input" th:value="${reimbursement.bxpz}">
                <div class="layui-btn-group" style="margin-bottom: -8px">
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm upload" lay-filter="upLoad"
                            lay-data="{fileType:'reimburse'}"><i class="layui-icon"></i>上传
                    </button>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="deleteFile"><i
                            class="layui-icon"></i>删除
                    </button>
                </div>
                <table class="layui-hide" id="currentTableId2" name="currentTableId2" lay-filter="currentTableFilter2"
                       style="padding-top: 0px;margin-top: 0px"></table>
            </div>
        </div>

        <!-- 右侧悬浮按钮 -->
        <div class="right-bottom-btn">
            <button type="button" class="layui-btn" lay-filter="viewFysqBtn">
                <i class="layui-icon layui-icon-ok"></i>查看费用申请
            </button>
            <button type="button" class="layui-btn" lay-submit lay-filter="saveBtn">
                <i class="layui-icon layui-icon-ok"></i>保存
            </button>
            <button type="button" class="layui-btn" lay-filter="cancleBtn">
                <i class="layui-icon layui-icon-close"></i>取消
            </button>
        </div>
    </div>
</form>

<script th:src="@{/lib/jquery-3.4.1/jquery-3.4.1.min.js}" charset="utf-8"></script>
<script th:src="@{/lib/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{/lib/coco-message/coco-message.js}" charset="utf-8"></script>
<script th:src="@{/lib/xm-select-v1.2.2/xm-select.js}" charset="utf-8"></script>
<script th:src="@{/js/lay-config.js}" charset="utf-8"></script>

<script type="text/javascript" th:inline="javascript">
    AjaxUtil.ctx = /*[[@{/}]]*/'';
    var travelExpense = [];//差旅费
    var updateflag = 0;//更新标志

    layui.use(['form', 'table', 'treeTable', 'layCascader', 'upload'], function () {
        var form = layui.form,
            table = layui.table,
            layer = layui.layer,
            upload = layui.upload;
        var fysq = $("#fysq").val();

        //下拉框回显
        function set_select(id, value) {
            let obj = $("#" + id)
            obj.find("option:contains('" + value + "')").attr("selected", true)
            obj.parent().find(".layui-select-title").find("input").val(value)
        }

        if ($("#slval").val() != null && $("slval").val() != "")
            set_select('sl', $("#slval").val());

        //监听税率
        form.on('select(sl)', function (data) {
            console.log(data.value);
            if ($("#bzje").val() != '') {
                var bzje = parseFloat($("#bzje").val());
                var sl = parseInt(data.value, 10);
                var bhsje = (bzje * 100) / (100 + sl);
                $("#bhsje").val(bhsje.toFixed(2));
                $("#sf").val((bzje - bhsje).toFixed(2));
            }
        });

        $("#bzje").on("input", function (e) {
            //获取input输入的值
            var bzje = parseFloat(e.delegateTarget.value);
            if (isNaN(bzje)) {
                bzje = 0;
            } else {
                var sqje = parseFloat($("#sqje").val());
                if (bzje > sqje)
                    Message.error("报账金额与申请金额不符!", 1500);
                else {
                    var sl = parseInt($("#sl").val(), 10);
                    var bhsje = (bzje * 100) / (100 + sl);
                    $("#bhsje").val(bhsje.toFixed(2));
                    $("#sf").val((bzje - bhsje).toFixed(2));
                }
            }
        });

        // 用于存放表格数据
        var dataExpense = new Array();
        $.ajax({
            url: AjaxUtil.ctx + 'staActualexpenses/list/' + fysq,
            type: "post",
            async: false,
            dataType: "json",
            success: function (result) {
                dataExpense = result.data.rows;
            }
        });
        //差旅费
        var currTable1 = table.render({
            elem: '#currentTableId1',
            data: dataExpense,
            cols: [
                [
                    {type: "checkbox", align: 'center'},
                    {field: 'xh', title: '序号', width: '8%'},
                    {field: 'ccrxm', title: '出差人', width: '10%'},
                    {field: 'ccdd', title: '出差地点', width: '18%'},
                    {field: 'qsrq', title: '起始日期', width: '13%'},
                    {field: 'jsrq', title: '结束日期(含)', width: '14%'},
                    {field: 'ccts', title: '出差天数', width: '11%'},
                    {field: 'zj', title: '总计(元)', width: '10%'},
                    {field: 'rpj', title: '日平均(元)'}
                ]
            ],
            autoSort: true,
            initSort: {
                field: 'xh', //排序字段
                type: 'asc' //排序方式:desc 降序,asc 升序
            }
        });
        // 监听新建按钮（差旅费）
        $("button[lay-filter='subAdd']").click(function () {
            layer.open({
                title: '新建差旅费',
                type: 2,
                maxmin: true,
                shade: 0.2,
                area: [layerwidth + 'px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'staTravelexpenses/forAdd',
                end: function (index) {
                    if (updateflag == 1) {
                        updateflag = 0;

                        //刷新表格
                        dataExpense.push(travelExpense);
                        currTable1.reload();
                    }
                }
            });
        });
        // 监听编辑按钮（差旅费）
        $("button[lay-filter='subEdit']").click(function () {
            if (dataExpense.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId1')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要编辑的差旅费！", 1500);
            } else if (data.length > 1) {
                Message.warning("请选择一条记录进行编辑操作！", 1500);
            } else {
                travelExpense = {
                    "xh": data[0].xh,
                    "ccr": data[0].ccr,
                    "ccrxm": data[0].ccrxm,
                    "ccdd": data[0].ccdd,
                    "ccts": data[0].ccts,
                    "qsrq": data[0].qsrq,
                    "jsrq": data[0].jsrq,
                    "jtf": data[0].jtf,
                    "zsf": data[0].zsf,
                    "cb": data[0].cb,
                    "zj": data[0].zj,
                    "rpj": data[0].rpj
                };
                layer.open({
                    title: '编辑差旅费',
                    type: 2,
                    maxmin: true,
                    shade: 0.2,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'staTravelexpenses/forUpdate',
                    end: function (index) {
                        if (updateflag == 1) {
                            updateflag = 0;

                            for (var i = 0; i < dataExpense.length; i++) {
                                var item = dataExpense[i];
                                if (item.LAY_CHECKED) {//条件：选中
                                    dataExpense[i] = travelExpense;
                                    break;
                                }
                            }
                            //刷新表格
                            currTable1.reload();
                        }
                    }
                });
            }
        });
        // 监听查看按钮（差旅费）
        $("button[lay-filter='subView']").click(function () {
            if (dataExpense.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId1')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要浏览的差旅费！", 1500);
            } else if (data.length > 1) {
                Message.warning("请选择一条记录进行浏览！", 1500);
            } else {
                travelExpense = {
                    "xh": data[0].xh,
                    "ccr": data[0].ccr,
                    "ccrxm": data[0].ccrxm,
                    "ccdd": data[0].ccdd,
                    "ccts": data[0].ccts,
                    "qsrq": data[0].qsrq,
                    "jsrq": data[0].jsrq,
                    "jtf": data[0].jtf,
                    "zsf": data[0].zsf,
                    "cb": data[0].cb,
                    "zj": data[0].zj,
                    "rpj": data[0].rpj
                };
                var index = layer.open({
                    title: '浏览差旅费',
                    type: 2,
                    maxmin: true,
                    shade: 0.2,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'staTravelexpenses/forView',
                    end: function () {
                        layer.close(index);
                    }
                });
            }
        });
        // 监听删除按钮（差旅费）
        $("button[lay-filter='subDelete']").click(function () {
            if (dataExpense.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId1')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要删除的差旅费！", 1000);
                return;
            }
            for (var i = 0; i < dataExpense.length; i++) {
                var item = dataExpense[i];
                if (item.LAY_CHECKED) {//条件：选中
                    dataExpense.splice(i, 1);//移除后后造成数组下标索引发生变化，所以下面需要i--
                    i--;
                }
            }
            //刷新表格
            currTable1.reload();
        });
        //双击（差旅费）
        table.on('rowDouble(currentTableFilter1)', function (obj) {
            var data = obj.data;
            travelExpense = {
                "xh": data.xh,
                "ccr": data.ccr,
                "ccrxm": data.ccrxm,
                "ccdd": data.ccdd,
                "ccts": data.ccts,
                "qsrq": data.qsrq,
                "jsrq": data.jsrq,
                "jtf": data.jtf,
                "zsf": data.zsf,
                "cb": data.cb,
                "zj": data.zj,
                "rpj": data.rpj
            };
            var index = layer.open({
                title: '浏览差旅费',
                type: 2,
                maxmin: true,
                shade: 0.2,
                area: [layerwidth + 'px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'staTravelexpenses/forView',
                end: function () {
                    layer.close(index);
                }
            });
        });

        // 用于存放表格数据
        var dataBxpz = new Array();
        if ([[${reimbursement.bxpz}]] != null && [[${reimbursement.bxpz}]] != "") {
            dataBxpz = eval('(' + [[${reimbursement.bxpz}]] + ')');
        }
        //报销凭证
        var currTable2 = table.render({
            elem: '#currentTableId2',
            data: dataBxpz,
            cols: [
                [
                    {type: "checkbox", align: 'center'},
                    {type: 'numbers', align: 'center'},
                    {field: 'wjm', title: '文件名', width: '30%'},
                    {field: 'scrq', title: '上传日期', width: '15%', align: 'center'},
                    {field: 'sm', title: '说明', edit: 'text'}
                ]
            ],
            autoSort: false,
            limits: [10, 15, 20, 25, 50, 100],
            limit: 10,
            page: false,
            skin: 'grid',
            done: function (res, curr, count) { // done为数据渲染完的回调
            }
        });

        //文件上传
        upload.render({
            elem: '.upload' //绑定元素
            , url: AjaxUtil.ctx + 'fileupload/upload'
            , methd: 'post'
            , accept: 'file'
            , data: {}
            , done: function (res) {
                if (0 === res.code) {
                    var curData = {
                        "wjm": res.data.fileName,
                        "scrq": res.data.fileDate,
                        "Url": res.data.fileUrl
                    };
                    console.log(res.data);
                    dataBxpz.push(curData);
                    currTable2.reload();
                } else
                    layer.alert("上传文件出现错误！");

            }
            , error: function () {
                layer.alert("上传文件出现错误！");
            }
            , before: function (res) {
                let fileType = this.fileType;
                this.data.fileType = fileType;
            }
        });
        $("button[lay-filter='deleteFile']").click(function () {
            if (dataBxpz.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId2')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要删除的报销凭证！", 1000);
                return;
            }
            for (var i = 0; i < dataBxpz.length; i++) {
                var item = dataBxpz[i];
                if (item.LAY_CHECKED) {//条件：选中
                    dataBxpz.splice(i, 1);//移除后后造成数组下标索引发生变化，所以下面需要i--
                    i--;
                }
            }
            //刷新表格
            currTable2.reload();
        });
        //双击（报销凭证）
        table.on('rowDouble(currentTableFilter2)', function (obj) {
            window.open(obj.data.Url);
        });

        // 监听查看费用申请按钮
        $("button[lay-filter='viewFysqBtn']").click(function () {
            var index = parent.layer.open({
                title: '查看费用申请',
                type: 2,
                shade: 0.3,
                // maxmin: true,
                shadeClose: true,
                area: ['1030px', '700px'],
                content: AjaxUtil.ctx + 'staBudgetapproval/forApplyView/' + fysq,
                end: function () {
                    layer.close(index);
                }
            });
        });

        // 监听确认按钮
        form.on('submit(saveBtn)', function (data) {
            var sqje = parseFloat($("#sqje").val());
            var bzje = parseFloat($("#bzje").val());
            if (bzje != sqje) {
                Message.error("报账金额与申请金额不符!", 1500);
                return false;
            }

            //报销凭证
            var dataWB = [];
            for (const item of dataBxpz) {
                var dfWb = {
                    "id": item.id,
                    "wjm": item.wjm,
                    "Url": item.Url,
                    "scrq": item.scrq,
                    "sm": item.sm
                };
                dataWB.push(dfWb);
            }
            $("#bxpz").val(JSON.stringify(dataWB));
            data.field.bxpz = JSON.stringify(dataWB);

            var index = layer.load(0, {shade: 0.1});
            AjaxUtil.post({
                url: AjaxUtil.ctx + "staReimbursement/doUpdate",
                data: data.field,
                success: function (res) {
                    layer.close(index);
                    if (res.code === 0) {
                        Message.success(1500, res.message, function () {
                            parent.setUpdateFlag();

                            //差旅费
                            var travleExpenses = [];
                            for (const item of dataExpense) {
                                var expense = {
                                    "zb": fysq,
                                    "xh": item.xh,
                                    "ccr": item.ccr,
                                    "ccdd": item.ccdd,
                                    "qsrq": item.qsrq,
                                    "jtf": item.jtf,
                                    "zsf": item.zsf,
                                    "cb": item.cb,
                                    "jsrq": item.jsrq,
                                    "ccts": item.ccts,
                                    "zj": item.zj,
                                    "rpj": item.rpj
                                };
                                travleExpenses.push(expense);
                            }
                            //保存差旅费
                            AjaxUtil.post({
                                url: AjaxUtil.ctx + "staActualexpenses/batchInsert/" + fysq,
                                contentType: "application/json",
                                data: JSON.stringify(travleExpenses),
                                success: function (res) {
                                    if (res.code === 0) {
                                        // Message.success(1500, res.message, function () {
                                        //
                                        // });
                                    } else {
                                        // Message.error(res.message, 1000);
                                    }
                                },
                                error: function (error) {
                                }
                            });

                            var iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                        });
                    } else {
                        Message.error(res.message, 1000);
                    }
                },
                error: function (error) {
                    Message.error(error.message, 1000)
                }
            });
        });

        // 监听取消按钮
        $("button[lay-filter='cancleBtn']").click(function () {
            var iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
        });
    });

    function setTravelExpense(expense) {
        travelExpense = expense;
    }

    function getTravelExpense() {
        return travelExpense;
    }

    function setUpdateFlag() {
        updateflag = 1;
    }
</script>
</body>
</html>