<!DOCTYPE html>
<html>

<head lang='zh'>
    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="renderer" content="webkit"/>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=0"/>
    <title>Luckysheet</title>
    <link rel='stylesheet' href='/static/js/luckysheet/plugins/css/pluginsCss.css'/>
    <link rel='stylesheet' href='/static/js/luckysheet/plugins/plugins.css'/>
    <link rel='stylesheet' href='/static/js/luckysheet/css/luckysheet.css'/>
    <link rel='stylesheet' href='/static/js/luckysheet/assets/iconfont/iconfont.css'/>
    <link charset="utf-8" rel="stylesheet" href="/static/css/layui.css?v=1.0.0">
    <script>
        var _PageHeight = document.documentElement.clientHeight,
            _PageWidth = document.documentElement.clientWidth;
        var _LoadingTop = _PageHeight > 61 ? (_PageHeight - 61) / 2 : 0,
            _LoadingLeft = _PageWidth > 215 ? (_PageWidth - 215) / 2 : 0;
        var _LoadingHtml = '<div id="loadingDiv" style="position:absolute;left:0;width:100%;height:' + _PageHeight + 'px;top:0;background:#f3f8ff;opacity:1;filter:alpha(opacity=80);z-index:10000;"><div style="position: absolute; cursor1: wait; left: ' + _LoadingLeft + 'px; top:' + _LoadingTop + 'px; width: auto; height: 57px; line-height: 57px; padding-left: 50px; padding-right: 5px; color: #696969; font-family:\'Microsoft YaHei\';"><img style="width:200px;height:200px" src="../images/loading.gif"></div></div>';
        document.write(_LoadingHtml);
        document.onreadystatechange = completeLoading;

        function completeLoading() {
            if (document.readyState == "complete") {
                var loadingMask = document.getElementById('loadingDiv');
                loadingMask.parentNode.removeChild(loadingMask);
            }
        }

    </script>
    <script src="/static/js/layui.js?v=1.0.0"></script>
    <script src="/static/js/exceljs.js"></script>
    <script src="/static/js/fileSave.js"></script>
    <script src="/static/js/luckysheet/luckSheetExcel.js"></script>
    <script src="/marketfront/static/js/luckysheet_old/plugins/js/plugin.js?v=1.0.0"></script>
    <script src="/marketfront/static/js/luckysheet_old/luckysheet.umd.js?v=1.0.0"></script>
    <script src="/static/js/api.config.js"></script>
    <script src="/static/js/util.js?v=1.0.0"></script>
    <script src="/static/js/url.js?v=1.0.0"></script>
    <script src="/static/js/exportExcel.js"></script>
    <script src="/static/js/fullScreen.js"></script>
</head>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    html,
    body {
        height: 100%;
    }

    #monthSelect {
        padding: 10px 0px;
    }
</style>

<body style="background: #fff;">
<div class="layui-inline" id="monthSelect" style="width: 100%">
    <div class="layui-input-inline">
        <form>
            <label>控制权限</label>
            <select name="city" id="editStatus" style="width: 70px">
                <option value="0">开启</option>
                <option value="1">关闭</option>
            </select>
            <label> 可编辑列：从 </label><input type="text" id="editFrom" style="width: 50px"
                                               onkeyup="this.value=this.value.replace('-','')"></input> 到 <input
            type="text" id="editTo" style="width: 50px"
            onkeyup="this.value=this.value.replace('-','')"></input>
        </form>
    </div>
    <div style="float: right;padding-right: 10px" id="shareBtn">
        <button id="share" class="btn btn-primary"
                style="padding:3px 6px;font-size: 18px;margin-right: 10px;width: 100px">分享
        </button>
    </div>
    <div style="float: right;padding-right: 10px" id="newShareBtn">
        <button id="newShare" class="btn btn-primary"
                style="padding:3px 6px;font-size: 18px;margin-right: 10px;width: 100px">分享
        </button>
    </div>
</div>
<div style="height:90%;width: 100%;">
    <div id="luckysheet" style="width:100%;height:100%">
    </div>
</div>
<script>
    //监听window是否全屏，并进行相应的操作,支持esc键退出
    window.onresize = function () {
        var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen ||
            document.msFullscreenElement || document.fullscreenElement
        );//!document.webkitIsFullScreen都为true。因此用!!
        if (isFull == false) {
            $("#exitFullScreen").css("display", "none");
            $("#fullScreen").css("display", "");
        } else {
            $("#exitFullScreen").css("display", "");
            $("#fullScreen").css("display", "none");
        }
    }
</script>
<script>
    var lockFlag = 'see';
    util.ajaxJson("", ctx + "/market/cadvLedger/getRoleByCode", {}, function (res) {
        console.log("html" + res.result);
        if (res.result == 1) {
            lockFlag = 'add';//省级
        } else {
            lockFlag = 'updata';//管理员
        }
    });
    var id = '' //  模板id 查看/修改load时候用
    var powerFlag = '0'; // 权限控制 0 开启 1关闭
    var excelId = '';
    var flag = false; // 控制excel是否可以编辑
    var adminFlag = false;
    var userId; // 用户ID
    var excelInfo = {};
    var isAdmin = '';
    var excelLevel = '';
    var toolBar = '';
    var type = '';
    var emptyExcel = false;
    var fullScreenState = false;
    $(function () {
        userId = JSON.parse(window.top.sessionStorage.userInfo).loginNo
    })
    layui.use(['laydate', 'form'], function () {
        var laydate = layui.laydate;
        var form = layui.form;
        form.on('select(powerFlag)', function (data) {
            powerFlag = data.value
        })

        // 获取数据
        function getData() {
            // 先销毁excel重新加载
            if (window.luckysheet) {
                window.luckysheet.destroy();
            }
            //拿参数的
            var excelId = $(window.parent.document).find("#excelId").attr("value");
            console.log(excelId);
            type = '2';
            toolBar = '';
            var url = '/market/cOnlineExcelMarket/getExcelInfo';
            util.ajaxJson("数据加载中", ctx + url, {
                "id": excelId ? excelId : '',
            }, function (res) {
                if (res.result == 0) {
                    // 查看和修改时 下拉框赋值
                    excelInfo = res.body.excelInfo;
                    excelLevel = res.body.excelLevel;
                    isAdmin = res.body.isExcelAdmin;
                    emptyExcel = res.body.emptyExcel;
                    $("#editFrom").val(excelInfo.editConStart);
                    $("#editTo").val(excelInfo.editConEnd);
                    $("#editStatus").val(excelInfo.editStatus);
                    console.log(type);
                    if (type == '2') {
                        if (isAdmin) {
                            toolBar += '<input id="imports" type="file" class="btn btn-primary" style="padding:3px 6px;font-size: 12px;margin-right: 10px;"></input>';
                        }
                    }
                    if (isAdmin) {
                        toolBar += '<button id="exports" class="btn btn-primary btn-danger" style="padding:3px 6px;font-size: 12px;margin-right: 10px;">导出</button>';
                    }
                    toolBar += '<button id="saves" class="btn btn-primary btn-danger" style=" padding:3px 6px; font-size: 12px; margin-right: 10px;">保存</button>';
                    toolBar += '<button id="closeExcel" class="btn btn-primary" style="padding:3px 6px;font-size: 12px;margin-right: 10px;">返回</button><button id="fullScreen" class="btn btn-primary" style="padding:3px 6px;font-size: 12px;margin-right: 10px;">全屏显示</button><button id="exitFullScreen" class="btn btn-primary" style="padding:3px 6px;font-size: 12px;margin-right: 10px;display:none">退出全屏</button>';
                    var eJson = res.body.excelJson;
                    var cellData = luckysheet.transToCellData(eJson[0].data);
                    eJson[0].celldata = cellData;
                    initExcel(res.body.excelJson);
                }
            });
            //initExcel()
        }

        // 表格初始化
        function initExcel(data, name) {
            if (type == '1') {
                flag = false
            } else {
                flag = true
            }
            if (isAdmin) {
                adminFlag = true;
            }
            var fileName = excelInfo.fileName;
            if ($.trim(name) != '') {
                fileName = name;
            }
            try {
                luckysheet.create({
                    container: 'luckysheet',
                    data: data,
                    showsheetbar: false, // 底部sheet显示/隐藏
                    showsheetbarConfig: {
                        add: false, //新增sheet
                        menu: false, //sheet管理菜单
                        sheet: false //sheet页显示
                    },
                    showstatisticBar: false, // 底部计数
                    showtoolbar: true,
                    myFolderUrl: '',
                    showtoolbarConfig: {
                        undoRedo: true, //撤销重做，注意撤消重做是两个按钮，由这一个配置决定显示还是隐藏
                        paintFormat: true, //格式刷
                        currencyFormat: true, //货币格式
                        percentageFormat: true, //百分比格式
                        numberDecrease: true, // '减少小数位数'
                        numberIncrease: true, // '增加小数位数
                        moreFormats: true, // '更多格式'
                        font: true, // '字体'
                        fontSize: true, // '字号大小'
                        bold: true, // '粗体 (Ctrl+B)'
                        italic: true, // '斜体 (Ctrl+I)'
                        strikethrough: true, // '删除线 (Alt+Shift+5)'
                        underline: true, // '下划线 (Alt+Shift+6)'
                        textColor: true, // '文本颜色'
                        fillColor: true, // '单元格颜色'
                        border: true, // '边框'
                        mergeCell: true, // '合并单元格'
                        horizontalAlignMode: true, // '水平对齐方式'
                        verticalAlignMode: true, // '垂直对齐方式'
                        textWrapMode: true, // '换行方式'
                        textRotateMode: false, // '文本旋转方式'
                        image: false, // '插入图片'
                        link: false, // '插入链接'
                        chart: false, // '图表'（图标隐藏，但是如果配置了chart插件，右击仍然可以新建图表）
                        postil: false, //'批注'
                        pivotTable: false,  //'数据透视表'
                        function: true, // '公式'
                        frozenMode: true, // '冻结方式'
                        sortAndFilter: true, // '排序和筛选'
                        conditionalFormat: false, // '条件格式'
                        dataVerification: false, // '数据验证'
                        splitColumn: true, // '分列'
                        screenshot: false, // '截图'
                        findAndReplace: true, // '查找替换'
                        protection: false, // '工作表保护'
                        print: false, // '打印'
                    },
                    showinfobar: true, // 顶部信息 文件名称 按钮
                    allowUpdate: false, // 是否允许操作表格后的后台更新 在线文档websocket时为true
                    allowEdit: flag, // 是否允许前台编辑
                    title: fileName, // 文件名称
                    lang: 'zh',
                    enableAddRow: true,
                    showstatisticBar: false, // 底部计数
                    showstatisticBarConfig: {
                        count: false, // 计数栏
                        view: false, // 打印视图
                        zoom: false, // 缩放
                    },
                    functionButton: toolBar,
                    cellRightClickConfig: {
                        copy: false, // 复制
                        copyAs: false, // 复制为
                        paste: false, // 粘贴
                        insertRow: true, // 插入行
                        insertColumn: true, // 插入列
                        deleteRow: true, // 删除选中行
                        deleteColumn: true, // 删除选中列
                        deleteCell: false, // 删除单元格
                        hideRow: false, // 隐藏选中行和显示选中行
                        hideColumn: false, // 隐藏选中列和显示选中列
                        rowHeight: true, // 行高
                        columnWidth: true, // 列宽
                        clear: false, // 清除内容
                        matrix: false, // 矩阵操作选区
                        sort: false, // 排序选区
                        filter: false, // 筛选选区
                        chart: false, // 图表生成
                        image: false, // 插入图片
                        link: false, // 插入链接
                        data: false, // 数据验证
                        cellFormat: false, // 设置单元格格式
                        mComplete: false,
                        mCetup: false,
                        mRevoke: false
                    },
                    hook: {
                        cellMousedown: function (a, b, c) {

                        },
                        cellUpdateBefore: function (r, c) {

                        },
                        cellMousedownBefore: function (a, p, s) {

                        },
                        rangePasteBefore: function (range, data) {

                        },
                    },
                })
            } catch (err) {
                console.log(err)
            }
            if (isAdmin == false) {
                $("#editStatus").attr('disabled', true);
                $("#editFrom").attr('disabled', true);
                $("#editTo").attr('disabled', true);
                $("#shareBtn").hide();
                $("#newShareBtn").hide();
            } else {
                $("#editStatus").attr('disabled', false);
                $("#editFrom").attr('disabled', false);
                $("#editTo").attr('disabled', false);
                $("#shareBtn").show();
                $("#newShareBtn").show();
            }
            if (emptyExcel == true) {
                $("#shareBtn").show();
                $("#saves").hide();
                $("#newShareBtn").hide();
            } else {
                $("#shareBtn").hide();
                $("#saves").show();
                if (isAdmin) {
                    $("#newShareBtn").show();
                }
                // console.log("执行自动保存定时器")
                // var t1 = window.setInterval(function autoSave() {
                //     console.log("执行自动保存")
                //     var excelId = $(window.parent.document).find("#excelId").attr("value");
                //     var sheetName = luckysheet.getSheet().name;
                //     var excelData = luckysheet.getSheet(sheetName);
                //     var urlsave = '/market/cOnlineExcelMarket/saveExcel';
                //     var editFrom = $("#editFrom").val();
                //     var editTo = $("#editTo").val();
                //     var editStatus = $("#editStatus").val();
                //     var excelName = luckysheet.toJson().title;
                //     if ($.trim(editFrom) == '' && $.trim(editTo) == '') {
                //
                //     } else if (/^\d*$/.test(editFrom) && /^\d*$/.test(editTo)) {
                //         if (editFrom == 0) {
                //             window.top.$vm.$message({
                //                 message: '自动保存出错：可编辑列开始不能为0',
                //                 type: 'info'
                //             })
                //             return;
                //         }
                //         if (editFrom > editTo) {
                //             window.top.$vm.$message({
                //                 message: '自动保存出错：可编辑列的起始列不能大于结束列',
                //                 type: 'info'
                //             })
                //             return;
                //         }
                //     } else if (/^[a-zA-Z]+$/.test(editFrom) && /^[a-zA-Z]+$/.test(editTo)) {
                //
                //     } else {
                //         window.top.$vm.$message({
                //             message: '自动保存出错：可编辑列必须全部为字母或数字',
                //             type: 'info'
                //         });
                //         return;
                //     }
                //     util.ajaxJson(null, ctx + '/market/cOnlineExcelMarket/checkExcelEmpty', {
                //         data: excelData,
                //     }, function (data) {
                //         if (data.result == 1) {
                //             window.top.$vm.$message({
                //                 message: data.desc,
                //                 type: 'error'
                //             });
                //         } else {
                //             util.ajaxJson(null, ctx + urlsave, {
                //                 data: excelData,
                //                 id: excelId,
                //                 editConStart: editFrom,
                //                 editConEnd: editTo,
                //                 excelName: excelName,
                //                 editStatus: editStatus
                //             }, function (data) {
                //                 if (data.result == 1) {
                //                     window.top.$vm.$message({
                //                         message: data.desc,
                //                         type: 'error'
                //                     })
                //                 } else {
                //                     // window.top.$vm.$message({
                //                     //     message: '自动保存成功',
                //                     //     type: 'info'
                //                     // });
                //                     //console.log(data);
                //                     //getData()
                //                 }
                //             });
                //         }
                //     });
                // }, 15000)
            }
            if (excelInfo.shareStatus == '1') {
                $("#editTo").attr('disabled', true);
                $("#editFrom").attr('disabled', true);
            } else {
                $("#editTo").attr('disabled', false);
                $("#editFrom").attr('disabled', false);
            }
            initHandel();
        }

        function isNumber(val) {
            var regPos = /^\d+(\.\d+)?$/; //非负浮点数
            var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/;
            //负浮点数
            if (regPos.test(val) && regNeg.test(val)) {
                return true;
            } else {
                return false;
            }
        }

        function processShare(type) {
            //  当前工作表名
            var excelId = $(window.parent.document).find("#excelId").attr("value");
            var sheetName = luckysheet.getSheet().name;
            var excelData = luckysheet.getSheet(sheetName);
            var urlsave = '/market/cOnlineExcelMarket/saveExcel';
            var editFrom = $("#editFrom").val();
            var editTo = $("#editTo").val();
            var editStatus = $("#editStatus").val();
            var excelName = luckysheet.toJson().title;
            //校验可编辑列
            if ($.trim(editFrom) == '' && $.trim(editTo) == '') {

            } else if (/^\d*$/.test(editFrom) && /^\d*$/.test(editTo)) {
                if (editFrom == 0) {
                    window.top.$vm.$message({
                        message: '可编辑列开始不能为0',
                        type: 'info'
                    })
                    return;
                }
                if (editFrom > editTo) {
                    window.top.$vm.$message({
                        message: '可编辑列的起始列不能大于结束列',
                        type: 'info'
                    })
                    return;
                }
            } else if (/^[a-zA-Z]+$/.test(editFrom) && /^[a-zA-Z]+$/.test(editTo)) {

            } else {
                window.top.$vm.$message({
                    message: '可编辑列必须全部为字母或数字',
                    type: 'info'
                })
                return;
            }
            util.ajaxJson("正在加载中", ctx + '/market/cOnlineExcelMarket/checkExcelEmpty', {
                data: excelData,
            }, function (data) {
                if (data.result == 1) {
                    window.top.$vm.$message({
                        message: data.desc,
                        type: 'error'
                    });
                } else {
                    //excelJson, editFrom, editTo, editStatus, excelName, excelId, type
                    window.parent['shareExcel'](excelData, editFrom, editTo, editStatus, excelName, excelId, type);
                }
            });
        }

        // 绑定按钮事件
        function initHandel() {
            $("#closeExcel").on("click", function () {
                window.parent['backToExcelList']('true');
            })
            $("#fullScreen").on("click", function () {
                if (fullScreenState) {
                    fullScreenState = false;
                    $("#fullScreen").html('全屏显示');
                } else {
                    fullScreenState = true;
                    $("#fullScreen").html('退出全屏');
                }
                window.parent['fullScreen']('true');
                //fullScreen();
            })
            //退出全屏
            $("#exitFullScreen").on("click", function () {
                exitFullscreen();
            })
            //分享
            $('#share').off("click").click(function () {
                if (fullScreenState) {
                    fullScreenState = false;
                    $("#fullScreen").html('全屏显示');
                    window.parent['fullScreen']('true');
                }
                processShare(1);
            });
            //新增分享
            $('#newShare').off("click").click(function () {
                if (fullScreenState) {
                    fullScreenState = false;
                    $("#fullScreen").html('全屏显示');
                    window.parent['fullScreen']('true');
                }
                processShare(2);
            });
            // 保存
            $('#saves').off("click").click(function () {
                //  当前工作表名
                var excelId = $(window.parent.document).find("#excelId").attr("value");
                var sheetName = luckysheet.getSheet().name;
                var excelData = luckysheet.getSheet(sheetName);
                var urlsave = '/market/cOnlineExcelMarket/saveExcel';
                var editFrom = $("#editFrom").val();
                var editTo = $("#editTo").val();
                var editStatus = $("#editStatus").val();
                var excelName = luckysheet.toJson().title;
                if ($.trim(editFrom) == '' && $.trim(editTo) == '') {

                } else if (/^\d*$/.test(editFrom) && /^\d*$/.test(editTo)) {
                    if (editFrom == 0) {
                        window.top.$vm.$message({
                            message: '可编辑列开始不能为0',
                            type: 'info'
                        })
                        return;
                    }
                    if (editFrom > editTo) {
                        window.top.$vm.$message({
                            message: '可编辑列的起始列不能大于结束列',
                            type: 'info'
                        })
                        return;
                    }
                } else if (/^[a-zA-Z]+$/.test(editFrom) && /^[a-zA-Z]+$/.test(editTo)) {

                } else {
                    window.top.$vm.$message({
                        message: '可编辑列必须全部为字母或数字',
                        type: 'info'
                    });
                    return;
                }
                util.ajaxJson("正在加载中", ctx + '/market/cOnlineExcelMarket/checkExcelEmpty', {
                    data: excelData,
                }, function (data) {
                    if (data.result == 1) {
                        window.top.$vm.$message({
                            message: data.desc,
                            type: 'error'
                        });
                    } else {
                        util.ajaxJson("正在加载中", ctx + urlsave, {
                            data: excelData,
                            id: excelId,
                            editConStart: editFrom,
                            editConEnd: editTo,
                            excelName: excelName,
                            editStatus: editStatus
                        }, function (data) {
                            if (data.result == 1) {
                                window.top.$vm.$message({
                                    message: data.desc,
                                    type: 'error'
                                })
                            } else {
                                window.top.$vm.$message({
                                    message: '保存成功',
                                    type: 'info'
                                });
                                console.log(data);
                                getData()
                            }
                        });
                    }
                });
            })
            // 导出
            $('#exports').click(function () {
                var excelName = luckysheet.toJson().title;
                exportExcel(luckysheet.getluckysheetfile(), excelName)
            })
            // 导入
            $("#imports").change(function (evt) {
                var files = evt.target.files;
                if (files == null || files.length == 0) {
                    window.top.$vm.$message({
                        message: '没有文件导入',
                        type: 'info'
                    })
                    return;
                }
                var name = files[0].name;
                var suffixArr = name.split("."),
                    suffix = suffixArr[suffixArr.length - 1];
                if (suffix != "xlsx") {
                    window.top.$vm.$message({
                        message: '目前只支持xlsx文件的导入',
                        type: 'info'
                    })
                    return;
                }
                // 解析文件
                LuckyExcel.transformExcelToLucky(
                    files[0],
                    function (exportJson, luckysheetfile) {
                        console.log(exportJson);
                        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
                            window.top.$vm.$message({
                                message: '无法读取excel文件的内容，当前不支持xls文件',
                                type: 'info'
                            })
                            return;
                        }
                        // 销毁原来的excel
                        window.luckysheet.destroy();
                        // 重新加载
                        var a = exportJson.sheets[0];
                        a.name = '';
                        initExcel([a], name.replace('.xlsx', ''));
                        // 绑定按钮事件
                        initHandel()
                    }
                );
            });
        }

        getData()
    })

</script>
</body>

</html>
