<!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-form layuimini-form" style="padding-bottom: 100px">
        <input type="hidden" id="id" name="id" class="layui-input" th:value="${payapproval.id}">
        <div class="layui-form-item layui-inline" style="width: 100%">
           <!-- <label class="layui-form-label" style="width: 10%">费用申请</label>-->
            <div class="layui-input-inline" style="width: 80%">
                <input type="hidden" id="fysq" name="fysq" class="layui-input" th:value="${payapproval.fysq}" readonly>
                <!--<input type="text" id="fysqmc" name="fysqmc" class="layui-input" th:value="${payapproval.fysqmc}"
                       readonly>-->
            </div>
        </div>
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label" style="width: 10%">任务书</label>
            <div class="layui-input-inline" style="width: 80%">
                <input type="text" id="rwsmc" name="rwsmc" class="layui-input" th:value="${payapproval.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: 30%">
                <input type="text" id="htmc" name="htmc" class="layui-input" th:value="${payapproval.htmc}" disabled readonly>
               <!-- <select name="ht" id="ht" lay-filter="ht" lay-verify="required" lay-reqtext="合同不能为空">
                    <option value="">&#45;&#45; 请选择 &#45;&#45;</option>
                    <option th:each="item:${htList}" th:text="${item.htmc}" th:value="${item.id}"></option>
                </select>-->
            </div>
            <label class="layui-form-label required" style="width: 15%">合同金额(万元)</label>
            <div class="layui-input-inline" style="width: 30%">
                <input type="number" id="htje" name="htje" class="layui-input" lay-verify="required"
                       lay-reqtext="合同金额不能为空" autocomplete="off" th:value="${payapproval.htje}" 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: 30%">
                <input type="text" id="fkjhmc" name="fkjhmc" class="layui-input" th:value="${payapproval.fkjhmc}+' / '+${payapproval.zfje}+'/'+${payapproval.yfkje}"
                       disabled readonly>
                <!--<select name="fkjh" id="fkjh" lay-filter="fkjh" lay-verify="required" lay-reqtext="付款计划不能为空">
                    <option th:each="item:${payplanList}"
                            th:text="${item.jhmc} + ' / ' + ${item.zfje}+' / '+${item.yfkje}"
                            th:value="${item.id}"
                            th:attr="disabled=${item.yfkje > item.zfje ? 'disabled' : null}">
                    </option>
                </select>-->
            </div>
            <label class="layui-form-label required" style="width: 15%">本次付款金额(万元)</label>
            <div class="layui-input-inline" style="width: 30%">
                <input type="number" id="bcfkje" name="bcfkje" class="layui-input" lay-verify="required"
                       lay-reqtext="本次付款金额不能为空" autocomplete="off" th:value="${payapproval.bcfkje}">
            </div>
        </div>
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label" style="width: 10%">合同文件</label>
            <div class="layuimini-container" style="margin-left: 90px; margin-right: 20px; padding-bottom: 10px">
                <input type="hidden" id="htwj" name="htwj" class="layui-input" th:value="${payapproval.htwj}">
                <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:'payhtwj'}"><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>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="btnView2"><i
                            class="layui-icon">&#xe63c;</i>查看
                    </button>
                </div>
                <table class="layui-hide" id="currentTableId1" name="currentTableId1" lay-filter="currentTableFilter1"
                       style="padding-top: 0px;margin-top: 0px"></table>
                <label>请在合同管理中修改文件</label>
            </div>
        </div>
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label" style="width: 10%">验收资料</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="${payapproval.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:'payyszl'}"><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>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="btnView2"><i
                            class="layui-icon">&#xe63c;</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>

<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 travelExpense = [];//差旅费
    var updateflag = 0;//更新标志

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

        //下拉框回显
        function set_select(id, value) {
            let obj = $("#" + id)
            obj.find("option:contains('" + value + "')").attr("selected", true)
            obj.parent().find(".layui-select-title").find("input").val(value)
        }

        if ($("#htmc").val() != null && $("htmc").val() != "")
            set_select('ht', $("#htmc").val());
        if ($("#fkjhmc").val() != null && $("fkjhmc").val() != "")
            set_select('fkjh', $("#fkjhmc").val());

        //监听合同
        form.on('select(ht)', function (data) {
            var len = $("#fkjh")[0].length;
            while (len > 1)
                $("#fkjh")[0].options[--len].remove();

            if (data.value == "") {
                $("#htje").val("");
            } else {
                var htList = [[${htList}]];
                for (let ht of htList) {
                    if (ht.id == data.value) {
                        $("#htje").val(ht.htje);
                        break;
                    }
                }

                // $.ajax({
                //     url: AjaxUtil.ctx + 'prjPayplan/list/' + data.value,
                //     type: "post",
                //     async: false,
                //     dataType: "json",
                //     success: function (result) {
                //         var dataFkjh = result.data.rows;
                //         console.log('list'+result);
                //         // 假设data是包含合同数据的数组
                //         // 通过id获取select元素的DOM对象
                //         console.log(dataFkjh);
                //         var selectElement = document.getElementById('fkjh');
                //         // 清空select元素的选项
                //         selectElement.innerHTML = '';
                //         dataFkjh.forEach(function(item) {
                //             var optionElement = document.createElement('option');
                //             optionElement.value = item.id;
                //             console.log(item.yfkje)
                //             if (item.yfkje==item.zfje){
                //                 optionElement.disabled = true; // 设置为不可选择
                //             }else if (item.yfkje>item.zfje){
                //                 optionElement.disabled = true; // 设置为不可选择
                //                 alert('该合同下名称为'+item.jhmc+'的付款计划关联的付款申请，总付款额大于付款计划金额，已付款金额为'+item.yfkje+'万元，请联系系统管理员处理该问题！！')
                //             }
                //             if (item.yfkje==null){
                //                 item.yfkje = 0
                //             }
                //             optionElement.innerText = item.jhmc+' / '+item.zfje+'/'+item.yfkje;
                //             selectElement.appendChild(optionElement);
                //         });
                //
                //     }
                // });
            }
            $("#fkjh").val(0);
            form.render('select');

            return false;
        });

        $("#bcfkje").blur(function (e) {
            var bcfkje = parseFloat(e.delegateTarget.value);

            if (bcfkje < 0) {
                alert("金额不能为负数或无效的数字，请重新输入！");
                e.delegateTarget.value = "";
            }else if (bcfkje>1000){
                alert("本次付款金额单位为万元，请确认当前数据无误。")
            }
        });

        // 用于存放表格数据
        var dataHtwj = new Array();
        if ([[${payapproval.htwj}]] != null && [[${payapproval.htwj}]] != "") {
            dataHtwj = eval('(' + [[${payapproval.htwj}]] + ')');
        }
        //合同文件
        var currTable1 = table.render({
            elem: '#currentTableId1',
            data: dataHtwj,
            cols: [
                [
                    {type: "checkbox", align: 'center'},
                    {type: 'numbers', align: 'center',title: '序号'},
                    {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: 10,
            page: true,
            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();
        });
        $("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 ([[${payapproval.yszl}]] != null && [[${payapproval.yszl}]] != "") {
            dataYszl = eval('(' + [[${payapproval.yszl}]] + ')');
        }
        //验收资料
        var currTable2 = table.render({
            elem: '#currentTableId2',
            data: dataYszl,
            cols: [
                [
                    {type: "checkbox", align: 'center'},
                    {type: 'numbers', align: 'center',title: '序号'},
                    {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: 10,
            page: true,
            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) {
            const  htje = document.getElementById('htje').value;/*
            var selectElement = document.getElementById("fkjh");
            var selectedText = selectElement.options[selectElement.selectedIndex].text.split('/');*/
            const fysq = document.getElementById('fysq').value;
            const bcfkje = parseFloat(document.getElementById('bcfkje').value);
            var oldbcfkje = [[${payapproval.bcfkje}]];
            const jhfke = [[${payapproval.zfje}]];
            const  yfkje = [[${payapproval.yfkje}]];
            var fkje;
            var bzje;
            var fymc;/*
            if (bcfkje > selectedText[1].replace(/\s+/g, '')){
                Message.warning('本次付款金额，不能大于付款计划金额！',2000);
                return ;
            }*/
            console.log(jhfke);
            if (bcfkje > jhfke){
                layer.msg('本次付款金额，不能大于付款计划金额！',{icon:2},function () {
                    return false;
                });
            }else
            if (bcfkje+parseFloat(yfkje)-oldbcfkje > jhfke ){
                Message.warning('该付款计划下已申请付款金额加上本次付款金额，大于付款计划金额！',2000);
                return ;
            }else
            if ( (fkje-oldbcfkje+bcfkje) > bzje){
                layer.msg('该项目费用类别为'+fymc+' 下的付款申请总金额已超出总报账金额，已申请的付款金额为:'+(fkje-oldbcfkje)+'万元，报账金额为：'+bzje+'万元',{icon:2},function () {
                    return;
                });
            }else {
                $.ajax({
                    url: AjaxUtil.ctx + 'staBudgetapproval/getKmze/?id='+fysq,
                    type: "post",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        if (result.code == 0){
                            var kmze = result.data;
                            if (kmze.length > 0){
                                var kmzes = kmze[0];
                                fkje = kmzes.yfze;
                                bzje = kmzes.bzze;
                                fymc = kmzes.fymc;
                            }
                        }else if (result.code == -1){
                            layer.msg(result.message,{icon:2},function (){
                                return false;
                            })
                        }

                    }
                })
                console.log(fkje);
                console.log(bzje);
                console.log(oldbcfkje)
                console.log(bcfkje)
                console.log(fkje-oldbcfkje+bcfkje)
                console.log((fkje-oldbcfkje+bcfkje) > bzje)
                //合同文件
                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);
                }
                $("#htwj").val(JSON.stringify(dataWB_Htwj));
                data.field.htwj = 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 index = layer.load(0, {shade: 0.1});
                AjaxUtil.post({
                    url: AjaxUtil.ctx + "staPayapproval/doUpdate?id="+[[${payapproval.id}]],
                    data: data.field,
                    success: function (res) {
                        setTimeout(() => {
                            if (res.code === 0) {
                                layer.msg(res.message,{icon:1},function () {
                                    parent.setUpdateFlag();
                                });
                            }else if (res.code === 1){
                                layer.msg(res.message,{icon:2},function () {
                                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                                })
                            }
                        }, 1500);

                    },
                    error: function (error) {
                        Message.error(error.message, 1000)
                    }
                });
                return false;
            }
        });

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

    function setTravelExpense(expense) {
        travelExpense = expense;
    }

    function getTravelExpense() {
        return travelExpense;
    }

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