﻿
@Component
export default class MyClearFeishuBot extends Script {
    // DS服务器多少秒向KV服务器拿一次Bot的链接，不建议太频繁获取，一般也不会改这个
    @mw.Property({ displayName: "Bot链接更新频率(s)", tooltip: "DS服务器多少秒向KV服务器拿一次Bot的链接，不建议太频繁获取，一般也不会改这个" })
    private IntervalOfUpdateLink: number = 60;
    // 是否允许客户端调方法用消息机器人
    @mw.Property({ displayName: "允许客户端发送", tooltip: "是否允许客户端调方法用消息机器人（没有需要的话建议不开），本质上是做了一次rpc，实际还是在服务器上调用，url不暴露给C端是比较安全的" })
    private allowClientSend: boolean = false
    // 当前Bot机器人的链接
    private curBotLink: string = undefined;
    // 脚本实例
    public static instance: MyClearFeishuBot = undefined;
    /** 当脚本被实例后，会在第一帧更新前调用此函数 */
    protected onStart(): void {
        MyClearFeishuBot.instance = this;
        if (SystemUtil.isServer()) {


            if (SystemUtil.isServer()) {
                if (SystemUtil.isPIE) {
                    DataStorage.setTemporaryStorage(true);
                }
                else {
                    DataStorage.setTemporaryStorage(false);
                }
            }


            // 尝试获取BotUrl
            this.getBotUrl()
            /**设置更新检测，方便开发者在创作者中心统一配置 */
            setInterval(() => {
                this.getBotUrl()
            }, this.IntervalOfUpdateLink * 1000)
            // 添加监听器
            Event.addClientListener("MyClearFeishuBotSend2Feishu", (eventplayer: Player, msg: string) => {
                // 如果允许客户端发送的话，服务器会把消息发出来的
                if (this.allowClientSend) {
                    this.send2Feishu(msg);
                }
                else {
                    console.warn("[MyClearFeishuBot] 哦吼~ 你好像没有打开允许客户端发送功能，这里就不给你发送了哦");
                }
            })
        }
    }


    /**[双端可用] 将文本内容发送给飞书机器人，如果不在属性列表把“允许客户端发送”打开的话，是无法让客户端发送飞书信息的
     * @param str 要发送的文本内容
     */
    public static sendText(str: string) {
        // 如果是服务器，直接调方法实现
        if (SystemUtil.isServer()) {
            MyClearFeishuBot.instance.send2Feishu(str)
        } else {
            // 如果是客户端，发送事件给服务器，服务器来实现
            Event.dispatchToServer("MyClearFeishuBotSend2Feishu", str)
        }
    }

    /**[仅服务器] 发送消息的实现
     * @param str 
     */
    private send2Feishu(str: string) {
        if (SystemUtil.isServer() && this.curBotLink != undefined) {
            mw.fetch(this.curBotLink, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: `{ "msg_type": "text", "content": { "text": "${str}" } }`
            });
        }

    }

    //[仅服务器] 获取并设置当前kv后台的bot机器人的url
    private getBotUrl() {
        if (SystemUtil.isServer()) {
            DataStorage.asyncGetData("MyClearFeishuBot").then(result => {
                /**如果kv存储服务器上没有任何信息 */
                if (result && result.code == 200 && result.data == undefined) {
                    // 初始化为“请在这里填入你飞书Bot的WebHook”
                    DataStorage.asyncSetData("MyClearFeishuBot", "请在这里填入你飞书Bot的WebHook")
                    console.warn("[MyClearFeishuBot] 请在创作者中心>游戏服务>数据储存>数据类型自定义>搜索key:“MyClearFeishuBot”，并填上你的飞书Bot的WebHook地址");
                }
                else if (result && result.code == 200 && result.data != undefined) {
                    if (result.data == "请在这里填入你飞书Bot的WebHook") {
                        console.warn("[MyClearFeishuBot] 请在创作者中心>游戏服务>数据储存>数据类型自定义>搜索key:“MyClearFeishuBot”，并填上你的飞书Bot的WebHook地址");
                    }
                    else {
                        if (this.curBotLink != result.data) {
                            console.log("[MyClearFeishuBot] 获取BotUrl成功，旧址：“" + this.curBotLink + "”已更改为新址：“" + result.data + "”");
                            this.curBotLink = result.data;
                        }
                        else {
                            console.log("[MyClearFeishuBot] 获取BotUrl成功，无更新，沿用旧址：“" + this.curBotLink + "”")
                        }
                    }
                }
                else {
                    console.warn("[MyClearFeishuBot] 尝试获取BotUrl失败，错误代码" + result.code);
                }
            })
        }
        else {
            return;
        }
    }



}