<!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-tab layui-tab-card">
        <ul class="layui-tab-title">
            <li class="layui-this">常规</li>
            <li>预算</li>
        </ul>
        <div class="layui-tab-content">
            <!--常规开始-->
            <div class="layui-tab-item layui-show" style="min-height: 550px; margin-bottom: 5px">
                <form class="layui-form" action="" lay-filter="formDemo">
                    <div class="layui-form layuimini-form">
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">名称</label>
                            <div class="layui-input-inline" style="width: 70%">
                                <input type="hidden" id="id" name="id" class="layui-input"
                                       th:value="${annualbudget.id}">
                                <input type="text" id="mc" name="mc" class="layui-input" th:value="${annualbudget.mc}">
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">任务书</label>
                            <div class="layui-input-inline" style="width: 70%">
                                <input type="hidden" id="rws" name="rws" class="layui-input"
                                       th:value="${annualbudget.rws}">
                                <input type="text" id="rwsmc" name="rwsmc" class="layui-input"
                                       th:value="${annualbudget.rwsmc}" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">项目执行期</label>
                            <div class="layui-input-inline" style="width: 70%">
                                <input type="hidden" name="qs" id="qs" class="layui-input" th:value="${qs}">
                                <input type="hidden" name="wc" id="wc" class="layui-input" th:value="${wc}">
                                <input type="text" id="xmzxq" name="xmzxq" class="layui-input"
                                       th:value="${annualbudget.xmzxq}" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label required" style="width: 10%">年份</label>
                            <div class="layui-input-inline" style="width: 70%">
                                <input type="text" id="nf" name="nf" class="layui-input" th:value="${annualbudget.nf}">
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">说明</label>
                            <div class="layui-input-inline" style="width: 70%">
                                <textarea id="sm" name="sm" class="layui-textarea" style="width: 100%;height: 150px"
                                          th:text="${annualbudget.sm}"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">申请人</label>
                            <div class="layui-input-inline" style="width: 25%">
                                <input type="text" name="sqrxm" class="layui-input" th:value="${annualbudget.sqrxm}"
                                       readonly>
                            </div>
                            <label class="layui-form-label" style="width: 10%">申请时间</label>
                            <div class="layui-input-inline" style="width: 30%">
                                <input type="text" id="sqsj" name="sqsj" class="layui-input"
                                       th:value="${annualbudget.sqsj}">
                                <tip>日期格式：yyyy-MM-dd</tip>
                            </div>
                        </div>
                        <!--                        <div class="layui-form-item layui-inline" style="width: 100%">-->
                        <!--                            <label class="layui-form-label" style="width: 70px">审批状态</label>-->
                        <!--                            <div class="layui-input-inline" style="width: 855px">-->
                        <!--                                <input type="text" id="spzt" name="spzt" class="layui-input" value="未提交" readonly>-->
                        <!--                            </div>-->
                        <!--                        </div>-->
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">可研报告</label>
                            <div class="layui-input-inline" style="width: 70%">
                                <input type="text" id="xmmc" name="xmmc" class="layui-input"
                                       th:value="${annualbudget.xmmc}" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">ERP编号</label>
                            <div class="layui-input-inline" style="width: 25%">
                                <input type="text" id="erpbh" name="erpbh" class="layui-input"
                                       th:value="${annualbudget.erpbh}" readonly>
                            </div>
                            <label class="layui-form-label" style="width: 10%">项目类型</label>
                            <div class="layui-input-inline" style="width: 30%">
                                <input type="text" id="xmlxmc" name="xmlxmc" class="layui-input"
                                       th:value="${annualbudget.xmlxmc}" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 10%">电科院负责人</label>
                            <div class="layui-input-inline" style="width: 25%">
                                <input type="text" id="xmfzrxm" name="xmfzrxm" class="layui-input"
                                       th:value="${annualbudget.xmfzrxm}" readonly>
                            </div>
                            <label class="layui-form-label" style="width: 10%">所属部门</label>
                            <div class="layui-input-inline" style="width: 30%">
                                <input type="text" id="ssbmmc" name="ssbmmc" class="layui-input"
                                       th:value="${annualbudget.ssbmmc}" readonly>
                            </div>
                        </div>

                        <!-- 右侧悬浮按钮 -->
                        <div class="right-bottom-btn" style="margin-bottom: 5px">
                            <button class="layui-btn" lay-filter="viewRwsBtn">
                                <i class="layui-icon layui-icon-file"></i>查看任务书
                            </button>
                            <button class="layui-btn" lay-filter="cancleBtn">
                                <i class="layui-icon layui-icon-close"></i>取消
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            <!--常规结束-->
            <!--预算开始-->
            <div class="layui-tab-item" style="min-height: 550px; padding-left: 30px; padding-right: 30px">
                <form class="layui-form" action="" lay-filter="formDemo">
                    <div class="layui-form layuimini-form">
                        <div class="layui-form-item" style="margin-bottom: -10px">
                            <div class="layui-inline">
                                <label class="layui-form-label"
                                       style="width: fit-content; margin-bottom: -10px">单位：万元</label>
                                <label class="layui-form-label" style="width: 170px"></label>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label" style="width: 70px; margin-left: -10px">项目总预算</label>
                                <div class="layui-input-inline" style="width: 100px">
                                    <input type="text" id="rwsys" name="rwsys" class="layui-input" th:value="${rwsys}"
                                           readonly>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label" style="width: 60px; margin-left: -15px">年度经费</label>
                                <div class="layui-input-inline" style="width: 100px">
                                    <input type="text" id="ndczje" name="ndczje" class="layui-input"
                                           th:value="${ndczje}" readonly>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label" style="width: 70px; margin-left: -15px">年度备用金</label>
                                <div class="layui-input-inline" style="width: 100px; margin-right: -15px">
                                    <input type="number" id="ndbyj" name="ndbyj" class="layui-input" autocomplete="off">
                                </div>
                            </div>
                        </div>

                        <table class="layui-hide layui-table-view" id="currentTableId"
                               lay-filter="currentTableFilter"></table>

                        <!-- 右侧悬浮按钮 -->
                        <div class="right-bottom-btn" style="margin-bottom: 5px">
                            <button class="layui-btn" id="btn" lay-filter="viewRwsBtn">
                                <i class="layui-icon layui-icon-file"></i>查看任务书
                            </button>
                            <button type="button" class="layui-btn" lay-filter="saveBtnYs">
                                <i class="layui-icon layui-icon-ok"></i>申请修改
                            </button>
                            <button class="layui-btn" lay-filter="cancleBtn">
                                <i class="layui-icon layui-icon-close"></i>取消
                            </button>
                        </div>
                    </div>
                </form>
            </div>
            <!--预算结束-->
        </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-v2.6.3/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">
    //删除键盘的所有默认行为
    // document.onkeypress = function(e) {
    //     e.preventDefault();
    // }
    //全局禁用enter
    document.onkeydown = function (e) {
        var ev = (typeof event != 'undefined') ? window.event : e
        if (ev.keyCode == 13) {
            return false
        }
    }
    AjaxUtil.ctx = /*[[@{/}]]*/'';
    layui.use(['form', 'treeTable', 'layCascader', 'tableSelect', 'laydate'], function () {
        var form = layui.form,
            layer = layui.layer,
            treeTable = layui.treeTable,
            laydate = layui.laydate;
        var rwsId = $("#rws").val(),
            ysId = $("#id").val();
        var zjfy = 0;
        var xm = [[${annualbudget.mc}]];
        var xmid = [[${annualbudget.id}]];
        //用于审批列表重新提交
        var spList;
        var spListId;

        //申请时间
        laydate.render({
            elem: '#sqsj',
            value: new Date()
        });

        AjaxUtil.get({
            url: AjaxUtil.ctx + 'prjApproverecord/spLists/' + xmid + '/prj_AnnualBudgetRecord',
            success: function (res) {
                var a   = res.length -1;
                if (res[a] != null) {
                    spList = res[a].wc
                    spListId =res[a].id
                } else {
                    spList = -1;
                }
            }
        });


        // 监听查看任务书按钮
        $("button[lay-filter='viewRwsBtn']").click(function (e) {
            parent.layer.open({
                title: '查看项目任务书',
                type: 2,
                shade: 0.3,
                // maxmin: true,
                shadeClose: true,
                area: ['1100px', '750px'],
                content: AjaxUtil.ctx + 'prjProject/forView/' + rwsId,
                end: function (index) {
                    layer.close(index);
                }
            });
            // e.target.blur();//主动去除焦点
            return false;
        });

        //预算
        var dataBudget1 = new Array();
        $.ajax({
            url: AjaxUtil.ctx + 'prjAnnualbudgetdetail/list/' + ysId,
            type: "post",
            async: false,
            dataType: "json",
            success: function (result) {
                dataBudget1 = result;
                for (let i = 0; i < dataBudget1.length; i++) {
                    if (dataBudget1[i].fymc.indexOf('总计') > -1) {
                        zjfy = i;
                    }
                }
                $("#ndbyj").val(dataBudget1[zjfy].byj);
                $("#rwsys").val(dataBudget1[zjfy].xmzys);
            }
        });
        //查看年度预算（项目总预算）
        var dataBudget = new Array();
        $.ajax({
            url: AjaxUtil.ctx + 'prjAnnualbudget/list/' + ysId,
            type: "post",
            async: false,
            dataType: "json",
            success: function (result) {
                dataBudget = result;
            }
        });
        var insTb;

        function loadTreetable() {
            insTb = treeTable.render({
                elem: '#currentTableId',
                data: dataBudget,
                skin: 'grid',
                style: 'overflow:auto',
                tree: {
                    treeColIndex: 1,
                    treeSpid: "",   //最上级的父级id
                    iconIndex: 1,   // 折叠图标显示在第几列
                    isPidData: true,// 是否是id、pid形式数据
                    idName: 'bm',  // id字段名称
                    pidName: 'fj', // pid字段名称
                    arrowType: 'arrow2',
                    getIcon: 'ew-tree-icon-style2',
                    openName: 'bm'
                },
                treeDefaultClose: false,
                page: false,
                // toolbar: '#toolbarDemo',
                cols: [
                    [
                        {type: 'numbers', width: '3%'},
                        {field: 'fymc', width: '30%', title: '费用名称'},
                        {field: 'xmzys', width: '12%', title: '项目总预算', edit: 'number'},
                        {field: 'xtjsyzx', width: '15%', title: '系统计算已执行'},
                        {field: 'sjyzx', width: '12%', title: '实际已执行'},
                        {field: 'ysje', width: '10%', title: '预算金额'},
                        {field: 'xmz', width: '9%', title: '项目组', edit: 'number'},
                        {field: "byj", width: '9%', title: '备用金'}
                    ]
                ],
                edit: function (obj) {
                    if (obj.data.edit === false)
                        return false;
                    else
                        return true;
                }
            });
        }

        loadTreetable();

        //年度备用金
        $("#ndbyj").on("input", function (e) {
            //获取input输入的值
            var ndbyj = parseFloat(e.delegateTarget.value);
            if (isNaN(ndbyj))
                ndbyj = 0;
            dataBudget[zjfy].byj = ndbyj;

            var xmz = 0, byj = 0;
            if (dataBudget[zjfy].xmz != null) {
                xmz = parseFloat(dataBudget[zjfy].xmz);
                if (isNaN(xmz))
                    xmz = 0;
            }
            if (dataBudget[zjfy].byj != null) {
                byj = parseFloat(dataBudget[zjfy].byj);
                if (isNaN(byj))
                    byj = 0;
            }
            var ysje = xmz + byj;
            if (ysje == 0)
                dataBudget[zjfy].ysje = "";
            else
                dataBudget[zjfy].ysje = ysje;

            loadTreetable();
        });

        // 监听单元格编辑
        treeTable.on('edit(currentTableId)', function (obj) {
            var value = obj.value,
                item = obj.data,
                colName = obj.field;
            if (item.children == undefined) {
                //当前行预算
                setCurBudget(item.bm, colName, value);
                //父级预算
                setFjBudget(item.fj);
            }

            var xmz = 0, byj = 0;
            if (dataBudget[zjfy].xmz != null) {
                xmz = parseFloat(dataBudget[zjfy].xmz);
                if (isNaN(xmz))
                    xmz = 0;
            }
            if (dataBudget[zjfy].byj != null) {
                byj = parseFloat(dataBudget[zjfy].byj);
                if (isNaN(byj))
                    byj = 0;
            }
            var ysje = xmz + byj;
            if (ysje == 0)
                dataBudget[zjfy].ysje = "";
            else
                dataBudget[zjfy].ysje = ysje;

            loadTreetable();
        });

        //当前行预算
        function setCurBudget(bm, colName, value) {
            for (var i = 0; i < dataBudget.length; i++) {
                if (bm == dataBudget[i].bm) {
                    value = parseFloat(value);
                    if (value<0){
                        alert("金额不能为负数或无效的数字，请重新输入！");
                        value = null;
                    }
                    if (isNaN(value))
                        value = null;

                    //当前数据不能大于总预算列的值
                    if (dataBudget[i].xmzys != null) {
                        if (value !== null && value > parseFloat(dataBudget[i].xmzys*1.2).toFixed(6)) {
                            alert("输入金额不能超过项目总预算列120%！");
                            return; // 返回，不进行后续处理
                        }
                        if (dataBudget[i].sjyzx!=null&&dataBudget[i].sjyzx + value>parseFloat(dataBudget[i].xmzys).toFixed(6)*1.2){
                            alert("该科目年度预算申请总和已超过该科目总预算的120%！")
                            return;
                        }

                    }else {
                        if(value == null || value == ''){
                            value = ''
                        }else {
                            alert("输入金额不能超过项目总预算列的120%！")
                            return;
                        }
                    }
                    if (colName == "xmz") {
                        dataBudget[i].xmz = value;
                    } else if (colName == "byj") {
                        dataBudget[i].byj = value;
                    } else if (colName == "xtjsyzx") {
                        dataBudget[i].xtjsyzx = value;
                    } else if (colName == "sjyzx") {
                        dataBudget[i].sjyzx = value;
                    }

                    //正在编辑的预算
                    var xmz = 0, byj = 0;
                    if (dataBudget[i].xmz != null) {
                        xmz = parseFloat(dataBudget[i].xmz);
                        if (isNaN(xmz))
                            xmz = 0;
                    }
                    if (dataBudget[i].byj != null) {
                        byj = parseFloat(dataBudget[i].byj);
                        if (isNaN(byj))
                            byj = 0;
                    }
                    var ysje = xmz + byj;
                    if (ysje == 0)
                        dataBudget[i].ysje = '';
                    else
                        dataBudget[i].ysje = ysje;

                    break;
                }
            }
        }

        //父级预算
        function setFjBudget(fj) {
            if (fj != null && fj != '') {
                var xmzys = 0, xmz = 0, byj = 0, xtjsyzx = 0, sjyzx = 0;
                //子节点的值相加
                for (var j = 0; j < dataBudget.length; j++) {
                    if (fj == dataBudget[j].fj) {
                        // var t = parseFloat(dataBudget[j].xmzys);
                        // if (!isNaN(t))
                        //     xmzys += t;
                        var t1 = parseFloat(dataBudget[j].xmz);
                        if (!isNaN(t1))
                            xmz += t1;
                        var t2 = parseFloat(dataBudget[j].byj);
                        if (!isNaN(t2))
                            byj += t2;
                        var t3 = parseFloat(dataBudget[j].xtjsyzx);
                        if (!isNaN(t3))
                            xtjsyzx += t3;
                        var t4 = parseFloat(dataBudget[j].sjyzx);
                        if (!isNaN(t4))
                            sjyzx += t4;
                    }
                }

                //更新父节点的值
                for (var j = 0; j < dataBudget.length; j++) {
                    if (fj == dataBudget[j].bm) {
                        // if (xmzys == 0)
                        //     dataBudget[j].xmzys = '';
                        // else
                        //     dataBudget[j].xmzys = xmzys.toFixed(2);
                        if (xmz == 0)
                            dataBudget[j].xmz = '';
                        else
                            dataBudget[j].xmz = xmz.toFixed(2);
                        if (xtjsyzx == 0)
                            dataBudget[j].xtjsyzx = '';
                        else
                            dataBudget[j].xtjsyzx = xtjsyzx.toFixed(2);
                        if (sjyzx == 0)
                            dataBudget[j].sjyzx = '';
                        else
                            dataBudget[j].sjyzx = sjyzx.toFixed(2);

                        var ysje = xmz + byj;
                        if (ysje == 0)
                            dataBudget[j].ysje = "";
                        else
                            dataBudget[j].ysje = ysje.toFixed(2);

                        setFjBudget(dataBudget[j].fj);
                        break;
                    }
                }
            }
        }

        //组织要保存的数据
        function getBudget(budgets, data) {
            var budget = {
                "id": data.id,
                "fymc":data.fymc,
                "nys":data.nys,
                "fj":data.fj,
                "bm":data.bm,
                "xmzys": data.xmzys,
                "ysje": data.ysje,
                "xmz": data.xmz,
                "byj": data.byj
            };
            budgets.push(budget);
            if (data.children != undefined) {
                getChildNode(budgets, data);
            }
        }

        function getChildNode(budgets, data) {
            for (let item of data.children) {
                getBudget(budgets, item);
            }
        }

        // 监听保存按钮（项目预算）
        $("button[lay-filter='saveBtnYs']").click(function () {
            var rwsys = $("#rwsys").val();
            var ndczje = $("#ndczje").val();

            console.log(spList)
            console.log(spListId)
            for (let i = 0; i < dataBudget.length; i++) {
                if (dataBudget[i].fj==''){
                    var ysje = dataBudget[i].ysje;
                }
            }
            if (ndczje === "" && ndczje === null){
                Message.error("年度经费为空，不能申请年段预算");
                return false;
            }
            if (ysje === null){
                Message.error("预算金额不能为空",1500);
                return false;

            }
            if ( ysje > ndczje){
                Message.error("预算金额不能大于年度经费！",1500);
                return false;
            }
            if ( ysje < ndczje){
                Message.error("预算金额不能小于年度经费！",1500);
                return false;
            }
            if (rwsys == "") {
                Message.error("任务书预算不能为空，请完善任务书项目预算！", 1500);
                return false;
            }

            var item = dataBudget.find((item) => item.fymc == "总计");
            var ndzys = item.xmzys;
            if (ndzys == null) {
                return false;
            }
            if (parseFloat(ndzys) > parseFloat(rwsys)) {
                Message.error("年度总预算不能超过任务书预算！", 1500);
                return false;
            }
            if (parseFloat(ndzys) > parseFloat(rwsys)) {
                Message.error("年度总预算不能超过任务书预算！", 1500);
                return false;
            }

            var data = insTb.options.data;
            var budgets = new Array();
            for (var i = 0; i < data.length; i++) {
                getBudget(budgets, data[i]);
            }
            var index = layer.load(0, {shade: 0.1});
            if (spList == false){
                layer.confirm("该年度预算的修改申请还存在未结束的审批流程，是否重新提交?",function (index) {
                    AjaxUtil.get({
                        url:AjaxUtil.ctx + 'prjApproverecord/updatSpList/'+spListId,
                        success:function (res) {
                            //添加修改记录
                            AjaxUtil.post({
                                url: AjaxUtil.ctx + 'PrjAnnualBudgetRecord/addUpdateApplyRecord/',
                                contentType: "application/json",
                                data: JSON.stringify(budgets),
                                success: function (res) {
                                    layer.close(index);
                                    if (res.code === 0) {
                                        var project = {
                                            "xm":xm,
                                            "xmid":xmid,
                                            "zt":"未提交"
                                        }
                                        //添加审批记录
                                        AjaxUtil.post({
                                            url: AjaxUtil.ctx + "prjApproverecord/doUpdatApprove",
                                            data:project,
                                            success: function (res) {
                                                Message.success(res.message, 2000);
                                                layer.load(0, {shade: 0.1});
                                                setTimeout(function() {
                                                    parent.layer.close(parent.layer.getFrameIndex(window.name)); // 关闭子窗口
                                                }, 1000);
                                                // parent.layer.close(parent.layer.getFrameIndex(window.name));// 关闭子窗口
                                            },
                                            error: function (error) {
                                            }
                                        });
                                    } else {
                                        Message.error("修改记录添加失败", 2000);
                                    }
                                }
                            });
                        }
                        })
                })
                }else{
                //添加修改记录
                AjaxUtil.post({
                    url: AjaxUtil.ctx + 'PrjAnnualBudgetRecord/addUpdateApplyRecord/',
                    contentType: "application/json",
                    data: JSON.stringify(budgets),
                    success: function (res) {
                        layer.close(index);
                        if (res.code === 0) {
                            var project = {
                                "xm":xm,
                                "xmid":xmid,
                                "zt":"未提交"
                            }
                            //添加审批记录
                            AjaxUtil.post({
                                url: AjaxUtil.ctx + "prjApproverecord/doUpdatApprove",
                                data:project,
                                success: function (res) {
                                    Message.success(res.message, 2000);
                                    layer.load(0, {shade: 0.1});
                                    setTimeout(function() {
                                        parent.layer.close(parent.layer.getFrameIndex(window.name)); // 关闭子窗口
                                    }, 1000);
                                    // parent.layer.close(parent.layer.getFrameIndex(window.name));// 关闭子窗口
                                },
                                error: function (error) {
                                }
                            });
                        } else {
                            Message.error("修改记录添加失败", 2000);
                        }
                    }
                });
                }



        });

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