<!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: 60px">项目名称</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: 60px">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: 60px">创建人</label>
                            <div class="layui-input-inline" style="width: 140px">
                                <input type="text" id="cjr" name="cjr" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label" style="width: 100px">周期（区间）</label>
                            <div class="layui-input-inline" style="width: 100px">
                                <input type="text" name="kssj" id="kssj" placeholder="开始时间" class="layui-input" readonly>
                            </div>
                            <div class="layui-form-mid" style="margin: 0 5px;">-</div>
                            <div class="layui-input-inline" style="width: 100px">
                                <input type="text" name="jssj" id="jssj" placeholder="结束时间" class="layui-input" readonly>
                            </div>
                        </div>
                        <!-- 周期（区间）和按钮放在同一行 -->
                        <div class="layui-inline" style="display: flex; align-items: center;">
                            <div class="layui-inline">
                                <label class="layui-form-label" style="width: 60px">合同名称</label>
                                <div class="layui-input-inline" style="width: 140px">
                                    <input type="text" id="htmc" name="htmc" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline" >
                                <label class="layui-form-label" style="width: 60px;">审批状态</label>
                                <div class="layui-input-inline" style="width: 140px;">
                                    <select name="spzt" lay-filter="status" class="layui-select">
                                        <option value="">全部</option>
                                        <option value="未锁定">未锁定</option>
                                        <option value="锁定中">锁定中</option>
                                        <option value="已锁定">已锁定</option>
                                    </select>
                                </div>
                            </div>

                            <div class="layui-inline" style="margin-left: 20px;">
                                <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>

                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm" lay-event="add">
                    <i class="layui-icon layui-icon-addition" style="font-size: 10px;"></i>新建
                </button>
                <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-normal" lay-event="spOption">-->
<!--                    <i class="layui-icon layui-icon-file" 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-file" style="font-size: 10px;"></i>修改审批列表
                </button>
                <button class="layui-btn layui-btn-sm " lay-event="xgsq">
                    <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" lay-event="viewXgsq"
                        id="viewXgsq">
                    查看修改申请
                </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>
<!--                <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>-->
            </div>
        </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 type="text/html" id="cz">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="htht">
            <i class="layui-icon layui-icon-return" style="font-size: 10px;"></i>回退
        </button>
    </div>

</script>
<script>
    // 获取所有需要去除空格的输入框
    const inputs = [
        document.getElementById('rwsmc'),
        document.getElementById('erpbh'),
        document.getElementById('cjr'),
        document.getElementById('htmc')
    ];
    // 为每个输入框添加事件监听
    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 type="text/javascript" th:inline="javascript">
    AjaxUtil.ctx = /*[[@{/}]]*/'';
    var updateflag = 0;
    layui.use(['form', 'table','tableSelect', 'treeTable','laydate'], function () {
        var form = layui.form,
            table = layui.table,
            tableSelect = layui.tableSelect,
            laydate = layui.laydate;
        var userId = $("#userId").val();
        var userPostName = [[${userPostName}]]
        console.log(userPostName)
        var currTable = table.render({
            elem: '#currentTableId',
            url: AjaxUtil.ctx + 'prjContract/list/'+userId,
            method: 'get',
            toolbar: '#toolbarDemo',
            // defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [
                    {type: "checkbox", fixed: 'left'},
                    {type: 'numbers', field: 'center',title: '序号',fixed: 'left'},
                    {field: 'zwmc',width: '20%',title:'项目名称',fixed: 'left'},
                    {field: 'spzt',width: '10%',title: '审批状态',align: 'left'},
                    {field: 'erpbh',width: '10%',title: 'ERP编号',align: 'left'},
                    {field: 'htje', width: '8%', title: '合同金额(万元)', align: 'right',templet:function (row) {
                        return row.htje.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

                        }},
                    {field: 'yfje',width: '10%',title: '已付金额（万元）',align: 'right',templet:function (row) {
                        return row.yfje.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

                        }},
                    {width: '7%',title: '使用率(%)',align: 'right',templet:function (row) {
                            const yfjeValue = Number(row.yfje); // 将获取到的值转换为数值类型
                            const htjeValue = Number(row.htje);
                            if (yfjeValue > htjeValue){
                                return '数据异常';
                            }
                            if (!isNaN(yfjeValue) &&!isNaN(htjeValue) && yfjeValue!== 0) { // 避免除数为0
                                const syl =  (yfjeValue / htjeValue) * 100;
                                return syl.toFixed(2) + '%';// 乘以100转换为百分比形式
                            }
                            return '0%';
                        }},
                    {field: 'htmc', width: '20%', title: '合同名称'},
                    {field: 'zbpc', width: '8%', title: '招标批次'},
                    {field: 'zxdw', width: '8%', title: '中选单位'},
                    {field: 'sfsxtndw', width: '8%', title: '是否系统内单位', align: 'center', templet: function (d) {
                            if (0 == d.sfsxtndw) {
                                return '<span class="layui-badge layui-bg-blue">是</span>';
                            } else {
                                return '<span class="layui-badge layui-bg-orange">否</span>';
                            }
                        }
                    },
                    {field: 'zq', width: '6%',title: '周期(月)',align: 'left'},
                    {field: 'kssj',width: '10%',title: '执行周期（开始）',align: 'center'},
                    {field: 'jssj',width: '10%',title: '执行周期（结束）',align: 'center'},
                    {field: 'cjrxm', width: '8%', title: '创建人', align: 'center'},
                    {field: 'cjsj', width: '10%', title: '创建时间', align: 'center'},
                    {field: 'yssj', width: '10%', title: '验收时间', align: 'center'},
                    {title: '操作',width: '5%',toolbar:'#cz',align: 'center',fixed: 'right'}
                ]
            ],
            autoSort: false,
            limits: [10, 15, 20, 25, 50, 100,200,500],
            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 (userPostName !='科技项目管理专责'&&userPostName !='科技项目管理专责2'&& userId !=1) {
                    document.getElementById("viewXgsq").style.display = 'none';
                }
            }
        });
        //申请时间
        laydate.render({
            elem: '#kssj',
            done: function (value, date, endDate) {
                sqsj1 = $("#kssj").val();
                sqsj2 = $("#jssj").val();
                if (sqsj1 != "" && sqsj2 != "") {
                    if (sqsj1 > sqsj2) {
                        Message.warning("起始时间不能晚于终止时间！", 1500);
                        $("#kssj").val("");

                    }
                }
            }
        });
        laydate.render({
            elem: '#jssj',
            done: function (value, date, endDate) {
                sqsj1 = $("#kssj").val();
                sqsj2 = $("#jssj").val();
                if (sqsj1 != "" && sqsj2 != "") {
                    if (sqsj1 > sqsj2) {
                        Message.warning("终止时间不能早于开始时间！", 1500);
                        $("#jssj").val("");

                    }
                }
            }
        });

        // 监听搜索操作
        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", {
                "htmc": '',
                "rwsmc": '',
                "cjr":'',
                "erpbh":'',
                "kssj":'',
                "jssj":''
            });
            // 执行搜索重载
            currTable.reload({
                page: {
                    curr: 1
                },
                where: form.val("search-form")
            });
            return false;
        });

        // 监听行工具事件
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '新建合同',
                    type: 2,
                    shade: 0.3,
                    maxmin: true,
                    area: ['950px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'prjContract/forAdd',
                    end: function (index) {
                        // 重载表格
                        if (updateflag == 1)
                            currTable.reload();
                        updateflag = 0;
                    }
                });
            } else if (obj.event == 'edit') {
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要编辑的合同！", 1500);
                } else if (data[0].length > 1) {
                    Message.warning("请选择一条记录进行编辑操作！", 1500);
                } else if (data[0].spzt =='已锁定'&& userId !=42){
                    Message.warning("该合同已锁定不能编辑！")
                }else {
                    xmApproval = {
                        "spzt": data[0].spzt
                    };
                    var index = layer.open({
                        title: '编辑合同',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        area: ['950px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjContract/forUpdate/' + data[0].id,
                        end: function (index) {
                            // 重载表格
                            if (updateflag == 1)
                                currTable.reload();
                            updateflag = 0;
                        }
                    });
                }
            } else if (obj.event == 'view') {
                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 {
                    var index = layer.open({
                        title: '浏览合同',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        area: ['950px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjContract/forView/' + data[0].id
                    });
                }
            }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 {
                    xmApproval = {
                        "xmid": data[0].id,
                        "xm": data[0].htmc,
                        "zt": data[0].spzt,
                        "htje": data[0].htje
                    };
                    var index = layer.open({
                        title: '审批意见',
                        type: 2,
                        shade: 0.3,
                        maxmin: true,
                        shadeClose: true,
                        area: ['1020px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjContract/forApproveUpdate/' + data[0].id + '?spzt=' + data[0].spzt,
                        end: function () {
                            if (updateflag == 1)
                                currTable.reload();
                            updateflag = 0;
                            layer.close(index);
                        }
                    });
                }
            }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 {
                    xmApproval = {
                        "xmid": data[0].id,
                        "xm": data[0].htmc
                    };
                    var index = layer.open({
                        title: '审批列表',
                        type: 2,
                        shade: 0.3,
                        maxmin: true,
                        shadeClose: true,
                        area: ['1300px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjContract/forApproveList',
                        end: function () {
                            layer.close(index);
                        }
                    });
                }
            }else if (obj.event === 'tjsp'){
                {
                    var prjContract = table.cache["currentTableId"];
                    if (prjContract.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 {
                        xmApproval = {
                            "xmid": data[0].id,
                            "xm": data[0].htmc,
                            "spzt": data[0].spzt,
                            "htje": data[0].htje
                        };
                        if (data[0].spzt == null) {
                            xmApproval.zt = "未提交";
                            data[0].spzt = "未提交";
                        }

                        var content = AjaxUtil.ctx + 'prjContract/forApproveAdd';
                        if (data[0].spzt != "未提交" && data[0].spzt != "未提交(返回)")
                            content = AjaxUtil.ctx + 'prjContract/forApproveUpdate/' + data[0].id + '?spzt=' + data[0].spzt;

                        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 === 'xgsq'){
                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 {
                    xmApproval = {
                        "spzt": data[0].spzt
                    };
                    var index = layer.open({
                        title: '修改合同',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        area: ['1050px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'prjContract/forXgUpdate/' + data[0].id,
                        end: function (index) {
                            // 重载表格
                            if (updateflag == 1)
                                currTable.reload();
                            updateflag = 0;
                        }
                    });
                }
            }else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                var num;
                AjaxUtil.get({
                    url: AjaxUtil.ctx + "prjContract/getPayApply/"+data[0].id,
                    contentType: "application/json",
                    success: function (res) {
                        console.log(res.data)
                         num = res.data;

                if (data == null || data.length === 0) {
                    Message.warning("请选择要删除的合同！", 1500);
                    return;
                }
                else if (data[0].cjr != userId&&userPostName !='科技项目管理专责'&&userPostName !='科技项目管理专责2'){
                    Message.warning('你不是当前合同创建人，不能删除！',1500);
                    return;
                }
                else if (data[0].spzt !== '未锁定'&&userPostName !='科技项目管理专责'&&userPostName !='科技项目管理专责2'){
                    Message.warning('当前合同已锁定，不能删除',1500);
                    return;
                }else if (num !=0&&userPostName !='科技项目管理专责'&&userPostName !='科技项目管理专责2'){
                    Message.warning("当前合同仍关联"+num+"条付款申请，请先处理关联项！",2000)
                }else {
                layer.confirm('确定删除合同吗？', function (index) {
                    layer.close(index);
                    AjaxUtil.post({
                        url: AjaxUtil.ctx + "prjContract/batchDelete?Id="+ data[0].id,
                        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 === 'export'){

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

                    }
                });
            }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+ "prjContractXg/ViewXGSQ",
                    end: function () {
                        layer.close(index);
                    }
                });
            }
        //     else if (obj.event === 'exportExcel') {
        //         var formData = form.val('search-form');
        //         console.log(formData);
        //         var formDataString = JSON.stringify(formData);
        //         AjaxUtil.post({
        //             url:AjaxUtil.ctx +'prjContract/getAllGL/'+formDataString,
        //             timeout: 15000, //大批量导出时会出现超时问题
        //             success: function(res){
        //                 console.log(res);
        //                 table.exportFile('currentTableId',res.data,'xlsx');
        //             },
        //             error:function (error) {
        //                 Message.error(error,2000)   b
        //             }
        //         });
        });
        table.on('tool(currentTableFilter)',function (obj) {
            var data = obj.data;
            if (obj.event ==='htht'){
                if (userId != 1 && userId != 42){
                    layer.msg("暂无权限!",{icon: 2});
                    return;
                }else if (data.spzt != '已锁定'){
                    layer.msg('数据未锁定，无需回退！',{icon: 2});
                    return;
                }else {
                    AjaxUtil.post({
                        url: AjaxUtil.ctx +'prjContractXg/updateHtht',
                        contentType:"application/json",
                        data: JSON.stringify(data),
                        success: function (res) {
                            if (res.code === 0){
                                layer.msg(res.message,{icon:1});
                                // 表格重载
                                currTable.reload();
                            }
                        },
                        error:function (error) {
                            layer.msg('系统异常，请联系管理员！',{icon:3});

                        }
                    });
                }

            }

        });

        //双击
        table.on('rowDouble(currentTableFilter)', function (obj) {
            data = obj.data;
            var index = layer.open({
                title: '查看合同',
                type: 2,
                shade: 0.2,
                maxmin: true,
                area: ['950px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'prjContract/forView/' + data.id,
                end: function (index) {
                    layer.close(index);
                }
            });
        });
    });

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