UpdateSeoTdk.php 14.7 KB
<?php

namespace App\Console\Commands;

use App\Helper\Arr;
use App\Helper\Common;
use App\Helper\Gpt;
use App\Helper\Translate;
use App\Models\Ai\AiCommand;
use App\Models\Mail\Mail;
use App\Models\Project\DeployOptimize;
use App\Models\User\User;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * 初始化项目
 * Class InitProject
 * @package App\Console\Commands
 * @author zbj
 * @date 2023/10/8
 */
class UpdateSeoTdk extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update_seo_tdk';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '一键生成tdk';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * '表' => [
     *      '指令key' => '表字段'
     * ]
     * @return array
     * @author zbj
     * @date 2023/11/3
     */
    protected $maps = [
        'gl_web_custom_template' => [
            'page_title' => 'title',
            'page_meta_keywords' => 'keywords',
            'page_meta_description' => 'description',
        ],
        'gl_product' => [
            'product_title' => 'seo_mate.title',
            'product_meta_keywords' => 'seo_mate.keyword',
            'product_meta_description' => 'seo_mate.description',
        ],
        'gl_product_category' => [
            'product_cat_title' => 'seo_title',
            'product_cat_meta_keywords' => 'seo_keywords',
            'product_cat_meta_description' => 'seo_des',
        ],
        'gl_blog' => [
            'blog_title' => 'seo_title',
            'blog_meta_keywords' => 'seo_keywords',
            'blog_meta_description' => 'seo_description',
        ],
        'gl_blog_category' => [
            'blog_cat_title' => 'seo_title',
            'blog_cat_meta_keywords' => 'seo_keywords',
            'blog_cat_meta_description' => 'seo_des',
        ],
        'gl_news' => [
            'news_title' => 'seo_title',
            'news_meta_keywords' => 'seo_keywords',
            'news_meta_description' => 'seo_description',
        ],
        'gl_news_category' => [
            'news_cat_title' => 'seo_title',
            'news_cat_meta_keywords' => 'seo_keywords',
            'news_cat_meta_description' => 'seo_des',
        ],
        'gl_product_keyword' => [
            'tags_title' => 'seo_title',
            'tags_meta_keywords' => 'seo_keywords',
            'tags_meta_description' => 'seo_description',
            'tags_content_title' => 'keyword_title',
            'tags_content_description' => 'keyword_content',
        ]
    ];

    /**
     * topic-对相应字段
     * @var array
     */
    protected $topic_fields = [
        'gl_web_custom_template' => 'name',
        'gl_product' => 'title',
        'gl_product_category' => 'title',
        'gl_blog' => 'name',
        'gl_blog_category' => 'name',
        'gl_news' => 'name',
        'gl_news_category' => 'name',
        'gl_product_keyword' => 'title'
    ];

    /**
     * 使用核心关键词的key 数量
     * @var array
     */
    protected $core_keyword_keys = [
        'page_meta_keywords' => 1,
        'blog_cat_meta_keywords' => 8,
        'news_cat_meta_keywords' => 8,
    ];

    /**
     * @return bool
     */
    public function handle()
    {
        while (true) {
            $project_id = Redis::rpop('updateSeoTdk');
            if (!$project_id) {
                sleep(2);
                continue;
            }
            echo date('Y-m-d H:i:s') . ' start project_id: ' . $project_id . PHP_EOL;
            try {
                ProjectServer::useProject($project_id);
                $this->seo_tdk($project_id);
                DB::disconnect('custom_mysql');
            }catch (\Exception $e){
                echo date('Y-m-d H:i:s') . ' error: ' . $project_id . '->' . $e->getMessage() . PHP_EOL;
            }
            echo date('Y-m-d H:i:s') . ' end: ' . $project_id . PHP_EOL;
        }
    }

    public function seo_tdk($project_id)
    {
        $data = [];
        $update = [
            'created_at'=>date('Y-m-d H:i:s')
        ];//更新统计
        $ai_commands = AiCommand::where('is_batch', 1)->select('key', 'scene', 'ai')->get()->toArray();
        $ai_commands = Arr::setValueToKey($ai_commands, 'key');
        foreach ($this->maps as $table => $map) {
            $update[$table] = ['total_page'=>0, 'title'=>0, 'keyword'=>0, 'des'=>0];
            echo date('Y-m-d H:i:s') . '更新--' . $table . ': 项目id' . $project_id . PHP_EOL . json_encode($update[$table]);
            $list = DB::connection('custom_mysql')->table($table)->get()->toArray();
            if (!empty($list)) {
                foreach ($list as $v) {
                    echo '打印数据:'.date('Y-m-d H:i:s') . $update[$table]['total_page'].PHP_EOL;
                    $update[$table]['total_page']++;
                    $v = (array)$v;
                    echo date('Y-m-d H:i:s') . '更新--' . $table . ':id' . $v['id'] . PHP_EOL;
                    $data = [];
                    $json_field = '';
                    echo date('Y-m-d H:i:s') . json_encode($map) . PHP_EOL;
                    foreach ($map as $ai_key => $field) {
                        $field_arr = explode('.', $field);
                        if (count($field_arr) > 1) {
                            $json_field = $field_arr[0];
                            $value = json_decode($v[$field_arr[0]], true)[$field_arr[1]] ?? '';
                        } else {
                            $value = $v[$field] ?? '';
                        }
                        //已有值的 跳过
                        if ($value) {
                            echo $field.'已有值 跳过' . PHP_EOL;
                            continue;
                        }
                        //AI生成
                        if (!empty($ai_commands[$ai_key]['ai'])) {
                            $prompt = $this->getPrompt($project_id, $ai_commands[$ai_key]['ai'], $table, $v);
                            if(!$prompt){
                                continue;
                            }
                            echo date('Y-m-d H:i:s') . 11111111 . PHP_EOL;
                            if (count($field_arr) > 1) {
                                if($field_arr[1] == 'title'){
                                    $update[$table]['title']++;
                                }elseif ($field_arr[1] == 'keyword'){
                                    $update[$table]['keyword']++;
                                }elseif ($field_arr[1] == 'description'){
                                    $update[$table]['des']++;
                                }
                                $data[$field_arr[0]][$field_arr[1]] = $this->ai_send($prompt);
                            }else{
                                if($field == 'title' || $field == 'seo_title'){
                                    $update[$table]['title']++;
                                }
                                if($field == 'keywords' || $field == 'seo_keywords'){
                                    $update[$table]['keyword']++;
                                }
                                if($field == 'seo_description' || $field == 'description' || $field == 'seo_des'){
                                    $update[$table]['des']++;
                                }
                                $data[$field] = $this->ai_send($prompt);
                            }
                        } else {
                            //直接使用topic
                            if (count($field_arr) > 1) {
                                $data[$field_arr[0]][$field_arr[1]] = $v[$this->topic_fields[$table]] ?? '';
                                //使用核心关键词
                                if(in_array($ai_key, array_keys($this->core_keyword_keys))){
                                    $data[$field_arr[0]][$field_arr[1]] = $this->mainKeywords($project_id, $this->core_keyword_keys[$ai_key]);
                                    if(!empty($data[$field_arr[0]][$field_arr[1]])){
                                        if($field_arr[1] == 'title'){
                                            $data[$table]['title']++;
                                        }elseif ($field_arr[1] == 'keyword'){
                                            $data[$table]['keyword']++;
                                        }elseif ($field_arr[1] == 'description'){
                                            $data[$table]['des']++;
                                        }
                                    }
                                }
                            }else{
                                echo date('Y-m-d H:i:s') . 22222222222222 .$field . PHP_EOL;
                                $data[$field] = $v[$this->topic_fields[$table]] ?? '';
                                //使用核心关键词
                                if(in_array($ai_key, array_keys($this->core_keyword_keys))){
                                    $data[$field] = $this->mainKeywords($project_id, $this->core_keyword_keys[$ai_key]);
                                    if(!empty($data[$field])){
                                        if($field == 'title' || $field == 'seo_title'){
                                            $update[$table]['title']++;
                                        }
                                        if($field == 'keywords' || $field == 'seo_keywords'){
                                            $update[$table]['keyword']++;
                                        }
                                        if($field == 'seo_description' || $field == 'description' || $field == 'seo_des'){
                                            $update[$table]['des']++;
                                        }
                                    }
                                }
                                echo date('Y-m-d H:i:s') . 333333 . PHP_EOL;
                            }
                        }
                    }
                    if(!$data){
                        continue;
                    }
                    if($json_field){
                        $old_data = json_decode($v[$field_arr[0]], true);
                        foreach ($old_data as $kk=>$vv){
                            empty($data[$json_field][$kk]) && $data[$json_field][$kk] = $vv;
                        }
                        $data[$json_field] = json_encode($data[$json_field]);
                    }
                    DB::connection('custom_mysql')->table($table)->where(['id' => $v['id']])->update($data);
                }
                $update[$table] = json_encode($update[$table]);
            }
        }
        DB::table('gl_project_update_tdk')->insert($update);
    }

    public function getPrompt($project_id, $prompt, $table, $data){
        $lang = '';
        if(strpos($prompt, '{topic}') !== false){
            $topic = $data[$this->topic_fields[$table]] ?? '';
            if(!$topic){
                echo 'topic为空 跳过' . PHP_EOL;
                return false;
            }
            $prompt = str_replace('{topic}', $topic, $prompt);
            $lang = $this->getLang($topic);
        }
        if(strpos($prompt, '{keyword}') !== false) {
            $keyword = $this->mainKeywords($project_id, 1);
            if(!$keyword){
                echo '核心关键词为空 跳过' . PHP_EOL;
                return false;
            }
            $prompt = str_replace('{keyword}', $keyword, $prompt);
            !$lang && $lang = $this->getLang($keyword);
        }
        if(strpos($prompt, '{company name}') !== false) {
            $company_name = $this->companyName($project_id);
            if(!$company_name){
                echo '公司英文全称为空 跳过' . PHP_EOL;
                return false;
            }
            $prompt = str_replace('{company name}', $company_name, $prompt);
        }
        $prompt .= '.Please answer in ' . ($lang ?: 'English');

        echo $prompt . PHP_EOL;

        return $prompt;
    }

    /**
     * @remark :获取公司英文名称
     * @name   :companyName
     * @author :lyh
     * @method :post
     * @time   :2023/10/30 11:22
     */
    public function companyName($project_id, $key = '')
    {
        $data = [
            'product_long_description',
        ];
        $projectOptimizeModel = new DeployOptimize();
        $info = $projectOptimizeModel->read(['project_id' => $project_id], ['id', 'company_en_name', 'company_en_description']);
        if (in_array($key, $data)) {
            return $info['company_en_description'];
        } else {
            return $info['company_en_name'];
        }
    }

    /**
     * @remark :获取公司核心关键词
     * @name   :mainKeywords
     * @author :lyh
     * @method :post
     * @time   :2023/10/30 11:22
     */
    public function mainKeywords($project_id, $num)
    {
        $str = '';
        $projectOptimizeModel = new DeployOptimize();
        $info = $projectOptimizeModel->read(['project_id' => $project_id], ['id', 'main_keywords']);
        if (!empty($info['main_keywords'])) {
            $main_keywords = explode("\r\n", $info['main_keywords']);
            //随机取
            shuffle($main_keywords);
            $main_keywords = array_slice($main_keywords, 0, $num);
            $str = implode(",", $main_keywords);
        }
        return $str;
    }

    public function getLang($content){
        $result = Translate::translateSl($content);
        if (isset($result['texts']['sl']) && isset(Translate::$tls_list[$result['texts']['sl']])) {
            $lang = Translate::$tls_list[$result['texts']['sl']]['lang_en'];
        } else {
            $lang = 'English';
        }
        return $lang;
    }

    /**
     * @remark :AI发送
     * @name   :ai_send
     * @author :lyh
     * @method :post
     * @time   :2023/8/19 10:40
     */
    public function ai_send($prompt)
    {
        $text = Gpt::instance()->openai_chat_qqs($prompt);
        $text = Common::deal_keywords($text);
        return Common::deal_str($text);
    }

    /**
     * @remark :发送站内信
     * @name   :send_message
     * @author :lyh
     * @method :post
     * @time   :2023/11/4 10:22
     */
    public function send_message($project_id){
        $user = new User();
        $userInfo = $user->read(['project_id'=>$project_id,'role_id'=>0]);
        $data["title"] = "seo更新通知---完成";
        $data["user_list"] = $userInfo['id'];
        $data["content"] = "seo更新成功,更新完成时间".date('Y-m-d H:i:s');
        $mail = new Mail();
        return $mail->add($data);
    }
}