<?php

namespace app\admin\model;

use app\BaseModel;
use think\facade\Db;


class KeywordLanguages  extends BaseModel
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    
    // 语言表对应关键词
    public function keyword()
    {
        return $this->belongsTo(Keyword::class, 'keyword_id');
    }


    //根据聊天内容匹配关键词
    public static function getKeywordByContent($content){
        $content = strip_tags($content);
        //缓存关键词列表
        $keywordList = cache('keywordList');
        //if (!$keywordList) {
            $keywordList = self::where('status', 1)->field(['id','language_code', 'name'])->order('weight','desc')->select()->toArray();
            cache('keywordList', $keywordList);
        //}
        //$keyword_ids = KeywordLanguages::getKeywordByContent($param['content']);
        $list = [];
        $all_match = [];//完全匹配的关键词
        $match = []; //模糊匹配的关键词
        foreach ($keywordList as $keyword) {
            //判断content是否包含关键词
            if (strpos($content, $keyword['name']) !== false) {
                if ($keyword['name'] == $content) {
                    $all_match[] = $keyword['id'];
                } else {
                    $match[] = $keyword['id'];
                }
                $list[] = $keyword['id'];
            }
        }
        if ($all_match) {
            Db::name('keyword_languages')->whereIn('id', $all_match)->inc('all_match_num', 1)->update();
        }
        if ($match) {
            Db::name('keyword_languages')->whereIn('id', $match)->inc('match_num', 1)->update();
        }
        return $list;
    }
}