extFunction.js 17.8 KB
// 扩展函数
import Store from '../store';
import server from './server';
import {showDanger, showSuccess, showWarning} from '../assets/config/loading.js';


/**
 * 验证用户
 */
const checkUser = (extendsetting) => {
    return window.userLogin.checkUser(extendsetting, showDanger, showSuccess);
}

function copyText(text){
    const input = document.createElement('input');
    document.body.appendChild(input);
    input.setAttribute('value', text);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
}

const getDocumentDetail = (extendsetting, userId) => {
    var gridKey = extendsetting.gridKey;
    if (!extendsetting.docConfigApi || !extendsetting.docConfigApi.documentDetailUrl) {
        return;
    }
    var getDetailUrl = extendsetting.docConfigApi.documentDetailUrl;
    if (getDetailUrl && getDetailUrl !== '' && getDetailUrl != null) {
        // 同步球球
        $.ajaxSettings.async = false;
        $.get(getDetailUrl, {gridKey: gridKey, userId: userId}, function (res) {
            // 请求成功
            if (res && res.code === 0) {
                localStorage.setItem('documentDetail', JSON.stringify(res.data));
                // 文档信息
                var detail = res.data.detail;
                Store.documentDetail = detail;
                // 设置文档标题
                var docName = detail.docName;
                if (docName) {
                    extendsetting.title = docName;
                }
                // 创建用户和创建用户Id
                extendsetting.userInfo.userName = detail.createUserName;
                extendsetting.userInfo.userId = detail.createUserId;
                extendsetting.showShareFlag = detail.createUserId === userId;
                // 设置文档权限
                var isUpdate = res.data.isUpdate;
                extendsetting.allowUpdate = isUpdate;
            }
        })
        $.ajaxSettings.async = true;
    }
}

/**
 * 文档名称处理
 */
const docNameInit = () => {
    // 未配置则不处理
    if (!server.docConfigApi || !server.docConfigApi.updateDocNameUrl) {
        return;
    }
    var updateDocNameUrl = server.docConfigApi.updateDocNameUrl;
    var docNameObj = $("#luckysheet_info_detail_input");
    if (docNameObj && updateDocNameUrl && updateDocNameUrl !== '' && updateDocNameUrl != null) {
        $("#luckysheet_info_detail_input").on("blur", function (e) {
            var docName = $(this).val();
            $.get(updateDocNameUrl, {docId: Store.documentDetail.id, newName: docName}, function (res) {
                // 请求成功
                if (res && res.code === 0) {
                    showSuccess('文档名称修改成功!');
                }
            })
        });
    }
}

/**
 * 获取在线用户
 */
const getOnlineUser = () => {
    var config = server.docConfigApi;
    if (config.getOnlineUser) {
        var documentString = localStorage.getItem('documentDetail');
        var createUserId = '';
        if (documentString) {
            var documentObj = JSON.parse(documentString);
            createUserId = documentObj.detail.createUserId;

        }

        var arr = ['<span #css class="badge bg-primary rounded-pill online-item-user">__</span>', '<span #css class="badge bg-secondary rounded-pill online-item-user">__</span>'
            , '<span #css class="badge bg-success rounded-pill online-item-user">__</span>', '<span #css class="badge bg-danger rounded-pill online-item-user">__</span>'
            , '<span #css class="badge bg-warning text-dark rounded-pill online-item-user">__</span>', '<span #css class="badge bg-info text-dark rounded-pill online-item-user">__</span>',
            '<span #css class="badge bg-light text-dark rounded-pill online-item-user">__</span>']

        $.get(config.getOnlineUser, {gridKey: server.gridKey}, function (res) {
            // 请求成功
            if (res && res.code === 0) {
                var html = Object.keys(res.data).map(function (key) {
                    let index = parseInt(Math.random() * (arr.length - 1), (arr.length - 1));
                    var name = res.data[key];
                    var lineHeightCss = ``;
                    if (name.length > 3) {
                        lineHeightCss = 'style="line-height: 20px!important;"';
                    }
                    if (key !== createUserId) {
                        return arr[index].replace('__', name).replace('#css', lineHeightCss);;
                    }
                }).join('')
                $('#onlint-user-view').find('.badge').remove();
                $('#onlint-user-view').append(html);
            }
        })
    }
}

/**
 * 展示文档的日志
 */
const documentLogInit = () => {
    var config = server.docConfigApi;
    if (config && config.documentHistoryUrl) {
        // 获取日志列表
        // let getLog = function (callback){
        //     $.ajaxSettings.async = false;
        //     $.get(config.documentHistoryUrl, {gridKey: server.gridKey}, function (res) {
        //         if (res && res.code === 0 && res.data) {
        //             var log = res.data;
        //
        //             var itemHtml = [];
        //             Object.keys(log).forEach(function (key) {
        //                 var htmls = [];
        //                 var arr = log[key];
        //                 arr.forEach(function (v){
        //                     var html = `<div class="historyItem">
        //                         <div class="txt">
        //                             <div class="txtContent">
        //                                 <p>【${v.nickName}】【${v.dateTime}】${v.content}</p>
        //                             </div>
        //                         </div>
        //                     </div>`;
        //                     htmls.push(html);
        //                 })
        //
        //                 itemHtml.push(`<div class="content">
        //                 <div class="item">
        //                     <div class="year active">${key}</div>
        //                     <div class="historyList open">
        //                          ${htmls.join('')}
        //                     </div>
        //                 </div>
        //             </div>`);
        //
        //             })
        //             var html = `<div id="documentHistory" style="width: 400px;position: absolute;right: 20px;z-index: 9999;top: 53px;">
        //                     <div class="card">
        //                       <div class="card-header">
        //                         <i class="fa fa-history" aria-hidden="true"></i>&nbsp;&nbsp;历史数据
        //                         <button type="button" class="btn-close" aria-label="Close" style="float: right;"></button>
        //                       </div>
        //                       <div class="card-body" style="padding: 10px;max-height: 500px;overflow: auto">
        //                         <div class="custom-timeline">
        //                             <div class="w1200">
        //                                 ${itemHtml.join(',')}
        //                             </div>
        //                         </div>
        //                       </div>
        //                     </div>
        //             </div>`;
        //             callback(html);
        //         } else {
        //             showDanger('暂无日志信息!');
        //         }
        //     }).error(function (err) {
        //         if (err && err.responseJSON && err.responseJSON.resp_msg) {
        //             showDanger(err.responseJSON.resp_msg);
        //         }
        //     });
        //     $.ajaxSettings.async = true;
        // }
        let getLog = function (callback) {
            $.ajaxSettings.async = false;
            $.get(config.documentHistoryUrl, {gridKey: server.gridKey}, function (res) {
                if (res && res.code === 0 && res.data) {
                    var log = res.data;

                    var itemHtml = [];
                    Object.keys(log).forEach(function (key) {
                        var arr = log[key];
                        arr.forEach(function (v) {
                            var html = `<li class="list-group-item d-flex justify-content-between align-items-start">
                                    <div class="ms-2 me-auto" style="word-break: break-all;">
                                      <div class="fw-bold">${v.nickName}</div>
                                      ${v.content}
                                    </div>
                                    <span class="badge bg-primary rounded-pill">${v.between}</span>
                                  </li>`
                            itemHtml.push(html);
                        })
                    })
                    var html = `<div id="documentHistory" style="width: 400px;position: absolute;right: 20px;z-index: 9999;top: 53px;">
                            <div class="card">
                              <div class="card-header">
                                <i class="fa fa-history" aria-hidden="true"></i>&nbsp;&nbsp;历史数据  
                                <button type="button" class="btn-close" aria-label="Close" style="float: right;"></button>
                              </div>
                              <div class="card-body" style="padding: 10px;max-height: 500px;overflow: auto">
                                <ol class="list-group list-group-numbered">
                                    ${itemHtml.join('')}
                                </ol>
                              </div>
                            </div>
                    </div>`;
                    callback(html);
                } else {
                    showDanger('暂无日志信息!');
                }
            }).error(function (err) {
                if (err && err.responseJSON && err.responseJSON.resp_msg) {
                    showDanger(err.responseJSON.resp_msg);
                }
            });
            $.ajaxSettings.async = true;
        }

        $('#document_history_000').click(function () {

            getLog(function (html) {
                $('.luckysheet').append(html);
                $('#documentHistory').fadeIn(3000);

                $('.year').click(function () {
                    let flag = $(this).hasClass('active')
                    if (flag) {
                        $(this).removeClass('active').siblings('.historyList').slideUp()
                    } else {
                        $(this).addClass('active').siblings('.historyList').slideDown()
                    }
                })

                $('button[aria-label="Close"]').click(function () {
                    $('#documentHistory').fadeOut("slow");
                    setTimeout(function () {
                        $('#documentHistory').remove();
                    }, 2000)
                });
            });
        });

        $('#document_share_000').click(function () {
            if (!server.docConfigApi || !server.docConfigApi.documentShare) {
                return;
            }

            // 弹框展示分享信息
            var showShareModal = function (callback) {
                var html = `<div class="modal fade" id="shareModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                  <div class="modal-dialog">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title">文档分享</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <div class="modal-body">
                        <input type="hidden" id="shareId">
                        <form class="was-validated">
                          <!--<div class="mb-3">
                            <label for="userAccount" class="col-form-label">分享地址:</label>
                            <input type="text" class="form-control" readonly="readonly" id="shareUrl" required>
                          </div>-->
                          <div class="mb-3">
                            <label for="shareUrl" class="col-form-label">分享地址:</label>
                           <div class="input-group">
                              <input type="text" class="form-control" readonly="readonly" id="shareUrl"  aria-label="分享地址" aria-describedby="button-copy">
                              <button class="btn btn-outline-secondary" type="button" id="button-copy">预览</button>
                          </div>
                          </div>
                          
                          <div class="mb-3">
                            <label for="isReadView" class="col-form-label">读取权限:</label>
                            <div class="form-check d-flex" id="isReadView">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="isRead" value="1" id="isRead1"
                                           checked>
                                    <label class="form-check-label" for="isRead1">
                                        
                                    </label>
                                </div>
                                <div class="form-check mx-lg-2">
                                    <input class="form-check-input" type="radio" name="isRead" value="2" id="isRead2">
                                    <label class="form-check-label" for="isRead2">
                                        
                                    </label>
                                </div>
                            </div>
                           </div>
                           <div class="mb-3">
                            <label for="isEditView" class="col-form-label">编辑权限:</label>
                            <div class="form-check d-flex" id="isEditView">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="isEdit" value="1" id="isEdit1"
                                           checked>
                                    <label class="form-check-label" for="isEdit1">
                                        
                                    </label>
                                </div>
                                <div class="form-check mx-lg-2">
                                    <input class="form-check-input" type="radio" name="isEdit" value="2" id="isEdit2">
                                    <label class="form-check-label" for="isEdit2">
                                        
                                    </label>
                                </div>
                            </div>
                           </div>
                          <!--<div class="mb-3">
                            <label for="userPassword" class="col-form-label">分享密码:</label>
                            <input type="password" id="userPassword" class="form-control" aria-describedby="passwordHelpInline" required>
                          </div>-->
                        </form>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" id="shareConfirm">分享</button>
                      </div>
                    </div>
                  </div>
                </div>`;

                $('#shareModal').remove();
                $(html).appendTo('body');


                var shareModal = new bootstrap.Modal(document.getElementById('shareModal'), {
                    keyboard: true
                })

                // 创建分享链接
                $.get(server.docConfigApi.documentShare.createShareUrl, {
                    gridKey: server.gridKey,
                    serverUrl: window.extApiConfig.BASE_URL,
                    baseUrl: window.location.origin
                }, function (res) {
                    if (res && res.code == 0) {
                        // 分享地址
                        $('#shareUrl').val(res.data.shareUrl);
                        $('#shareId').val(res.data.shareId);
                        $('#shareConfirm').attr('data-id',res.data.id);
                        shareModal.show();
                    }
                })

                $('#button-copy').on('click', function (event) {
                    // copyText($('#shareUrl').val());
                    // showSuccess('复制成功')
                    window.top.open($('#shareUrl').val());
                })
                // 确认
                $('#shareConfirm').on('click', function (event) {
                    var shareId = $('#shareId').val()
                    callback({
                        shareId:shareId,
                        isRead:$('input[name="isRead"]:checked').val(),
                        isEdit:$('input[name="isEdit"]:checked').val(),
                        sharePwd:$('input[name="userPassword"]:checked').val(),
                    }, shareModal);

                })
            }

            showShareModal(function (params,modal) {
                // 保存权限
                $.get(server.docConfigApi.documentShare.confirmShareUrl, params, function (res) {
                    if (res && res.code == 0) {
                        // 分享地址
                         showSuccess(res.msg);
                        modal.hide();
                    } else {
                        showWarning(res.msg);
                    }
                })
            });

        });

    }
}


export {
    checkUser,
    getDocumentDetail,
    docNameInit,
    getOnlineUser,
    documentLogInit
}