<?php


namespace App\Listeners;


use App\Events\ExternalAndGroupOperateEvent;
use App\Models\OpenWork\External\ExternalGroupOperateRecord as Model;
use App\Models\OpenWork\External\User as UserModel;
use App\Servers\DB\DbService;

class ExternalAndGroupOperateListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function handle(ExternalAndGroupOperateEvent $event)
    {
        $data['corpid']                 = $event->corpId;               //授权方企微ID
        $data['chat_id']                = $event->chatId;               //群id
        $data['change_type']            = $event->changeType;           //变更类型，当前默认update
        $data['update_detail_type']     = $event->updateDetailType;     //变更详情类型：1:成员入群、2:成员退群
        $data['join_scene']             = $event->joinScene;            //入群时有值，0:成员邀请入群、3：扫描群二维码入群
        $data['quit_scene']             = $event->quitScene;            //退群时有值，0:自己退群、1：群主/群管理员移出
        //$data['external_userid']        = $event->externalUserId;     //外部联系人ID
        $memChangeArray                 = $event->memChangeArray;         //变更的群成员数组
        $data['insert_time']            = time();
        $data['update_time']            = time();

        (new DbService())->getConnectionNameByCorpId($event->corpId);

        $Model     = new Model();
        $userModel = new UserModel();
        //需要处理$menChangeStr
        foreach ($memChangeArray as $value) {
            //判断群成员是否为外部人员 在 kailin_openwork_external表中是否存在
            if ($userModel->query()->where('corpid', '=', $event->corpId)->where('external_userid', '=', $value)->exists()) {
                $data['external_userid'] = $value;
                $Model->query()->insert($data);
            }
        }


    }

}