ProjectAssociationServices.php 6.7 KB
<?php

namespace App\Services\Aside\ProjectAssociation;

use App\Enums\Common\Code;
use App\Exceptions\BsideGlobalException;
use App\Models\ProjectAssociation\ProjectAssociation;
use App\Services\BaseService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class ProjectAssociationServices extends BaseService
{
    /**
     * 保存aicc与项目关系数据
     * @param array $data
     * @return bool
     * @throws BsideGlobalException
     */
    public function save(array $data)
    {
        $bool = false;
        DB::beginTransaction();
        try {
            # V6项目ID
            $project_id = (int)$data['project_id'] ?? 0;
            $isRes      = ProjectAssociation::query()->where('project_id', $project_id)->first();
            if (!$isRes) {
                $isRes             = new ProjectAssociation();
                $isRes->project_id = $project_id;
            }
            # AICC朋友ID
            $isRes->friend_id = $data['friend_id'] ?? 0;
            # AICC朋友昵称
            $isRes->nickname = $data['nickname'] ?? 0;
            # AICC用户ID
            $isRes->user_id = $data['user_id'] ?? 0;
            # AICC用户姓名
            $isRes->user_name = $data['user_name'] ?? '';
            # AICC朋友头像
            $isRes->image       = $data['image'] ?? '';
            $isRes->binding_app = $data['app'] ?? 1;
            $bool               = $isRes->save();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $e->getMessage();
            errorLog('V6与AICC关联失败', $data, $e);
            $this->fail('请检查操作是否正确!', Code::SERVER_MYSQL_ERROR);
        }
        return $bool;
    }

    /**
     * status - 正常
     * @param $project_id
     * @param $app
     * @return ProjectAssociation|Builder|Model|object|null
     */
    public function normal($project_id, $app)
    {
        return ProjectAssociation::query()->whereProjectId($project_id)->whereStatus(ProjectAssociation::STATUS_NORMAL)->whereBindingApp($app)->first();
    }

    /**
     * status - 禁用
     * @param $project_id
     * @return ProjectAssociation|Builder|Model|object|null
     */
    public function disabled($project_id)
    {
        return ProjectAssociation::query()->whereProjectId($project_id)->whereStatus(ProjectAssociation::STATUS_DISABLED)->first();
    }

    /**
     * 初始化数据/修改数据
     * @param $project_id
     * @param $status
     * @param $app
     * @return array
     */
    public function saveProject($project_id, $status, $app)
    {
        $bool = false;
        DB::beginTransaction();
        $isRes = $this->disabled($project_id);
        if (is_null($isRes)) {
            $isRes = new ProjectAssociation();
        }
        $isRes->project_id  = $project_id;
        $isRes->user_id     = (int)env('AICC_WECHAT_USER_ID');
        $isRes->status      = $status;
        $isRes->binding_app = $app;
        try {
            $bool = $isRes->save();
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
        }
        return compact('bool', 'isRes');
    }


    /**
     * 关闭状态
     * @param ProjectAssociation $res
     * @param int $status 1 - 正常, 0 - 禁用
     * @return bool
     */
    public function closedState($res, $status)
    {
        DB::beginTransaction();
        $bool = false;
        try {
            $res->status = $status;
            $bool        = $res->save();
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
        }
        return $bool;
    }

    /**
     * 获取AICC微信列表数据
     * @param ProjectAssociation $res
     * @param int $type 绑定app应用类型
     * @param bool $cache 是否缓存
     * @return mixed
     */
    public function getAiccWechatLists($res, $type = ProjectAssociation::PERSONAL_WECHAT, $cache = false)
    {
        $redis_key = 'aicc_friend_lists_' . $type . '_' . (int)env('AICC_WECHAT_USER_ID');
        $result    = $cache ? false : redis_get($redis_key);
        if (empty($result)) {
            $apiUrl = ProjectAssociation::getApplicationApiUrl($type);
            $url    = env('AICC_URL') . $apiUrl;
            $result = curlGet($url);
            if (!empty($result['data'])) {
                redis_set($redis_key, json_encode($result), 60);
            }
        } else {
            $result = json_decode($result, true);
        }
        $result['info'] = [
            'friend_id' => $res->friend_id ?? 0,
            'nickname'  => $res->nickname ?? '',
            'user_name' => $res->user_name ?? '',
            'image'     => $res->image ?? '',
        ];
        return $result;
    }

    /**
     * 获取AI客服列表
     * @author zbj
     * @date 2024/9/7
     */
    public function getWorkChatRoomList($search = '', $friend_id = 0){
        $param = [
            'search' => $search,
            'time' => time(),
        ];
        if(!$search && $friend_id){
            $param['friend_id'] = $friend_id;
        }
        $param['sign'] = $this->getSign($param);
        $url = 'https://hub.ai.cc/api/globalso_ai_customer_service/chatroom_list';
        $result = Http::withoutVerifying()->withOptions(['proxy' => env('CURL_PROXY')])->post($url, $param)->json();
        if(empty($result) || $result['status'] != 200){
            return [];
        }
        return $result;
    }

    /**
     * 获取AI客服列表
     * @throws \Exception
     * @author zbj
     * @date 2024/9/7
     */
    public function sendMessage($friend_id, $content, $type = 'Text'){
        $param = [
            'friend_id' => $friend_id,
            'content' => $content,
            'type' => $type,
        ];
        $param['sign'] = $this->getSign($param);
        $url = 'https://hub.ai.cc/api/globalso_ai_customer_service/send_msg';
        $result = Http::withoutVerifying()->withOptions(['proxy' => env('CURL_PROXY')])->timeout(30)->post($url, $param)->json();
        if(empty($result) || $result['status'] != 200){
            throw new \Exception($result['message'] ?? '');
        }
        return true;
    }

    /**
     * @param $data
     * @return string
     */
    public function getSign($data)
    {
        if (empty($data) || FALSE == is_array($data))
            return '';
        unset($data['sign']);
        ksort($data);
        // 放弃http_build_query 会将空数据字段抛弃
        // $string = http_build_query($data);
        $tem = [];
        foreach ($data as $key => $val) {
            $tem[] = $key . '=' . urlencode($val);
        }
        $string = implode('&', $tem);
        $key = md5('quanqiusou.com');
        $sign = md5($string . $key);
        return $sign;
    }
}