<?php
namespace app\common\model;

use think\Db;
use think\Model;

class UserModel extends Model
{
    protected function setCreateTimeAttr()
    {
        return time();
    }

    protected function setCreateIpAttr()
    {
        return request()->ip();
    }

    /**
     * 设置推广人信息
     * User: Eric
     * DateTime: 2018-10-24 23:00
     * @param $spread
     * @param $uid
     * @return UserModel|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function setSpread($spread, $uid)
    {
        //当前用户信息
        $userInfo = self::where('id', $uid)->find();
        if (!$userInfo)
            return true;
        //当前用户有上级直接返回
        if ($userInfo->spread_uid)
            return true;
        //没有推广编号直接返回
        if (!$spread) return true;
        if ($spread == $uid) return true;

        //记录分销等级关系
        $ur['fx_level'] = 1;
        $ur['user_id'] = $spread;
        $ur['child_id'] = $uid;
        $ur['create_time'] = time();
        Db::name('user_relations')->insert($ur);

        //根据$spread查找当前推广人是否有上线，如果有上线则记录二级记录 find
        $find = self::where('id', $spread)->value('spread_uid');
        if ($find) {
            $ur['fx_level'] = 2;
            $ur['user_id'] = $find;
            Db::name('user_relations')->insert($ur);
        }

        $data['spread_uid'] = $spread;
        $data['spread_time'] = time();

        return self::update($data,['id'=>$uid]);
    }
}