<!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">-->
    <!--                <form class="layui-form" action="" lay-filter="formDemo">-->
    <div class="layui-form layuimini-form" style="padding-bottom: 100px">
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label required" style="width: 80px">年份</label>
            <div class="layui-input-inline" style="width: 360px">
                <input type="hidden" name="zb" id="zb" class="layui-input" th:value="${xm}">
                <input type="hidden" name="qs" id="qs" class="layui-input" th:value="${qs}">
                <input type="hidden" name="wc" id="wc" class="layui-input" th:value="${wc}">
                <input type="hidden" id="ysjecz" name="ysjecz" class="layui-input" th:value="${ysjecz}">
                <input type="number" id="nf" name="nf" maxlength="4" lay-verify="required" lay-reqtext="年份不能为空"
                       class="layui-input">
            </div>
         <!--   <label class="layui-form-label " style="width: 80px">序号</label>
            <div class="layui-input-inline" style="width: 360px">
                <input type="text" id="xh" name="xh" autocomplete="off" class="layui-input">
            </div>-->
        </div>
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label required" style="width: 80px">出资单位</label>
            <div class="layui-input-inline" style="width: 360px">
                <input type="hidden" name="czdw" id="czdw" class="layui-input">
                <input type="text" id="dwmc" name="dwmc" lay-verify="required" lay-reqtext="出资单位不能为空"
                       class="layui-input" readonly>
            </div>
            <label class="layui-form-label required" style="width: 80px">出资金额(万)</label>
            <div class="layui-input-inline" style="width: 360px">
                <input type="number" id="czje" name="czje" lay-verify="required" lay-reqtext="出资金额不能为空"
                       class="layui-input" readonly>
            </div>
        </div>
        <div class="layui-form-item layui-inline" style="width: 100%">
            <label class="layui-form-label" style="width: 80px">承担单位</label>
            <div class="layuimini-container" style="width: 840px; margin-left: 109px">
                <div id="toolbarSheme" class="layui-btn-group" style="margin-bottom: -8px">
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subAdd"><i
                            class="layui-icon"></i>新建
                    </button>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subEdit"><i
                            class="layui-icon"></i>编辑
                    </button>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subView"><i
                            class="layui-icon">&#xe63c;</i>查看
                    </button>
                    <button type="button" class="layui-btn  layui-btn-primary layui-btn-sm" lay-filter="subDelete"><i
                            class="layui-icon"></i>删除
                    </button>
                </div>
                <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"
                       style="padding-top: 0px;margin-top: 0px"></table>
            </div>
        </div>

        <!-- 右侧悬浮按钮 -->
        <div class="right-bottom-btn">
            <button class="layui-btn" lay-submit lay-filter="saveBtn">
                <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 id="tpl1" type="text/html">
    <input type="text" id="mc" name="mc" lay-verify="required" lay-reqtext="单位不能为空" class="layui-input">
</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="@{/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 czfaId = -1;
    var updateflag = 0;
    var cdCompany = [];
    layui.use(['form', 'table', 'tableSelect'], function () {
        var form = layui.form,
            table = layui.table,
            layer = layui.layer,
            tableSelect = layui.tableSelect;
        $("#nf").val(new Date().getFullYear());

        //出资单位
        tableSelect.render({
            elem: '#dwmc',
            checkedKey: 'id',
            searchKey: 'mc',
            searchPlaceholder: '搜索单位',
            table: {
                url: AjaxUtil.ctx + 'baseCompany/dwlist',
                cols: [
                    [
                        {type: 'radio',title: '😊'},
                        {type: 'numbers', align: 'center',title: '序号'},
                        {field: 'mc', title: '单位',width:'80%'}
                    ]
                ]
            },
            done: function (elem, data) {
                var NEWJSON = [];
                var NEWJSON1 = [];
                layui.each(data.data, function (index, item) {
                    NEWJSON.push(item.mc);
                    NEWJSON1.push(item.id);
                });
                elem.val(NEWJSON.join(","));
                $("#czdw").val(NEWJSON1.join(","));
            }
        });

        // 用于存放表格数据
        var tableData = new Array();
        //承担单位
        table.render({
            elem: '#currentTableId',
            data: tableData,
            cols: [
                [
                    {type: "checkbox"},
                    {type: 'numbers', align: 'center',title: '序号',width: '8%'},
                    {field: 'dwmc', title: '单位', width: '40%'},
                    {field: 'skje', title: '收款金额(万)', width: '18%'},
                    {field: 'bz', title: '备注', width: '20%'}
                ]
            ],
            autoSort: true,
            initSort: {
                field: 'xh', //排序字段
                type: 'asc' //排序方式:desc 降序,asc 升序
            }
        });
        //监听新建按钮（承担单位）
        $("button[lay-filter='subAdd']").click(function () {
            var index = layer.open({
                title: '新建承担单位',
                type: 2,
                // maxmin: true,
                shade: 0.2,
                area: [layerwidth + 'px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'prjUndertakecompany/forAdd/' + parseInt($("#zb").val()) + '?ysjecz=' + $("#ysjecz").val() + '&czjecz=' + $("#czje").val(),
                end: function (index) {
                    if (updateflag == 1) {
                        updateflag = 0;
                        var oldData = table.cache["currentTableId"];

                        var item = {
                            "xh": cdCompany.xh,
                            "dw": cdCompany.dw,
                            "dwmc": cdCompany.dwmc,
                            "skje": cdCompany.skje,
                            "bz": cdCompany.bz
                        };
                    }
                    console.log(oldData);
                    //刷新表格
                    oldData.push(item);
                    table.reload('currentTableId', {
                        data: oldData
                    });

                    //出资金额
                    var czje = 0;
                    for (let item of oldData) {
                        czje += parseFloat(item.skje);
                    }
                    $("#czje").val(czje);

                }
            });
        });
        // 监听编辑按钮(承担单位）
        $("button[lay-filter='subEdit']").click(function () {
            var companys = table.cache["currentTableId"];
            if (companys.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 {
                cdCompany = {
                    "xh": data[0].xh,
                    "dw": data[0].dw,
                    "dwmc": data[0].dwmc,
                    "skje": data[0].skje,
                    "bz": data[0].bz
                };

                var index = layer.open({
                    title: '编辑承担单位',
                    type: 2,
                    // maxmin: true,
                    shade: 0.2,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'prjUndertakecompany/forUpdate',
                    end: function (index) {
                        if (updateflag == 1) {
                            updateflag = 0;
                            var oldData = table.cache["currentTableId"];

                            var currCompany = {
                                "xh": cdCompany.xh,
                                "dw": cdCompany.dw,
                                "dwmc": cdCompany.dwmc,
                                "skje": cdCompany.skje,
                                "bz": cdCompany.bz
                            };

                            for (var i = 0; i < oldData.length; i++) {
                                var item = oldData[i];
                                if (item.LAY_CHECKED) {//条件：选中
                                    oldData.splice(i, 1);//移除后后造成数组下标索引发生变化，所以下面需要i--
                                    break;
                                }
                            }
                            //刷新表格
                            var currData = oldData;
                            currData.push(currCompany);
                            table.reload('currentTableId', {
                                data: currData
                            });

                            //出资金额
                            var czje = 0;
                            for (let item of currData) {
                                czje += parseFloat(item.skje);
                            }
                            $("#czje").val(czje);
                        }
                    }
                });
            }
        });
        // 监听查看按钮(承担单位）
        $("button[lay-filter='subView']").click(function () {
            var companys = table.cache["currentTableId"];
            if (companys.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 {
                cdCompany = {
                    "xh": data[0].xh,
                    "dw": data[0].dw,
                    "dwmc": data[0].dwmc,
                    "skje": data[0].skje,
                    "bz": data[0].bz
                };

                var index = layer.open({
                    title: '浏览承担单位',
                    type: 2,
                    // maxmin: true,
                    shade: 0.2,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'prjUndertakecompany/forView'
                });
            }
        });
        // 监听删除按钮（承担单位）
        $("button[lay-filter='subDelete']").click(function () {
            var companys = table.cache["currentTableId"];
            if (companys.length == 0)
                return;

            var checkStatus = table.checkStatus('currentTableId')
                , data = checkStatus.data;
            if (data == null || data.length === 0) {
                Message.warning("请选择要删除的单位！", 1000);
                return;
            }

            var oldData = table.cache["currentTableId"];
            for (var i = 0; i < oldData.length; i++) {
                var item = oldData[i];
                if (item.LAY_CHECKED) {//条件：选中
                    oldData.splice(i, 1);//移除后后造成数组下标索引发生变化，所以下面需要i--
                    i--;
                }
            }
            var currData = oldData;
            table.reload('currentTableId', {
                data: currData
            });

            //出资金额
            if (currData.length == 0)
                $("#czje").val('');
            else {
                var czje = 0;
                for (let item of currData) {
                    czje += parseFloat(item.skje);
                }
                $("#czje").val(czje);
            }
        });
        //双击（承担单位）
        table.on('rowDouble(currentTableFilter)', function (obj) {
            var data = obj.data;
            cdCompany = {
                "xh": data.xh,
                "dw": data.dw,
                "dwmc": data.dwmc,
                "skje": data.skje,
                "bz": data.bz
            };

            var index = layer.open({
                title: '浏览承担单位',
                type: 2,
                // maxmin: true,
                shade: 0.2,
                area: [layerwidth + 'px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'prjUndertakecompany/forView',
                end: function () {
                    layer.close(index);
                }
            });
        });

        // 监听确认按钮
        form.on('submit(saveBtn)', function (data) {
            var nf = $("#nf").val();
            var qs = $("#qs").val();
            var wc = $("#wc").val();
            if (nf < qs || nf > wc) {
                Message.error(nf + "不在项目起止时间内！", 1500);
                return false;
            }


            var url = AjaxUtil.ctx;
            if (czfaId == -1)
                url += "prjFeescheme/doAdd";
            else
                url += "prjFeescheme/doUpdate";

            //基本信息
            var index = layer.load(0, {shade: 0.1});
            AjaxUtil.post({
                url: url,
                data: data.field,
                success: function (res) {
                    layer.close(index);
                    if (res.code === 0) {
                        Message.success(1500, res.message, function () {
                            czfaId = res.data.id;
                            $("#id").val(czfaId);
                            parent.setUpdateFlag();

                            //承担单位
                            var companys = [];
                            var oldCompanys = table.cache["currentTableId"];
                            for (const item of oldCompanys) {
                                var company = {
                                    "zb": czfaId,
                                    "xh": item.xh,
                                    "dw": item.dw,
                                    "dwmc": item.dwmc,
                                    "skje": item.skje,
                                    "bz": item.bz
                                };
                                companys.push(company);
                            }
                            AjaxUtil.post({
                                url: AjaxUtil.ctx + "prjUndertakecompany/batchInsert/" + czfaId,
                                contentType: "application/json",
                                data: JSON.stringify(companys),
                                success: function (res) {
                                    if (res.code === 0) {
                                        // Message.success(1500, res.message, function () {
                                        //
                                        // });
                                    } else {
                                        // Message.error(res.message, 1000);
                                    }
                                },
                                error: function (error) {
                                }
                            });

                            //关闭当前层
                            var iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                        });
                    } else {
                        Message.error(res.message, 1000);
                    }
                },
                error: function (error) {
                    layer.close(index);
                }
            });
            return false;
        });

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

    //设置更新标志
    function setUpdateFlag() {
        updateflag = 1;
    }

    function setCdCompany(company) {
        cdCompany = company;
    }

    function getCdCompany() {
        return cdCompany;
    }
</script>
</body>
</html>