<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

class Plantask extends Controller
{
    //每月初自动结算上个月的业绩
    public function auto_yeji(){
        $date = date('Ym').'01';

        //找一个没结算的
        $wallet = Db::name('user_wallet')->where('last_jiesuan_date','lt',$date)->order('id asc')->find();
        if(empty($wallet)){
            echo $date.'没有了';
            exit;
        }

        echo $date.'开始'.$wallet['user_id'];

        //直推
        $list = $this->get_my_down_list($wallet);
        $down_uids = array_column($list,'user_id');

        //间推
        $list2 = $this->get_my_downdown_list($down_uids,$wallet);
        $down_down_uids = array_column($list2,'user_id');

        //团队ids
        $tuandui_ids = array_merge($down_uids,$down_down_uids);

        $tuandui_ids[] = $wallet['user_id'];

        //团队总业绩
        $tuanduizongyeji = Db::name('pay_order')
            ->where('user_id','IN',$tuandui_ids)
            ->where('table_name','money_recharge')
            ->where('order_status',1)
            ->whereTime('createtime','month')
            ->sum('order_amount');

        //我所在等级的比例
        $bili = Db::name('intro_level_config')->where('id',$wallet['intro_level'])->value('intro_bili');
        $bili = $bili ?: 0;

        $yongjin = bcdiv(bcmul($tuanduizongyeji,$bili,2),100,2);

        Db::startTrans();
        if($yongjin > 0){
            $rs_wallet = model('wallet')->lockChangeAccountRemain($wallet['user_id'],'intromoney',$yongjin,'111',$remark='团队返佣,总业绩'.$tuanduizongyeji);
            if($rs_wallet['status'] === false){
                Db::rollback();
                echo '发放失败'.$wallet['user_id'];
                exit;
            }
        }

        //结算完成
        $rs1 = Db::name('user_wallet')->where('user_id',$wallet['user_id'])->update(['last_jiesuan_date' => $date]);
        if($rs1 === false){
            Db::rollback();
            echo '更新失败'.$wallet['user_id'];
            exit;
        }

        Db::commit();
        echo '结束'.$wallet['user_id'];
    }

    //获取我的直推
    private function get_my_down_list($wallet){
        $chuju = config('site.intro_chuju_min_money');

        //直推，下级，入金，等级比我低，未出局
        $list = Db::name('user_wallet')->alias('uw')
            ->field('uw.user_id,uw.money,uw.intro_level,uw.intro_uid')
            ->where('uw.intro_uid',$wallet['user_id'])          //我邀请的
            ->where('uw.intro_level','neq','-1')             //入金了
            ->where('uw.intro_level','elt',$wallet['intro_level'])   //等级比我低
            ->where('uw.money','egt',$chuju)   //金额小于500，出局
            ->select();

        return !empty($list) ? $list : [];
    }

    //获取我的间推
    private function get_my_downdown_list($down_uids = false,$wallet){
        if($down_uids === false){
            $list = $this->get_my_down_list($wallet);
            $down_uids = array_column($list,'user_id');
        }

        if(empty($down_uids)){
            return [];
        }

        $chuju = config('site.intro_chuju_min_money');

        //间推，下下级，入金，未出局，等级比我低，等级比自己的上级低
        $list2 = Db::name('user_wallet')->alias('uw')
            ->field('uw.user_id,uw.money,uw.intro_level,uw.intro_uid')
            ->join('user_wallet intro','uw.intro_uid = intro.user_id','LEFT')  //加这里，就是防止：下下级当中，虽然都比我低，但是有可能高于自己的上级（也就是我的直推）
            ->whereIN('uw.intro_uid',$down_uids)  //下下级
            ->where('uw.intro_level','neq','-1')             //入金了
            ->where('uw.money','egt',$chuju)   //金额小于500，出局
            ->where('uw.intro_level','elt',$wallet['intro_level'])   //等级比我低
            ->where('uw.intro_level <= intro.intro_level')   //加这里，就是防止：下下级当中，虽然都比我低，但是有可能高于自己的上级（也就是我的直推）
            ->select();

        return !empty($list2) ? $list2 : [];
    }


}
