<?php

namespace App\Models;

use App\Models\AccountsInfo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Exception;
use Log;
use Illuminate\Support\Carbon;
class Subordinate extends Model
{
    const TABLE = 'QPPlatformDB.dbo.Subordinate';
    protected $table = self::TABLE;
    protected $primaryKey = 'UserID';
    public $timestamps = false;

    protected static function setCommission($params)
    {
        $user_id = $params['user_id'];//被设置用户
        $spreader_id = $params['spreader_id'];//上级用户
        $commission = (int)$params['commission'];//设置的点位数
        if($commission > 100){
            return ['status'=>false,'msg'=>'设置失败,比例不能大于100'];
        }
        $user_info = AccountsInfo::select('UserID','SpreaderID')->find($user_id);//被设置用户信息
        if(empty($user_info)){
            return ['status'=>false,'msg'=>'当前用户不存在'];
        }

        if($spreader_id != 0){
            $spreader_info = self::where('UserID',$spreader_id)->first();//上级代理点位数
            if($commission > $spreader_info->Commission){
                return ['status'=>false,'msg'=>'设置失败,比例不能大于上级'];
            }
        }

        $subordinate = self::where('SpreaderID',$user_id)->value('Commission');//下级代理点数
        if($subordinate > $commission){
            return ['status'=>false,'msg'=>'设置失败,比例不能小于下级'];
        }
        

        $user_commission = self::where('UserID',$user_id)->value('Commission');
        //判断是否设置过点位
        if(!empty($user_commission)){
            try{
                $result = self::where('UserID',$user_id)->update(['Commission'=>$commission]);
                return ['status'=>true,'msg'=>'设置成功'];
            }catch(Exception $e){
                Log::channel('setCommission')->info($e->getMessage());
                return ['status'=>false,'msg'=>'设置失败'];
            }
        }
        $insert['UserID'] = $user_id;
        $insert['SpreaderID'] = $spreader_id;
        $insert['Commission'] = $commission;
        $insert['CreateAt'] = now();
        $insert['Level'] = $spreader_info->Level+1;
        try{
            $result = self::insert($insert);
            return ['status'=>true,'msg'=>'设置成功'];
        }catch(Exception $e){
            Log::channel('setCommission')->info($e->getMessage());
            return ['status'=>false,'msg'=>'设置失败'];
        }
    }


}
