<?php

namespace app\subscribe;

use app\common\model\User;
use app\common\model\UserPart;
use app\common\model\Broker as BrokerModel;
use think\Event;

class Broker
{
    /**
     * 经纪人添加后事件
     */
    public function onBrokerAdd($broker)
    {
        $part = UserPart::where('userid', $broker['userid'])->find();
        //判断是否有上级
        if (!empty($part)) {
            //有上级时判断是否有上级里有经纪人
            $user = User::where('id', $broker['userid'])->find();
            if (!empty($user['brokerid'])) {
                //上级有经纪人判断是否相同门店
                $upper_broker = BrokerModel::where('id', $user['brokerid'])->find();
                if ($upper_broker['agentid'] == $broker['agentid']) {
                    //相同门店将下级的经纪人更改为自己
                    $this->setNextId($broker['userid'], $broker['id']);
                } else {
                    //不同门店将自己的下级都转给上级经纪人
                    User::where('id', $broker['userid'])->update(['brokerid' => $broker['id']]);
                    UserPart::where('puserid', $broker['userid'])->update(['puserid' => $upper_broker['userid']]);
                }
            } else {
                //上级没有经纪人时将下级的经纪人更改为自己
                $this->setNextId($broker['userid'], $broker['id']);
            }
        } else {
            //无上级将下级的经纪人更改为自己
            $this->setNextId($broker['userid'], $broker['id']);
        }

        //成为经纪人删除上级关系
        UserPart::where('userid', $broker['userid'])->delete();
    }

    /**
     * 设置下级关系
     * @param int $user_id 需要变更下级人的id
     * @param int $broker_id 需要把这些人变为哪个经纪人的id
     * @param int $new_user_id 需要把这些人变为哪个上级的id，不传表示不变
     */
    private function setNextId($user_id, $broker_id)
    {
        $user_ids = $this->_getNextId($user_id);
        $user_ids[] = $user_id;
        User::where('id', 'in', $user_ids)->update(['brokerid' => $broker_id]);
    }

    /**
     * 获取下级id
     */
    private function _getNextId($user_id)
    {
        if (!is_array($user_id)) {
            $user_id = [$user_id];
        }
        $userIds = UserPart::where('puserid', 'in', $user_id)->column('userid');
        if (!empty($userIds)) {
            return array_merge($this->_getNextId($userIds), $userIds);
        } else {
            return $userIds;
        }
    }

    /**
     * 自定义订阅列表
     */
    public function subscribe(Event $event)
    {
        $event->listen('brokerAdd', [$this, 'onBrokerAdd']);
    }
}
