<?php


namespace app\controller\api\entropybarter;
use alipay\aop\AlipayConfig;
use alipay\aop\AopCertClient;
use alipay\aop\request\AlipayTradePrecreateRequest;
use alipay\aop\request\AlipayFundTransUniTransferRequest;
use crmeb\basic\BaseController;
use Endroid\QrCode\QrCode;
use think\db\Where;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\App;



class User extends BaseController
{
    protected $merId;
    protected $source;

    /**
     * UserExtract constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->source = $this->request->header('source');
        $this->merId =  $this->request->header('merId');
    }
    public function test(){
        dump($order_236 = new Order_236());
    }

    /**
     * @param $user
     * @param $top_id
     * 创建用户
     */
    public function create($uid,$top_id,$mer_id)
    {
//        $table_name='rrx_entropy_barter_user_'.$mer_id;
//        $exist = Db::query("show tables like '$table_name'");
//        if(empty($exist)){
//         return '';
//        }
//        $top_eb_id=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$top_id)->find();
//        $insert_data=[
//            'uid'=>$uid,
//            'top_eb_id'=>$top_eb_id['top_eb_id'],
//            'ctime'=>time()
//        ];
//        Db::name('entropy_barter_user_'.$mer_id)->insert($insert_data);
    }

    public function xcx_bangding()
    {
        try {


            $param=$this->request->param();
            Db::name('log')->insert(['data'=>json_encode($param)]);
            Db::name('log')->insert(['data'=>'商品详情绑定推荐关系 进来了']);
            $share_id=$this->request->params(['share_id']);
            $mer_id=$this->request->params(['mer_id']);
            if(!$mer_id['mer_id']){
                Db::name('log')->insert(['data'=>'商品详情绑定推荐关系---商户ID 未传']);
            }
            if(!$share_id['share_id']){
                Db::name('log')->insert(['data'=>'商品详情绑定推荐关系---分享ID 未传']);
            }
            Db::name('log')->insert(['data'=>'商品详情绑定推荐关系--商户ID：'.$mer_id['mer_id']]);
            $mer_data=Db::name('merchant')->where('mer_id',$mer_id['mer_id'])->value('merchant_type');
            if($mer_data==2){
                $uid = $this->request->uid();
                Db::name('log')->insert(['data'=>'商品详情绑定推荐关系--用户ID：'.$uid]);

                Db::name('log')->insert(['data'=>json_encode($share_id)]);
                $spread_uid=Db::name('product_share')->where('id',$share_id['share_id'])->value('uid');
                Db::name('log')->insert(['data'=>Db::name('product_share')->getLastSql()]);
                if(!$spread_uid){
                    return app('json')->fail('未查询到分享人的ID');
                }
                $this->bangding($uid,$spread_uid,$mer_id['mer_id']);
                $this->cxb_bangding($uid,$spread_uid);
            }
        }catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'绑定关系错误：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
        }
    }

    /**
     * @param $uid
     * @param $spread_uid
     * 绑定幸福宝的关系
     */
    public function cxb_bangding($uid,$spread_uid)
    {
        $spread_uid_user=Db::name('user')->where('uid',$uid)->value('spread_uid');
        Db::name('log')->insert(['data'=>'绑定幸福宝的关系进来了他的上级ID'.$spread_uid_user]);
        if($spread_uid_user==0){
            Db::name('user')->where('uid',$uid)->update(['spread_uid'=>$spread_uid]);
        }
    }
    /**
     *绑定推荐关系
     */
    public function bangding($uid='',$spread_uid='',$mer_id='')
    {
        try {
            Db::name('log')->insert(['data'=>'进来了User']);
            if(!$uid){
                $uid = $this->request->uid();
            }
            if(!$mer_id){
                $mer_id=$this->request->params(['mer_id']);
                if(empty($mer_id['mer_id'])){
                    return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
                }else{
                    $mer_id=$mer_id['mer_id'];
                }
            }
            Db::name('log')->insert(['data'=>'mer_id----'.json_encode($mer_id)]);
            $data=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
            if($data){
                return app('json')->fail('已绑定推荐关系');
            }
            $phone=$this->request->params(['phone']);
            if(!empty($phone['phone'])||$spread_uid){
                if(!$spread_uid){
                    $spread_uid=Db::name('user')->where('account',$phone['phone'])->value('uid');
                }
                if(!$spread_uid){
                    return app('json')->fail('未查询到推荐人信息');
                }
                $top_eb_id=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$spread_uid)->value('eb_id');
                if(!$top_eb_id){
                    if($mer_id==236){
                        $top_eb_id='13';
                    }elseif ($mer_id==276){
                        $top_eb_id='12';
                    }elseif ($mer_id=='290'){
                        $top_eb_id='1';
                    }elseif ($mer_id=='148'){
                        $top_eb_id=0;
                    }
                }
            }else{
                $top_eb_id=Db::name('user')->where('uid',$uid)->value('spread_uid');
                $top_eb_id=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$top_eb_id)->value('eb_id');
                if(!$top_eb_id){
                    if($mer_id==236){
                        $top_eb_id='13';
                    }elseif ($mer_id==276){
                        $top_eb_id='12';
                    }elseif ($mer_id=='290'){
                        $top_eb_id='1';
                    }elseif ($mer_id=='148'){
                        $top_eb_id=0;
                    }
                }
            }
            $type = 1;
            if($mer_id == '290'){
                $type = 0;
            }
            $insert_data=[
                'uid'=>$uid,
                'top_eb_id'=>$top_eb_id,
                'ctime'=>time(),
                'type'=>$type
            ];
            Db::name('log')->insert(['data'=>'添加数据--'.json_encode($insert_data)]);
            if($mer_id!=290){
                if($top_eb_id){
                    $bill=[
                        'from_id'=>'0',
                        'number'=>30,
                        'to_id'=>$top_eb_id,
                        'type'=>'1',
                        'order_no'=>time(),
                        'remarks'=>'邀请好友得30积分',
                        'pm'=>1,
                        'status'=>2,
                        'on_line'=>1,
                        'mer_id'=>$mer_id
                    ];
                    $this->eb_user_bill($bill);
                    Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$top_eb_id)->inc('integral',30)->update();
                }
            }
            $res=Db::name('entropy_barter_user_'.$mer_id)->insertGetId($insert_data);
            $insertData=[
                'eb_id'=>$res,
                'key'=>'proportion',
            ];
            $re=Db::name('entropy_barter_config_user_'.$mer_id)->insert($insertData);
            if($res&&$re){
                return app('json')->success('绑定成功');
            }else{

                return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
            }
        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
        }

    }
    /*
     * 绑定状态
     */
    public function bangding_status()
    {
        $uid = $this->request->uid();
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $data=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
        if($data){
            return app('json')->success(['status'=>1]);
        }else{
            return app('json')->success(['status'=>2]);
        }
    }
    /**12171
     * @param $order
     * @param $type 1 线上 2线下
     * 订单
     * 修改用户 类型 比例  完成
     */
    public function order($order, $type)
    {
        try {
            Db::name('log')->insert(['data'=>'user._______'.json_encode($order)]);

            $mer_id=$order['mer_id'];
            Db::name('log')->insert(['data'=>'商户id0'.$mer_id]);
            if($mer_id=='290'){
                return $this->pay_orrder_290($order,$type);
            }elseif($mer_id=='236'){
                Db::name('log')->insert(['data'=>'商户id1'.$mer_id]);
                try {
                    $order_236=new Order_236();
                    Db::name('log')->insert(['data'=>'商户id2'.json_encode($order_236)]);
                    return $order_236-> order($order, $type);
                }catch (\Exception $e) {
                    Db::name('log')->insert(['data'=>'地宝订单支付出错：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
                }

            }
        }catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'地宝订单支付出错lll：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
        }

        $user=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$order['uid'])->find();
        $update=[];
        $update_config=[];
        //增加消费总额/积分
        $weizhi=strpos($order['money'],'.');
        if($weizhi){
            $money=substr($order['money'],'0',$weizhi);
        }else{
            $money=$order['money'];
        }
        $update_user=[
            'cumulative_money'=>bcadd($order['money'],$user['cumulative_money'],2),

        ];
//        if($mer_id=='276'||$mer_id=='236'){
//            if($order['money']>=1){
//                if($user['first_consumption_one']==1){
//                    if($type==2){
//
//                        $bill=[
//                            'from_id'=>'0',
//                            'number'=>100,
//                            'to_id'=>$user['eb_id'],
//                            'type'=>'1',
//                            'order_no'=>$order['order_no'],
//                            'remarks'=>'首次消费满1元赠送100积分',
//                            'pm'=>1,
//                            'status'=>2,
//                            'on_line'=>2,
//                            'mer_id'=>$mer_id
//                        ];
//                        $this->eb_user_bill($bill);
//                        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$user['eb_id'])->inc('integral',100)->update();
//                        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$user['eb_id'])->inc('first_consumption_one',1)->update();
//
//                    }else{
//
//                        $bill=[
//                            'from_id'=>'0',
//                            'number'=>100,
//                            'to_id'=>$user['eb_id'],
//                            'type'=>'1',
//                            'order_no'=>$order['order_no'],
//                            'remarks'=>'首次消费满1元赠送100积分',
//                            'pm'=>1,
//                            'status'=>1,
//                            'on_line'=>1,
//                            'mer_id'=>$mer_id
//                        ];
//                        $this->eb_user_bill($bill);
//                        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$user['eb_id'])->inc('first_consumption_one',1)->update();
//                    }
//
//                }
//            }
//        }
        if($user['type']==1){
            if($update_user['cumulative_money']>=6000){
                $update['integral']='6000';
            }
        }
        $reward_one=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_one')->find();
        if($update_user['cumulative_money']>=$reward_one||$mer_id=='236'){
            if($type==2){
                Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$user['eb_id'])->update($update_user);
                $bill=[
                    'from_id'=>'0',
                    'number'=>$money,
                    'to_id'=>$user['eb_id'],
                    'type'=>'1',
                    'order_no'=>$order['order_no'],
                    'remarks'=>'消费得积分',
                    'pm'=>1,
                    'status'=>2,
                    'on_line'=>2,
                    'mer_id'=>$mer_id
                ];
                $this->eb_user_bill($bill);
            }else{
                $bill=[
                    'from_id'=>'0',
                    'number'=>$money,
                    'to_id'=>$user['eb_id'],
                    'type'=>'1',
                    'order_no'=>$order['order_no'],
                    'remarks'=>'消费得积分',
                    'pm'=>1,
                    'status'=>1,
                    'on_line'=>1,
                    'mer_id'=>$mer_id
                ];
                $this->eb_user_bill($bill);
            }
        }
        $eb_user=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$order['uid'])->find();

        $reward_two=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_two')->find();
        $reward_three=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_three')->find();
        $reward_four=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_four')->find();
        Db::name('log')->insert(['data'=>'这是我总共的消费'.$eb_user['cumulative_money']]);
        Db::name('log')->insert(['data'=>'1'.json_encode($reward_one)]);
        Db::name('log')->insert(['data'=>'2'.json_encode($reward_two)]);
        Db::name('log')->insert(['data'=>'3'.json_encode($reward_three)]);
        Db::name('log')->insert(['data'=>'4'.json_encode($reward_four)]);
        if($eb_user['cumulative_money']>=$reward_one['value'] and $eb_user['cumulative_money']<$reward_two['value']){
            $update['type']=2;
            $update_config['value']=$reward_one['id'];
        }elseif ($eb_user['cumulative_money']>=$reward_two['value'] and $eb_user['cumulative_money']<$reward_three['value']){
            $update['type']=3;
            $update_config['value']=$reward_two['id'];
        }elseif ($eb_user['cumulative_money']>=$reward_three['value'] and $eb_user['cumulative_money']<$reward_four['value']){
            $update['type']=4;
            $update_config['value']=$reward_three['id'];
        }elseif ($eb_user['cumulative_money']>=$reward_four['value']){
            $update['type']=5;
            $update_config['value']=$reward_four['id'];
        }
        //修改此用户佣金比例
        if($type==2){
            Db::name('entropy_barter_config_user_'.$mer_id)->where('eb_id',$user['eb_id'])->update($update_config);
            //修改此用户类型   2 会员 3经理 4 总监 5 总裁
            Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$user['eb_id'])->update($update);
        }
        //是否有上级
        if($user['top_eb_id']){
            $top_user=Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$user['top_eb_id'])->find();
            $wallet=bcmul($order['money'],bcmul(30,0.01,2),2);
            if($top_user['integral']>=$wallet){
                if($type==2){
                    $bill=[
                        'from_id'=>'0',
                        'number'=>$wallet,
                        'to_id'=>$top_user['eb_id'],
                        'type'=>'2',
                        'order_no'=>$order['order_no'],
                        'remarks'=>'直推佣金',
                        'pm'=>1,
                        'status'=>2,
                        'on_line'=>2,
                        'mer_id'=>$mer_id
                    ];
                    $this->eb_user_bill($bill);
                    Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$top_user['eb_id'])->inc('wallet',$wallet)->update();
                    Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$top_user['eb_id'])->dec('integral',$wallet)->update();
                }else{
                    $bill=[
                        'from_id'=>'0',
                        'number'=>$wallet,
                        'to_id'=>$top_user['eb_id'],
                        'type'=>'2',
                        'order_no'=>$order['order_no'],
                        'remarks'=>'直推佣金',
                        'pm'=>1,
                        'status'=>1,
                        'on_line'=>1,
                        'mer_id'=>$mer_id
                    ];
                    $this->eb_user_bill($bill);
                }
            }
            $top_level=Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$top_user['top_eb_id'])->find();
            if($top_level){
                    $table_name='entropy_barter_config_'.$mer_id;
                $cproportion=Db::name('entropy_barter_config_user_'.$mer_id)
                    ->alias('ebcu')
                    ->leftJoin($table_name .' ebc','ebcu.value=ebc.id')
                    ->where('eb_id',$top_level['eb_id'])
                    ->field('ebc.proportion')
                    ->find();
                $integral=bcmul($money,bcmul($cproportion['proportion'],'0.01',2),2);
                if($integral>0){
                    if($type==2) {
                        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$top_level['eb_id'])->inc('integral',$integral)->update();
                        $bill=[
                            'from_id'=>'0',
                            'number'=>$integral,
                            'to_id'=>$top_level['eb_id'],
                            'type'=>'2',
                            'order_no'=>$order['order_no'],
                            'remarks'=>'团队积分奖励',
                            'pm'=>1,
                            'status'=>2,
                            'on_line'=>2,
                            'mer_id'=>$mer_id
                        ];
                        $this->eb_user_bill($bill);
                    }else{
                        $bill=[
                            'from_id'=>'0',
                            'number'=>$integral,
                            'to_id'=>$top_level['eb_id'],
                            'type'=>'1',
                            'order_no'=>$order['order_no'],
                            'remarks'=>'团队积分奖励',
                            'pm'=>1,
                            'status'=>1,
                            'on_line'=>1,
                            'mer_id'=>$mer_id
                        ];
                        $this->eb_user_bill($bill);
                    }
                }
            }
        }

    }
    //账单记录
    public function eb_user_bill($bill)
    {
        $insert=[
            'from_id'=>$bill['from_id'],
            'number'=>$bill['number'],
            'to_id'=>$bill['to_id'],
            'type'=>$bill['type'],
            'order_no'=>$bill['order_no'],
            'remarks'=>$bill['remarks'],
            'pm'=>$bill['pm'],
            'ctime'=>time(),
            'on_line'=>$bill['on_line'],
            'status'=>$bill['status'],
            'pm2_msg'=>$bill['pm2_msg']??'',
            'mer_id'=>$bill['mer_id'],
            'commission_scale'=>$bill['commission_scale']??0,
            'commission_type'=>$bill['commission_type']??0,
            'to_user_type'=>$bill['to_user_type']??'',
            'to_user_type_1'=>$bill['to_user_type_1']??'',

        ];
        Db::name('log')->insert(['data'=>json_encode($insert)]);
        Db::name('entropy_barter_bill')->insert($insert);

    }
    //积分赠送
    public function give_integral()
    {
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $param=$this->request->param();
        $uid = $this->request->uid();
        $cxbuser_from=Db::name('user')->where('uid',$uid)->find();
        $cxbuser_to=Db::name('user')->where('uid',$param['to_id'])->find();
        $user=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
        $touser=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$param['to_id'])->find();
        if(!$touser){
            return app('json')->fail('未查询到用户（赠送）');
        }
        $from_id=$user['eb_id'];
        $to_id=$touser['eb_id'];
        $number=$param['unmber'];
        if($user['integral']<$number){
            return app('json')->fail('积分不足，赠送失败。');
        }
        $update_from=[
            'integral'=>$number
        ];
        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$from_id)->update($update_from);
        $bill=[
            'from_id'=>$from_id,
            'number'=>$number,
            'to_id'=>$to_id,
            'type'=>'1',
            'order_no'=>'0',
            'remarks'=>'赠送给'.$cxbuser_to['nickname'].$number.'积分',
            'pm'=>2,
            'status'=>2,
            'mer_id'=>$mer_id
        ];
        $this->eb_user_bill($bill);
        $update_to=[
            'integral'=>$number
        ];
        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$to_id)->update($update_to);
        $bill=[
            'from_id'=>$from_id,
            'number'=>$number,
            'to_id'=>$to_id,
            'type'=>'1',
            'order_no'=>'0',
            'remarks'=>$cxbuser_from['nickname'].'赠送给我'.$number.'积分',
            'pm'=>1,
            'status'=>2,
            'mer_id'=>$mer_id
        ];
        $this->eb_user_bill($bill);

        return app('json')->success('赠送成功');
    }
    //搜索好友
    public function search_friends()
    {
        $phone=$this->request->params(['phone']);
        if(!empty($phone)){
            app('json')->fail('未接收到参数 phone');
        }
        $user_data=Db::name('user')->where('account',$phone)->field('uid')->find();
        if(!$user_data){
            app('json')->fail('未查询到用户--'.$phone);
        }
        return app('json')->success(['uid'=>$user_data['uid']]);
    }
    //个人中心
    public function personals()
    {
        $uid=$this->request->uid();
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $userdata=Db::name('entropy_barter_user_'.$mer_id)
            ->alias('ebu')
            ->leftJoin('user u','u.uid=ebu.uid')
            ->where('ebu.uid',$uid)
            ->find();
        if (!$userdata){
            return app('json')->fail('还未注册');
        }
        $unsettled_integral=Db::name('entropy_barter_bill')
            ->where('mer_id',$mer_id)
            ->where('type',1)
            ->where('to_id',$userdata['eb_id'])
            ->where('pm',1)
            ->where('status',1)
            ->sum('number');
        $userdata['unsettled_integral']=$unsettled_integral;
        if($userdata['avatar']=='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png'){
            $userdata['avatar']=Db::name('user_account')->where('type',1)->where('uid',$uid)->value('avater');
            if(empty($userdata['avatar'])){
                $userdata['avatar']=Db::name('user_account')->where('type',2)->where('uid',$uid)->value('avater');
                if(empty($userdata['avatar'])){
                    $userdata['avatar']='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png';
                }
            }
        }
        if($mer_id==290){
            $userdata['url']=$this->zhongjiankangyang_pic($userdata);
        }
        if ($userdata)
            return app('json')->success($userdata);
        else
            return app('json')->fail('暂无数据');
    }

    public function zhongjiankangyang_pic($user)
    {
        if($user['type']!=0){
            if($user['pay_goods_type']==1){
                switch ($user['type']){
                    case 3:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type3pay_goods_type1.png';
                        break;
                    case 4:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type4pay_goods_type1.png';
                        break;
                    case 5:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type5pay_goods_type1.png';
                        break;
                    case 6:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type6pay_goods_type1.png';
                        break;
                    case 7:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/heijin.png';
                        break;
                    case 1:
                    default:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type1pay_goods_type1.png';
                }
            }elseif($user['pay_goods_type']==2){
                switch ($user['type']){
                    case 3:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type3pay_goods_type2.png';
                        break;
                    case 4:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type4pay_goods_type2.png';
                        break;
                    case 5:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type5pay_goods_type2.png';
                        break;
                    case 6:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type6pay_goods_type2.png';
                        break;
                    case 7:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/heijin.png';
                        break;
                    case 2:
                    default:
                        $url='https://app.bjtdba.com/applet/static/images/zjky/type2pay_goods_type2.png';
                }
            }
        }else{
            $url=1;
        }
        return $url;
    }
    //下级用户
    public function subordinate()
    {
        [$page,$limit] = $this->getPage();
        $uid=$this->request->uid();
        $type=$this->request->params(['type']);
        if(empty($type['type'])){
            return app('json')->fail('未获取到参数: type');
        }
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $type=$type['type'];
        if($type==1){
//            $user_data=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->field('nickname,account，create_time,')->select();
            $ebuser=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
            $user_data=Db::name('entropy_barter_user_'.$mer_id)->where('top_eb_id',$ebuser['eb_id'])->page($page,$limit)->select();
            $num=Db::name('entropy_barter_user_'.$mer_id)->where('top_eb_id',$ebuser['eb_id'])->count('eb_id');
            if($user_data->isEmpty()){
                return app('json')->success([]);
            }
            $user_data=$user_data->toArray();
            foreach ($user_data as $k=>&$v){
                $cxb_user=Db::name('user')->where('uid',$v['uid'])->field('nickname,avatar,create_time')->find();
                $v['avatar']=$cxb_user['avatar'];
                if($cxb_user['avatar']=='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png'){
                    $v['avatar']=Db::name('user_account')->where('type',1)->where('uid',$v['uid'])->value('avater');
                    if(empty($v['avatar'])){
                        $v['avatar']=Db::name('user_account')->where('type',2)->where('uid',$v['uid'])->value('avater');
                        if(empty($v['avatar'])){
                            $v['avatar']='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png';
                        }
                    }
                }

                $v['nickname']=$cxb_user['nickname'];
                $v['create_time']=date('Y-m-d H:i:s',$v['ctime']);
                $v['money']=Db::name('store_order')->where('mer_id',$mer_id)->where('uid',$v['uid'])->where('paid',1)->where('status','<>','-1')->sum('total_price');
                $v['order']=Db::name('store_order')->where('mer_id',$mer_id)->where('uid',$v['uid'])->where('paid',1)->where('status','<>','-1')->count('order_id');
                $v['extension']=Db::name('entropy_barter_user_'.$mer_id)->where('top_eb_id',$v['eb_id'])->count('eb_id');
            }
        }elseif($type==2){
            $ebuser=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
            $top_user=Db::name('entropy_barter_user_'.$mer_id)->where('top_eb_id',$ebuser['eb_id'])->select();
            if($top_user->isEmpty()){
                return app('json')->success([]);
            }
            $top_user=$top_user->toArray();
            $ids='';
            foreach ($top_user as $k=>$v){
                $ids.=$v['eb_id'].',';
            }
            $ids=explode(',',rtrim($ids,','));
            $user_data=Db::name('entropy_barter_user_'.$mer_id)->whereIn('top_eb_id',$ids)->page($page,$limit)->select();
            $num=Db::name('entropy_barter_user_'.$mer_id)->whereIn('top_eb_id',$ids)->count('eb_id');
            if($user_data->isEmpty()){
                return app('json')->success([]);
            }
            $user_data=$user_data->toArray();
            foreach ($user_data as $k=>&$v){
                $cxb_user=Db::name('user')->where('uid',$v['uid'])->field('nickname,avatar,create_time')->find();
//                dd($cxb_user);
                $v['avatar']=$cxb_user['avatar'];
                if($cxb_user['avatar']=='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png'){
                    $v['avatar']=Db::name('user_account')->where('type',1)->where('uid',$v['uid'])->value('avater');
                    if(empty($v['avatar'])){
                        $v['avatar']=Db::name('user_account')->where('type',2)->where('uid',$v['uid'])->value('avater');
                        if(empty($v['avatar'])){
                            $v['avatar']='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png';
                        }
                    }
                }

                $v['nickname']=$cxb_user['nickname'];

                $v['create_time']=date('Y-m-d H:i:s',$v['ctime']);
                $v['money']=Db::name('store_order')->where('mer_id',$mer_id)->where('paid',1)->where('uid',$v['uid'])->sum('total_price');
                $v['order']=Db::name('store_order')->where('mer_id',$mer_id)->where('paid',1)->where('uid',$v['uid'])->count('order_id');
            }
        }else{
            $user_data=[];
        }
        return app('json')->success(compact('user_data','num'));
    }
    //确认收货
    public function take($order_no)
    {
        Db::name('log')->insert(['data'=>'易熵易物我走进来了']);
        try {
            $mer_id=Db::name('store_order')->where('order_sn',$order_no)->value('mer_id');
            if($mer_id=='290'){
                $this->take_290($order_no);
            }
            $data=Db::name('entropy_barter_bill')->where('mer_id',$mer_id)->where('order_no',$order_no)->select();
            $order_data=Db::name('store_order')->where('order_sn',$order_no)->find();
            if($order_data['pay_price']>=1){
                $true=true;
            }else{
                $true=false;
            }
            Db::name('log')->insert(['data'=>'数据---'.json_encode($data)]);
            if($data->isEmpty()){
                return '12';
            }
            $data=$data->toArray();
        foreach ($data as $k=>$v){
//            if($true){
//                Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$v['to_id'])->inc('integral',100)->update();
//            }
            $true=false;
            if($v['status']=='1'){
                if($v['type']==2){
                    Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$v['to_id'])->inc('wallet',$v['number'])->update();
                    Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$v['to_id'])->dec('integral',$v['number'])->update();
                    Db::name('entropy_barter_bill')->where('id',$v['id'])->update(['status'=>2]);
                }elseif ($v['type']==1){
                    Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$v['to_id'])->inc('integral',$v['number'])->update();
                    Db::name('entropy_barter_bill')->where('id',$v['id'])->update(['status'=>2]);
                }
            }
        }
            $uid=Db::name('store_order')->where('order_sn',$order_no)->value('uid');

            $eb_user=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();

            $reward_one=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_one')->find();
            $reward_two=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_two')->find();
            $reward_three=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_three')->find();
            $reward_four=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_four')->find();
            Db::name('log')->insert(['data'=>'这是我总共的消费'.$eb_user['cumulative_money']]);
            Db::name('log')->insert(['data'=>'1'.json_encode($reward_one)]);
            Db::name('log')->insert(['data'=>'2'.json_encode($reward_two)]);
            Db::name('log')->insert(['data'=>'3'.json_encode($reward_three)]);
            Db::name('log')->insert(['data'=>'4'.json_encode($reward_four)]);
            $update_config=[];
            $update=[];
            if($eb_user['cumulative_money']>=$reward_one['value'] and $eb_user['cumulative_money']<$reward_two['value']){
                $update['type']=2;
                $update_config['value']=$reward_one['id'];
            }elseif ($eb_user['cumulative_money']>=$reward_two['value'] and $eb_user['cumulative_money']<$reward_three['value']){
                $update['type']=3;
                $update_config['value']=$reward_two['id'];
            }elseif ($eb_user['cumulative_money']>=$reward_three['value'] and $eb_user['cumulative_money']<$reward_four['value']){
                $update['type']=4;
                $update_config['value']=$reward_three['id'];
            }elseif ($eb_user['cumulative_money']>=$reward_four['value']){
                $update['type']=5;
                $update_config['value']=$reward_four['id'];
            }
            Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$eb_user['eb_id'])->update(['cumulative_money'=>bcadd($eb_user['cumulative_money'],$order_data['pay_price'],2)]);
            //修改此用户佣金比例
            Db::name('entropy_barter_config_user_'.$mer_id)->where('eb_id',$eb_user['eb_id'])->update($update_config);
            //修改此用户类型   2 会员 3经理 4 总监 5 总裁
            Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$eb_user['eb_id'])->update($update);




        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
        }
    }
    //退款
    public function refund($order_no)
    {
        try {
            $mer_id=Db::name('store_order')->where('order_sn',$order_no)->value('mer_id');
            $data=Db::name('entropy_barter_bill')->where('mer_id',$mer_id)->where('order_no',$order_no)->select();
            if($data->isEmpty()){
                return "123123131";
            }
            $data=$data->toArray();
            foreach ($data as $k=>$v){
                Db::name('entropy_barter_bill')->where('id',$v['id'])->update(['status'=>3]);
                if($v['status']=='2'){
                    if($v['type']==2){
                        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$v['to_id'])->dec('wallet',$v['number'])->update();
                        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$v['to_id'])->inc('integral',$v['number'])->update();
                    }elseif ($v['type']==1){
                        Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$v['to_id'])->dec('integral',$v['number'])->update();
                    }
                }
            }
            $uid=Db::name('store_order')->where('order_sn',$order_no)->value('uid');

            $eb_user=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();

            $reward_one=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_one')->find();
            $reward_two=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_two')->find();
            $reward_three=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_three')->find();
            $reward_four=Db::name('entropy_barter_config_'.$mer_id)->where('key','reward_four')->find();
            Db::name('log')->insert(['data'=>'2'.json_encode($reward_one)]);
            Db::name('log')->insert(['data'=>'2'.json_encode($reward_two)]);
            Db::name('log')->insert(['data'=>'3'.json_encode($reward_three)]);
            Db::name('log')->insert(['data'=>'4'.json_encode($reward_four)]);
            $update_config=[];
            $update=[];
            if($eb_user['cumulative_money']>=$reward_one['value'] and $eb_user['cumulative_money']<$reward_two['value']){
                $update['type']=2;
                $update_config['value']=$reward_one['id'];
            }elseif ($eb_user['cumulative_money']>=$reward_two['value'] and $eb_user['cumulative_money']<$reward_three['value']){
                $update['type']=3;
                $update_config['value']=$reward_two['id'];
            }elseif ($eb_user['cumulative_money']>=$reward_three['value'] and $eb_user['cumulative_money']<$reward_four['value']){
                $update['type']=4;
                $update_config['value']=$reward_three['id'];
            }elseif ($eb_user['cumulative_money']>=$reward_four['value']){
                $update['type']=5;
                $update_config['value']=$reward_four['id'];
            }else{
                $update['type']=1;
                $update_config['value']=0;
            }
            //修改此用户佣金比例
            Db::name('entropy_barter_config_user')->where('eb_id',$eb_user['eb_id'])->update($update_config);
            //修改此用户类型   2 会员 3经理 4 总监 5 总裁
            Db::name('entropy_barter_user_'.$mer_id)->where('eb_id',$eb_user['eb_id'])->update($update);
        }catch (Exception $exception){
            Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
        }
    }

    /**
     * 我的订单
     */
    public function my_order()
    {
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        [$page,$limit] = $this->getPage();
        $uid=$this->request->uid();
        $status=$this->request->params(['status']);
//        //订单状态（0：待发货；1：待收货；3：已完成；4售后   -2 待支付）
//        $page=1;
//        $limit=10;
//        $status['status']='1';
//        $uid=1824;
        $where=$status;
        if(empty($where['status'])){
            $where=[];
        }elseif ($where['status']==999){
            $where=[];
        }

        if($status['status']==4|| $status['status']=='-1'){
//            $data=Db::name('store_refund_order')->where('uid',$uid)->where('mer_id',276)->page($page,$limit)->select();
            $data=Db::name('store_order')->order('create_time','desc')->where('status','in','-1,4')->where('uid',$uid)->where('mer_id',$mer_id)->page($page,$limit)->select();
            if($data->isEmpty()){
                return app('json')->success([]);
            }
        }elseif($status['status']=='-2'){
            $data=Db::name('store_order')->order('create_time','desc')->where('uid',$uid)->where('is_del','0')->where('paid',0)->where('mer_id',$mer_id)->page($page,$limit)->select();

        }elseif ($status['status']==3){
            $data=Db::name('store_order')->order('create_time','desc')->where('uid',$uid)->where('is_del','0')->where('mer_id',$mer_id)->where('status',3)->page($page,$limit)->select();
        }elseif($status['status']==0){
            $data=Db::name('store_order')->order('create_time','desc')->where('uid',$uid)->where('is_del','0')->where('mer_id',$mer_id)->where('status',0)->page($page,$limit)->select();
        }else{
            $data=Db::name('store_order')->order('create_time','desc')->where($where)->where('is_del','0')->where('uid',$uid)->where('paid',1)->where('mer_id',$mer_id)->page($page,$limit)->select();
        }
        if($data->isEmpty()){
            return app('json')->success([]);
        }
        $data=$data->toArray();
        foreach ($data as $k=>&$v){
            $goods_data=Db::name('store_order_product')
                ->alias('sop')
                ->leftJoin('store_product sp','sop.product_id=sp.product_id')
                ->where('order_id',$v['order_id'])
                ->field('sp.image,sp.store_name,sop.product_num,sop.product_price,sop.product_id')
                ->find();
            $v['product']=$goods_data;
            $v['orderProduct']=Db::name('store_order_product')->where('order_id',$v['order_id'])->select();
        }
        return app('json')->success($data);
    }
    //提现
    public function withdrawal()
    {
        $param=$this->request->param();
        $money=$param['money'];
        $uid=$this->request->uid();
        $extract_type=$param['extract_type'];
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $userData = Db::name('user') -> where('uid',$uid) -> find();
        if($extract_type==2){

            if($userData['ali_user_id'] == '0' || $userData['ali_user_id'] == ''){
                return app('json')->success('未绑定支付宝账户');
            }
        }
//        $user=Db::name('user')->where('uid',$uid)->find();
        $eb_id=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
        if(empty($eb_id)){
            return app('json')->success('未查询到用户信息');
        }
        if(bcsub($eb_id['wallet'],$money,2)<'0'){
            return app('json')->fail('提现失败，佣金不够');
        }
//        if($money>'200'){
//            return app('json')->fail('一次最高提现200');
//        }
        if (!$userData){
            return app('json')->fail('用户信息错误');
        }
        if($extract_type==2){
            $order_sn='Ali'.time().rand('111111111','999999999');

        }elseif ($extract_type==1){
            $order_sn='wx'.time().rand('111111111','999999999');
        }
        $service_money=bcmul($money,'0.06',2);
//        $money=bcsub($money,$service_money,2);

        $insert_data=[
            'uid'=>$uid,
            'real_name'=>$userData['nickname'],
            'extract_type'=>$extract_type,
            'extract_price'=>$money,
            'type'=>1,
            'order_sn'=>$order_sn,
            'status'=>0,
            'withdrawal_type'=>2,
            'mer_id'=>$mer_id,
            'service_money'=>$service_money
        ];
        if($extract_type==2){
            $insert_data['alipay_code']=$userData['account'];
        }elseif ($extract_type==1){
            $insert_data['wechat']=$userData['account'];
        }
        Db::name('user_extract')->insert($insert_data);

        $bill=[
            'from_id'=>'0',
            'number'=>$money,
            'to_id'=>$eb_id['eb_id'],
            'type'=>'2',
            'order_no'=>$order_sn,
            'remarks'=>'提现待审核',
            'pm'=>2,
            'status'=>1,
            'pm2_msg'=>'提现',
            'on_line'=>1,
            'mer_id'=>$mer_id
        ];
        $this->eb_user_bill($bill);
        Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->dec('wallet',$money)->update();


        return app('json')->success('提交成功等待审核');
    }




    //团队订单
    public function order_lst()
    {
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        [$page,$limit] = $this->getPage();
        $uid=$this->request->uid();
        $click_id=$this->request->params(['click_id']);
        $type = $this -> request -> params(['type']);//默认线上订单
        if(empty($click_id) || $click_id['click_id']=='0'){
           return app('json')->fail('未查询到用户');
        }else{
           $click_id=$click_id['click_id'];
        }
        if($type['type'] == 1){
            $data=Db::name('store_order')->where('uid',$click_id)->page($page,$limit)->order('order_id','desc')->where('mer_id',$mer_id)->where('paid',1)->where('status','<>','-1')->field('order_id,uid,order_sn,create_time,total_price')->select();
        }elseif ($type['type']==2){
            $data = Db::name('order_merchant') -> where('uid',$click_id) ->page($page,$limit)->order('id','desc')->where('mer_id',$mer_id)->where('paid',1)->field('id as order_id,uid,out_trade_no as order_sn,create_time,money as total_price') ->select();
        }
        if($data->isEmpty()){
            return app('json')->success([]);
        }
        $data=$data->toArray();

        $eb_id=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
        foreach ($data as $k=>&$v){
            if($type['type']==1){

                $bill=Db::name('entropy_barter_bill')->where('mer_id',$mer_id)->where('order_no',$v['order_sn'])->where('on_line',1)->where('to_id',$eb_id['eb_id'])->find();
            }else{
                $bill=Db::name('entropy_barter_bill')->where('mer_id',$mer_id)->where('order_no',$v['order_sn'])->where('on_line',2)->where('to_id',$eb_id['eb_id'])->find();

            }
            if($bill['type']==1){
                $v['msg']='团队奖励'.$bill['number'].'积分';
            }elseif ($bill['type']==2){
                $v['msg']='直推奖励'.$bill['number'].'佣金';
            }

            if($bill['status']==1){
                $v['status']='待确定';
            }elseif ($bill['status']==2){
                $v['status']='有效';
            }elseif ($bill['status']==3){
                $v['status']='已失效';
            }
        }

        return app('json')->success($data);
    }



    /**
     * 单笔转账接口
     */
    public function transfer()
    {

        $app_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/appCertPublicKey.crt';
        $alipay_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/alipayCertPublicKey.crt';
        $alipay_root_cert_path=dirname(__FILE__). '/../../../../extend/alipay/aop/cert/alipayRootCert.crt';
        $url = "https://openapi.alipay.com/gateway.do";
        $app_id="2021002194632049";
        $privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGxceDFVT6VTYClinyAdY4PxE6MadNYLZ3sbLOLV14e39kuu1lkKDBZ/KPRNruPlSPGdiRVe+L8v4rsVk6bthsS/vMk5aH1wQyt58/HvHmZ5QVo3U5UD7cgqqefTcRJjKhjjM1rU/OrOkOqyssaLRukW3jeKRlBccUgtaGsXXrbMxWYpzl1OMDhKRRUVxu3LTfqlMpHghOasQrgyD92q9wlUN7U6hBYzGUocO/N3sz97PZwptwWAW0r3CFdlLCpgnMr+xb/Zh8td1OKGl3wEghiGavgDDlc2+w/xtk1SZ3pJbnGAU+D+oyJ6r76po6vkyGIlLrKp/zQ50az7fObzgNAgMBAAECggEBAK60szERlMkaEAih92gQGTsCo5+keMnX0UjO1LvGv7rfwQ7GBVYZklGrjVRDTrHL8wJ70w+amptFDgVVMXncZzh4aG5c4heu8q+pGLyf9DlwnIWQT736O+YQqun2YGogSqwYkgYBuH2NGKKd66pytPPhutYN+WAZfesXPHrSizRJtZMfuZvvGzm6ZJLZ1LmhvkOuLrX4xrJGRs1nAwZOmOfi4MY5VASblfPj59fUim9hErocNaX4uiMVwmhQl2QuOM/EbTd1UkW+dkV/gyQMOFzpcfN+SEi+hdLN+JiR9TVEcwity6ihOG5+3X33GKzfY4WFxeHHUaqA0SQWSkKofMECgYEA5OF5Imtq8/6JjWJ0jvYCpUnj9742McGJZTWBoTn9Hp0d3bwyE3YbH8pBVJyvzlfPKB9TUjE2FzVZvQtxEu+ZxToccp/LPqlgITWNHCmEtzAgXW7ww2PafgDZJ2QRSyjLUeRIWSAkeilj64XMCEC/bEs/nb5nmUb2gnsNTvvpMLUCgYEA3lMMtaIZH1fMI4XMNaPFzeRiKc0FIcLEem/efnPetPuOCujIWQJ/x9cCDCcfqO59I1FXQuiC/E1dFvme2qs/H7h2bFu8RG0M/ZQWd9twg31Sh+R7gCQakFERag8HXc4AWfBGXCvMu1SmSovU49KecSLxYGOAUdp77j1GxtLiePkCgYAQjc45ExPVOd+w/iH4BQsD8Wgvju5Ugu7xBwGtK4iHIk36r5XfmnczwWkgOYTto6Qz/rAEDdMfspge+CjhebrhbOaJ08zbZ1ywijL+inIy3aQ5ncCEIUC4RE9wbehiSz0JWz1wVMbOnxe+/RpYrnYp2vdq7U6I430IyuWXhNjE0QKBgEtJUmd7oghEIgPxfiq37/b+HOPM4q0BGKnhkjW+JS+idAJru9SwjPbub2oQIZ+CS2wXUnZ86EZqKFjsZQflr7WdMLUXB5UgXKLOcCFcdSiB2t3b2JqXH0u5uCzzM+pnJSVPwXPa/TR+wOVDnu8bVr43OAgNCdouI4OUyo/vv/N5AoGATJaIvpsZ9v1zmhbtJbgPBM9dhD2PIp2ufZ7yvhGGzA02FqAbyAeVsI2d+W+uA6jJ1X87x27pQv//mFoFXStxX3/bhdgTWbUYEWobAhw1jBS1rMQfLuBGGI/LsHGhzau3U+59erC5sYhGgZKSdXDyjOduWQlPWAv6ufkNZ+I3FCU=";

// 证书模式的测试
        $alipayConfig = new AlipayConfig();
        $alipayConfig->setAppId($app_id);
        $alipayConfig->setCharset("utf-8");
        $alipayConfig->setFormat("json");
        $alipayConfig->setSignType("RSA2");
        $alipayConfig->setServerUrl($url);
        $alipayConfig->setPrivateKey($privateKey);

// content 和 path 只需要设置一个即可
        $alipayConfig->setAppCertPath($app_cert_path);
//$alipayConfig->setAppCertContent()
        $alipayConfig->setAlipayPublicCertPath($alipay_cert_path);
//$alipayConfig->setAlipayPublicCertContent()
        $alipayConfig->setRootCertPath($alipay_root_cert_path);
//$alipayConfig->setRootCertContent()

        $aop = new AopCertClient($alipayConfig);
        $aop->isCheckAlipayPublicCert = true;

        $parameter = "{".
            "\"out_biz_no\":\"".rand(11111111,99999999)."\",".
            "\"remark\":\"测试\",".
//            "\"business_params\"":.json_encode(['payer_show_name_use_alias'=>'北京天地博爱网络科技有限公司']).
            "\"business_params\":\"{'payer_show_name_use_alias':'北京天地博爱网络科技有限公司'}\",".
            "\"biz_scene\":\"DIRECT_TRANSFER\",".
            "\"payee_info\":{".
            "\"identity\":\"3089507753@qq.com\",".
            "\"identity_type\":\"ALIPAY_LOGON_ID\",".
            "\"name\":\"唐世伟\"".
            "},".
            "\"trans_amount\":\"0.10\",".
            "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\",".
            "\"order_title\":\"提现测试\"".
            "}";
        Db::name('log')->insert(['data'=>$parameter]);
        $request = new AlipayFundTransUniTransferRequest ();
        $request->setBizContent($parameter);
        $response = $aop->execute($request);
        Db::name('log')->insert(['data'=>'【返回结果】'.$response]);
        $response=json_decode($response,true);
        if($response['alipay_fund_trans_uni_transfer_response']['code']=='10000'){
            return app('json')->success('提现成功');
        }else{
            return app('json')->fail($response['alipay_fund_trans_uni_transfer_response']['sub_msg']);
        }




//        $this->aop = new AopClient ();
//        //配置参数
//        $this->aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
//        $this->aop->appId = '2021002194632049';
//        $this->aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEArqx2duK0hD6gC4vxHsblNi8zFI+bObJmMpSdeFpgK8TDNe9BHGR/YZmNzWKLGQMNgVXEplEAsA6slQkXxzNstRobbsr+TRxdbE3PDo3+WnfzvNcs7IwW+fjY53W81BXttpuvVIcNqXVREUC4gfyUufq1J042tpr5HtzggJKuDLn3q80HtXNaLYqZxGYQrTLaabvh4mco1YWCbYOsPd1b6jKRA9TqaeQilC9cOHcleMNQGjet4p4eqEIGnhjEudslMM/heYtKFP4h38KTWmZfgMFPZPnDuGAgNvOOOpp6sG9waRkRSkOkakGPgxUlIUazSHAHUuO1iAltg+F5cA/OowIDAQABAoIBAQCDNrza+9xdB2pUojBkTUb8GCLIDESv5+rLjkZolYNu/aUjC/KecIQb/iy+n4scI+XuRU6vHWRl3PAaGLWLB39e4BjBdq3noSow5JZpOZNbxIYNUprFq0rLRvsxjIlnzH1A0ty3o6hIpv9Z9YNk6ieTOdkBiMijDfGcFJJ1IzqqBX9fOvvgWS/lDOrmVV2JN4W9AHJVvc/f4geKoRJICnG8vsHX6rxvRwQh5Rvmg4aqVsj8JGKT+CmA9p2S7TZlFFi43IKPk/2ij1Kubu8rMf52kTlonFmtjbakP5WK8KOQOcU616uj9E3QMiTaHn1+mVZYW5ZDRwywYTK9y9Xh08GZAoGBANcHXR1Te7rgvnclM+RB5n1ud90TcptufOVeCAPvx9Co6yuAV1U1EduOZ5opWVNPGN4uSX87/1/RP7WVMdQAJqGG3HOINL+HsJLX32y2wdppCefL+d8sbHVuYXeQHeu/zaprAXW8CuBtxGIJadz+mQwMsoupMhx24+f6gaVz53ltAoGBAM/0qm4p9+mF8N+ScxCPUXbxN+gCjcrc0Zx1hNtOSH6WPRz1xx56/M5PkRN/cbNpKmIugPahMqgEO4zE7zDm6O0HpztmBHa0vA6Tu3TV9kPpyWLl0fBnM5mNC5zxNI062XUj4DG2RbGktAWDGEfNXPsq8dFNTdzQsts4yuGy9u5PAoGAE9+JWpGBqPbmg4p7rkfs7oDMMTF/8R+YCXbUVNDPbdh+y6lz6NsbyGfz6UqTB+ESkk5C2rCH3KoxMi4UydwttdYJ/9+ByIXY6ulqq9iEOBRnJvYyJM8tQvktpug567TxZCO5odD8TFu4v7rQ/uzE5lkyEzhS+lB+pc0AOHNq3E0CgYA2UtOys4PvnO2vebJVQRsm1xyjnwcrV0Pqe0iZgXmul9CfIBVEARzJSD+9uC0bkP1haISH6NQyz+g+fbN+MtPmF3m4Ko4/9DasGCt/+eS7GPdivmZ5RnxUQGQoO1pfCmCEGTsXwWWzYjMkvXo6R4tikXVaF7efV2VhnxRgoT+gQQKBgQCknz2HhZryDYiAwi88WueQjDUumr2F1Iywjt8nYOhI3ryuO/kiqAI8E/hPbdpvo0L52fdqgeyAOkp7ubQ0pNOgfZv8SQmN3JIfGqcgaLgskg5rRQyQywGgsdCUpJEGklK0uJP6vXjVBn/WceHMXDRusuwLhHa+Aq3yF6Z3hRSpKw==';//私钥
//        $this->aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuUb+0sJSNXjWiG0VJIPzn55+18af/fubYMpRLlreu34ewMgLx1zpCNpB3wrA+dylfWPMAm8PzvKnakByB+VJ/LMNhWHmF8Qkdo4astAikjlI4TMQCK/G384NzrtjHR4DGCDM5CMVt1xw5noF7kNBMYIvgDfhMCYmygdlIjuVdIlVEoQKOsT0RaNMleES0aZvbjvBGkGM0dsetqUExSjid9BF1NAO2ET+J3XMxCtMgCUVmFUvxsCKe6Rapa1/Lk3rzIeG6CRpoabuYfPM9E+3y3f3luSOMXLfH9lOSW1RA8qrF+Ms1RZv8gmzUnbyrPLmmZPmmN/Qs6DGzDVg73fpSwIDAQAB';//APP公钥
//        $this->aop->apiVersion = '1.0';
//        $this->aop->signType = 'RSA2';
//        $this->aop->postCharset='UTF-8';
//        $this->aop->format='json';
//        //导入请求
//        $request = new AlipayFundTransToaccountTransferRequest ();
//        $request->setBizContent("{" .
//            "\"out_biz_no\":\"".rand(1111111,99999999999999)."\"," .//商户生成订单号
//            "\"payee_type\":\"ALIPAY_LOGONID\"," .//收款方支付宝账号类型
//            "\"payee_account\":\"3089507753@qq.com\"," .//收款方账号
//            "\"amount\":\"0.01\"," .//总金额
//            "\"payer_show_name\":\"北京天地博爱科技有限公司\"," .//付款方账户
//            "\"payee_real_name\":\"唐世伟\"," .//收款方姓名
//            "\"remark\":\"测试转账\"" .//转账备注
//            "}");
//        $result = $this->aop->execute ( $request);
//
//        dd($result);die;
//        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//        $resultCode = $result->$responseNode->code;
//        if(!empty($resultCode)&&$resultCode == 10000){
//            return true;
//        } else {
//            return false;
//        }
    }
    /**
     * 查单接口
     */
    public function query($order_number)
    {
        $this->aop = new AopClient ();
        //配置参数
        $this->init_aop_config();
        $request = new \AlipayFundTransOrderQueryRequest ();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"".$order_number."\"" .
            " }");
        $result = $this->aop->execute ( $request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            $res_arr['code'] = '00';
            $res_arr['data'] = $result;
        } else {
            $res_arr['code'] = '-1';
        }
        return $res_arr;
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 分销中心
     */
    public function my_distributor()
    {
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $uid= $uid=$this->request->uid();
        $user_data=Db::name('entropy_barter_user_'.$mer_id)
            ->alias('ebu')
            ->join('user u','u.uid=ebu.uid')
            ->where('ebu.uid',$uid)
            ->field('ebu.*,u.nickname,u.avatar')
            ->find();
        if($user_data['avatar']=='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png'){
            $user_data['avatar']=Db::name('user_account')->where('type',1)->where('uid',$uid)->value('avater');
            if(empty($user_data['avatar'])){
                $user_data['avatar']=Db::name('user_account')->where('type',2)->where('uid',$uid)->value('avater');
            }
        }
        $user_data['top_name']=Db::name('entropy_barter_user_'.$mer_id)
                ->alias('ebu')
                ->leftJoin('user u','u.uid=ebu.uid')
                ->where('ebu.eb_id',$user_data['top_eb_id'])
                ->value('u.nickname')??'无';
        //已提现佣金 包含未到账
        $withdrawnCash=Db::name('entropy_barter_bill')->where('mer_id',$mer_id)->where('type',2)->where('to_id',$user_data['eb_id'])->where('status','2')->where('pm','2')->where('status','<>',3)->where('pm2_msg','提现')->sum('number');
        //未结算佣金
        $unsettledCommission=Db::name('entropy_barter_bill')
            ->where('mer_id',$mer_id)
            ->where('type',2)
            ->where('to_id',$user_data['eb_id'])
            ->where('pm',1)
            ->where('status',1)
            ->sum('number');
        //未结算积分
        $unsettled_integral=Db::name('entropy_barter_bill')
            ->where('mer_id',$mer_id)
            ->where('type',1)
            ->where('to_id',$user_data['eb_id'])
            ->where('pm',1)
            ->where('status',1)
            ->sum('number');
        //分销佣金
        $distributionCommission=bcadd($user_data['wallet'],$unsettledCommission,2);
        //我的团队人数   一级 二级
        $my_team=Db::name('entropy_barter_user_'.$mer_id)->where('top_eb_id',$user_data['eb_id'])->column('eb_id');
        $my_team__number=Db::name('entropy_barter_user_'.$mer_id)->whereIn('top_eb_id',$my_team)->count('eb_id');
        $my_team__number+=Db::name('entropy_barter_user_'.$mer_id)->where('top_eb_id',$user_data['eb_id'])->count('eb_id');
        $data=[
            'user'=>$user_data,
            'withdrawnCash'=>bcadd($withdrawnCash,0,2),
            'unsettledCommission'=>bcadd($unsettledCommission,0,2),
            'distributionCommission'=>bcadd($distributionCommission,0,2),
            'my_team__number'=>$my_team__number,
            'unsettled_integral'=>$unsettled_integral
        ];
        return app('json')->success($data);

    }
    //商品列表
    public function product_lst()
    {
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        [$page,$limit] = $this->getPage();
        $cate_id=$this->request->params(['cate_id']);
        $key=$this->request->params(['key']);
        if(!empty($cate_id['cate_id'])) {
            if(empty($key['key'])){
                $data=Db::name('store_product_cate')->where('mer_cate_id',$cate_id['cate_id'])->where('mer_id',$mer_id)->column('product_id');
                $data=Db::name('store_product')
                    ->where('mer_id',$mer_id)
                    ->where('is_show', 1)
                    ->where('is_used ', 1)
                    ->where('stock ', '>', 0)
                    ->where('product_id','in',$data)
                    ->page($page,$limit)
                    ->select();
            }else{
                $data=Db::name('store_product_cate')->where('mer_cate_id',$cate_id['cate_id'])->where('mer_id',$mer_id)->column('product_id');
                $data=Db::name('store_product')
                    ->where('mer_id',$mer_id)
                    ->where('is_show', 1)
                    ->whereLike('store_name','%'.$key['key'].'%')
                    ->where('is_used ', 1)
                    ->where('stock ', '>', 0)
                    ->where('product_id','in',$data)
                    ->page($page,$limit)
                    ->select();
            }
        }else{
            if(empty($key['key'])){
            $data=Db::name('store_product')
                ->where('mer_id',$mer_id)
                ->where('is_show', 1)
                ->where('is_used ', 1)
                ->where('stock ', '>', 0)
                ->page($page,$limit)
                ->select();
            }else{
                $data=Db::name('store_product')
                    ->where('mer_id',$mer_id)
                    ->where('is_show', 1)
                    ->where('is_used ', 1)
                    ->where('stock ', '>', 0)
                    ->whereLike('store_name','%'.$key['key'].'%')
                    ->page($page,$limit)
                    ->select();
            }

        }
        if($data->isEmpty()){
            return app('json')->fail('暂无数据');
        }
        $data=$data->toArray();
        foreach($data as $k=>&$v){
            if($v['mer_id']==236){

                $v['pension']=bcmul($v['price'],0.10,2);
            }else{
                $v['pension']=bcmul($v['price'],0.02,2);
            }
        }
        return app('json')->success($data);
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 提现 记录
     */
    public function withdrawal_details()
    {
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $uid= $uid=$this->request->uid();
        $user=Db::name('entropy_barter_user_'.$mer_id)->where('uid',$uid)->find();
        if(empty($user)){
            return app('json')->fail('暂无用户信息');
        }
        $data=Db::name('entropy_barter_bill')->where('mer_id',$mer_id)->where('from_id',$user['eb_id'])->where('pm','2')->where('pm2_msg','提现')
                ->field('ctime,remarks,number,status')
                ->select();
        if($data->isEmpty()){
            return app('json')->fail('暂无提现记录');
        }
        $data=$data->toArray();
        foreach ($data as $k=>&$v){
            $v['ctime']=date('Y-m-d H:i:s',$v['ctime']);
            switch ($v['status']){
                case 1:
                    $v['status']='提现中';
                    break;
                case 2:
                    $v['status']='已提现';
                    break;
                case 3:
                    $v['status']='已拒绝';
                    break;

            }
        }
        return app('json')->success($data);
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 商户分类
     */
    public function category()
    {
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }else{
            $mer_id=$mer_id['mer_id'];
        }
        $cate=Db::name('store_category')->where('pid',0)->where('mer_id',$mer_id)->field('cate_name,store_category_id')->select();
        if ($cate->isEmpty()){
            return app('json')->fail('此商户没有分类');
        }
        $cate=$cate->toArray();
        return app('json')->success($cate);
    }

    public function order_lst_yanglao()
    {
        $uid=$this->request->uid();
        $mer_id=$this->request->params(['mer_id']);
        if(empty($mer_id['mer_id'])){
            return app('json')->fail('商户ID未传');
        }
        [$page,$limit] = $this->getPage();
        $data=Db::name('store_order')->where('is_del','0')->where('paid',1)->page($page,$limit)->where('mer_id',$mer_id['mer_id'])->where('status','in','0,1,2,3')->where('uid',$uid)->select();
        if($data->isEmpty()){
            return app('json')->success([]);
        }
        $data=$data->toArray();
        foreach ($data as $k=>&$v){
            $goods_data=Db::name('store_order_product')
                ->alias('sop')
                ->leftJoin('store_product sp','sop.product_id=sp.product_id')
                ->where('order_id',$v['order_id'])
                ->field('sp.image,sp.store_name,sop.product_num,sop.product_price,sop.product_id')
                ->find();
            $v['product']=$goods_data;
            $v['pension']=Db::name('user_bill')->where('uid',$uid)->where('source','0')->where('type_shop','0')->where(['link_id'=>$v['order_id']])->value('number');
        }
        return app('json')->success($data);
    }

    public function my_activation_code()
    {
        [$page, $limit] = $this->getPage();
        $uid=$this->request->uid();
        $code_data=Db::name('activation_code')
            ->alias('ac')
            ->where('ac.uid',$uid)
            ->where('ac.status','>','0')
            ->field('ac.code,ac.status as acstatus,ac.ctime as acctime,ac.utime as acutime,ac.uid as acuid,ac.id as acid,ac.use_uid')
            ->page($page,$limit)
            ->select()->toArray();
        foreach ($code_data as $k=>&$v){
            $v['use_user']=Db::name('user')->where('uid',$v['acuid'])->field('avatar,account,nickname')->find();
        }
        return app('json')->success($code_data);

    }
    //国腾名医单独处理
    public function pay_orrder_290($order,$type)
    {
        $uid=$order['uid'];
        $table_name='entropy_barter_user_290';
        $order=Db::name('store_order')->where('order_sn',$order['order_no'])->find();
        $order['order_no']=$order['order_sn'];
        $product=DB::name('store_cart')->where('cart_id',$order['cart_id'])->value('product_id');

        $imUserData=Db::name($table_name)->where('uid',$uid)->find();
        $top_data=Db::name($table_name)->where('eb_id',$imUserData['top_eb_id'])->find();
        if ($product=='362'||$product=='364'||$product=='363') {
            Db::name('store_order')->where('order_sn',$order['order_no'])->update(['is_split_to_tomorrow'=>1,'status'=>3]);
            if ($product == '362') {
                Db::name($table_name)->where('eb_id', $imUserData['eb_id'])->update(['type' => 1, 'pay_goods_type' => 1,'pay_status'=>1]);
            } else {
                Db::name($table_name)->where('eb_id', $imUserData['eb_id'])->update(['type' => 2, 'pay_goods_type' => 2,'pay_status'=>1]);

            }
        }
        /**
         * 奖励模式开始
         */
        Db::name('user_bill')->where('order_sn',$order['order_no'])->where('uid',$order['uid'])->where('source',0)->update(['status'=>1]);
        $order['money']=$order['pay_price'];
        $eb_one=$this->one_jiangli($top_data,$order,$table_name,$type);

        if(!$eb_one){
            if($imUserData['pay_status']!=1){
                $this->take_290($order['order_no'],1);
            }else{
                Db::name('log')->insert(['data'=>'已购买过合伙人商品或者创始人商品']);
            }
            return false;
        }
        //one_jiangli 推荐奖给了"它"
        $eb_two=$this->two_jiangli($top_data,$order,$table_name,$type);
        if(!$eb_two){
            if($imUserData['pay_status']!=1){
                $this->take_290($order['order_no'],1);
            }else{
                Db::name('log')->insert(['data'=>'已购买过合伙人商品或者创始人商品']);
            }
            return false;
        }
        //two_jiangli 推荐奖给了"它"
        $eb_three=$this->three_jiangli($eb_two,$order,$table_name,$type);
        if(!$eb_three){
            if($imUserData['pay_status']!=1){
                $this->take_290($order['order_no'],1);
            }else{
                Db::name('log')->insert(['data'=>'已购买过合伙人商品或者创始人商品']);
            }
            return false;
        }
        //three_jiangli 推荐奖给了"它"
        if($eb_one['eb_id']==$eb_two['eb_id']){
            $eb_four=$this->four_jiangli($eb_three,$order,$table_name,$type);
        }
        /**
         * 奖励模式结束
         */



    }
    //推荐奖
    public function one_jiangli($top_data,$order,$table_name,$type)
    {
//        dd($top_data['pay_status']==1&&$top_data['type']>2);
        if($top_data['pay_status']==1&&$top_data['type']>2){
            $proportion=$this->reward_proportion($top_data['type']);
            $money=bcmul($order['money'],"0.3",2);
            $msg=$proportion['msg'].'：推荐奖励';
            $bill_data=[
                'from_id'=>0,
                'to_id'=>$top_data['eb_id'],
                'type'=>2,
                'order_no'=>$order['order_no'],
                'remarks'=>$msg,
                'ctime'=>time(),
                'number'=>$money,//商业合伙人或联合创始人奖励为30%
                'pm'=>1,
                'status'=>'2',
                'on_line'=>$type,
                'mer_id'=>290,
                'commission_type'=>1,
                'commission_scale'=>30,
                'to_user_type'=>1,
                'to_user_type_1'=>$proportion['type'],
            ];


            //增加账单记录
            $this->eb_user_bill($bill_data);
            Db::name($table_name)->where('eb_id',$top_data['eb_id'])->inc('wallet',$money)->update();
            Db::name($table_name)->where('eb_id',$top_data['eb_id'])->inc('ranking_money',$money)->update();
            $data=[
                'type'=>$top_data['type'],
                'eb_id'=>$top_data['eb_id']
            ];
        }
        else{
//            if($top_data['type']>=1){
//                $money=bcmul($order['money'],"0.3",2);
//                Db::name($table_name)->where('eb_id',$top_data['eb_id'])->inc('precipitate',$money)->update();
//                $data=[
//                    'type'=>$top_data['type'],
//                    'eb_id'=>$top_data['eb_id']
//                ];
//            }
            $data=[12313];
        }
        return $data;
    }
    //一级奖励
    public function two_jiangli($top_data,$order,$table_name,$type)
    {

//        dd($top_data['type']>2);
        if($top_data['type']>2){
            $proportion=$this->reward_proportion($top_data['type']);
            $money=bcmul($order['money'],$proportion['proportion'],2);
            $msg=$proportion['msg'].'：管理奖励';
            $bill_data=[
                'from_id'=>0,
                'to_id'=>$top_data['eb_id'],
                'type'=>2,
                'order_no'=>$order['order_no'],
                'remarks'=>$msg,
                'ctime'=>time(),
                'number'=>$money,//商业合伙人或联合创始人奖励为30%
                'pm'=>1,
                'status'=>'2',
                'on_line'=>$type,
                'mer_id'=>290,
                'commission_type'=>1,
                'commission_scale'=>$proportion['proportion']*100,
                'to_user_type'=>2,
                'to_user_type_1'=>$proportion['type'],
            ];
            //增加账单记录
            $this->eb_user_bill($bill_data);
            Db::name($table_name)->where('eb_id',$top_data['eb_id'])->inc('wallet',$money)->update();
            Db::name($table_name)->where('eb_id',$top_data['eb_id'])->inc('ranking_money',$money)->update();
            $data=[
                'eb_id'=>$top_data['eb_id'],
                'type'=>$top_data['type']
            ];
        }else{
            $top_1_id=$this->recursion_top($top_data['top_eb_id'],'0');
            if($top_1_id==0){
                return false;
            }
            $top_1_data=Db::name($table_name)->where('eb_id',$top_1_id)->find();
            $proportion=$this->reward_proportion($top_1_data['type']);
            $money=bcmul($order['money'],$proportion['proportion'],2);
            $msg=$proportion['msg'].'：管理奖励';
            $bill_data=[
                'from_id'=>0,
                'to_id'=>$top_1_data['eb_id'],
                'type'=>2,
                'order_no'=>$order['order_no'],
                'remarks'=>$msg,
                'ctime'=>time(),
                'number'=>$money,//商业合伙人或联合创始人奖励为30%
                'pm'=>1,
                'status'=>'2',
                'on_line'=>$type,
                'mer_id'=>290,
                'commission_type'=>1,
                'commission_scale'=>$proportion['proportion']*100,
                'to_user_type'=>2,
                'to_user_type_1'=>$proportion['type'],
            ];
            //增加账单记录
            $this->eb_user_bill($bill_data);
            Db::name($table_name)->where('eb_id',$top_1_data['eb_id'])->inc('wallet',$money)->update();
            Db::name($table_name)->where('eb_id',$top_1_data['eb_id'])->inc('ranking_money',$money)->update();
            $data=[
                'type'=>$top_1_data['type'],
                'eb_id'=>$top_1_data['eb_id']
            ];
        }
        return $data;
    }
    //二级奖励
    public function three_jiangli($top_data,$order,$table_name,$type)
    {
        $top=$top_data;
        $top_data=Db::name($table_name)->where('eb_id',$top['eb_id'])->find();
        $top_top_data=Db::name($table_name)->where('eb_id',$top_data['top_eb_id'])->find();
////        dd($top_top_data>2);
//        dd($top['type']==$top_top_data['type']||$top['type']>$top_top_data['type']);
        if($top_top_data['type']>2){
            if($top['type']==$top_top_data['type']||$top['type']>$top_top_data['type']){
                $proportion=$this->reward_proportion($top_top_data['type']);
                $proportion['proportion']='0.02';
                $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,3);
            }elseif($top['type']<$top_top_data['type']){

                if($top_top_data['type']==4){
                    $proportion=$this->reward_proportion($top_top_data['type']);
                    $proportion['proportion']='0.06';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,3);

                }elseif($top_top_data['type']==5){
                    if($top['type']==3){
                        $proportion=$this->reward_proportion($top_top_data['type']);
                        $proportion['proportion']='15';
                        $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,3);
                        return false;
                    }else{
                        $proportion=$this->reward_proportion($top_top_data['type']);
                        $proportion['proportion']='0.09';
                        $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,3);
                    }
                }elseif($top_top_data['type']==3){
                    $proportion=$this->reward_proportion($top_top_data['type']);
                    $proportion['proportion']='0.03';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,3);
                }

            }
            $data=[
                'eb_id'=>$top_top_data['eb_id'],
                'type'=>$top_top_data['type']
            ];
        }else{
            $top_1_id=$this->recursion_top($top_data['top_eb_id'],'0');

            if($top_1_id==0){
                return false;
            }
            $top_1_data=Db::name($table_name)->where('eb_id',$top_1_id)->find();

            if($top['type']==$top_1_data['type']||$top['type']>$top_1_data['type']){
                $proportion=$this->reward_proportion($top_1_data['type']);
                $proportion['proportion']='0.02';
                $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_1_data['eb_id'],$table_name,$proportion,3);

            }elseif($top['type']<$top_1_data['type']){
                if($top_1_data['type']==4){
                    $proportion=$this->reward_proportion($top_1_data['type']);
                    $proportion['proportion']='0.06';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_1_data['eb_id'],$table_name,$proportion,3);

                }elseif($top_1_data['type']==5){
                    $proportion=$this->reward_proportion($top_1_data['type']);
                    $proportion['proportion']='0.09';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_1_data['eb_id'],$table_name,$proportion,3);

                }elseif($top_1_data['type']==3){
                    $proportion=$this->reward_proportion($top_1_data['type']);
                    $proportion['proportion']='0.02';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,3);
                }

            }
            $data=[
                'eb_id'=>$top_1_data['eb_id'],
                'type'=>$top_1_data['type']
            ];
        }
        return  $data;
    }
    //三级奖励
    public function four_jiangli($top_data,$order,$table_name,$type)
    {
        $top=$top_data;
        $top_data=Db::name($table_name)->where('eb_id',$top['eb_id'])->find();
        $top_top_data=Db::name($table_name)->where('eb_id',$top_data['top_eb_id'])->find();

        if(!$top_top_data){
            return false;
        }
        if($top_top_data['type']>2){
            if($top['type']<$top_top_data['type']){
                if($top_top_data['type']==4){
                    $proportion=$this->reward_proportion($type);
                    $proportion['proportion']='0.06';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,4);

                }elseif($top_top_data['type']==5){
                    $proportion=$this->reward_proportion($type);
                    $proportion['proportion']='0.09';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,4);
                }elseif($top_top_data['type']==3){
                    $proportion=$this->reward_proportion($type);
                    $proportion['proportion']='0.03';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_top_data['eb_id'],$table_name,$proportion,4);
                }

            }
            $data=[
                'eb_id'=>$top_top_data['eb_id'],
                'type'=>$top_top_data['type']
            ];
        }else{
            $top_1_id=$this->recursion_top($top_data['top_eb_id'],'0');

            if($top_1_id==0){
                return false;
            }
            $top_1_data=Db::name($table_name)->where('eb_id',$top_1_id)->find();
            if($top['type']<$top_1_data['type']){
                if($top_1_data['type']==4){
                    $proportion=$this->reward_proportion($top_1_data['type']);
                    $proportion['proportion']='0.06';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_1_data['eb_id'],$table_name,$proportion,4);
                    $data=[
                        'eb_id'=>$top_1_data['eb_id'],
                        'type'=>$top_1_data['type']
                    ];
                }elseif($top_1_data['type']==5){
                    $proportion=$this->reward_proportion($top_1_data['type']);
                    $proportion['proportion']='0.09';
                    $this->jiangli_cl($type,$order['money'],$order['order_no'],$top_1_data['eb_id'],$table_name,$proportion,4);
                    $data=[
                        'eb_id'=>$top_1_data['eb_id'],
                        'type'=>$top_1_data['type']
                    ];
                }else{
                    return false;
                }

            }else{
                return false;
            }

        }
        return  $data;
    }
    public function jiangli_cl($type,$money,$order_no,$eb_id,$table_name,$proportion,$to_user_type)
    {

        $money=bcmul($money,$proportion['proportion'],2);
        $msg=$proportion['msg'].'：管理奖励';
        $bill_data=[
            'from_id'=>0,
            'to_id'=>$eb_id,
            'type'=>2,
            'order_no'=>$order_no,
            'remarks'=>$msg,
            'ctime'=>time(),
            'number'=>$money,//商业合伙人或联合创始人奖励为30%
            'pm'=>1,
            'status'=>'2',
            'on_line'=>$type,
            'mer_id'=>290,
            'commission_type'=>1,
            'commission_scale'=>$proportion['proportion']*100,
            'to_user_type'=>$to_user_type,
            'to_user_type_1'=>$proportion['type'],
        ];
//        dd($bill_data);
        //增加账单记录
        $this->eb_user_bill($bill_data);
        Db::name($table_name)->where('eb_id',$eb_id)->inc('wallet',$money)->update();
        Db::name($table_name)->where('eb_id',$eb_id)->inc('ranking_money',$money)->update();
    }
    //获取奖励比例
    public function reward_proportion($type)
    {
        switch ($type){

            case '3':
                $proportion=[
                    "proportion"=>'0.03',
                    'msg'=>'经理',
                    'type'=>3,
                ];
                break;
            case '4':
                $proportion=[
                    "proportion"=>'0.09',
                    'msg'=>'总监',
                    'type'=>4,
                ];
                break;
            case '5':
                $proportion=[
                    "proportion"=>'0.18',
                    'msg'=>'总裁',
                    'type'=>5,
                ];
                break;
            default:
            case '2':
            case '1':
            $proportion=[
                "proportion"=>'0',
                'msg'=>'其它',
                'type'=>0,
            ];
        }
        return $proportion;
    }
    //国腾名医确认收货单独处理
    public function take_290($order_no,$type=2)

    {
        Db::name('log')->insert(['data'=>'290进来了5']);
        if($type==1){
            $store_table_name='store_order';
            $eb_table_name='entropy_barter_user_290';
            $orde_data=Db::name($store_table_name)->where('order_sn',$order_no)->find();
            $eb_data=Db::name($eb_table_name)->where('uid',$orde_data['uid'])->find();
//            Db::name('user_bill')->where('order_sn',$order_no)->where('uid',$orde_data['uid'])->where('source',0)->update(['status'=>1]);
    //        $mer_id=Db::name('store_order')->where('order_sn',$order_no)->value('mer_id');
    //        $data=Db::name('entropy_barter_bill')->where('mer_id',$mer_id)->where('order_no',$order_no)->select();
    //        foreach ($data as $k=>$v){
    //            if($v['status']=='1'){
    //                if($v['type']==2){
    //                    Db::name($eb_table_name)->where('eb_id',$v['to_id'])->inc('wallet',$v['number'])->update();
    //                    Db::name($eb_table_name)->where('eb_id',$v['to_id'])->dec('integral',$v['number'])->update();
    //                    Db::name('entropy_barter_bill')->where('id',$v['id'])->update(['status'=>2]);
    //                }elseif ($v['type']==1){
    //                    Db::name($eb_table_name)->where('eb_id',$v['to_id'])->inc('integral',$v['number'])->update();
    //                    Db::name('entropy_barter_bill')->where('id',$v['id'])->update(['status'=>2]);
    //                }
    //            }
    //        }
            //特殊的地方开始处理了
            //如果是特殊商品可以接着执行
            $product_id=Db::name('store_cart')->where('cart_id',$orde_data['cart_id'])->value('product_id');
            if($product_id==''){
                return '';
            }elseif ($product_id=='362'||$product_id=='364'||$product_id=='363'){
//                Db::name('store_order')->where('order_sn',$order_no)->update(['is_split_to_tomorrow'=>1,'status'=>3]);
                //查找上级是否可升级  $eb_data['top_eb_id']--上级ID
//                if($product_id=='362'){
//                    Db::name($eb_table_name)->where('eb_id',$eb_data['eb_id'])->update(['type'=>2,'pay_goods_type'=>2]);
//                }else{
//                    Db::name($eb_table_name)->where('eb_id',$eb_data['eb_id'])->update(['type'=>1]);
//
//                }
                $top_data=Db::name($eb_table_name)->where('eb_id',$eb_data['top_eb_id'])->find();
                if($top_data['type']!=0){
                    Db::name('log')->insert(['data'=>'上级是会员']);
                    $this->recursion($top_data['eb_id']);
                }else{
                    Db::name('log')->insert(['data'=>'上级不是会员'.$top_data['eb_id']]);
                }
            }
        }
    }

    public function recursion($eb_id)
    {
        try {
        $eb_table_name='entropy_barter_user_290';//1111
        $eb_data=Db::name($eb_table_name)->where('eb_id',$eb_id)->find();
        if($eb_data['type']==1){//一和二是同级别
            $eb_data['type']=2;
        }
        if($eb_data['type']==0){
            return '';
        }
        Db::name('guoteng_famous_doctor_relation')->insert(['uid'=>$eb_data['uid'],'type'=>$eb_data['type'],'create_time'=>date('Y-m-d H:i:s')]);

        $top_upgrade_num=Db::name('guoteng_famous_doctor_relation')->where('type',$eb_data['type'])->where('uid',$eb_data['uid'])->count('id');

        if($top_upgrade_num>=3){//如果该等级的数量大于3则升级
            if($eb_data['type']==5){
                return  '已达到最高级别';
            }

            Db::name($eb_table_name)->where('uid',$eb_data['uid'])->update(['type'=>$eb_data['type']+1]);
            if($eb_data['type']+1==3){
//                $money=Db::name($eb_table_name)->where('uid',$eb_data['uid'])->value('precipitate');
                $money=systemConfig('manager_reward');
                $bill_data=[
                    'from_id'=>0,
                    'to_id'=>$eb_data['eb_id'],
                    'type'=>2,
                    'order_no'=>'0000000000000000',
                    'remarks'=>'升级经理奖励',
                    'ctime'=>time(),
                    'number'=>$money,//商业合伙人或联合创始人奖励为30%
                    'pm'=>1,
                    'status'=>'2',
                    'on_line'=>1,
                    'mer_id'=>290,
                    'commission_type'=>1,
                    'commission_scale'=>0,
                ];
                //增加账单记录
                $this->eb_user_bill($bill_data);
                Db::name($eb_table_name)->where('eb_id',$eb_data['eb_id'])->inc('wallet',$money)->update();
                Db::name($eb_table_name)->where('eb_id',$eb_data['eb_id'])->inc('ranking_money',$money)->update();

            }
            if($eb_data['top_eb_id']!=0){
                $this->recursion($eb_data['top_eb_id']);
            }else{
                return '成功1';
            }
        }else{
            return '小于3';
        }
        return '成功2';

        }catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'订单支付出错：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
        }
    }
    //提现手续费
    public function withdrawal_service()
    {
        $data=$param=$this->request->param();
        $money=$data['money']??'';
        if($money==''){
            return app('json')->fail('金额错误');
        }
        if($money=='.'){
            return app('json')->fail('金额类型错误');

        }
        if( $this->source =='yhc') {
            $yhc_withdrawal_rate=merchantConfig($this->merId,'yhc_withdrawal_rate');
            $service_money=bcmul($money, $yhc_withdrawal_rate/100,2);
            $money=bcsub($money,$service_money,2);
            $service=$yhc_withdrawal_rate.'%';
        }else{
            $service_money=bcmul($money,'0.1',2);
            $money=bcsub($money,$service_money,2);
            $service='10%';
        }

        return app('json')->success(['service_money'=>$service_money,'money'=>$money,'service'=>$service]);
    }
    public function get_mp_access_token()
    {
        $access_token = Cache::get('wx9082e5ac2fdb513f1_mp_access_token');
        if ($access_token)
            return $access_token;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9082e5ac2fdb513f&secret=88980d4455cd48e258c6bdff28029383";
        $res = curlGet($url);
        Cache::set('wx9082e5ac2fdb513f1_mp_access_token', $res['access_token'], $res['expires_in']);
        return $res['access_token'];
    }
    public function getQrCode($pid, $uid,$mer_id)
    {
        $user = app()->make(\app\controller\merchant\user\User::class);
        $access_token = $this->get_mp_access_token();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $data['scene'] = 'spread=' . $uid . '&mer_id=' . $mer_id;
        $data['page'] = 'pages/users/entranceList/entrance';
        $res = $user->posturl($url, $data);
        Db::name('log')->insert(['data'=>'小程序获取二维码'.json_encode($res)]);
        //判断是否是 json格式
        if (is_null(json_decode($res))) {
            $new_file = (int)(microtime(true) * 1000);
            $dir = iconv("UTF-8", "GBK", "./public/mpqrcode");
            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }
            $path = $dir . '/' . $new_file . ".jpg";
            file_put_contents($path, $res);
            $imgurl = env('APP_URL') . "/mpqrcode/" . $new_file . ".jpg";

            return ['qrcode' => $imgurl, 'path' => $path];
        } else {
            //没有接收到数据流
            return false;
        }

    }



    public function share()
    {
        $mer_id = $this->request->params(['mer_id']);
        $uid = $this->request->uid();
        $mer_id = $mer_id['mer_id'] ?? '';
        if ($mer_id == '') {
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }
        $qrcode = $this->getQrCode('', $uid, $mer_id);
        if (!$qrcode)
            return app('json')->fail('获取小程序二维码失败');
        $path = $qrcode['path'];
        $qrcode = $qrcode['qrcode'];
        $pdata['image']='https://app.bjtdba.com/applet/static/images/zjky/zjkyshare.png';
        $pic_list = array(
            $pdata['image'],
        );
        try {


            $bg_w = 800; // 背景图片宽度
            $bg_h = 1300; // 背景图片高度

            $background = imagecreatetruecolor($bg_w, $bg_h); // 背景图片
            imagecolorallocate($background, 0, 0, 0);
            $red = imagecolorallocate($background, 255, 255, 255);
            imagefill($background, 0, 0, $red);

            $pic_count = count($pic_list);
            $lineArr = array(); // 需要换行的位置
            $space_x = 3;
            $space_y = 3;
            $line_x = 0;
            switch ($pic_count) {
                case 1: // 中间位置并排
                    $start_x = 0;
                    $start_y = 0;
                    $pic_w = intval($bg_w);
                    $pic_h = intval(800);
                    break;
            }
            foreach ($pic_list as $k => $pic_path) {
                if (!strstr($pic_path, 'http')) {
                    $pic_path = 'https:' . $pic_path;
                }
                $kk = $k + 1;
                if (in_array($kk, $lineArr)) {
                    $start_x = $line_x;
                    $start_y = $start_y + $pic_h + $space_y;
                }
                $pathInfo = pathinfo($pic_path);
                switch (strtolower($pathInfo['extension'])) {
                    case 'jpg':
                    case 'jpeg':
                        $imagecreatefromjpeg = 'imagecreatefromjpeg';
                        break;
                    case 'png':
                        $imagecreatefromjpeg = 'imagecreatefrompng';
                        break;
                    case 'gif':
                    default:
                        $imagecreatefromjpeg = 'imagecreatefromstring';
                        $pic_path = file_get_contents($pic_path);
                        break;
                }
                $resource = $imagecreatefromjpeg($pic_path);
                if ($k == 0) {
                    imagecopyresized($background, $resource, $start_x, $start_y, 0, 0, $pic_w, $pic_h, imagesx($resource), imagesy($resource)); // 最后两个参数为原始图片宽度和高度，倒数两个参数为copy时的图片宽度和高度
                }
            }

            header("Content-type: image/jpg");
            $filename1 = time();
            $filename = './public/shareimg/' . $filename1 . '.png';
            imagegif($background, $filename);
            $filename = 'http://app.bjtdba.com/shareimg/' . $filename1 . '.png';
            $filelink = [
                'Bold' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
                'Normal' => 'public/font/Alibaba-PuHuiTi-Regular.otf',
            ];
            $config = array(
                'image' => array(
                    array(
                        'url' => $qrcode,//二维码资源
                        'stream' => 0,
                        'left' => 147,
                        'top' => 398,
                        'right' => 0,
                        'bottom' => 0,
                        'width' => 300,
                        'height' => 300,
                        'opacity' => 100
                    )
                ),
                'background' => $filename
            );
            $data = setSharePoster($config, 'routine/spread/poster');
            unlink($path);
            if (empty($data)) {
                return app('json')->fail('生成海报失败请重新尝试');
            }

            return app('json')->success(['url'=>env('APP_URL') . $data['dir']]);
        }catch (\Exception $e) {
            unlink($path);
            return app('json')->fail('生成海报失败请重新尝试');

        }
    }

    //排行榜
    public function ranking_list()
    {
        $mer_id = $this->request->params(['mer_id']);
        $mer_id = $mer_id['mer_id'] ?? '';
        if ($mer_id == '') {
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }
        if($mer_id!=290){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }
        $data=Db::name('entropy_barter_user_290')->order('ranking_money','desc')->where('ranking_money','<>',0)->alias('ebu')->leftJoin('user u','u.uid=ebu.uid')->field('ranking_money as wallet,u.avatar,u.nickname')->select();
        if($data->isEmpty()){
            return app('json')->fail('数据正在回炉打造，马上就好');
        }else{
            $data=$data->toArray();
        }
        return  app('json')->success($data);
    }

    public function zjky_signireward_record()
    {
        $mer_id = $this->request->params(['mer_id']);
        $mer_id = $mer_id['mer_id'] ?? '';
        if ($mer_id == '') {
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }
        if($mer_id!=290){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }
        $uid=$this->request->uid();
        $singin_time=time();
        $find_data=Db::name('zjky_signireward_record')->where('member_id',$uid)->order('addtime','desc')->value('addtime');
        if($find_data>strtotime(date('Ymd'))){
            return app('json')->fail('今天已经签到过了');
        }
        Db::name('zjky_signireward_record')->insert(['member_id'=>$uid,'reward_socre'=>1,'signin_time'=>$singin_time,'addtime'=>time()]);
        $now_score=Db::name('entropy_barter_user_290')->where('uid',$uid)->count('integral');
        return app('json')->success(['code'=>0,'now_score'=>$now_score,'reward_socre'=>'1']);
    }

    public function get_zjky_signireward_record()
    {
        $mer_id = $this->request->params(['mer_id']);
        $mer_id = $mer_id['mer_id'] ?? '';
        if ($mer_id == '') {
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }
        if($mer_id!=290){
            return app('json')->fail('请联系技术人员排查问题，感谢您的反馈');
        }
        $uid=$this->request->uid();
        $show_day_arr=Db::name('zjky_signireward_record')->where('member_id',$uid)->column('signin_time');

        foreach ($show_day_arr as $k=>&$v){
            $v=date('Y-m-d',$v);
        }
        $score=Db::name('zjky_signireward_record')->where('member_id',$uid)->sum('reward_socre');
        $find_data=Db::name('zjky_signireward_record')->where('member_id',$uid)->order('addtime','desc')->value('addtime');
        if($find_data>strtotime(date('Ymd'))){
            $today_is_signin=1;
        }else{
            $today_is_signin=0;
        }
        return app('json')->success(['score'=>$score,'show_day_arr'=>$show_day_arr,'today_is_signin'=>$today_is_signin]);
    }
    //查找上级递归循环
    public function recursion_top($eb_id,$my_type)
    {

        $data=Db::name('entropy_barter_user_290')->where('eb_id',$eb_id)->field('top_eb_id,eb_id,type,pay_status')->find();

        if(!$data){
            return 0;
        }
        if($data['pay_status']==1&&$data['type']>2){
//            return $data['eb_id'];
            return  $data['eb_id'];
        }elseif($data['pay_status']!=1||$data['type']<2){
            return $this->recursion_top($data['top_eb_id'],$my_type);
        }
    }
}
















