<!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">
                                <input type="text" id="bh" name="bh" 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.code}"></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="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" style="width: 70px">项目负责人</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <input type="hidden" id="xmfzr" name="xmfzr" class="layui-input">
                                <input type="text" id="xmfzrxm" name="xmfzrxm" placeholder="可多选" autocomplete="off" class="layui-input" readonly>
                            </div>
                        </div>
                        <br>
                        <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="ssbmmc" name="ssbmmc" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <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>
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
    </div>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
<!--        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="view">
            <i class="layui-icon layui-icon-file" style="font-size: 10px;"></i>查看
        </button>-->
        <button class="layui-btn layui-btn-sm" lay-event="export" style="background-color: black">
            <i class="layui-icon layui-icon-export" style="font-size: 10px;"></i>导出列表
        </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>

<script>
    // 获取所有需要去除空格的输入框
    const inputs = [
        document.getElementById('xmmc'),
        document.getElementById('erpbh')
    ];
    // 为每个输入框添加事件监听
    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 = /*[[@{/}]]*/'';

    layui.use(['form', 'table', 'tableSelect','layCascader'], function () {
        var form = layui.form,
            table = layui.table,
            tableSelect = layui.tableSelect,
            layCascader = layui.layCascader;
        var year = document.getElementById('nf').value;

        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);
            }
        });

        var currTable = table.render({
            elem: '#currentTableId',
            url: AjaxUtil.ctx + 'staBudgetapproval/list_feemanage/?nf='+year,
            method: 'post',
            toolbar: '#toolbarDemo', // 自定义模板
            // toolbar: '#toolbarDemo',
            // defaultToolbar: ['filter', 'print'],
            cols: [
                [
                    {type: "radio", title:'😊' ,fixed: 'left'},
                    {type: 'numbers', align: 'center', fixed: 'left',title: '序号'},
                    // {field: 'id', title: 'ID',hide:true},
                    {field: 'zwmc', width: '20%', title: '项目名称',fixed: "left"},
                    {field: 'erpbh', width: '8%', title: 'ERP编号'},
                    {field: 'xmlxmc', width: '10%', title: '项目类型'},
                    {field: 'xmfzrxm', width: '6%', title: '项目负责人'},
                    {field: 'ssbmmc', width: '8%', title: '所属部门'},
                    {field: 'nf', width: '5%', title: '年份', align: 'center'},
                    {field: 'xmzys', width: '6%', title: '总预算'},
                    {field: 'ysje', width: '6%', title: '预算金额'},
                    {field: 'xmz', width: '5%', title: '项目组'},
                    {field: 'sqje', width: '7%', title: '已申请金额'},
                    {field: 'bzje', width: '7%', title: '已报账金额'},
                    {field: 'byj', width: '5%', title: '备用金'},
                    {field: 'byjsqje', width: '8%', title: '备用金已申请'},
                    {field: 'byjbzje', width: '8%', title: '备用金已报账'},
                    {field: 'ye', width: '5%', title: '余额'},
                    {field: 'byjye', width: '7%', title: '备用金余额'},
                    {field: 'rzbfb', width: '7%', 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));
            }
        });



        // 监听搜索操作
        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", {
                "xmmc": '',
                "erpbh": '',
                "xmlx": '',
                "xmfzrxm": '',
                "ssbmmc": '',
                "nf": '0'
            });
            // 执行搜索重载
            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) //排序方式
                }
            });
        });

        //项目负责人
        tableSelect.render({
            elem: '#xmfzrxm',
            checkedKey: 'id',
            searchKey: 'xm',
            searchPlaceholder: '搜索姓名',
            table: {
                url: AjaxUtil.ctx + 'basePerson/rylist',
                cols: [
                    [
                        {type: "checkbox", fixed: 'left'},
                        {type: 'numbers', align: 'center',title: '序号'},
                        {field: 'xm', width: '15%', title: '姓名', align: 'left'},
                        {field: 'dwmc', title: '公司/单位', align: 'left',width: '30%'},
                        {field: 'bmmc', title: '部门',align: 'left',width: '30%'}
                    ]
                ]
            },
            done: function (elem, data) {
                var NEWJSON = [];
                var NEWJSON1 = [];
                layui.each(data.data, function (index, item) {
                    NEWJSON.push(item.xm);
                    NEWJSON1.push(item.id);
                })
                elem.val(NEWJSON.join(","));
                $("#xmfzr").val(NEWJSON1.join(","));
            }
        });

        // 监听工具栏事件
        table.on('toolbar(currentTableFilter)', function (obj) {
        if (obj.event == 'view') {
            var dataApproval = table.cache["currentTableId"];
            if(dataApproval.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 {
                xmApproval = {
                    "id": data.id,
                    "zwmc": data.zwmc,
                    "erpbh":data.erpbh,
                    "xmlxmc": data.xmlxmc,
                    "xmfzrxm": data.xmfzrxm,
                    "ssbmmc": data.ssbmmc
                }
                layer.open({
                    title: '浏览费用申请',
                    type: 2,
                    shade: 0.3,
                    maxmin: true,
                    shadeClose: true,
                    area: ['1020px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'staBudgetapproval/forApplyView/' + data[0].id,
                    end: function (index) {
                        layer.close(index);
                    }
                });
                // layer.full(index);
            }
        }
        else if (obj.event === 'exportExcel') {
            
            var dataApproval = table.cache["currentTableId"];
            if(dataApproval.length == 0)
                return;

            let a = document.createElement('a');
            a.href = AjaxUtil.ctx + 'staBudgetapproval/exportExcel';
            a.click();
            a.parentNode.removeChild(a);
        }
        else if (obj.event === 'export'){

            var formData = form.val('search-form');
            console.log(formData);
            var formDataString = JSON.stringify(formData);
            AjaxUtil.post({
                url:AjaxUtil.ctx +'staBudgetapproval/getAllGL/'+formDataString,
                timeout: 15000, //大批量导出时会出现超时问题
                success: function(res){
                    console.log(res);
                    table.exportFile('currentTableId',res.data,'xlsx');
                },
                error:function (error) {
                    Message.error(error,2000)

                }
            });
        }
        });
    });
    function setUpdateFlag() {
        updateflag = 1;
    }
    function getXmApproval() {
        return xmApproval;
    }
    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>