<?php


namespace App\Services;

use App\Exceptions\TencentImFriendException;
use App\Models\User;
use App\Models\UserFriendApplyRecord;
use App\Traits\TencentIm;
use Illuminate\Support\Facades\DB;

class TencentImFriendService
{
    use TencentIm;

    const ADD_FRIEND_TYPE_SINGLE = 'Add_Type_Single';   //表示单向加好友
    const ADD_FRIEND_TYPE_BOTH = 'Add_Type_Both';   //表示双向加好友
    const IM_IDENTIFIER_PREFIX = 'IM_USER_';

    const CHECK_FRIEND_TYPE_SINGLE = 'CheckResult_Type_Single'; //只会检查 From_Account 的好友表中是否有 To_Account，不会检查 To_Account 的好友表中是否有 From_Account
    const CHECK_FRIEND_TYPE_BOTH = 'CheckResult_Type_Both'; //既会检查 From_Account 的好友表中是否有 To_Account，也会检查 To_Account 的好友表中是否有 From_Account

    const ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK = 'AddSource_Type_100';   //加好友来源 通讯录

    const TENCENT_REST_APIS = [
        'friendAddItem' => 'v4/sns/friend_add',   //单个添加好友,
        'friendGet' => 'v4/sns/friend_get', //拉取好友,
        'friendCheck' => 'v4/sns/friend_check', //校验好友
        'black_add' => 'v4/sns/black_list_add', //拉黑好友
        'black_del' => 'v4/sns/black_list_delete', //删除拉黑好友
    ];

    static public function verifyUserApplyFriendExists(User $fromUser, User $toUser)
    {

    }

    //添加好友记录
    public function addApplyFriendRecord(User $user, array $options = [])
    {
        try {
            DB::beginTransaction();

            $toUser = User::find($options['to_user_id']);

            if (!$toUser) {
                throw new TencentImFriendException('好友账号不存在');
            }

            //检测是否已经有记录

            $friendApplyRecordModel = UserFriendApplyRecord::query()
                ->where(['from_user_id' => $user->id, 'to_user_id' => $toUser->id])
                ->latest()
                ->first();


            if ($friendApplyRecordModel) {
                if (UserFriendApplyRecord::APPLY_STATUS_100 === $friendApplyRecordModel->apply_status) {
                    throw new TencentImFriendException('已发出好友添加申请,请勿重复操作');
                }

                if (UserFriendApplyRecord::APPLY_STATUS_101 === $friendApplyRecordModel->apply_status) {
                    throw new TencentImFriendException('已经是好友关系,请勿重复操作');
                }

                if (UserFriendApplyRecord::APPLY_STATUS_101 === $friendApplyRecordModel->apply_status) {
                    throw new TencentImFriendException('已经是好友关系,请勿重复操作');
                }
            }


            if (!$friendApplyRecordModel) {
                $friendApplyRecordModel = new UserFriendApplyRecord();
            }

            //添加发起申请记录
            $applyData = [
                'from_user_id' => $user->id,
                'to_user_id' => $toUser->id,
                'type' => UserFriendApplyRecord::APPLY_TYPE_100,
                'apply_status' => UserFriendApplyRecord::APPLY_STATUS_102,
                'apply_raw_data' => [
                    'remark' => $options['remark'] ?? '',
                    'group' => $options['group_id'] ?? '',
                ],
            ];

            $friendApplyRecordModel->fill($applyData);

            //添加接收

            if (!$friendApplyRecordModel->save()) {
                throw new \Exception('写入好友申请记录失败');
            }
            DB::commit();
            return $friendApplyRecordModel;
        } catch (\Exception $e) {
            DB::rollBack();
            return ['error' => $e->getMessage()];
        } catch (TencentImFriendException $e) {
            DB::rollBack();
            return ['error' => $e->getMessage()];
        }

    }

    /**
     * 发起添加 IM 好友  （单个用户）
     * @param string $fromAccount
     * @param string $toAccount
     * @param array $options
     * @return \Psr\Http\Message\ResponseInterface
     * @throws TencentImFriendException
     * @throws \App\Exceptions\TencentImAccountException
     * @throws \App\Exceptions\TencentImException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function friendAddItem(string $fromAccount, string $toAccount, array $options = [])
    {
        //TODO 请求添加好友前先拉取好友状态

        $this->restApiName = self::TENCENT_REST_APIS['friendAddItem'];
        $baseApiHost = $this->getTencentImRestApiBaseHost();
        $params = self::prepareFriendAddItemOptions($fromAccount, $toAccount, $options);
        $apiResult = $this->requestApi($baseApiHost, $params);
        self::verifyApiResult($apiResult);
        if ($apiResult['ResultItem'][0]['ResultInfo'] || ($apiResult['ResultItem'][0]['ResultCode'] != 0)) {
            throw new TencentImFriendException('添加好友失败:  ' . $apiResult['ResultItem'][0]['ResultInfo']);
        }
        return $apiResult;
    }

    //拉取好友
    public function friendGet(string $fromAccount, int $pageStartIndex = 0)
    {
        $this->restApiName = self::TENCENT_REST_APIS['friendGet'];
        $baseApiHost = $this->getTencentImRestApiBaseHost();
        $params = [
            'From_Account' => $fromAccount,
            'StartIndex' => $pageStartIndex,
            'StandardSequence' => $StandardSequence ?? 0,
            'CustomSequence' => $CustomSequence ?? 0
        ];
        $apiResult = $this->requestApi($baseApiHost, $params);
        return $apiResult;
    }

    //检验好友
    public function friendCheck(string $fromAccount, array $toAccounts, string $checkType = self::ADD_FRIEND_TYPE_BOTH)
    {
        $this->restApiName = self::TENCENT_REST_APIS['friendCheck'];
        $baseApiHost = $this->getTencentImRestApiBaseHost();
        $params = [
            'From_Account' => $fromAccount,
            'To_Account' => $toAccounts,
            'CheckType' => 'CheckResult_Type_Both'
        ];
        $apiResult = $this->requestApi($baseApiHost, $params);
        self::verifyApiResult($apiResult);
        return $apiResult;
    }


    /**
     * 构建添加好友api 请求数组
     * @param string $fromAccount 需要添加好友的用户IM id
     * @param string $toAccount 被申请添加好友的用户IM id
     * @param array $options
     * @param string $options ['AddType']  加好友方式
     * @param string $options ['AddSource'] 好友来源
     * @param string $options ['ForceAddFlags'] 管理员强制加好友标记：1表示强制加好友，0表示常规加好友方式
     * @param string $options ['Remark'] 好友备注
     * @param string $options ['AddWording'] 形成好友关系时的附言信息
     * @param string $options ['GroupName'] 分组信息，添加好友时只允许设置一个分组
     * @return array
     */
    static public function prepareFriendAddItemOptions(string $fromAccount, string $toAccount, array $options)
    {
        // string $addType = self::ADD_FRIEND_TYPE_BOTH,
        // string $addSource = self::ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK,
        // string $remark = '',
        // bool $forceAddFlags = false
        $result = [
            'From_Account' => $fromAccount,
//            'AddSource' => $options['AddSource'] ?? self::ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK,  //好友来源
            'AddType' => $options['AddType'] ?? self::ADD_FRIEND_TYPE_BOTH, //加好友方式
            'ForceAddFlags' => empty($options['ForceAddFlags']) ? 0 : ($options['ForceAddFlags'] ? 1 : 0),         //管理员强制加好友标记：1表示强制加好友，0表示常规加好友方式
        ];

        $AddFriendItem = [];
        $AddFriendItem['To_Account'] = $toAccount;
        //好友来源
        $AddFriendItem['AddSource'] = $options['AddSource'] ?? self::ADD_FRIEND_ADD_SOURCE_TYPE_ADDRESS_BOOK;

        //好友备注
        if (!empty($options['Remark'])) {
            $AddFriendItem['Remark'] = $options['Remark'];
        }

        //形成好友关系时的附言信息
        if (!empty($options['AddWording'])) {
            $AddFriendItem['AddWording'] = $options['AddWording'];
        }

        //分组信息，添加好友时只允许设置一个分组
        if (!empty($options['GroupName'])) {
            $AddFriendItem['GroupName'] = $options['GroupName'] ? 1 : 0;
        }

        $result['AddFriendItem'][] = $AddFriendItem;

        unset($options);
        unset($AddFriendItem);
        return $result;

    }


    //拉黑
    public function friend_black_add(string $fromAccount, string $toAccount)
    {
        $this->restApiName = self::TENCENT_REST_APIS['black_add'];
        $baseApiHost = $this->getTencentImRestApiBaseHost();
        $params = [
            'From_Account' => $fromAccount,
            'To_Account' => array($toAccount),
        ];
        $apiResult = $this->requestApi($baseApiHost, $params);
        return $apiResult;
    }

    //取消拉黑
    public function friend_black_del(string $fromAccount, string $toAccount)
    {
        $this->restApiName = self::TENCENT_REST_APIS['black_del'];
        $baseApiHost = $this->getTencentImRestApiBaseHost();
        $params = [
            'From_Account' => $fromAccount,
            'To_Account' => array($toAccount),
        ];
        $apiResult = $this->requestApi($baseApiHost, $params);
        return $apiResult;
    }

}
