<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\api\controller\atransfer;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\UserModel;
use app\common\model\bbfxshop\Fenxiao;
use app\common\model\bbfxshop\Order;


class User extends Base
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Atransfer;
    }

    public function index(){
        $config = $this->model->getSet();
        $alldown = \app\common\model\bbfxshop\FenxiaoUser::getAllDown($this->user['id']);

        $level1user = Fenxiao::getLevelUser1($this->user['id']);

        $money_total = 0;
        $money_ok = 0;
        $list = $alldown['users'];
        $team_list = [];
        $level1user_money = [];
        if($config['zhitui_user_atransfer'] == 1){
            $list = $level1user;
            $team_list = $alldown['users'];

            if(!empty($level1user)){
                
                foreach($level1user as $key => $val){
                    $item_money_total = 0;

                    $level1user1 = Fenxiao::getLevelUser1($val['id']);
                    if(!empty($level1user1)){
                        $uids = array_column($level1user1,"id");
                        $item_money_total = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.is_pay'=>1,'o.user_id'=>['in',$uids],'o.refund_status'=>['in',[-1,0,2]]])->sum('og.price');
                        $item_money_total = round($item_money_total,2);
                    }

                    $money_total += $item_money_total;
                    
                    $level1user_money[$val['id']] = $item_money_total;
                }

                $money_total = round($money_total,2);
            }

            $log_list = Db::name("bbfx_atransfer_user")->alias("a")->join("bbfx_user b","a.m_user_id=b.id","LEFT")->where(['a.uniacid'=>UNIACID,'a.user_id'=>$this->user['id'],'a.type'=>$config['zhitui_user_atransfer']])->field("a.*,b.nickname,b.avatar")->select();
            foreach($log_list as &$val){
                $val['avatar'] = cdnurl($val['avatar']);
                $val['createtime'] = date('Y-m-d H:i:s',$val['createtime']);
                $money = round($level1user_money[$val['f_user_id']],2);
                $money_ok += $money;
                $val['money'] = $money;
            }
            unset($val);
            $money_ok = round($money_ok,2);
            $money = max(0,round($money_total - $money_ok,2));
        }
        else{

            if(!empty($level1user)){
                $uids = array_column($level1user,"id");
                $money_total = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.is_pay'=>1,'o.user_id'=>['in',$uids],'o.refund_status'=>['in',[-1,0,2]]])->sum('og.price');
                $money_total = round($money_total,2);
            }

            
            $money_ok = $money_total;
            $log_list = Db::name("bbfx_atransfer_user")->alias("a")->join("bbfx_user b","a.m_user_id=b.id","LEFT")->where(['a.uniacid'=>UNIACID,'a.user_id'=>$this->user['id'],'a.type'=>$config['zhitui_user_atransfer']])->field("a.*,b.nickname,b.avatar")->select();
            foreach($log_list as &$val){
                // $val['money'] = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.is_pay'=>1,'o.user_id'=>$val['m_user_id'],'o.refund_status'=>['in',[-1,0,2]]])->sum('og.price');
                // $val['money'] = round($val['money'],2);
                // $money_ok += $val['money'];
                $val['money'] = $money_total;
                $val['avatar'] = cdnurl($val['avatar']);
                $val['createtime'] = date('Y-m-d H:i:s',$val['createtime']);
            }
            unset($val);
            $money_total = round($money_total,2);
            $money_ok = round($money_ok,2);
            $money = max(0,round($money_total - $money_ok,2));
        }

        __success("操作成功",['list'=>$list,'team_list'=>$team_list,'log_list'=>$log_list,'money_total'=>$money_total,'money_ok'=>$money_ok,'money'=>$money]);
    }

    public function transfer(){
        $config = $this->model->getSet();
        $money = max(0,$this->param('money/d'));
        $m_user_id = $this->param('m_user_id/d');
        $f_user_id = $this->param('f_user_id/d');
        if($money <= 0){
            // __error("请输入需要转移的业绩");
        }
        $alldown = \app\common\model\bbfxshop\FenxiaoUser::getAllDown($this->user['id']);

        $uids = $alldown['ids'];
        
        if(empty($uids) || !in_array($m_user_id,$uids)){
            __error("选择转移的用户不属于自身团队下的用户");
        }

        if($config['zhitui_user_atransfer'] == 1){
            $level1user = Fenxiao::getLevelUser1($this->user['id']);
            $uids = array_column($level1user,"id");
            if(empty($uids) || !in_array($f_user_id,$uids)){
                __error("选择转移业绩的的直推用户不属于自身直推用户");
            }

            if($m_user_id == $f_user_id){
                __error("不可转给相同用户");
            }

            $log = Db::name("bbfx_atransfer_user")->where(['uniacid'=>UNIACID,'type'=>1,'user_id'=>$this->user['id'],'f_user_id'=>$f_user_id])->select();
            if(!empty($log)){
                __error("该用户的直推业绩已被转移，请勿重复转移");
            }
        }
        else{
            $log = Db::name("bbfx_atransfer_user")->where(['uniacid'=>UNIACID,'type'=>0,'user_id'=>$this->user['id']])->select();
            if(!empty($log)){
                __error("您的直推业绩已被转移，请勿重复转移");
            }
        }

        // $level1user = Fenxiao::getLevelUser1($this->user['id']);
        // if(!empty($level1user)){
            // $uids = array_column($level1user,"id");
            // $money_total = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.user_id'=>['in',$uids],'o.is_pay'=>1,'o.refund_status'=>['in',[-1,0,2]]])->sum('og.price');
        // }
        // $money_ok = Db::name("bbfx_atransfer_user")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id']])->sum("money");
        // $money_nok = max(0,round($money_total - $money_ok,2));
        // if($money > $money_nok){
        //     __error("您最多还可转移{$money_nok}元业绩");
        // }

        

        $data = [
            'uniacid'=>UNIACID,
            'type'=>$config['zhitui_user_atransfer'],
            'user_id'=>$this->user['id'],
            'm_user_id'=>$m_user_id,
            // 'money'=>$money,
            'createtime'=>time()
        ];

        if($config['zhitui_user_atransfer'] == 1){
            $data['f_user_id'] = $f_user_id;
        }

        try {
            Db::name("bbfx_atransfer_user")->insert($data);
        } catch (\Exception $e) {
            __error($e->getMessage());
        }

        __success("操作成功");
    }

    public function delete(){
        $id = $this->param("id/d");
        $log = Db::name("bbfx_atransfer_user")->where(['uniacid'=>UNIACID,'id'=>$id,'user_id'=>$this->user['id']])->find();
        if(empty($log)){
            __error("记录不存在或已被删除");
        }

        $res = Db::name("bbfx_atransfer_user")->where(['id'=>$log['id']])->delete();
        if($res){
            __success("删除成功");
        }
        else{
            __error("删除失败");
        }
    }
}