<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>ElementSync - AppUIAuto</title>
    <link rel="stylesheet" href="./layui/css/layui.css" media="all">
    <link rel="stylesheet" href="./layui/modules/css/soulTable.css" media="all"/>
    <script type="text/javascript" src="./layui/layui.js"></script>
    <script type="text/javascript" src="./layui/clipboard.js"></script>
</head>
<body>
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo layui-bg-black">ElementSync</div>
        <!-- 头部区域（可配合layui 已有的水平导航） -->
        <div class="layui-fluid">
            <div class="layui-row">
                <form class="layui-form layui-form-pane" action="" style="margin-left: 190px;padding: 10px">
                    <div class="layui-form-item">
                        <label class="layui-form-label layui-hide-xs" style="width: 180px">请输入页面对象根目录</label>
                        <div class="layui-input-inline layui-hide-xs" style="width: 45%">
                            <input type="text" name="rootPath" lay-verify="required" placeholder="请输入页面对象根目录"
                                   autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-form-mid" style="padding: 0!important;">
                            <button type="button" class="layui-btn" lay-submit lay-filter="formSubmit">立即同步</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <!-- 左侧导航区域（可配合layui已有的垂直导航） -->
            <ul class="layui-nav layui-nav-tree">
                <li class="layui-nav-item layui-nav-itemed">
                    <a href="#">特殊分组</a>
                    <dl class="layui-nav-child">
                        <dd><a class="pageRequest" href="#"
                               data-param="{&quot;elementType&quot;: &quot;&quot;,&quot;pageID&quot;: &quot;&quot;}">全部数据</a>
                        </dd>
                        <dd><a class="pageRequest" href="#"
                               data-param="{&quot;elementType&quot;: 3,&quot;pageID&quot;: &quot;&quot;}">个人数据</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item">
                    <a href="#">Py文件读取</a>
                    <dl id="view" class="layui-nav-child"></dl>
                </li>
            </ul>
        </div>
        <script id="itemData" type="text/html">
            {{# layui.each(d, function(index, item){ }}
            <dd><a class="pageRequest" href="#"
                   data-param="{&quot;pageID&quot;: &quot;{{ item.pageID }}&quot;}">{{
                item.pageName }}</a></dd>
            {{# }); }}
            {{# if(d.length === 0){ }}
            <dd><a href="#">未加载到数据</a></dd>
            {{# } }}
        </script>
    </div>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="margin: 20px">
            <form class="layui-row layui-form layui-form-pane" action="">
                <div class="layui-hide layui-form-item">
                    <input type="text" name="selectType" value="fuzzy">
                </div>
                <div class="layui-col-sm12 layui-form-item">
                    <div class="layui-inline" style="display: inline">
                        <label class="layui-form-label" style="width: 60px;">名称</label>
                        <div class="layui-input-inline" style="width: 12%;">
                            <input type="text" name="elementName" class="layui-input" placeholder="请输入元素名称">
                        </div>
                    </div>
                    <div class="layui-inline" style="display: inline">
                        <label class="layui-form-label" style="width: 90px;">Android</label>
                        <div class="layui-input-inline" style="width: 18%;">
                            <input type="text" name="elementAndroidLocate" class="layui-input"
                                   placeholder="请输入Android定位关键值">
                        </div>
                    </div>
                    <div class="layui-inline" style="display: inline">
                        <label class="layui-form-label" style="width: 60px;">IOS</label>
                        <div class="layui-input-inline" style="width: 18%;">
                            <input type="text" name="elementIOSLocate" class="layui-input" placeholder="请输入IOS定位关键值">
                        </div>
                    </div>
                    <div class="layui-inline" style="display: inline">
                        <label class="layui-form-label" style="width: 60px;">备注</label>
                        <div class="layui-input-inline" style="width: 12%;">
                            <input type="text" name="elementRemark" class="layui-input" placeholder="请输入备注">
                        </div>
                    </div>
                    <div class="layui-inline" style="display: inline">
                        <button type="button" class="layui-btn mgl-20" lay-submit lay-filter="search"><i
                                class="layui-icon">&#xe615;</i>查询
                        </button>
                        <button class="layui-btn layui-btn-primary" type="reset" lay-active="reset">重置</button>
                    </div>
                </div>
            </form>
            <table id="myTable" lay-filter="myTable"></table>
            <script type="text/html" id="expandAll">
                <div class="layui-card" style="margin: 10px;border: 1px solid #f1f2f6;">
                    <div class="layui-card-header" style="background-color: #ced6e0">
                        <h3 style="display: inline">Python代码</h3>
                        <button data-clipboard-target="#{{d.elementName}}" style="display: inline;margin-bottom: 5px;"
                                type="button" class="js-clipboard layui-btn layui-btn-radius layui-btn-primary">
                            一键复制
                        </button>
                    </div>
                    <div id="{{d.elementName}}" class="layui-card-body" style="background-color: #2b2b2b">
                        <h3>
                            # {{d.elementRemark}}<br>
                            <span style="color: #90548c">self</span><span style="color: #a2b1bd">.{{d.elementName}}_locator ={</span><br>
                            {{# if(typeof d.elementAndroidLocate == 'string' && d.elementAndroidLocate.length > 0){ }}
                            <div style="text-indent: 1em"><span style="color: #638655">'Android'</span><span
                                    style="color: #a2b1bd">: {</span></div>
                            <div style="text-indent: 2em"><span style="color: #638655">{{d.elementAndroidLocate}}</span>
                            </div>
                            <div style="text-indent: 1em"><span style="color: #a2b1bd">}</span><span
                                    style="color: #cb7530">,</span></div>
                            {{# } }}
                            {{# if(typeof d.elementIOSLocate == 'string' && d.elementIOSLocate.length > 0){ }}
                            <div style="text-indent: 1em"><span style="color: #638655">'iOS'</span><span
                                    style="color: #a2b1bd">: {</span></div>
                            <div style="text-indent: 2em"><span style="color: #638655">{{d.elementIOSLocate}}</span>
                            </div>
                            <div style="text-indent: 1em"><span style="color: #a2b1bd">}</span></div>
                            {{# } }}
                            <span style="color: #a2b1bd">}</span><br>
                            <span style="color: #90548c">self</span><span style="color: #a2b1bd">.{{d.elementName}} = Element(</span><span
                                style="color: #90548c">self</span><span
                                style="color: #a2b1bd">.d</span><span style="color: #cb7530">,</span> <span
                                style="color: #90548c">self</span><span
                                style="color: #a2b1bd">.{{d.elementName}}_locator)</span><br>
                        </h3>
                    </div>
                </div>
            </script>
            <script type="text/html" id="toolbar">
                <a class="layui-btn layui-btn-sm" lay-event="clearFilter">清除所有筛选条件</a>
                <a class="layui-btn layui-btn-sm" lay-event="addElement">添加</a>
            </script>
            <script type="text/html" id="elementTypeTpl">
                {{# if(d.elementType === 0){ }}
                <div style="background-color: #5FB878;border-radius:5px;text-align: center;color: #ffffff">已保存</div>
                {{# } else if(d.elementType === 1){ }}
                <div style="background-color: #FF5722;border-radius:5px;text-align: center;color: #ffffff">新添加</div>
                {{# } else if(d.elementType === 2){ }}
                <div style="background-color: #FFB800;border-radius:5px;text-align: center;color: #ffffff">被修改</div>
                {{# } else { }}
                <div style="background-color: #2F4056;border-radius:5px;text-align: center;color: #ffffff">未知</div>
                {{# } }}
            </script>
        </div>
    </div>

    <div class="layui-footer">
        <!-- 底部固定区域 -->
        <div class="layui-layout-right" style="margin-right: 30px">
            作者：张远涛&emsp;&emsp;说明文档：<a href="http://www.baidu.com">http://www.baidu.com</a>
        </div>
    </div>
</div>
<script>
    // 自定义模块
    layui.config({
        base: '/layui/modules/'   // LayUI第三方模块所在目录
        , layimResPath: '/layui/modules/layim/dist/layim-assets/'   // LayIM模块资源存放路径
    }).extend({
        soulTable: 'soulTable/soulTable',
        tableChild: 'soulTable/tableChild',
        tableMerge: 'soulTable/tableMerge',
        tableFilter: 'soulTable/tableFilter',
        excel: 'soulTable/excel',
        layim: 'layim/dist/layim'   // 导入LayIM模块
    });

    //JS
    layui.use(['element', 'layer', 'util', 'upload', 'form', 'table', 'soulTable', 'laytpl', 'layim'], function () {
        const element = layui.element
            , layer = layui.layer
            , util = layui.util
            , upload = layui.upload
            , form = layui.form
            , table = layui.table
            , soulTable = layui.soulTable
            , laytpl = layui.laytpl
            , layim = layui.layim
            , $ = layui.$;

        let clipboard;
        let elementType = "";
        let pageID = "";

        function menuClick() {
            $(".pageRequest").click(function (data) {
                const param = JSON.parse(data.target.getAttribute("data-param"));
                elementType = param.elementType;
                pageID = param.pageID;
                table.reload('myTable', {
                    where: param
                })
            });
        }

        function flashPages() {
            $.get('/page/all', function (response) {
                const data = response.data;
                const getTpl = itemData.innerHTML
                    , view = document.getElementById('view');
                laytpl(getTpl).render(data, function (html) {
                    view.innerHTML = html;
                });
                menuClick();
                element.render();
            });
        }

        // 页面加载初始化时触发
        $(function () {
            /* 删除之前的聊天记录 */
            let cache =  layui.layim.cache();
            let local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
            //删除本地聊天记录
            delete local.chatlog;
            //向localStorage同步数据
            layui.data('layim', {
                key: cache.mine.id
                ,value: local
            });

            // 初始化时最小化聊天窗口
            layim.setChatMin();
            // 设置聊天状态，此处作为初始化提示
            layim.setChatStatus('<span style="color:#2678b3;">tips: 国外服务加载较慢，请耐心等待哦~</span>');

            // 向 chatgpt 表插入一个 myprompt 字段，如果该表不存在，则自动建立，用于存储聊天上下文
            layui.sessionData('chatgpt', {
                key: 'myprompt'
                , value: ''
            });

            flashPages();
            clipboard = new ClipboardJS('.js-clipboard');
            clipboard.on('success', function (e) {
                layer.msg('复制成功');
                e.clearSelection();
            });

            clipboard.on('error', function (e) {
                layer.msg('复制失败');
            });
        });

        // 提交同步元素请求
        form.on('submit(formSubmit)', function (data) {
            const loading = layer.load(2);
            $.ajax({
                type: 'post',
                url: '/element/sync',
                dataType: 'json',
                data: data.field,
                success: function (res) {
                    layer.close(loading);
                    table.reload('myTable', {
                        where: {
                            elementType: ''
                        }
                    })
                    flashPages();
                    if (res.code == "0") {
                        layer.open({
                            title: '同步结果'
                            , content: '同步成功'
                            , icon: 1
                        });
                    } else {
                        layer.open({
                            title: '同步结果'
                            , content: '同步失败，请检查路径是否正确！'
                            , icon: 2
                        });
                    }
                },
                error: function (errMsg) {
                    layer.close(loading);
                    console.log(errMsg);
                }
            })
            return false;
        });

        // 提交搜索请求
        form.on('submit(search)', function (data) {
            data.field["elementType"] = elementType;
            data.field["pageID"] = pageID;
            table.reload('myTable', {
                where: data.field
            })
        });

        //处理属性 为 lay-active 的所有元素事件
        util.event('lay-active', {
            reset: function (othis) {
                table.reload('myTable', {
                    where: {
                        elementType: elementType,
                        pageID: pageID
                    }
                })
            }
        });

        table.render({
            elem: '#myTable'
            , id: 'myTable'
            , url: '/element/data'
            , where: {
                elementType: ''
            }
            , height: 'full-200'
            , toolbar: '#toolbar'
            , page: false
            , totalRow: true
            , defaultToolbar: ['filter', 'exports']
            , overflow: {
                type: 'title'
                , hoverTime: 300 // 悬停时间，单位ms, 悬停 hoverTime 后才会显示，默认为 0
                , color: 'black' // 字体颜色
                , bgColor: 'white' // 背景色
            }
            , initSort: {
                field: 'elementType' //排序字段，对应 cols 设定的各字段名
                , type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
            }
            , cols: [
                [
                    {title: '#', width: 50, children: '#expandAll', childWidth: 'full'},
                    {
                        field: 'elementType',
                        title: '元素状态',
                        width: 140,
                        sort: true,
                        filter: true,
                        templet: '#elementTypeTpl'
                    },
                    {field: 'elementName', title: '元素名', width: 200, sort: true, filter: true},
                    {field: 'elementAndroidLocate', title: '元素Android端定位值', width: 485, sort: true, filter: true},
                    {field: 'elementIOSLocate', title: '元素IOS端定位值', width: 485, sort: true, filter: true},
                    {field: 'elementRemark', title: '元素备注', width: 300, filter: true},
                    // {field: 'pageID', title: '所属页面ID', width: 200, sort: true, filter: true},
                ]
            ]
            , done: function (data) {
                soulTable.render(this);
            }
        });

        table.on('toolbar(myTable)', function (obj) {
            if (obj.event === 'clearFilter') {
                // 清除所有筛选条件并重载表格
                // 参数: tableId
                soulTable.clearFilter('myTable')
            } else if (obj.event === 'addElement') {
                layer.open({
                    type: 2,
                    area: ['700px', '450px'],
                    fixed: false, //不固定
                    maxmin: true,
                    resizing: false,
                    content: 'addElement',
                    success: function (layero, index) {
                        let iframe = window['layui-layer-iframe' + index];
                        console.log(iframe);
                        // console.log("父组件" + pageID);
                        iframe.child(pageID);
                    }
                });
            } else if (obj.event === 'chatGPT') {
                layer.open({
                    type: 2,
                    area: ['900px', '1000px'],
                    fixed: false, //不固定
                    maxmin: true,
                    resizing: false,
                    content: 'chatGPT'
                });
            }
        });

        // LayIM模块配置，并创建一个简约的聊天窗口
        layim.config({
            brief: true //是否简约模式（如果true则不显示主面板）
            , minRight: '370px' // 用户控制聊天面板最小化时、及新消息提示层的相对right的px坐标。
        }).chat({
            name: 'ChatGPT'
            , type: 'friend'
            , avatar: 'static/chatgpt.png'
            , id: -2
        });

        // 发送消息事件
        layim.on('sendMessage', function (res) {
            /* 获取聊天中对方的信息，并将状态装换为输入中 */
            let To = res.to;
            if(To.type === 'friend'){
                layim.setChatStatus('<span style="color:#ffa502;">(๑･`◡´･๑) 正在努力输入…</span>');
            }

            /* 获取聊天中自己的信息 */
            let Mine = res.mine;
            /* 读取sessionData中的上下文，并将本次的问题添加到上下文后面 */
            let localChatGPT = layui.sessionData('chatgpt');
            layui.sessionData('chatgpt', {
                key: 'myprompt'
                , value: localChatGPT.myprompt + " Q1:" + Mine.content
            });

            /* 发送ChatGPT请求，获取回答 */
            $.ajax({
                type: 'post',
                url: 'https://api.openai.com/v1/completions',
                // sk-xxxxxxxxx为OpenAI的api-key，每个账号有18美元的免费额度
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer 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"
                },
                dataType: 'json',
                data: JSON.stringify({
                    "prompt": layui.sessionData('chatgpt').myprompt,
                    "max_tokens": 2048,
                    "model": "text-davinci-003"
                }),
                success: function (res) {
                    // 将ChatGPT的回答添加到上下文中
                    layui.sessionData('chatgpt', {
                        key: 'myprompt'
                        , value: layui.sessionData('chatgpt').myprompt + " A1:" + res.choices[0].text
                    });
                    // 取消输入中状态，变为在线状态
                    layim.setChatStatus('<span style="color:#2ed573;">o(￣▽￣)ｄ 在线</span>');
                    // 回答可能为空，需要做下判断
                    if (res.choices[0].text.trim().length != 0) {
                        // 接受消息
                        layim.getMessage({
                            username: To.name //消息来源用户名
                            , avatar: To.avatar //消息来源用户头像
                            , id: To.id //消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
                            , type: To.type //聊天窗口来源类型，从发送消息传递的to里面获取
                            , content: res.choices[0].text.replace(/A1:/g, '').replace(/A1：/g, '').trim() //消息内容
                            , fromid: To.id //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题，不加会导致回答出现在聊天窗口的右边
                            , mine: false //是否我发送的消息，如果为true，则会显示在右方
                        });
                    } else {
                        layim.getMessage({
                            system: true //系统消息
                            , id: -2 //聊天窗口ID
                            , type: "friend" //聊天窗口类型
                            , content: 'w(ﾟДﾟ)w 对方不想理你，麻烦稍后再试~'
                        });
                    }
                },
                error: function (errMsg) {
                    if (errMsg.status === 503 || errMsg.status === 429) {
                        layim.setChatStatus('<span style="color:#ff4757;">X﹏X 失联中</span>');
                        //如果是来自于系统的聊天面板的消息
                        layim.getMessage({
                            system: true //系统消息
                            , id: -2 //聊天窗口ID
                            , type: "friend" //聊天窗口类型
                            , content: 'w(ﾟДﾟ)w 太多请求啦，麻烦稍后再试~'
                        });
                    }
                }
            })
        });
    });
</script>
</body>
</html>