<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 分销
 */
class Intro extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected $wallet = [];//登录用户的钱包

    public function __construct(){
        parent::__construct();

        $this->wallet = Db::name('user_wallet')->where('user_id',$this->auth->id)->find();

        if($this->wallet['intro_level'] == -1){
            $this->error('没有权限');
        }
    }

    //首页
    public function index(){

        $result = [
            'user_id' => $this->auth->id,
            'nickname' => $this->auth->nickname,
            'avatar'   => localpath_to_netpath($this->auth->avatar),
            'intro_level' => $this->wallet['intro_level'],
        ];

        //累计佣金
        $result['leijiyongjin'] = Db::name('user_intromoney_log')->where('user_id',$this->auth->id)->where('log_type','IN',[101,102,111])->sum('change_value');

        //下线总数
        $zhitui_ids  = Db::name('user_wallet')->where('intro_uid',$this->auth->id)->column('user_id');//直推
        $jiantui_ids = empty($zhitui_ids) ? [] : Db::name('user_wallet')->where('intro_uid','IN',$zhitui_ids)->column('user_id');//间推

        $result['xiaxianzongshu'] = count($zhitui_ids) + count($jiantui_ids);

        //可提现金额
        $result['ketixian'] = $this->wallet['intromoney'];

        //待入账金额，下面计算
        $result['dairuzhang'] = 0;

        //提现中
        $result['tixianzhong'] = Db::name('intro_user_take_cash')->where('user_id',$this->auth->id)->where('status',0)->sum('money');
        //已提现
        $result['yitixian'] = Db::name('intro_user_take_cash')->where('user_id',$this->auth->id)->where('status',1)->sum('money');

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

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

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

        //我的团队人数
        $result['wodetuandui'] = count($tuandui_ids);

        //邀请好友,直推人数
        $result['yaoqinghaoyou'] = count($down_uids);

        //分销订单
        $tuandui_ids[] = $this->auth->id;
        $result['fenxiaodingdan'] = Db::name('pay_order')->where('user_id','IN',$tuandui_ids)->where('table_name','money_recharge')->where('order_status',1)->whereTime('createtime','month')->count();

        //团队总业绩
        $result['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',$this->wallet['intro_level'])->value('intro_bili');
        $bili = $bili ?: 0;

        //待入账
        $result['dairuzhang'] = bcdiv(bcmul($result['tuanduizongyeji'],$bili,2),100,2);

        //我的佣金余额
        $result['intromoney'] = $this->wallet['intromoney'];

        $this->success('success',$result);
    }

    //获取我的直推
    private function get_my_down_list(){
        $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',$this->auth->id)          //我邀请的
            ->where('uw.intro_level','neq','-1')             //入金了
            ->where('uw.intro_level','elt',$this->wallet['intro_level'])   //等级比我低
            ->where('uw.money','egt',$chuju)   //金额小于500，出局
            ->select();

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

    //获取我的间推
    private function get_my_downdown_list($down_uids = false){
        if($down_uids === false){
            $list = $this->get_my_down_list();
            $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',$this->wallet['intro_level'])   //等级比我低
            ->where('uw.intro_level <= intro.intro_level')   //加这里，就是防止：下下级当中，虽然都比我低，但是有可能高于自己的上级（也就是我的直推）
            ->select();

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

    //分销订单列表
    public function fenxiao_order_list(){
        //直推
        $list = $this->get_my_down_list();
        $down_uids = array_column($list,'user_id');

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

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

        //加上我自己
        $tuandui_ids[] = $this->auth->id;

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

        //分销订单
        $list = Db::name('pay_order')->alias('o')->field('o.id,user.id as user_id,user.nickname,user.avatar,user.mobile,o.createtime,o.order_amount')
            ->join('user','o.user_id = user.id','LEFT')
            ->where('o.user_id','IN',$tuandui_ids)
            ->where('o.table_name','money_recharge')
            ->where('o.order_status',1)
            ->order('o.id desc')->autopage()->select();

        foreach($list as $key => $val){
            $val['yujiyongjin'] = bcdiv(bcmul($val['order_amount'],$bili,2),100,2);
            unset($val['order_amount']);

            $list[$key] = $val;

        }

        $this->success(1,$list);
    }

    //我的团队
    public function my_team(){
        $type = input('type',1);
        $keyword = input('keyword','');

        $wheresearch = [];
        if(!empty($keyword)){
            $wheresearch['user.nickname'] = ['LIKE','%'.$keyword.'%'];
        }

        //普通成员
        if($type == 1){

            //普通直推
            $zhitui_list  = Db::name('user_wallet')->alias('uw')
                ->field('uw.user_id,uw.money,uw.intro_level,uw.intro_uid,user.nickname')
                ->join('user','uw.user_id = user.id','LEFT')
                ->where('uw.intro_uid',$this->auth->id)          //我邀请的
                ->where('uw.intro_level','-1')             //没入金
                ->where($wheresearch)
                ->select();
            foreach($zhitui_list as $key => $val){
                $val['show_level'] = '直推普通成员';
                $val['tuanduiyeji'] = 0;

                $zhitui_list[$key] = $val;
            }


            $zhitui_ids  = Db::name('user_wallet')->where('intro_uid',$this->auth->id)->column('user_id');//直推id。这里单独查不用上面的，是因为可能直推入金了，间推没入金，间推不能给丢了
            $jiantui_list = empty($zhitui_ids) ? [] : Db::name('user_wallet')->alias('uw')
                ->field('uw.user_id,uw.money,uw.intro_level,uw.intro_uid,user.nickname')
                ->join('user','uw.user_id = user.id','LEFT')
                ->whereIN('uw.intro_uid',$zhitui_ids)//下下级
                ->where('uw.intro_level','-1')             //没入金
                ->where($wheresearch)
                ->select();
            foreach($jiantui_list as $key => $val){
                $val['show_level'] = '间推普通成员';
                $val['tuanduiyeji'] = 0;

                $jiantui_list[$key] = $val;
            }

            $result = array_merge($zhitui_list,$jiantui_list);

            $this->success(1,$result);

        }
        //一级成员
        if($type == 2){

            //出局
            $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,user.nickname')
                ->join('user','uw.user_id = user.id','LEFT')
                ->where('uw.intro_uid',$this->auth->id)          //我邀请的
                ->where('uw.intro_level','neq','-1')             //入金了
                ->where('uw.intro_level','elt',$this->wallet['intro_level'])   //等级比我低
                ->where('uw.money','egt',$chuju)   //金额小于500，出局
                ->where($wheresearch)
                ->select();
            if(!empty($list)){
                $down_uids = array_column($list,'user_id');

                $pay_order = Db::name('pay_order')->field('user_id,sum(order_amount) as yeji')
                    ->where('user_id','IN',$down_uids)->where('table_name','money_recharge')->where('order_status',1)->whereTime('createtime','month')
                    ->group('user_id')->select();

                foreach($list as $key => $val){
                    $val['show_level'] = '一级成员';
                    $val['tuanduiyeji'] = '0.00';
                    foreach($pay_order as $k => $v){
                        if($val['user_id'] == $v['user_id']){
                            $val['tuanduiyeji'] = $v['yeji'];
                        }
                    }

                    $list[$key] = $val;
                }
            }

            $this->success(1,$list);
        }

        //二级成员
        if($type == 3){
            //出局
            $chuju = config('site.intro_chuju_min_money');

            //直推，下级，入金，等级比我低，未出局
            $list = $this->get_my_down_list();
            $down_uids = array_column($list,'user_id');

            //间推，下下级，入金，未出局，等级比我低，等级比自己的上级低
            $list2 = empty($down_uids) ? [] : Db::name('user_wallet')->alias('uw')
                ->field('uw.user_id,uw.money,uw.intro_level,uw.intro_uid,user.nickname')
                ->join('user','uw.user_id = user.id','LEFT')
                ->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',$this->wallet['intro_level'])   //等级比我低
                ->where('uw.intro_level <= intro.intro_level')   //加这里，就是防止：下下级当中，虽然都比我低，但是有可能高于自己的上级（也就是我的直推）
                ->where($wheresearch)
                ->select();
            if(!empty($list2)){
                $down_down_uids = array_column($list2,'user_id');

                $pay_order = Db::name('pay_order')->field('user_id,sum(order_amount) as yeji')
                    ->where('user_id','IN',$down_down_uids)->where('table_name','money_recharge')->where('order_status',1)->whereTime('createtime','month')
                    ->group('user_id')->select();

                foreach($list2 as $key => $val){
                    $val['show_level'] = '二级成员';
                    $val['tuanduiyeji'] = '0.00';
                    foreach($pay_order as $k => $v){
                        if($val['user_id'] == $v['user_id']){
                            $val['tuanduiyeji'] = $v['yeji'];
                        }
                    }

                    $list2[$key] = $val;
                }
            }

            $this->success(1,$list2);
        }



    }

    //转余额。减少intromoney ,充值到 money，走一遍notify
    public function transform(){
        $freemoney = input('freemoney',0);
        if(!$freemoney){
            $this->error('请填写金额');
        }

        $money = floatval($freemoney);

        $min = 1;
        if($money < $min){
            $this->error('转换金额不能小于'.$min);
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'intromoney');
        if($money > $user_money){
            $this->error('转换金额不能大于可提现余额');
        }

        Db::startTrans();

        //扣除money
        $rs_wallet = model('Wallet')->lockChangeAccountRemain($this->auth->id,'intromoney',-$money,115,'转为充值余额');
        if($rs_wallet['status']===false)
        {
            Db::rollback();
            $this->error($rs_wallet['msg']);
        }

        //创建充值订单
        $data = [];
        $data['user_id'] = $this->auth->id;
        $data['out_trade_no'] = createUniqueNo('TP',$this->auth->id); // 数据库订单号加密
        $data['order_amount'] = $money;
        $data['createtime'] = time();

        $data['pay_type'] = 'transform'; //区别正常充值，唯一字段
        $data['platform'] = '';
        $data['order_status'] = 0;
        $data['table_name'] = 'money_recharge';
        $data['table_id'] = 0;
        $data['args'] = '';

        $orderid = Db::name('pay_order')->insertGetId($data);
        if(!$orderid){
            Db::rollback();
            $this->error('转入失败');
        }

        Db::commit();

        //立刻开始回调
        $notify = controller('Notify')->recharge_notify_do($data['out_trade_no'],15,'佣金转入充值');
        if(!$notify){
            $this->error('充值失败,请联系客服');
        }

        $this->success('操作成功');

    }



    //我的分销余额日志
    public function my_intromoney_log(){
        $type = input('type',0);

        $map = [
            'user_id' => $this->auth->id,
        ];

        if($type == 1){
            $map['change_value'] = ['gt',0];
        }
        if($type == 2){
            $map['change_value'] = ['lt',0];
        }

        $list = Db::name('user_intromoney_log')
            ->field('id,log_type,before,change_value,remain,remark,createtime')
            ->where($map)->order('id desc')->autopage()->select();
//        $list = $this->list_appen_logtext($list);

        $this->success('success',$list);
    }

    //提现配置
    public function take_cash_config(){

        $plat_bilv      = config('site.intro_takecash_plat_bili');
        $take_cash_days = config('site.intro_takecash_days');
        $take_cash_days_str = implode(',',$take_cash_days);

        $data = [
            'intromoney' => model('wallet')->getwallet($this->auth->id,'intromoney'),
            'plat_bilv'   => $plat_bilv,
            'user_bank'   => Db::name('user_bank')->where('user_id',$this->auth->id)->find(),
            'take_cash_days' => $take_cash_days_str,
            'remark'         => '每月'.$take_cash_days_str.'日可以提现',
            'take_cash_button' => in_array(date('d'),$take_cash_days) ? 1 : 0,
        ];

        $this->success('success',$data);
    }

    //提现before
    public function take_cash_before(){
        $freemoney = input('freemoney',0);
        if(!$freemoney){
            $this->error('请填写金额');
        }

        $money = floatval($freemoney);

        if($money<=0)
        {
            $this->error('金额必须大于0');
        }

        $min = config('site.intro_takecash_min_money');
        $max = config('site.intro_takecash_max_money');
        if($money < $min){
            $this->error('提现金额不能小于'.$min);
        }
        if($money > $max){
            $this->error('提现金额不能大于'.$max);
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'intromoney');
        if($money > $user_money){
            $this->error('提现金额不能大于可提现余额');
        }

        //平台手续费
        $plat_bilv = config('site.intro_takecash_plat_bili');
        $plat_money = bcdiv(bcmul($money,$plat_bilv,2),100,2);

        //减去手续费，得实得金额
        $get_money = bcsub($money,$plat_money,2);

        $data = [
            'money'      => $money,
            'plat_bilv'  => $plat_bilv,
            'plat_money' => $plat_money,
            'get_money'  => $get_money,
        ];
        $this->success(1,$data);
    }

    //提现
    public function take_cash(){
        $freemoney = input('freemoney',0);
//        $type = input('type',1);
        $type = 2;

        if(!$freemoney){
            $this->error('请填写金额');
        }

        if (!in_array($type,[1,2,3])) {
            $this->error('未知的提现类型');
        }

        //提现日期限制
        $take_cash_days = config('site.intro_takecash_days');
        if(!in_array(date('d'),$take_cash_days)){
            $take_cash_days_str = implode(',',$take_cash_days);
            $this->error('每月'.$take_cash_days_str.'日才可以提现');
        }


        //赋值money
        /*if($rc_id){
            $recharge_config = Db::name('take_cash_config')->where('id',$rc_id)->find();
            $money = $recharge_config['money'] ?: 0;
        }*/

        //自由输入覆盖
        if(!empty($freemoney)){
            $rc_id = 0;
            $money = floatval($freemoney);
        }

        //
        if($money<=0)
        {
            $this->error('金额必须大于0');
        }

        $min = config('site.intro_takecash_min_money');
        $max = config('site.intro_takecash_max_money');
        if($money < $min){
            $this->error('提现金额不能小于'.$min);
        }
        if($money > $max){
            $this->error('提现金额不能大于'.$max);
        }

        $check = Db::name('intro_user_take_cash')->where(['user_id'=>$this->auth->id,'status'=>0])->find();
        if($check){
            $this->error('您已经申请了提现,请等待审核');
        }

        $user_money = model('wallet')->getwallet($this->auth->id,'intromoney');
        if($money > $user_money){
            $this->error('提现金额不能大于可提现余额');
        }

        if($type == 1){
            $table_name = 'user_alipay';
            $account_json = Db::name($table_name)->where('user_id',$this->auth->id)->find();
            if(empty($account_json)){
                $this->error('未绑定对应的提现账号');
            }
        }elseif($type == 2){
            $table_name = 'user_bank';
            $account_json = Db::name($table_name)->where('user_id',$this->auth->id)->find();
            if(empty($account_json)){
                $this->error('未绑定对应的提现账号');
            }
        }elseif($type == 3){
            //微信支付
            $table_name = 'user_wechat';
            $account_json = Db::name($table_name)->where('user_id',$this->auth->id)->find();
            if(empty($account_json)){
                $this->error('未绑定对应的提现账号');
            }
        }

        //平台手续费
        $plat_bilv = config('site.intro_takecash_plat_bili');
        $plat_money = bcdiv(bcmul($money,$plat_bilv,2),100,2);

        //减去手续费，得实得金额
        $get_money = bcsub($money,$plat_money,2);

        $data = [
            'user_id' => $this->auth->id,
            'money' => $money,
            'plat_bilv'  => $plat_bilv,
            'plat_money' => $plat_money,
            'get_money'  => $get_money,
            'type' => $type,
            'acount_json' => json_encode($account_json),
            'createtime' => time(),
            'updatetime' => time(),
            'status' => 0,
        ];
        Db::startTrans();

        $log_id = Db::name('intro_user_take_cash')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('提现失败');
        }

        //扣除money
        $rs_wallet = model('Wallet')->lockChangeAccountRemain($this->auth->id,'intromoney',-$money,121,'提现(审核中)','intro_user_take_cash',$log_id);
        if($rs_wallet['status']===false)
        {
            Db::rollback();
            $this->error($rs_wallet['msg']);
        }

        Db::commit();
        $this->success('申请成功请等待审核');
    }

    //提现记录
    public function take_cash_log(){
        $list = Db::name('intro_user_take_cash')->field('id,money,get_money,type,createtime,status')->where(['user_id'=>$this->auth->id])->autopage()->select();
        foreach($list as $key => &$val){
            $val['remark'] = '';

            if($val['type'] == 1){
                $val['remark'] = '支付宝提现';
            }elseif($val['type'] == 2){
                $val['remark'] = '银行卡提现';
            }else{
                $val['remark'] = '微信提现';
            }
        }

        $this->success('success',$list);
    }

}
