<!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 required" style="width: 60px">任务书</label>
                            <div class="layui-input-inline" style="width: 810px">
                                <input type="hidden" id="rws" name="rws" class="layui-input" th:value="${contract.rws}"
                                       readonly>
                                <input type="text" id="rwsmc" name="rwsmc" class="layui-input"
                                       th:value="${contract.rwsmc}" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label required" style="width: 60px">合同名称</label>
                            <div class="layui-input-inline" style="width: 380px">
                                <input type="hidden" id="id" name="id" class="layui-input" th:value="${contract.id}">
                                <input type="text" id="htmc" name="htmc" th:value="${contract.htmc}" class="layui-input"
                                       readonly>
                            </div>
                            <label class="layui-form-label required" style="width: 100px">合同金额(万元)</label>
                            <div class="layui-input-inline" style="width: 290px">
                                <input type="number" id="htje" name="htje" class="layui-input" lay-verify="required"
                                       lay-reqtext="合同金额不能为空" autocomplete="off" th:value="${contract.htje}">
                            </div>
                        </div>

                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label " style="width: 60px">招标批次</label>
                            <div class="layui-input-inline" style="width: 380px">
                                <input type="text" id="zbpc" name="zbpc" autocomplete="off" class="layui-input"
                                       th:value="${contract.zbpc}" readonly>
                            </div>
                            <label class="layui-form-label " style="width: 100px">中选单位</label>
                            <div class="layui-input-inline" style="width: 270px">
                                <input type="text" id="zxdw" name="zxdw" class="layui-input" autocomplete="off"
                                       th:value="${contract.zxdw}" 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: 25%">
                                <input type="text" name="kssj" id="kssj" placeholder="开始时间" class="layui-input" lay-verify="required" lay-reqtext="开始时间不能为空" readonly>
                            </div>
                            <div class="layui-form-mid">-</div>
                            <div class="layui-input-inline" style="width: 25%">
                                <input type="text" name="jssj" id="jssj" placeholder="终止时间" class="layui-input" lay-verify="required" lay-reqtext="结束不能为空" 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: 80%">
                                <input type="hidden" id="rws" name="rws" class="layui-input" th:value="${contract.rws}"
                                       readonly>
                                <input type="text" id="rwsmc" name="rwsmc" class="layui-input"
                                       th:value="${contract.rwsmc}" 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: 25%">
                                <input type="hidden" id="id" name="id" class="layui-input" th:value="${contract.id}" >
                                <input type="text" id="htmc" name="htmc" lay-verify="required" lay-reqtext="合同名称不能为空" autocomplete="off" class="layui-input" th:value="${contract.htmc}">
                            </div>
                            <label class="layui-form-label required" style="width: 15%">合同金额(万元)</label>
                            <div class="layui-input-inline" style="width: 35%">
                                <input type="number" id="htje" name="htje" class="layui-input" lay-verify="required" lay-reqtext="合同金额不能为空"
                                       th:value="${contract.htje}"
                                       autocomplete="off">
                            </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: 25%">
                                <input type="text" id="zbpc" name="zbpc" autocomplete="off" class="layui-input" lay-verify="required" lay-reqtext="招标批次不能为空" th:value="${contract.zbpc}">
                            </div>
                            <label class="layui-form-label" style="width: 15%">中选单位</label>
                            <div class="layui-input-inline" style="width: 35%">
                                <input type="text" id="zxdw" name="zxdw" class="layui-input" autocomplete="off" th:value="${contract.zxdw}" >
                            </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: 25%">
                                <input type="text" name="kssj" id="kssj" placeholder="开始时间" class="layui-input" lay-verify="required" lay-reqtext="开始时间不能为空"
                                       th:value="${contract.kssj}"
                                       readonly>
                            </div>
                            <div class="layui-form-mid">-</div>
                            <div class="layui-input-inline" style="width: 25%">
                                <input type="text" name="jssj" id="jssj" placeholder="终止时间" class="layui-input" lay-verify="required" lay-reqtext="结束不能为空"
                                       th:value="${contract.jssj}"
                                       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: 25%">
                                <input type="text" id="yssj" name="yssj" autocomplete="off" class="layui-input" lay-verify="required" lay-reqtext="招标批次不能为空！" th:value="${contract.yssj}">
                            </div>
                            <label class="layui-form-label required" style="width: 15%">是否是系统内单位</label>
                            <div class="layui-input-inline" style="width: 10%">
                                <input type="text" name="display_sfsxtndw" id="display_sfsxtndw" placeholder="终止时间" class="layui-input" lay-verify="required" lay-reqtext="结束不能为空"
                                       th:value="${contract.sfsxtndw == 0?'是':'否'}"
                                       readonly>
                                <input type="hidden" name="sfsxtndw" id="sfsxtndw"
                                       th:value="${contract.sfsxtndw}">
                            </div>
                        </div>

                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 60px">合同文件</label>
                            <div class="layuimini-container"
                                 style="margin-left: 90px; margin-right: 20px; padding-bottom: 10px">
                                <input type="hidden" id="wj" name="wj" class="layui-input" th:value="${contract.wj}">
                                <div class="layui-btn-group" style="margin-bottom: -8px">
                                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm upload"
                                            id="upLoad1" lay-data="{fileType:'htwj'}"><i class="layui-icon"></i>上传
                                    </button>
                                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm"
                                            lay-filter="deleteFile1"><i class="layui-icon"></i>删除
                                    </button>
                                </div>
                                <table class="layui-hide" id="currentTableId1" name="currentTableId1"
                                       lay-filter="currentTableFilter1"
                                       style="padding-top: 0px;margin-top: 0px"></table>
                                <label>上传招标合同、中标通知书、合同流转单（上传文件形式：word.pdf.excel)。</label>
                            </div>
                        </div>

                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <label class="layui-form-label" style="width: 60px">验收资料</label>
                            <div class="layuimini-container"
                                 style="margin-left: 90px; margin-right: 20px; padding-bottom: 10px">
                                <input type="hidden" id="yszl" name="yszl" class="layui-input"
                                       th:value="${contract.yszl}">
                                <div class="layui-btn-group" style="margin-bottom: -8px">
                                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm upload"
                                            id="upLoad2" lay-data="{fileType:'yszl'}"><i class="layui-icon"></i>上传
                                    </button>
                                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm"
                                            lay-filter="deleteFile2"><i class="layui-icon"></i>删除
                                    </button>
                                </div>
                                <table class="layui-hide" id="currentTableId2" name="currentTableId2"
                                       lay-filter="currentTableFilter2"
                                       style="padding-top: 0px;margin-top: 0px"></table>
                                <label>需上传合同约定的技术报告、测试报告、第三方检测报告、图纸、文宣专利等乙方应提供成果；外委验收意见（包括完成情况表及专家签名）。</label>
                            </div>
                        </div>

                        <!-- 右侧悬浮按钮 -->
                        <div class="right-bottom-btn">
                            <button type="button" class="layui-btn" lay-submit lay-filter="saveBtn">
                                <i class="layui-icon layui-icon-ok"></i>保存
                            </button>
                            <button type="button" class="layui-btn" lay-filter="cancleBtn">
                                <i class="layui-icon layui-icon-close"></i>取消
                            </button>
                        </div>
                    </div>
                </form>
            </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-btn-group" style="margin-bottom: 0.5%">
                            <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm"
                                    lay-filter="btnAdd2"><i class="layui-icon"></i>新建
                            </button>
                            <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm"
                                    lay-filter="btnEdit2"><i class="layui-icon"></i>编辑
                            </button>
                            <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm"
                                    lay-filter="btnView2"><i class="layui-icon">&#xe63c;</i>查看
                            </button>
                            <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm"
                                    lay-filter="btnDelete2"><i class="layui-icon"></i>删除
                            </button>
                        </div>

                        <table class="layui-hide" id="currentTableId3" name="currentTableId3"
                               lay-filter="currentTableFilter3"></table>
                        <div class="layui-form-item layui-inline" style="width: 100%">
                            <div class="layui-input-block" style="margin-left: 1%; width: 85%;">
                                <p style="color: red;">注:现要求付款计划必须一次性填写完成，并且付款计划总金额等于合同金额!!
                                </p>
                            </div>
                        </div>
                        <!-- 右侧悬浮按钮 -->
                        <div class="right-bottom-btn" style="margin-bottom: 5px">
                            <button type="button" class="layui-btn" lay-submit lay-filter="saveBtn2">
                                <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/layui.js}" charset="utf-8"></script>
<script th:src="@{/lib/coco-message/coco-message.js}" charset="utf-8"></script>
<script th:src="@{/lib/xm-select-v1.2.2/xm-select.js}" charset="utf-8"></script>
<script th:src="@{/js/lay-config.js}" charset="utf-8"></script>

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

    layui.use(['form', 'table', 'treeTable', 'layCascader', 'upload','laydate'], function () {
        var form = layui.form,
            table = layui.table,
            layer = layui.layer,
            upload = layui.upload,
            laydate = layui.laydate;

        var htId = $("#id").val();
        var rwsId = $("#rws").val();
        var xmApproval = parent.getXmApproval();
        var spzt =xmApproval.spzt;
        var userPostName = [[${userPostName}]]
        var rwsqssj = [[${rwsqssj}]]
        var rwswcsj = [[${rwswcsj}]]

        console.log(spzt)
        //申请时间
        laydate.render({
            elem: '#kssj',
            done: function (value, date, endDate) {
                sqsj1 = $("#kssj").val();
                sqsj2 = $("#jssj").val();
                yssj = $("#yssj").val();
                if (rwsqssj ==''||rwswcsj==''){
                    layer.msg('请先选择任务书！',{icon:8});
                    $("#kssj").val("");
                    return;
                }
                if (sqsj1<rwsqssj){
                    layer.msg("合同开始时间不能早于任务书开始时间，应该在任务书项目周期内！",{icon:2})
                    $("#kssj").val("");
                    return;
                }
                if (sqsj2 !=''&&sqsj1 == sqsj2){
                    layer.msg('执行周期开始时间与结束时间不能为同一天！',{icon:2});
                    $("#kssj").val("");
                    return;
                }
                if (yssj != ''){
                    if (sqsj1 > yssj){
                        layer.msg('验收时间不能早于或等于合同开始时间！',{icon:2});
                        $("#kssj").val("");
                        return;
                    }
                }
                if (sqsj1 != "" && sqsj2 != "") {
                    if (sqsj1 > sqsj2) {
                        Message.warning("起始时间不能晚于终止时间！", 1500);
                        $("#kssj").val("");
                        return;
                    }
                }
            }
        });
        laydate.render({
            elem: '#jssj',
            done: function (value, date, endDate) {
                sqsj1 = $("#kssj").val();
                sqsj2 = $("#jssj").val();
                const currentDate = new Date();
                const sqsj3 = new Date(sqsj2);
                if (rwsqssj ==''||rwswcsj==''){
                    layer.msg('请先选择任务书！',{icon:8});
                    $("#jssj").val("");
                    return;
                }
                if (sqsj2>rwswcsj){
                    layer.msg("合同结束时间不能晚于任务书结束时间，应该在任务书项目周期内！",{icon:2})
                    $("#jssj").val("");
                    return;
                }
                if (sqsj1!=''&&sqsj1 == sqsj2){
                    layer.msg('执行周期开始时间与结束时间不能为同一天！',{icon:2});
                    $("#jssj").val("");
                    return;
                }
                if (sqsj1 != "" && sqsj2 != "") {
                    if (sqsj1 > sqsj2) {
                        Message.warning("终止时间不能早于开始时间！", 1500);
                        $("#jssj").val("");
                        return;
                    }
                }

            }
        });
        laydate.render({
            elem: '#yssj',
            done: function (value, date, endDate) {
                sqsj1 = $("#kssj").val();
                sqsj2 = $("#jssj").val();
                yssj = $("#yssj").val();
                if (sqsj1 != '' && yssj != ''){
                    if (yssj <= sqsj1){
                        layer.msg('验收时间不能早于或等于合同开始时间！',{icon:2});
                        $("#yssj").val("");

                    }
                }else {
                    layer.msg('请先填写执行周期！',{icon:8});
                    $("#yssj").val("");
                }

            }
        });

        // 用于存放表格数据
        var dataHtwj = new Array();
        if ([[${contract.wj}]] != null && [[${contract.wj}]] != "") {
            dataHtwj = eval('(' + [[${contract.wj}]] + ')');
        }
        //合同文件
        var currTable1 = table.render({
            elem: '#currentTableId1',
            data: dataHtwj,
            cols: [
                [
                    {type: "radio", fixed: 'left'},
                    {field: 'wjm', title: '文件名', width: '40%'},
                    {field: 'scrq', title: '上传日期', width: '15%', align: 'center'},
                    {field: 'sm', title: '说明', edit: 'text'}
                ]
            ],
            autoSort: false,

            limit: Number.MAX_VALUE,
            page: false,
            skin: 'grid',
            done: function (res, curr, count) { // done为数据渲染完的回调
            }
        });
        //文件上传
        upload.render({
            elem: '#upLoad1' //绑定元素
            , url: AjaxUtil.ctx + 'fileupload/upload'
            , methd: 'post'
            , accept: 'file'
            , data: {}
            , done: function (res) {
                if (0 === res.code) {
                    var curData = {
                        "wjm": res.data.fileName,
                        "scrq": res.data.fileDate,
                        "Url": res.data.fileUrl,
                        "sm": res.data.sm
                    };
                    dataHtwj.push(curData);
                    currTable1.reload();
                } else
                    layer.alert("上传文件出现错误！");
            }
            , error: function () {
                layer.alert("上传文件出现错误！");
            }
            , before: function (res) {
                let fileType = this.fileType;
                this.data.fileType = fileType;
            }
        });
        $("button[lay-filter='deleteFile1']").click(function () {
            if (dataHtwj.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId1')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要删除的文件！", 1000);
                return;
            }
            for (var i = 0; i < dataHtwj.length; i++) {
                var item = dataHtwj[i];
                if (item.LAY_CHECKED) {//条件：选中
                    dataHtwj.splice(i, 1);//移除后后造成数组下标索引发生变化，所以下面需要i--
                    i--;
                }
            }
            //刷新表格
            currTable1.reload();
        });

        //双击（合同文件）
        table.on('rowDouble(currentTableFilter1)', function (obj) {
            window.open(obj.data.Url);
        });


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

        //文件上传
        upload.render({
            elem: '#upLoad2' //绑定元素
            , url: AjaxUtil.ctx + 'fileupload/upload'
            , methd: 'post'
            , accept: 'file'
            , data: {}
            , done: function (res) {
                if (0 === res.code) {
                    var curData = {
                        "wjm": res.data.fileName,
                        "scrq": res.data.fileDate,
                        "Url": res.data.fileUrl,
                        "sm": res.data.sm
                    };
                    dataYszl.push(curData);
                    currTable2.reload();
                } else
                    layer.alert("上传文件出现错误！");
            }
            , error: function () {
                layer.alert("上传文件出现错误！");
            }
            , before: function (res) {
                let fileType = this.fileType;
                this.data.fileType = fileType;
            }
        });
        $("button[lay-filter='deleteFile2']").click(function () {
            if (dataYszl.length == 0)
                return;

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

        // 监听确认按钮(常规)
        form.on('submit(saveBtn)', function (data) {
            if (spzt !=='未锁定'&&userPostName !='科技项目管理专责'&&userPostName !='科技项目管理专责2'){
                Message.warning("该合同状态为锁定中，只能修改付款计划，不可修改常规信息！", 2000);
                return false;
            }
            //合同文件
            var dataWB_Htwj = [];
            for (const item of dataHtwj) {
                var dfWb = {
                    "id": item.id,
                    "wjm": item.wjm,
                    "Url": item.Url,
                    "scrq": item.scrq,
                    "sm": item.sm
                };
                dataWB_Htwj.push(dfWb);
            }
            $("#wj").val(JSON.stringify(dataWB_Htwj));
            data.field.wj = JSON.stringify(dataWB_Htwj);

            //验收资料
            var dataWB_Yszl = [];
            for (const item of dataYszl) {
                var dfWb = {
                    "id": item.id,
                    "wjm": item.wjm,
                    "Url": item.Url,
                    "scrq": item.scrq,
                    "sm": item.sm
                };
                dataWB_Yszl.push(dfWb);
            }
            $("#yszl").val(JSON.stringify(dataWB_Yszl));
            data.field.yszl = JSON.stringify(dataWB_Yszl);

            var url = AjaxUtil.ctx + "prjContract/doUpdate";
            if (htId == -1)
                url = AjaxUtil.ctx + "prjContract/doAdd";

            var index = layer.load(0, {shade: 0.1});
            AjaxUtil.post({
                url: url,
                data: data.field,
                success: function (res) {
                    if (res.code === 0) {
                        if (htId == -1) {
                            htId = res.data.id;
                            $("#id").val(htId);
                        }
                        parent.setUpdateFlag();
                        Message.success(res.message, 1000);
                    } else {
                        Message.error(res.message, 1000);
                    }
                    layer.close(index);
                },
                error: function (error) {
                    Message.error(error.message, 1000)
                }
            });

            return false;

            //验收资料
            var dataWB_Yszl = [];
            for (const item of dataYszl) {
                var dfWb = {
                    "id": item.id,
                    "wjm": item.wjm,
                    "Url": item.Url,
                    "scrq": item.scrq,
                    "sm": item.sm
                };
                dataWB_Yszl.push(dfWb);
            }
            $("#yszl").val(JSON.stringify(dataWB_Yszl));
            data.field.yszl = JSON.stringify(dataWB_Yszl);

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

            return false;
        });

        var dataFkjh = [[${dataFkjh}]]

        //付款计划
        var currTable3 = table.render({
            elem: '#currentTableId3',
            // url: AjaxUtil.ctx + 'prjPayplan/list/' + htId,
            // method: 'post',
            data: dataFkjh,
            cols: [
                [
                    {type: "checkbox"},
                    {type: 'numbers', align: 'center',title: '序号'},
                    {field: 'jhmc', title: '计划名称', width: '15%'},
                    {field: 'fkyq', title: '付款要求', width: '20%'},
                    {field: 'zfbl', title: '支付比例（%）', width: '14%'},
                    {field: 'zfje', title: '支付金额（万元）', width: '16%'},
                    {field: 'cjsj', title: '创建时间', align: 'center'},
                    {field: 'countpay', title: '关联付款申请', hide: true}
                ]
            ],
            autoSort: false,
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.rows //解析数据列表
                };
            }
        });
        //监听合同金额
        $("#htje").blur(function (e) {
            var htje = parseFloat(e.delegateTarget.value);
            if (htje < 0) {
                alert("金额不能为负数或无效的数字，请重新输入！");
                e.delegateTarget.value = "";
            }else if (htje>1000){
                alert("合同金额单位为万元，请确认当前数据无误。")
            }
        });
        // 监听新建按钮(付款计划)
        $("button[lay-filter='btnAdd2']").click(function () {
            htInfo = {
                "rws": rwsId,
                "ht": htId,
                "htje": $("#htje").val()
            }
            layer.open({
                title: '新建付款计划',
                type: 2,
                maxmin: true,
                shade: 0.2,
                area: [layerwidth + 'px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'prjPayplan/forAdd',
                end: function (index) {
                    // 重载表格
                    if (updateflag == 1)
                        // currTable3.reload()
                        var oldData = table.cache["currentTableId3"];
                    console.log('新建前'+oldData)
                    oldData.push(fkjh);
                    console.log('新建后'+oldData)
                    if (oldData != '' && oldData !=null) {
                        table.reload('currentTableId3', {
                            data: oldData,
                        })
                    }
                    updateflag = 0;
                }
            });
        });
        // 监听编辑按钮(付款计划)
        $("button[lay-filter='btnEdit2']").click(function () {
            var subTopics = table.cache["currentTableId3"];
            if (subTopics.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId3')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要编辑的付款计划！", 1500);
            } else if (data.length > 1) {
                Message.warning("请选择一条记录进行编辑！", 1500);
            } else {
                htInfo = {
                    "htje": $("#htje").val()
                }
                fkjh = {
                    'id':data[0].id,
                    'fysq':data[0].fysq,
                    'rws':data[0].rws,
                    'ht':data[0].ht,
                    'cjr':data[0].cjr,
                    'jhmc':data[0].jhmc,
                    'fkyq':data[0].fkyq,
                    'zfbl':data[0].zfbl,
                    'zfje':data[0].zfje,
                    'cjsj':data[0].cjsj,
                    'fkxx':data[0].fkxx,
                }
                layer.open({
                    title: '编辑付款计划',
                    type: 2,
                    maxmin: true,
                    shade: 0.2,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'prjPayplan/forUpdate',
                    end: function (index) {
                        // 重载表格
                        if (updateflag == 1)
                            console.log('编辑前'+subTopics)
                        updateflag = 0;
                        for (var i = 0; i < subTopics.length; i++) {
                            var item = subTopics[i];
                            if (item.LAY_CHECKED) {//选中
                                subTopics[i] = fkjh;
                                break;
                            }
                        }
                        //刷新表格
                        var currData = subTopics;
                        console.log('编辑后'+currData)
                        console.log(currData)
                        table.reload('currentTableId3', {
                            data: currData
                        });
                    }
                });
            }
        });
        // 监听查看按钮(付款计划)
        $("button[lay-filter='btnView2']").click(function () {
            var subTopics = table.cache["currentTableId3"];
            if (subTopics.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId3')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要浏览的付款计划！", 1500);
            } else if (data.length > 1) {
                Message.warning("请选择一条记录进行浏览！", 1500);
            } else {
                fkjh = {
                    'jhmc':data[0].jhmc,
                    'fkyq':data[0].fkyq,
                    'zfbl':data[0].zfbl,
                    'zfje':data[0].zfje,
                    'cjsj':data[0].cjsj,
                    'fkxx':data[0].fkxx,
                }
                layer.open({
                    title: '浏览付款计划',
                    type: 2,
                    maxmin: true,
                    shade: 0.2,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'prjPayplan/forView1',
                    end: function () {
                    }
                });
            }
        });
        // 监听删除按钮(付款计划)
        $("button[lay-filter='btnDelete2']").click(function () {
            var subTopics = table.cache["currentTableId3"];
            if (subTopics.length == 0)
                return;
            var checkStatus = table.checkStatus('currentTableId3')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要删除的付款计划！", 1500);
            } else {
                var failedItems = data.filter(item => item.countpay > 0);

                if (failedItems.length > 0) {
                    var failedMessages = failedItems.map(item => `计划名称: ${item.jhmc}, 关联的付款计划个数: ${item.countpay}`).join(', ');
                    Message.warning(`删除失败：以下付款计划已经付款: ${failedMessages}`, 1500);
                } else {
                    layer.confirm('确定删除所选中的付款计划吗？', function (index) {
                        layer.close(index);
                        for (var i = 0; i < subTopics.length; i++) {
                            var item = subTopics[i];
                            if (item.LAY_CHECKED) {//条件：选中
                                subTopics.splice(i, 1);//移除后后造成数组下标索引发生变化，所以下面需要i--
                                i--;
                            }
                        }
                        //刷新表格
                        var currData = subTopics;
                        table.reload('currentTableId3', {
                            data: currData
                        });
                    });
                }
            }
        });
        //双击（付款计划）
        table.on('rowDouble(currentTableFilter3)', function (obj) {
            var data = obj.data;
            fkjh = {
                'jhmc':data.jhmc,
                'fkyq':data.fkyq,
                'zfbl':data.zfbl,
                'zfje':data.zfje,
                'cjsj':data.cjsj,
                'fkxx':data.fkxx,
            }
            layer.open({
                title: '浏览付款计划',
                type: 2,
                maxmin: true,
                shade: 0.2,
                area: [layerwidth + 'px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'prjPayplan/forView1',
                end: function (index) {
                    layer.close(index);
                }
            });
        });
        //监听付款计划保存按钮
        form.on('submit(saveBtn2)', function (data) {
            var subTopics = table.cache["currentTableId3"];
            var htje =parseFloat($("#htje").val())
            var prjPayplanList =[];
            var count = 0;
            var sum = 0;
            if (!subTopics && subTopics.length === 0) {
                Message.warning("请先创建付款计划！！！", 1500);
                return;
            }
            for (let i = 0; i < subTopics.length; i++) {
                let zfje = parseFloat(subTopics[i].zfje) || 0;
                let scaledValue = (zfje * 100000).toFixed(8);
                sum += parseFloat(scaledValue);
            }
            count =sum/100000;
            for (const item of subTopics) {
                var prjPayplan = {
                    "id":item.id,
                    "fkxx": item.fkxx,
                    "fkyq": item.fkyq,
                    "ht": item.ht,
                    "jhmc": item.jhmc,
                    "rws": item.rws,
                    "zfbl": item.zfbl,
                    "zfje": item.zfje,
                };
                prjPayplanList.push(prjPayplan);
            }
            console.log(sum)
            console.log(count)
            console.log(htje)
            console.log(subTopics)
            if (count>htje){
                Message.warning("付款计划付款总金额大于合同金额！！！", 1500);
                return;
            }else if (count<htje){
                Message.warning("付款计划付款总金额小于合同金额！！！", 1500);
                return;
            }else {
                var index = layer.load(0, {shade: 0.1});
                AjaxUtil.post({
                    url: AjaxUtil.ctx + "prjPayplan/doAdd1/?htje="+htje,
                    contentType: "application/json",
                    data: JSON.stringify(prjPayplanList),
                    success: function (res) {
                        // layer.msg(res.message);
                        Message.success(res.message,1500)
                        layer.close(index);

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

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

    function getHtInfo() {
        return htInfo;
    }
    function getFkjh() {
        return fkjh;
    }
    function setFkjh(expense) {
        fkjh = expense;
    }
    function setUpdateFlag() {
        updateflag = 1;
    }
</script>
</body>
</html>