    <!DOCTYPE html>
<html lang="en" 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">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息(<b>收起-展开</b>)</legend>
            <div id="search-div" style="margin: 5px 10px -10px 0px">
                <form class="layui-form" action="" lay-filter="search-form">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 70px">项目名称</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <input type="text" id="xmmc" name="xmmc" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 70px">ERP编号</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <input type="text" id="erpbh" name="erpbh" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 70px">年份</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <select name="nf" id="nf" lay-filter="status">
                                    <option value="0">全部</option>
                                    <option th:each="item:${yearList}" th:text="${item.nf}" th:value="${item.nf}"></option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 70px">审批状态</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <select name="spzt" id="spzt" lay-filter="status">
                                    <option value="">全部</option>
                                    <!--<option th:each="item:${approveList}" th:text="${item.name}" th:value="${item.name}"></option>-->
                                    <option value="未提交">未提交</option>
                                    <option value="未提交(返回)">未提交(返回)</option>
                                    <option value="科技项目管理专责审批">科技项目管理专责审批</option>
                                    <option value="审批结束">审批结束</option>
                                </select>
                            </div>
                        </div>
                        <br/>
                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 70px">项目类型</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <select name="xmlx" id="xmlx" lay-filter="status">
                                    <option value="">全部</option>
                                    <option th:each="item:${xmlxList}" th:text="${item.name}" th:value="${item.code}"></option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label required" style="width: 70px">所属部门</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <input type="text" id="ssbmmc" name="ssbmmc" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 70px">任务书名称</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <input type="text" id="rwsmc" name="rwsmc" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 70px">是否修改</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <select name="sfxg" id="sfxg" lay-filter="status">
                                    <option value="">全部</option>
                                    <option value='0'>未修改</option>
                                    <option value='1'>已修改</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline" style="margin-left: 0px">
                            <button type="submit" class="layui-btn" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-reset-btn"><i class="layui-icon layui-icon-refresh"></i> 重 置 </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">

                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="edit">
                    <i class="layui-icon layui-icon-edit" style="font-size: 10px;"></i>编辑
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="view">
                    <i class="layui-icon layui-icon-file" style="font-size: 10px;"></i>查看
                </button>
<!--                <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">
                    <i class="layui-icon layui-icon-delete" style="font-size: 10px;"></i>删除
                </button>-->
<!--                <button class="layui-btn layui-btn-sm data-add-btn" lay-event="tjApprove">-->
<!--                    <i class="layui-icon layui-icon-ok" style="font-size: 10px;"></i>提交审批-->
<!--                </button>-->
<!--                <button class="layui-btn layui-btn-sm data-add-btn" lay-event="tjrevokeApprove" id="idd">-->
<!--                    <i class="layui-icon layui-icon-edit" style="font-size: 10px;"></i>撤销审批-->
<!--                </button>-->
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="spOption">
                    <i class="layui-icon layui-icon-edit" style="font-size: 10px;"></i>审核
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="spList">
                    <i class="layui-icon layui-icon-list" style="font-size: 10px;"></i>审批列表
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="xgjl">
                    <i class="layui-icon layui-icon-list" style="font-size: 10px;"></i>修改记录
                </button>
<!--                <button class="layui-btn layui-btn-sm data-add-btn" lay-event="fyApply">-->
<!--                    <i class="layui-icon layui-icon-list" style="font-size: 10px;"></i>费用申请-->
<!--                </button>-->
                <button class="layui-btn layui-btn-sm" lay-event="exportExcel" style="background-color: black">
                    <i class="layui-icon layui-icon-export" style="font-size: 10px;"></i>导出列表
                </button>
                <button class="layui-btn layui-btn-sm" lay-event="tongBu" style="background: #FF8040"
                        id="tbYzx">
                    同步已执行
                </button>
                <button class="layui-btn layui-btn-sm" lay-event="viewXgsq"
                        id="viewXgsq">
                    查看修改申请
                </button>
            </div>
        </script>
        <script>
            // 当文档加载完成后执行以下操作
            document.addEventListener('DOMContentLoaded', function() {
                // 获取下拉框元素
                var selectElement = document.getElementById('nf');
                // 获取当前年份并转换为字符串
                var currentYear = new Date().getFullYear().toString();

                // 遍历下拉框选项
                for (var i = 0; i < selectElement.options.length; i++) {
                    // 如果选项的值与当前年份相匹配，则将该选项设为被选中状态并结束循环
                    if (selectElement.options[i].value === currentYear) {
                        selectElement.options[i].selected = true;
                        break;
                    }
                }
            });
        </script>

        <input type="hidden" id="userId" name="userId" class="layui-input" th:value="${userId}">
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
    </div>
</div>

<script>
    // 获取所有需要去除空格的输入框
    const inputs = [
        document.getElementById('xmmc'),
        document.getElementById('erpbh'),
        document.getElementById('rwsmc')
    ];
    // 为每个输入框添加事件监听
    inputs.forEach(input => {
        input.addEventListener('input', function() {
            this.value = this.value.replace(/\s+/g, ''); // 去除空格
        });
    });
</script>
<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="@{/js/lay-config.js}" charset="utf-8"></script>
<script th:src="@{/lib/xm-select-v1.2.2/xm-select.js}" charset="utf-8"></script>
<script th:inline="javascript" type="text/javascript">
    AjaxUtil.ctx = /*[[@{/}]]*/'';
    var updateflag = 0;
    var xmApproval = {};

    layui.use(['form', 'table', 'tableSelect', 'laydate','layCascader'], function () {
        var form = layui.form
        table = layui.table;
        var userId = $("#userId").val();
        var selectedYear = $('#nf').val();
        layCascader = layui.layCascader;

        var index2 = layer.load(0, {shade: 0.1});
        AjaxUtil.get({
            url: AjaxUtil.ctx + 'userinfo/listDeptForSelect',
            success: function (res) {
                layer.close(index2);

                var datalist = [];
                for (let item of res.data) {
                    item.value = item.deptName;
                    item.label = item.deptName;
                    datalist.push(item);
                }
                console.log(datalist)
                // 扁平数据转树
                var options = arrayToTree(datalist, "50");

                // 初始化cascader实例
                var cascader = layCascader({
                    elem: '#ssbmmc',
                    clearable: true,
                    showAllLevels: false, // 配置仅显示最后一级
                    props: {
                        checkStrictly: true, // 配置选择任意一级选项
                    },
                    options: options
                });

                // 监听cascader变化
                cascader.changeEvent(function (value, node) {
                    // 主动关闭面板
                    cascader.close();
                    $("#deptId").val(value);
                    console.log(node);
                });
            },
            error: function (error) {
                layer.close(index2);
                Message.error('获取部门信息失败！', 1000);
            }
        });
        setTimeout(function() {
            // 在这里可以进行您的加载操作
            layer.msg('加载完成！', { icon: 1 });
            if (userId == 42){
                document.getElementById('idd').style.display = 'none';
                return false;
            }
            return  false;
            // 隐藏加载信息

        }, 100); // 2000


        var currTable = table.render({
            elem: '#currentTableId',
            url: AjaxUtil.ctx + 'prjAnnualbudget/list/?nf='+selectedYear,
            method: 'post',
            toolbar: '#toolbarDemo',
            // defaultToolbar: ['filter', 'print'],
            cols: [
                [
                    {type: "radio", fixed: 'left',title: '😊'},
                    {type: 'numbers', align: 'center',title: '序号'},
                    {field: 'spzt', width: '7%', title: '审批状态'},
                    {field: 'xmmc', width: '20%', title: '项目名称'},
                    // {field: 'rwsmc', width: '20%', title: '任务书名称'},
                    // {field: 'mc', width: '20%', title: '年度预算名称'},
                    {field: 'erpbh', width: '8%', title: 'ERP编号'},
                    {field: 'czje', width: '7%', title: '年预算（元）',align: 'right',templet:function (row) {
                        return row.czje.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                        }},
                    {field: 'sqje', width: '7%', title: '已申请（元）',align: 'right',templet:function (row) {
                        return row.sqje.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

                        }},
                    {field: 'bzze', width: '7%', title: '已报账（元）',align: 'right',templet:function (row) {
                        return row.bzze.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

                        }},
                    /*{field: 'yfze', width: '7%', title: '已付总额(元)', align: 'right'},*/
                    {templet: function (row) {
                            const czjeValue = Number(row.czje); // 将获取到的值转换为数值类型
                            const bzzeValue = Number(row.sqje);
                            if (bzzeValue > czjeValue){
                                return '数据异常';
                            }
                            if (!isNaN(czjeValue) &&!isNaN(bzzeValue) && bzzeValue!== 0) { // 避免除数为0
                                const syl =  (bzzeValue / czjeValue) * 100;
                                return syl.toFixed(2) + '%';// 乘以100转换为百分比形式
                            }
                            return '0%'; // 如果出现异常情况（比如除数为0等），返回默认值0
                        }, width: '7%',title: '使用率（%）',align: 'right'},
                    {field: 'nf', width: '5%', title: '年份'},
                    {field: 'ssbmmc', width: '10%', title: '所属部门'},
                    {field: 'sqrxm', width: '6%', title: '申请人'},
                    {field: 'sqsj', width: '8%', title: '申请时间', align: 'center'},
                    {field: 'xmlxmc', width: '10%', title: '项目类型'},
                    {field: 'xmfzrxm', width: '7%', title: '项目负责人'},



                    /*{field: 'sm', width: '10%', title: '说明'}*/
                ]
            ],
            autoSort: false,
            limits: [10, 15, 20, 25, 50, 100],
            limit: 10,
            page: true,
            skin: 'grid',
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.rows //解析数据列表
                };
            },
            done: function (res, curr, count) { // done为数据渲染完的回调
                // 测试打印出后端返回的权限列表
                // let permissionSet = [[${permissionSet}]];
                // console.log(JSON.stringify(permissionSet));
                if (userId != 40 && userId != 42 && userId != 1) {
                    document.getElementById("tbYzx").style.display = 'none';
                }
            }
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            // 执行搜索重载
            currTable.reload({
                page: {
                    curr: 1 // 页码从1开始
                },
                where: form.val("search-form")
            });
            return false;
        });

        // 监听重置操作
        form.on('submit(data-reset-btn)', function (data) {
            form.val("search-form", {
                "bh": '',
                "erpbh": '',
                "xmlx": '',
                "sfbyj": '',
                "xmmc": '',
                "ssbmmc": '',
                "nf": '0',
                "spzt": '',
                "sfbz": '',
                "dkyfzr": '',
                "rwsmc":''
            });
            // 执行搜索重载
            currTable.reload({
                page: {
                    curr: 1
                },
                where: form.val("search-form")
            });
            return false;
        });

        // 监听排序事件
        table.on('sort(currentTableFilter)', function (obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            // console.log(obj.field); //当前排序的字段名
            // console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
            // console.log(this); //当前排序的 th 对象
            //尽管我们的 table 自带排序功能，但并没有请求服务端。
            //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
            currTable.reload({
                initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    sortName: toLine(obj.field), //排序字段
                    sortOrder: toLine(obj.type) //排序方式
                }
            });
        });

        // 监听工具栏事件
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                layer.open({
                    title: '新建年度预算',
                    type: 2,
                    shade: 0.3,
                    maxmin: true,
                    area: ['1010px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'prjAnnualbudget/forAdd',
                    end: function () {
                        // 重载表格
                        if (updateflag == 1)
                            currTable.reload();
                        updateflag = 0;
                    }
                });
            } else if (obj.event == 'edit') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要编辑的年度预算！", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行编辑！", 1500);
                } else if (data[0].spzt == "作废") {
                    Message.warning("该年度预算已作废！", 1500);
                
                }
                // else if (data[0].sqr != userId) {
                //     Message.error("您不是该年度预算的申请人！", 1500);}
                else {
                    layer.open({
                        title: '编辑年度预算',
                        type: 2,
                        shade: 0.3,
                        maxmin: true,
                        shadeClose: true,
                        area: ['1010px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjAnnualbudget/forUpdate/' + data[0].id,
                        end: function () {
                            if (updateflag == 1)
                                currTable.reload();
                            updateflag = 0;
                        }
                    });
                }
            } else if (obj.event == 'view') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要查看的年度预算！", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行查看！", 1500);
                } else {
                    layer.open({
                        title: '查看年度预算',
                        type: 2,
                        shade: 0.3,
                        maxmin: true,
                        shadeClose: true,
                        area: ['1010px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjAnnualbudget/forView/' + data[0].id,
                        end: function () {
                        }
                    });
                }
            } else if (obj.event === 'delete') {  // 监听删除操作
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要删除的年度预算！", 1000);
                    return;
                } else {
                    for (let item of data) {
                        if (item.sqr != userId) {
                            Message.error("存在您不是申请人的年度预算，不能直接删除！", 2000);
                            return;
                        }
                        if (item.spzt != "未提交") {
                            if (item.spzt == "审批结束")
                                Message.warning("存在已审批结束的年度预算，不能直接删除！", 2000);
                            else if (data[0].spzt != null && data[0].spzt != '作废')
                                Message.warning("存在审批中的年度预算，不能直接删除！", 2000);
                            return;
                        }
                    }
                }
                layer.confirm('确定批量删除年度预算吗？', function (index) {
                    layer.close(index);
                    AjaxUtil.post({
                        url: AjaxUtil.ctx + "prjAnnualbudget/batchDelete",
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function (res) {
                            if (res.code === 0) {
                                Message.success(1500, res.message, function () {
                                    // 重载表格
                                    currTable.reload();
                                });
                            } else {
                                Message.error(res.message, 1000);
                            }
                        },
                        error: function (error) {
                        }
                    });
                });
            } else if (obj.event === 'tjApprove') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要提交审批的年度预算！", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行提交！", 1500);
                } else if (data[0].spzt == "审批结束") {
                    Message.warning("该年度预算已审批结束！", 1500);
                } else if (data[0].spzt == "作废") {
                    Message.warning("该年度预算已作废！", 1500);
                } else if (data[0].spzt != null && data[0].spzt.indexOf("未提交") < 0) {
                    Message.warning("该年度预算正在审批中……", 1500);
                }
                else if (data[0].sqr != userId) {
                    Message.error("您不是该年度预算的申请人！", 1500);}
                else {
                    if (isNaN(data[0].ysje) || isNaN(data[0].ysje))
                        Message.error("该完善年度预算明细后提交！", 1500);
                    else {
                        xmApproval = {
                            "xmid": data[0].id,
                            "xm": data[0].mc,
                            "zt": data[0].spzt,
                            "ysje": data[0].ysje
                        };
                        if (data[0].spzt == null) {
                            xmApproval.zt = "未提交";
                            data[0].spzt = "未提交";
                        }

                        var content = AjaxUtil.ctx + 'prjAnnualbudget/forApproveAdd';
                        if (data[0].spzt != "未提交")
                            content = AjaxUtil.ctx + 'prjAnnualbudget/forApproveUpdate/' + data[0].id + '?spzt=' + data[0].spzt;
                        console.log(content);

                        var index = layer.open({
                            title: '提交审批',
                            type: 2,
                            shade: 0.3,
                            maxmin: true,
                            shadeClose: true,
                            area: ['1015px', layerheight + 'px'],
                            content: content,
                            end: function () {
                                if (updateflag == 1)
                                    currTable.reload();
                                updateflag = 0;
                                layer.close(index);
                            }
                        });
                    }
                }
            } else if (obj.event === 'spOption') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要审批的年度预算！", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行审批！", 1500);
                } else if (data[0].spzt == null || data[0].spzt.indexOf("未提交") >= 0) {
                    Message.warning("该年度预算尚未提交审批！", 1500);
                } else if (data[0].spzt == "审批结束") {
                    Message.warning("该年度预算已审批结束！", 1500);
                } else if (data[0].spzt == "作废") {
                    Message.warning("该年度预算已作废！", 1500);
                } else {
                    // 判断当前人员是否是审核人
                    AjaxUtil.get({
                        url: AjaxUtil.ctx + "prjAnnualbudget/getshr?xmid="+data[0].id+'&spzt='+data[0].spzt,
                        contentType: "application/json",
                        success: function (res) {
                            if (res.code === -1) {
                             layer.msg(res.message,{icon:2});
                             return;
                            } else if (res.code === -2){
                                layer.msg(res.message,{icon:2});
                                return;
                            }else {
                                xmApproval = {
                                    "xmid": data[0].id,
                                    "xm": data[0].mc,
                                    "ysje": data[0].ysje
                                };
                                var index = layer.open({
                                    title: '审核',
                                    type: 2,
                                    shade: 0.3,
                                    maxmin: true,
                                    shadeClose: true,
                                    area: ['1020px', layerheight + 'px'],
                                    content: AjaxUtil.ctx
                                        + 'prjAnnualbudget/forApproveUpdate/' + data[0].id + '?spzt=' + data[0].spzt,
                                    end: function () {
                                        if (updateflag == 1)
                                            currTable.reload();
                                        updateflag = 0;
                                        layer.close(index);
                                    }
                                });
                            }
                        },
                        error: function (error) {
                        }
                    });
                }
            } else if (obj.event === 'spList') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要查看审批列表的年度预算！", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行查看！", 1500);
                } else if (data[0].spzt == null || data[0].spzt == "未提交") {
                    Message.warning("该年度预算尚未提交审批！", 1500);
                } else {
                    xmApproval = {
                        "xmid": data[0].id,
                        "xm": data[0].mc
                    };
                    var index = layer.open({
                        title: '审批列表',
                        type: 2,
                        shade: 0.3,
                        maxmin: true,
                        shadeClose: true,
                        area: ['1300px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjAnnualbudget/forApproveList',
                        end: function () {
                            layer.close(index);
                        }
                    });
                }
            } else if (obj.event === 'xgjl') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要查看审批列表的年度预算！", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行查看！", 1500);
                } else if (data[0].spzt == null || data[0].spzt == "未提交") {
                    Message.warning("该年度预算尚未提交审批！", 1500);
                } else {
                    xmApproval = {
                        "xmid": data[0].id,
                        "xm": data[0].mc
                    };
                    var index = layer.open({
                        title: '修改记录',
                        type: 2,
                        shade: 0.3,
                        maxmin: true,
                        shadeClose: true,
                        area: ['1300px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'PrjAnnualBudgetRecord/viewRecord',
                        end: function () {
                            layer.close(index);
                        }
                    });
                }
            } else if (obj.event === 'fyApply') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要申请费用的年度预算！", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行申请费用！", 1500);
                } else if (data[0].spzt == null || data[0].spzt.indexOf("未提交") >= 0) {
                    Message.warning("该年度预算尚未提交审批！", 1500);
                } else if (data[0].spzt == "作废") {
                    Message.warning("该年度预算已作废！", 1500);
                } else if (data[0].spzt != null && data[0].spzt != "审批结束" && data[0].spzt.indexOf("未提交") < 0) {
                    Message.warning("该年度预算正在审批中……", 1500);
                } else {
                    xmApproval = {
                        "xmid": data[0].rws,
                        "xmmc": data[0].rwsmc
                    };
                    layer.open({
                        title: '新建费用申请',
                        type: 2,
                        shade: 0.3,
                        maxmin: true,
                        area: ['1020px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjAnnualbudget/forApplyAdd/' + data[0].id,
                        end: function () {
                            // 重载表格
                            if (updateflag == 1)
                                currTable.reload();
                            updateflag = 0;
                        }
                    });
                }
            } else if (obj.event === 'exportExcel') {
                var dataBudget = table.cache["currentTableId"];
                if (dataBudget.length == 0)
                    return;

                var formData = form.val('search-form');
                // 获取form 表单代码
                console.log(formData);
                var formDataString = JSON.stringify(formData);
                let a = document.createElement('a');
                a.href = AjaxUtil.ctx + 'prjAnnualbudget/exportExcel/'+formDataString;
                a.click();
                a.parentNode.removeChild(a);
            }

    else if(obj.event==='tjrevokeApprove'){
            var projects = table.cache["currentTableId"];
            if (projects.length == 0)
                return;
            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要撤销的年度预算！", 1500);
            } else if (data.length > 1) {
                Message.warning("请选择一条记录进行撤销！", 1500);
            } else if (data[0].spzt == "审批结束") {
                Message.warning("该年度预算已审批结束！", 1500);
            }
           // else if (data[0].cjr != userId) {
               // Message.error("您不是该年度预算的创建人！", 1500);}
            else {
                xmApproval = {
                    "xmid": data[0].id,
                    "xm": data[0].zwmc,
                    "zt": "未提交"
                };
                if(data[0].spzt == null) {
                    xmApproval.zt = "未提交";
                    data[0].spzt = "未提交";
                }
                var project = {
                    "id": xmApproval.xmid,
                    "spzt": '未提交'
                }
                layer.confirm('确定撤销年度预算吗？', function (index) {
                    layer.close(index);
                    AjaxUtil.post({
                        url: AjaxUtil.ctx + "prjAnnualbudget/TJrevokeApprove",
                        contentType: "application/json",
                        data: JSON.stringify(project),
                        success: function (res) {
                            if (res.code === 0) {
                                Message.success(1500, res.message, function () {
                                    // 重载表格
                                    currTable.reload();
                                });
                            } else {
                                Message.error(res.message, 1000);
                            }
                        },
                        error: function (error) {
                        }
                    });
                });
            }
        }else if (obj.event==='tongBu'){
                var project = table.cache["currentTableId"];
                if (project.length == 0) {
                    return;
                }
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要同步数据的年度预算!", 1500);
                } else if (data.length > 1) {
                    Message.warning("请选择一条记录进行同步！", 1500);
                }  else {

                    layer.confirm('确定要将该年度预算进行数据同步吗？', function (index) {
                        layer.close(index);
                        AjaxUtil.get({
                            url: AjaxUtil.ctx + "updateSJYZXAndXTJSYZX/"+data[0].rws+"/"+data[0].id,
                            contentType: "application/json",
                            success: function (res) {
                                if (res.code === 0) {
                                    Message.success(1500, res.message, function () {
                                        // 重载表格
                                        currTable.reload();

                                    });
                                } else {
                                    Message.error(res.message, 1000);
                                }
                            },
                            error: function () {
                            }
                        });
                    });

                }
            }else  if (obj.event =="viewXgsq"){
                var index = layer.open({
                    title: '修改申请',
                    type: 2,
                    shade: 0.3,
                    maxmin: true,
                    shadeClose: true,
                    area: ['1300px', layerheight + 'px'],
                    content:  AjaxUtil.ctx+ "prjAnnualbudget/ViewXGSQ",
                    end: function () {
                        layer.close(index);
                    }
                });
            }
    });



        //双击
        table.on('rowDouble(currentTableFilter)', function (obj) {
            layer.open({
                title: '查看年度预算',
                type: 2,
                shade: 0.3,
                maxmin: true,
                shadeClose: true,
                area: ['1010px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'prjAnnualbudget/forView/' + obj.data.id,
                end: function (index) {
                    layer.close(index);
                }
            });
        });
    });
    function getXmApproval() {
        return xmApproval;
    }

    function setUpdateFlag() {
        updateflag = 1;
    }
    function arrayToTree(data, firstPid) {
        const result = [];
        getChildren(data, result, firstPid)
        return result;
    }
    function getChildren(data, result, parentId) {
        for (const item of data) {
            if (item.parentId === parentId) {
                const newItem = {...item, children: []};
                result.push(newItem);
                getChildren(data, newItem.children, item.deptId);
            }
        }
    }
</script>
</body>
</html>