import {readFile, readFileSync} from "fs";
import path from "path";
interface Word{
    bsm:string
    hz:string
    pyJs:string[]
    id:number
}
interface Ret{
    data:Word[]
    message:string
    haveMess:boolean
}
let words:Word[] = []

const loadWords = ()=>{
    const wordRaw =  readFileSync('./word.json','utf-8')
    words = JSON.parse(wordRaw)
    for (let i = 0; i< words.length ; i++){
        words[i].id =i;
    }
}

export default defineEventHandler((event):Ret=>{
    if (words.length===0){
        loadWords()
    }
    const retWords:Word[] = []
    const query = getQuery(event)
    // @ts-ignore
    if (query.words=="错误"||query.method=="错误"||!(query.method=="bsmf"||query.method=="bsmc"||query.method=="hz")||query.words.length>20){
        return {
            data:[],
            message:"参数错误",
            haveMess:true
        }
    }
    const word:string = query.words as unknown as string
    if (word==""){
        return {
            data:words,
            message:"",
            haveMess:false
        }
    }
    if (query.method=="hz"){
        for (let i =0;i<word.length;i++){
            for (let j=0;j<words.length;j++){
                if (words[j].hz.includes(word[i])){
                    let newWords:Word = words[j]
                    retWords.push(newWords)
                }
            }
        }
    }else if (query.method=="bsmf"){
        words.forEach((wf,index)=>{
            if (wf.bsm.startsWith(word)) retWords.push(wf)
        })
    }else if(query.method=="bsmc"){
        words.forEach((wf,index)=>{
            if (wf.bsm.includes(word)) retWords.push(wf)
        })
    }
    return {
        data:retWords,
        message:"",
        haveMess:false
    }
})