/**
 * <p>
 *  client.js
 * </p>
 *
 * @author Administrator
 * @since 2021/12/11
 */
layui.use(['layer', 'gtable', 'form', 'element', 'upload'], function () {
    const layer = layui.layer,
        gtable = layui.gtable;
    form = layui.form;
    // 用于临时存储查询条件
    let searchText = '';
    let clientTable;


    /**
     * 打开应用编辑页面
     */
    function openAppEditLayer(id) {
        layer.open({
            title: '客户端信息编辑',
            type: 1,
            area: ['600px', '650px'],
            btn: ['确定', '取消'],
            content: `
                 <form class="layui-form" lay-filter="clientInfoForm" style="overflow: hidden; padding: 15px 20px 0 0;" xmlns="http://www.w3.org/1999/html">
                    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 0px;color: #9f9f9f;border-color: #e3e3e3;">
                        <legend style="font-size: 16px;">通用信息</legend>
                    </fieldset>
                     <div class="lr-block">
                         <div class="l-block">
                            <div class="layui-form-item">
                                <label class="layui-form-label">客户端名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="title" lay-verify="required" placeholder="请输入客户端名称（必填）" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">展示排序</label>
                                <div class="layui-input-block">
                                    <input type="text" name="sort" lay-verify="required|number" placeholder="应用排列顺序" value="0" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">打开方式</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="target" value="_blank" title="在新页面打开" checked>
                                    <input type="radio" name="target" value="_self" title="在当前页打开">
                                </div>
                            </div>
                         </div>
                         <div class="selected-icon r-block">
                                <div class="current-icon">
                                    <input type="hidden" name="icon" value="">
                                    <div class="icon" id="icon-content"></div>
                                </div>
                                <a id="selectIconBtn" href="javascript:void(0);">选择图标</a>
                            </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">重定向地址</label>
                        <div class="layui-input-block">
                            <input type="text" name="webServerRedirectUri" autocomplete="off" placeholder="客户端访问地址（必填）" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 40px;color: #9f9f9f;border-color: #e3e3e3;">
                        <legend style="font-size: 16px;">单点登录配置</legend>
                    </fieldset>
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户端ID</label>
                        <div class="layui-input-block">
                            <input type="text" name="id" autocomplete="off" readonly placeholder="系统自动生成" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">访问密匙</label>
                        <div class="layui-input-block">
                            <input type="password" name="clientSecret" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户数据同步</label>
                        <div class="layui-input-block">
                            <input type="radio" name="userSync" value="false" title="不需要" checked>
                            <input type="radio" name="userSync" value="true" title="需要">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">系统登出接口</label>
                        <div class="layui-input-block">
                            <input type="text" name="logoutUri" autocomplete="off" placeholder="系统登出接口" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户注册接口</label>
                        <div class="layui-input-block">
                            <input type="text" name="insertUri" autocomplete="off" placeholder="用户注册接口" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户修改接口</label>
                        <div class="layui-input-block">
                            <input type="text" name="updateUri" autocomplete="off" placeholder="用户修改接口" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户删除接口</label>
                        <div class="layui-input-block">
                            <input type="text" name="deleteUri" autocomplete="off" placeholder="用户删除接口" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户查询接口</label>
                        <div class="layui-input-block">
                            <input type="text" name="verifyUri" autocomplete="off" placeholder="用户查询接口" class="layui-input">
                        </div>
                    </div>
                    <button type="submit" lay-submit id="appInfoSubmit" style="border: none; position: absolute"/>
                </form>
            `,
            success: function (layerObj, index) {
                if (id) {
                    getApp(id).then(appInfo => {
                        if (appInfo.userSync) {
                            appInfo.userSync = "true";
                        } else {
                            appInfo.userSync = "false";
                        }
                        form.val('clientInfoForm', appInfo);
                        let icon;
                        if (appInfo.icon != null && appInfo.icon.startsWith('icon-')) {
                            $('.current-icon div:first').attr('class', 'icon ' + appInfo.icon);
                        } else if (appInfo.icon.startsWith('/upload/')) {
                            $('#icon-content').html(`<img src="${ctx + appInfo.icon}" alt="" style="width: 100%; height: 100%; border-radius: 20px;"/>`);
                        } else {
                            $('#icon-content').html(`<img src="${appInfo.icon}" alt="" style="width: 100%; height: 100%; border-radius: 20px;"/>`);
                        }
                    })
                }
                form.render()
                bindSelectIconBtn(elem => showDefaultIcon(elem))
            },
            yes: function (index) {
                form.on('submit(clientInfoForm)', function () {
                    let formVal = form.val('clientInfoForm');
                    if (!formVal.icon) {
                        layer.msg('请选择图标', {icon: 5});
                        return false;
                    }
                    $.post(`${ctx}/sys/oauth/client/save`, formVal, function (res) {
                        if (res.flag && res.data) {
                            layer.msg('保存成功');
                            layer.close(index);
                            clientTable.reload();
                        } else {
                            layer.msg('保存失败', {icon: 5});
                        }
                    });
                    return false; //阻止表单跳转刷新
                });
                $('#appInfoSubmit').click();
            },
            end: function (index) {

            }
        });
    }


    /**
     * 显示默认的图标
     */
    function showDefaultIcon(elem) {
        let _this = $(this);
        if (elem instanceof jQuery) {
            _this = elem;
        }

        const _class = _this.attr('class');
        $('#icon-content').html('');
        if (_class.includes('icon-img')) {
            $('#icon-content').attr("class", "icon on").html(_this.html());
        } else {
            $('.current-icon div:first').attr('class', 'icon ' + _class);
        }

        const icon = _this.data('value');
        let data = form.val('clientInfoForm');
        data.icon = icon;
        form.val('clientInfoForm', data);
    }

    function bindSelectIconBtn(callback) {
        $('#selectIconBtn').on('click', function () {
            layer.open({
                title: '选择图标',
                type: 1,
                area: ['600px', '650px'],
                btn: ['确定', '取消'],
                content: `  
                            <ul class="icon-list">
                                <li class="icon-upload" id="upload-icon">
                                    <input type="hidden" name="icon" value="">
                                    <i class="layui-icon layui-icon-upload-drag"></i>
                                    <label>上传图标</label>
                                    <label class="tips">140px * 140px</label>
                                    <label class="tips">大小不超过1MB</label>
                                </li>
                                <li class="icon-altbook" data-value="icon-altbook"><div class="mask"></div></li>
                                <li class="icon-approvedsafety" data-value="icon-approvedsafety"><div class="mask"></div></li>
                                <li class="icon-boldness" data-value="icon-boldness"><div class="mask"></div></li>
                                <li class="icon-calculator" data-value="icon-calculator"><div class="mask"></div></li>
                                <li class="icon-cloud" data-value="icon-cloud"><div class="mask"></div></li>
                                <li class="icon-configured" data-value="icon-configured"><div class="mask"></div></li>
                                <li class="icon-dashmac" data-value="icon-dashmac"><div class="mask"></div></li>
                                <li class="icon-directmail" data-value="icon-directmail"><div class="mask"></div></li>
                                <li class="icon-dropbox" data-value="icon-dropbox"><div class="mask"></div></li>
                                <li class="icon-dunpai" data-value="icon-dunpai"><div class="mask"></div></li>
                                <li class="icon-excel" data-value="icon-excel"><div class="mask"></div></li>
                                <li class="icon-fanglian" data-value="icon-fanglian"><div class="mask"></div></li>
                                <li class="icon-googledocsblast" data-value="icon-googledocsblast"><div class="mask"></div></li>
                                <li class="icon-googlemapsrafaga" data-value="icon-googlemapsrafaga"><div class="mask"></div></li>
                                <li class="icon-icalmac" data-value="icon-icalmac"><div class="mask"></div></li>
                                <li class="icon-instagram" data-value="icon-instagram"><div class="mask"></div></li>
                                <li class="icon-internetdownloadmanager" data-value="icon-internetdownloadmanager"><div class="mask"></div></li>
                                <li class="icon-liveMessenger" data-value="icon-liveMessenger"><div class="mask"></div></li>
                                <li class="icon-liveSync" data-value="icon-liveSync"><div class="mask"></div></li>
                                <li class="icon-macappstorealt" data-value="icon-macappstorealt"><div class="mask"></div></li>
                                <li class="icon-magnifier" data-value="icon-magnifier"><div class="mask"></div></li>
                                <li class="icon-newswindows8" data-value="icon-newswindows8"><div class="mask"></div></li>
                                <li class="icon-notebook" data-value="icon-notebook"><div class="mask"></div></li>
                                <li class="icon-pc" data-value="icon-pc"><div class="mask"></div></li>
                                <li class="icon-search" data-value="icon-search"><div class="mask"></div></li>
                                <li class="icon-skyDrive" data-value="icon-skyDrive"><div class="mask"></div></li>
                                <li class="icon-windows8photos" data-value="icon-windows8photos"><div class="mask"></div></li>
                                <li class="icon-windowsmediaplayer" data-value="icon-windowsmediaplayer"><div class="mask"></div></li>
                                <li class="icon-yuansu" data-value="icon-yuansu"><div class="mask"></div></li>
                                <li class="icon-zipfile" data-value="icon-zipfile"><div class="mask"></div></li>
                            </ul>`,
                success() {
                    // 查询已上传的图标
                    loadUploadIconList($('#upload-icon'));
                    // 图标上传按钮初始化
                    bindUploadBtn();
                },
                yes(index) {
                    let iconElem = $('ul.icon-list > li.on:first');
                    if (iconElem.length > 0) {
                        callback && callback(iconElem)
                        layer.close(index);
                    } else {
                        showErrorMsg('请选择一个图标')
                    }
                },
                end() {

                },
            })
        })
    }

    /**
     * 绑定文件上传按钮
     */
    function bindUploadBtn() {
        layui.upload.render({
            elem: '#upload-icon',
            url: `${ctx}/sys/oauth/client/upload/icon`,
            multiple: false,
            auto: true,
            size: 1024, //限制文件大小，单位 KB
            accept: 'images',
            acceptMime: 'image/*', // 只显示图片类型
            done: function (res) {
                if (res.flag) { //上传成功
                    showOkMsg("上传成功")
                    loadUploadIconList($('#upload-icon'));
                } else {
                    layer.msg('上传失败', {icon: 5});
                }
            }
        });
    }


    function bindDelBtn() {
        $('.icon-list li a.btn-del').on('click', function (event) {
            // 阻止事件冒泡
            event.stopPropagation();
            layer.confirm('确定删除该图标吗？', {
                icon: 3,
                title: '提示',
                btn: ['确定', '取消']
            }, (index) => {
                layer.close(index);
                let id = $(this).data('id');
                Util.send(`/sys/file/delete/${id}`, {}, 'delete',).then((res) => {
                    if (res.flag) {
                        showOkMsg('删除成功');
                        loadUploadIconList($('#upload-icon'));
                    } else {
                        showErrorMsg('删除失败');
                    }
                }).catch((err) => {
                    showErrorMsg('删除失败');
                })
            });

        })
    }

    /**
     * 显示上传后的图标
     * @param path
     */
    function showImgIcon(path) {
        alert(17);
        const url = `${ctx}/${path}`;
        const img = `<img src="${url}" alt="" style="width: 100%; height: 100%; border-radius: 5px;" />`
        $('#icon-content').html(img);
        $('ul.icon-list li').removeClass('on')
    }

    function loadUploadIconList(target) {
        $('.icon-img').remove();
        Util.get(`/sys/oauth/client/upload/icon/list`).then(res => {
            if (res.flag) {
                let icon_files = res.data;
                if (icon_files && Array.isArray(icon_files)) {
                    let icons_html = "";
                    for (let file of icon_files) {
                        let url = `${ctx}${file.webUri}`;
                        let img = `<img src="${url}" alt="" style="width: 100%; height: 100%;" /><a class="btn-del" href="javascript:void(0);" data-id="${file.id}" >删&nbsp;&nbsp;除</a>`
                        icons_html += `<li class="icon-img" data-value="${file.webUri}">${img}<div class="mask"></div></li>`;
                    }
                    $(target).after(icons_html);
                }
            }

        }).catch(err => {
            showErrorMsg();
        }).finally(bindIconClickEvent);
    }

    function bindIconClickEvent() {
        // 图标点击选择事件
        $('ul.icon-list li:gt(0)').on('click', function (elem) {
            $(this).addClass('on').siblings().removeClass('on');
        });
        bindDelBtn();
    }


    /**
     * 查询应用
     * @param id 应用ID
     */
    async function getApp(id) {
        let appInfo = undefined;
        await $.ajax({
            url: `${ctx}/sys/oauth/client/get/${id}`,
            type: 'get',
            async: false,
            success: function (res) {
                if (res.flag) {
                    appInfo = res.data;
                }
            },
            error: function (err) {
                layer.msg('数据请求异常', {icon: 5});
            }
        });
        return appInfo;
    }


    const deleteRow = function (id, callback) {
        $.delete(`${ctx}/sys/oauth/client/delete/${id}`, {}, function (res) {
            res.msg = res.flag ? '删除成功' : res.msg;
            let icon = res.flag ? 1 : 5;
            layer.msg(res.msg, {icon, time: 2000}, function () {
                if (res.flag) {
                    clientTable.reload();
                }
            });
            callback && callback();
        });
    }


    /**
     * 数据表格点击事件
     */
    const tableEventCallback = function (obj) {
        let rowData = obj.data;
        switch (obj.event) {
            case 'add':
                openAppEditLayer();
                break;
            case 'query':
                searchText = $('#searchKeyInput').val().trim();
                let queryOps = {page: {current: 1}}
                if (searchText) {
                    queryOps.where = {title: searchText}
                }
                if ('' == searchText) {
                    queryOps.where = {title: null}
                }
                clientTable.reload(queryOps);
                break;
            case 'edit':
                openAppEditLayer(rowData.id);
                break;
            case 'delete':
                layer.confirm('确定要删除该条数据吗？', function (index) {
                    deleteRow(rowData.id, () => {
                        layer.close(index)
                    });
                });
                break;
        }
    }

    const dsTableOptions = {
        id: 'dsTable',
        url: `${ctx}/sys/oauth/client/page`,
        method: 'post',
        cols: [[
            {field: 'id', title: '客户端ID', hide: true},
            {field: 'title', title: '客户端名称', width: 350},
            {field: 'webServerRedirectUri', title: '客户端访问地址'},
            {
                field: 'target',
                title: '打开方式',
                width: 200,
                align: 'center',
                templet: data => data.target == '_blank' ? '新标签页' : '当前页'
            },
            {
                field: 'userSync',
                title: '用户数据同步',
                width: 200,
                align: 'center',
                templet: data => data.userSync == 'true' ? '是' : '否'
            },
            {fixed: 'right', align: 'center', title: '操作', toolbar: '#rowToolBar', width: 150}
        ]],
        onToolBarTable: tableEventCallback,
        onToolBarRow: tableEventCallback,
        done: function (res) {
            $('#searchKeyInput').val(searchText);
        }
    }
    clientTable = gtable.init(dsTableOptions);
});