import BaseDirective from "../BaseDirective";
import { cut, extract } from '@congcongcai/jieba.js'
import Utils from "../../utils/Utils";
import { uniq } from "lodash"; 
import OpenSingleDirective from "./OpenSingleDirective";
import config from "../../config";

class OpenMenuDirective extends BaseDirective {
    static name="打开菜单或者模糊匹配打开菜单"
    static beforeLoadDirectives = [OpenSingleDirective]
    match() {
        const { text } = this
        let result = null
        if(!result) {
            result = text.match(/打开(.*)(?=(?:菜单|功能|路径))/)
        }
        if (!result) {
            result = text.match(new RegExp(`打开(.*)(?=(?:[${Array.from(config.punctuationMark).join("|")}]?))`))
        }
        if (result && result.length >= 2 && !this.matchResult) {
            this.matchResult = result[1]
        }
        return !!this.matchResult
    }

    async excute({
        sendMsg = function () {}
    }) {
        let widgets = null
        widgets = this.getCompleteMenus()
        if (!widgets) {
            widgets = this.getPatternMenus()
        }
        if (!widgets) {
            return sendMsg("没有查找到此菜单,请检查语音是否正确")
        }
        if (widgets.length == 1) {
            return sendMsg(this.handleOneSingleMenu(widgets[0]))
        } else {
            this.data = {}
            this.data.type = "widgets"
            this.data.widgets = widgets
             sendMsg(`${this.widgetsToMsg(widgets)}`)
        }
    }

    handleOneSingleMenu(widget) {
        if (widget.url) {
            this.openSingleMenu(widget)
            return `打开${widget.label}成功`
        } else {
            this.data = {}
            this.data.type = "widgets"
            this.data.widgets = widget.widgets
            return `你打开的${widget.label}是一个菜单组,${this.widgetsToMsg(widget.widgets)}`
        }
    }

    widgetsToMsg (widgets) {
        return `有以下${widgets.length}个菜单\n${widgets.map((widget, index) => `${index + 1}.${widget.label}${widget.widgets ? "(菜单组)" : ""}`).join("\n")}\n请语音确认一下打开第几个菜单`
    }

    getCompleteMenus() {
        const result = Utils.findMenus({
            name: this.matchResult
        })
        const { widgets } = result
        return widgets.length > 0 ? widgets : null
    }

    getPatternMenus() {
        const weights = extract(this.matchResult, 4)
        let data = []
        if (weights.length == 0) return null
        weights.map(({ word }) => {
            const name = new RegExp(word)
            const result = Utils.findMenus({
                name
            })
            if(result.widgets.length > 0) {
                data = data.concat(result.widgets)
            }
        })
        data = uniq(data)
        return data.length > 0 ? data : null
    }

    openSingleMenu(widget) {
        Utils.openMenu({widget})
    }
}


export default OpenMenuDirective