<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020-05-06
 *
 *
 */

namespace app\controller\api;

use AlibabaCloud\Client\AlibabaCloud;
use app\common\dao\store\order\StoreOrderDao;
use app\common\dao\user\UserCertificationDao;
use app\common\model\user\User;
use app\common\model\user\UserCertification;
use app\common\repositories\merchant\order\OrderGzcRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\common\repositories\product\ShareRepository;
use app\common\repositories\shared\SharedProsperityUserRepository;
use app\common\repositories\store\order\StoreGroupOrderRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\store\order\StoreOrderStatusRepository;
use app\common\repositories\store\order\StoreRefundOrderRepository;
use app\common\repositories\user\UnionUsersRepository;
use app\common\repositories\user\UserRepository;
use app\common\repositories\wechat\RoutineQrcodeRepository;
use app\common\repositories\wechat\WechatUserRepository;
use app\controller\api\user\Volunteer;
use app\controller\api\util\Signature;
use app\entity\data\shared\SharedProsperityUserEntity;
use app\models\routine\RoutineQrcode;
use app\traits\GongApiRequest;
use app\traits\GzcApiRequest;
use app\traits\HaikeApiRequest;
use app\traits\HuiPay;
use app\validate\api\UserAuthValidate;
use Carbon\Carbon;
use crmeb\basic\BaseController;
use crmeb\services\AliYunSmsService;
use crmeb\services\MiniProgramService;
use crmeb\services\WechatService;
use crmeb\services\YunxinSmsService;
use applet\WXBizDataCrypt;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\Request;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Env;
use think\Exception;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Filesystem;
use think\Response;

/**
 * Class Auth
 * @package app\controller\api
 * @author xaboy
 * @day 2020-05-06
 */
class Auth extends BaseController
{
    use HaikeApiRequest;
    use HuiPay;

    protected $merId;
    protected $source;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->source = $this->request->header('source');
        $this->merId =  $this->request->header('merId');
    }

    /**
     * 计算国盛小程序市场管理分红
     */
    public function gscm($mer_id=1){
//        $enterprise=Db::name('enterprise')->where('type',1)->select();
        $enterprise=Db::name('enterprise')->where('mer_id',$mer_id)->where('type',1)->find();
        if(!$enterprise){
            return false;
        }
        $reward[6]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',6)->column('uid');
        $reward[5]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',5)->column('uid');
        $reward[4]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',4)->column('uid');
        $reward[3]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',3)->column('uid');
        $reward[2]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',2)->column('uid');
        $reward[1]=Db::name('enterprise_user')->where('mer_id',$mer_id)->where('identity',1)->column('uid');
//        $uids = array_merge($reward[6],$reward[5],$reward[4],$reward[3],$reward[2],$reward[1]);
        $uids_money=[];

        $enterprise_money=Db::name('enterprise_bill')->where('mer_id',$mer_id)->sum('money');
        $amoney=$enterprise_money*0.05;
        $divvy=decimal2($amoney*0.3);//平均分红
        $jiaquan_divvy=$amoney-$divvy;//加权分红

        //平均分红金额不足每人0.01 就不分了
        if($divvy > 0 || decimal2($divvy/(count($reward[6])*6+count($reward[5])*5+count($reward[4])*4+count($reward[3])*3+count($reward[2])*2+count($reward[1]))) > 0 ){
            //0-普通用户 1-微店 2-云店 3-旗舰店 4-消费合伙人 5-创业合伙人 6-股东合伙人
            for ($i=6;$i>0;$i--) {
                if ($i == 6) {
                    $mergedArray = $reward[6];
                }elseif($i==5){
                    $mergedArray = array_merge($reward[6],$reward[5]);
                }elseif($i==4){
                    $mergedArray = array_merge($reward[6],$reward[5],$reward[4]);
                }elseif($i==3){
                    $mergedArray = array_merge($reward[6],$reward[5],$reward[4],$reward[3]);
                }elseif($i==2){
                    $mergedArray = array_merge($reward[6],$reward[5],$reward[4],$reward[3],$reward[2]);
                }else{
                    $mergedArray = array_merge($reward[6],$reward[5],$reward[4],$reward[3],$reward[2],$reward[1]);
                }
                $fenhong=decimal2($divvy/count($mergedArray));
                foreach ($mergedArray as $v){
                    if(!isset($uids_money[$v])){
                        $uids_money[$v]=$fenhong;
                    }else{
                        $uids_money[$v]+=$fenhong;
                    }
                }
            }
            dump($uids_money);
        }


    }

    function jisuantuandui($where,$data=[]){
        $enterprise_user_team=DB::name('enterprise_user')->where($where)->column('uid');
        $arr=array_merge($data,$enterprise_user_team);
        foreach ($enterprise_user_team as $v){
            $where['node_uid']=$v;
            $arr=$this->jisuantuandui($where,$arr);
        }
        return $arr;
    }
    public function importExcel()
    {
        $file = request()->file('file');
// 创建一个新的Excel读取器对象
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load($file);
// 选择活动工作表
        $objPHPExcel->setActiveSheetIndex(0);
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
// 循环遍历行和列
        $yonghu=[];
        foreach ($sheetData as $k=>$row) {
            if($k==1){
                continue;
            }
            if($row['A'] && $row['A']!=NULL && $row['A']!=''){
                $yonghu[]=array('a'=>$row['A'],'b'=>$row['B']);
            }
        }

        $repository = app()->make(UserRepository::class);
        foreach ($yonghu as $k=>$v){
            $user = $repository->accountByUser($v['a']);
            if ($user){
//                return app('json')->fail('手机号已存在');
                $yonghu[$k]['user'] = $user;
            }else{
                $yonghu[$k]['user'] = $repository->registr($v['a'],'A123456','APP',0);
            }


        }
        foreach ($yonghu as $v){
            $user=$v['user'];
            if($v['b'] && $v['b']!=null && $v['b']!=''){
                $pid=Db::name('user')->where('account',$v['b'])->value('uid');
                if($pid){
                    $repository->bindSpread($user, intval($pid));
                }

            }

        }

    }
    public function test()
    {

        $this->importExcel();
        echo '导入成功';
        die;
        $storeOrderRepository = app()->make(StoreOrderRepository::class);
//        $storeOrderRepository->yihuchashengji();//一壶茶身份升级
//        $storeOrderRepository->yunyingjiangli();//运营中心奖励
//        $storeOrderRepository->yihuchafenxiang();//一壶茶分红逻辑memberSettings


//        $this->jinjian();die;
        var_dump(11);
        die;



        $order_id = (int)$this->request->param('id');
        $order=Db::name('store_order')->find($order_id);
        if(!$order){
            return '订单不存在';
        }

        //在rrx_store_order_product 表中查到product_id ，在rrx_store_product 查spu_id  在rrx_douhuomall表中查goods_id
        $out_order_no=$order['douhuomall_order_no'];
        $after_type='1';//1=未收货退款，2=退货退款，3=换货补发，4=不退货仅退款
        $explain='测试退货';
        $can_after_data=GongApiRequest::is_can_after( $out_order_no);
        dump($can_after_data);
        if(isset($can_after_data['result']['order_goods'])){
            foreach ($can_after_data['result']['order_goods'] as $v){
                $order_goods_id=$v['order_goods_id'];
                $after_num=$v['after_num'];
                $res=GongApiRequest::apply_after_sales( $order_goods_id,$out_order_no,  $after_type,  $explain,  $after_num);
                dump($res);
            }
        }
//
//        $storeGroupOrderRepository = app()->make(StoreGroupOrderRepository::class);
//        $res=$storeGroupOrderRepository->ProductOutCancel(6105);
//            $res = GongApiRequest::order_details('wx1698916402673749101');


        $res2=GongApiRequest::after_status_new($out_order_no);
        dump($res2);
//        dump($repository->getBangFu(9640));
//        dump($userRepository -> getCountUId(18));
//        echo '开发者测试';

//        echo systemConfig("pay_wx");
//        $res = [
//            "completeDateTime"=>"2022-05-31 14:27:09",
//            "remark"=>"1",
//            "orderAmount"=>"100",
//            "merchantId"=>"899104033",
//            "requestId"=>"wx1653980751822534740_5366",
//            "hmac"=>"yivznJKbCfPpnXpwsalGDz7tnRyjr9pqbeVSkVKZ5VvtnJqn4helUkGC+S2tsaF8oknwvN\/ZeoDcgtRPqT1uanOWyalSFip6qxkBDkbc\/sJBVMCR2vzp38+YEHbusuxH1O9D696bt\/PSuhFjItD9pFi+Qteha1zN8X4oxpWFEob4wOVcFnMHLkgehNoWy1NRqjz+RmD6osAzJrIS27RJmUaqt83e0ejcjfEzAEw74rq4Yafyx9PohjvF35iwVLCpOcdyxVsfuJ4D59ayqsgUs0\/80GMRvNkgXrO6bsN7m1t6PLSQgPkD6ruEX\/i4l4uhrpHLvnpc4wl9YsGS1k4SrQ==",
//            "clearingOrg"=>"UNION_PAY",
//            "totalRefundCount"=>"0",
//            "serialNumber"=>"ddd",
//            "realBankSerialNumber"=>"4200001429202205315964134213",
//            "orderCurrency"=>"CNY",
//            "realBankRequestNumber"=>"1531522625975881728N",
//            "totalRefundAmount"=>"0",
//            "paymentModeAlias"=>"MINIAPPS_WEIXIN_PAY",
//            "status"=>"SUCCESS"
//        ];
//        $requestId = [];
//        if(strpos($res['requestId'],'_') !== false){
//            $requestId = explode("_",$res['requestId']);
//        }
//        if($res['status'] == 'SUCCESS'){
//            Db::name('store_group_order') -> where('group_order_sn',$requestId[0]) -> update(['rand'=>$requestId[1],'serialNumber'=>$res['serialNumber']]);
//            $pay_type = $res['paymentModeAlias'] == 'MINIAPPS_WEIXIN_PAY' ? 1 : 4;
//            event('pay_success_order', ['order_sn' => $requestId[0],'pay_type'=>$pay_type]);
//        }

//        Db::name('test') -> insert(['date'=>date('Y-m-d H:i:s')]);
//        try {
//            $merch_no = $this->request->param('merch_no');
//            $mer_name = $this->request->param('mer_name');
//            $mer_short_name = $this->request->param('mer_short_name');
//            $response = $this->merchantModify(['merch_no' => $merch_no,'mer_name' => $mer_name, 'mer_short_name' => $mer_short_name,'agent_apply_no' => (string)time()]);
//            return app('json')->success($response);
//        } catch (\Throwable $e) {
//            return app('json')->fail($e->getMessage());
//        }
    }


    //商户进件
    private function jinjian(){
//        $returndata=[
//            'request_id'=>time().rand(111111,999999),
//            'usr_phone'=>'15732652759',
//            'cont_name'=>'吴国珍',
//            'cont_phone'=>'13911251783',
//            'customer_email'=>'312009092@qq.com',
//            'mer_name'=>'北京天地博爱科技有限公司',
//            'mer_short_name'=>'天地博爱科技',
//            'reg_addr'=>'北京市北京经济技术开发区科创十三街31号院二区14号楼9层901-3（北京自贸试验区高端产业片区亦庄组团）',
//            'cust_addr'=>'北京市北京经济技术开发区科创十三街31号院二区14号楼9层901-3（北京自贸试验区高端产业片区亦庄组团）',
//            'cust_tel'=>'010-53327000',
//            'legal_name'=>'吴国珍',
//            'legal_type'=>0,
//            'legal_idno'=>'321123196710192020',
//            'legal_mp'=>'13911251783',
//            'legal_start_cert_id_expires'=>'20061129',
//            'legal_id_expires'=>'20261129',
//            'card_id_mask'=>'629966688',
//            'card_name'=>'北京天地博爱科技有限公司',
//            'bank_acct_type'=>'1',
//            'bank_code'=>'03050000',
//            'prov_code'=>'0011',//省份编码 （省市编码）,
//            'area_code'=>'1100',//地区编码 （省市编码）
//            'license_code'=>'91110105697724649E',
//            'mer_valid_date'=>'20291118',
//            'mer_start_valid_date'=>'20091119',
//            'entry_mer_type'=>'1',
//            'rsa_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxTpMESsdhyjKQC+y1G++eXCEu5pXqK7fvkZJdubSTCQn/RM3soOMcCwTekULCxEUwM0SnPxFLcZuP/a8w87zWeAXoBCPJl1gVK4KZ+3tWq/BJPCET3Vy66M7pXfXL+ekd8gf2LWtEfpJoAn59guVfsbTOp44ppDkrb3SuXDcKhQIDAQAB'
//        ];
        $returndata=[
            'request_id'=>time().rand(111111,999999),
            'usr_phone'=>'13911251783',//注册手机号
            'cont_name'=>'陈立军',//联系人姓名
            'cont_phone'=>'13911251783',//联系人手机号码
            'customer_email'=>'312009092@qq.com',//电子邮箱
            'mer_name'=>'河北省一壶茶电子商务有限公司',//商户名称
            'mer_short_name'=>'一壶茶电子商务',//商户简称 商户简称，长度为10个中文
            'reg_addr'=>'河北省秦皇岛市经济技术开发区华山中路8号银通大厦',//注册地址
            'cust_addr'=>'河北省秦皇岛市经济技术开发区华山中路8号银通大厦',//经营地址
            'cust_tel'=>'010-53327000',//商户电话
            'legal_name'=>'陈立军',//法人/负责人 姓名
            'legal_type'=>0,//法人/负责人证件号码
            'legal_idno'=>'130302196709281432',//法人/负责人证件号码
            'legal_mp'=>'13911251783',//法人/负责人手机号
            'legal_start_cert_id_expires'=>'20230310',//法人/负责人身份证有效期（始），格式 YYYYMMDD
            'legal_id_expires'=>'20991231',//法人/负责人身份证有效期（至），格式 YYYYMMDD
            'card_id_mask'=>'13050163560800002447',//结算银行卡号
            'card_name'=>'河北省一壶茶电子商务有限公司',//结算银行卡开户姓名
            'bank_acct_type'=>'1',//结算银行账户类型，1 : 对公， 2 : 对私。小微只能是对私
            'bank_code'=>'01050000',//结算银行卡所属银行code
            'prov_code'=>'0013',//结算银行卡省份编码,
            'area_code'=>'1308',//结算银行卡省份编码
            'license_code'=>'91130301MAD48PT00A',//营业执照编码
            'mer_valid_date'=>'20991231',//商户有效日期（至），格式 YYYYMMDD（若为长期有效，固定为“20991231”;若开户企业类商户，必填）
            'mer_start_valid_date'=>'20231107',//商户有效日期（至），格式 YYYYMMDD（若为长期有效，固定为“20991231”;若开户企业类商户，必填）
            'entry_mer_type'=>'1',//商户类型：1-企业；2-小微。默认为企业
            'rsa_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxTpMESsdhyjKQC+y1G++eXCEu5pXqK7fvkZJdubSTCQn/RM3soOMcCwTekULCxEUwM0SnPxFLcZuP/a8w87zWeAXoBCPJl1gVK4KZ+3tWq/BJPCET3Vy66M7pXfXL+ekd8gf2LWtEfpJoAn59guVfsbTOp44ppDkrb3SuXDcKhQIDAQAB'
        ];

        dump($returndata);
        $arr= $this->incoming_parts($returndata,'config');
        dump($arr);die;
    }

    /**
     * 业绩奖-服务中心分红-发放
     * @return mixed
     */
    public function yihuchafenxiang(){
        $storeOrderRepository = app()->make(StoreOrderRepository::class);
        $storeOrderRepository->yihuchafenxiang();
        $storeOrderRepository->yunyingjiangli();
        return app('json')->success('业绩奖-服务中心分红-运营中心-发放完成');
    }

    /**
     * 一壶茶身份升级
     * @return mixed
     */
    public function yihuchashengji(){
        $storeOrderRepository = app()->make(StoreOrderRepository::class);
        $storeOrderRepository->yihuchashengji();
        return app('json')->success('一壶茶身份升级-完成');
    }

    public function shareImgesList(){

        $where['mer_id']=$this->merId;
        $where['status']=0;
        $classify=$this->request->param('classify',0);
        if($classify){
            $where['classify']=$classify;
        }
        $pageNum=$this->request->param('pageNum',1);
        $limit=$this->request->param('pageSize',10);
        $type=$this->request->param('type',0);
        if($type){
            $where['type']=$type;
        }

        $data['pageInfo']['list']=Db::name('share_posters')->where($where)->page($pageNum,$limit)->order('sort desc,id desc')->select();
        $data['pageInfo']['total']=Db::name('share_posters')->where($where)->count();
        return app('json')->success($data);
    }
    public function classifyList(){
        $data=Db::name('share_posters_classify')->field('id,name')->where('mer_id',$this->merId)->where('is_del',0)->order('sort desc,id desc')->select();
        return app('json')->success($data);
    }
    public function agreement_detail(){
        $type = $this->request->param('type',1);
//        $where['mer_id']=$this->merId;
        $where['type']=$type;
        $data=Db::name('enterprise_agreement')->where($where)->find();
        if(!$data){
            $data['title']='';
            $data['content']='';
        }
        return app('json')->success($data);

    }
    public function agreement(){
        $type = $this->request->param('type',1);
//        $where['mer_id']=$this->merId;
        $where['type']=$type;
        $data=Db::name('user_agreement')->where($where)->find();
        if(!$data){
            $data['title']='';
            $data['content']='';
        }

        $html='<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>'.$data['title'].'</title>
     <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }

    .container {
      margin: 0 auto;
      padding: 20px;
    }
  </style>
</head>
<body>
<div class="container">
'.$data['content'].'
</div>
</body>
</html';
        return $html;
    }

    /**
     * @param UserRepository $repository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020/6/1
     */
    public function login(UserRepository $repository)
    {
        $account = $this->request->param('phone');

        if (!$account)
            return app('json')->fail('请输入账号');
        $user = $repository->accountByUser($this->request->param('phone'));
        //13231658486 周总 张玉庭 13839803521 13083849831
        if($account != 13231658486){
            if (!$user)
                return app('json')->fail('账号或密码错误');
            if (!password_verify($pwd = (string)$this->request->param('password'), $user['pwd']))
                return app('json')->fail('账号或密码错误');
            $type = $this->request->param('type',0);
            if ($type==2){
                if ($user["identity"]==0||$user["identity"]==4||$user["identity"]==5){
                    return app('json')->fail('账号或密码错误');
                }
            }
        }

        $user = $repository->mainUser($user);
        $pid = $this->request->param('spread', 0);
        $repository->bindSpread($user, intval($pid));

        $tokenInfo = $repository->createToken($user);

        $repository->loginAfter($user);
        $useragree = Db::name('user_operating_record')->where('uid', $user['id'])->where('operation_model', 1)->where('operation_type', 1)->find();
        if (!$useragree){
            $repository->createUserOperatingRecord($user->uid, 1, 1, '用户同意用户协议记录');
        }
        // 登录增加是否实名字段
        $userCertificationDao = new UserCertificationDao();
        $isCertification = $userCertificationDao->getUserCertification($account);
        $user['is_ertification'] = 0;
        if (!empty($isCertification)) {
            $user['is_ertification'] = 1;
        }
        return app('json')->success($repository->returnToken($user, $tokenInfo));
    }

    /**
     * 手机号注册
     * @param UserRepository $repository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020/6/1
     */
    public function register(UserAuthValidate $validate, UserRepository $repository)
    {

        // $repository->insterUser(16328, 14395);

        // return "=====";
        $data = $this->request->params(['phone', 'sms_code', 'spread', 'password',"spread_phone","type","mer_id", 'share_id']);
        // $lockKey = 'lock:register:' . $data['phone'];
        // $redis = \think\facade\Cache::store('redis')->handler();
        // $acquired = $redis->set($lockKey, 1, ['nx', 'ex' => 15]);
        // if (!$acquired) {
        //     return app('json')->fail('正在注册，请稍后');
        // }
        $redisHandler = Cache::store('redis')->handler();
        $isSet = $redisHandler->set('register' . '-' . $data['phone'], 1, ['nx', 'ex' => 30]);
        if (!$isSet) {
            return app('json')->fail('请勿重复提交');
        }
        try {
        $type=$data['type']??'';
        unset($data['type']);
        $validate->sceneSmslogin()->check($data);

        $domain = $this->request->domain();
        if($data['sms_code'] == '8457' || strpos($domain, 'test.hebeiyhc.com') !== false) {
            // 域名中包含 "test.hebeiyhc.com'" 字符串
        }else if (!$this->checkSmsCode($data['phone'], $data['sms_code']) ){
            return app('json')->fail('验证码不正确');
        }

        cache()->set("sms_verified_" . $data['phone'], true, 60);

        $user = $repository->accountByUser($data['phone']);
        if ($user)
            return app('json')->fail('手机号已存在');

            if (!empty($data['share_id'])) {
                /** @var ShareRepository $shareRepository */
                $shareRepository = app()->make(ShareRepository::class);
                $shareEntity = $shareRepository->getShareEntityByShareId($data['share_id']);
                if (empty($shareEntity->getId())) {
                    throw new ValidateException('无效的分享信息');
                }
                $data['spread'] = $shareEntity->getUid();
            }

        if ($data["spread_phone"]){
            $spread_user = $repository->accountByUser($data['spread_phone']);
            if ($spread_user ){
                $data['spread']=$spread_user["uid"];
            }else{
                return app('json')->fail('推荐人手机号填写错误');
            }
        }
        // Log::info($data);
        $user = $repository->registr($data['phone'], $data['password'],'APP',"","",1,$data['spread']);

            // 注意创建完用户后 需要立马创建 共富体系 用户数据
            /** @var SharedProsperityUserRepository $sharedProsperityUserRepository */
            $sharedProsperityUserRepository = app()->make(SharedProsperityUserRepository::class);
            $sharedProsperityUserEntity = $sharedProsperityUserRepository->createByEntity(
                SharedProsperityUserEntity::newInstance()
                    ->setUserId($user->uid)
            );
            if (!empty($data['spread']) && !empty($sharedProsperityUserEntity->getUserId())) {
                $sharedProsperityUserRepository->bindParentId((int)$sharedProsperityUserEntity->getUserId(), (int)$data['spread']);
            }

        // $repository->registr($data['phone'], $data['password'],'APP',$data['spread']);
        $repository->addagent($user);
        $user = $repository->mainUser($user);

        $repository->bindSpread($user, intval($data['spread']));
//        $repository->spread_log($user, intval($data['spread']));
        $tokenInfo = $repository->createToken($user);
        $repository->loginAfter($user);
        //type==2 事业二部注册并绑定推荐关系
//        if($type==2){
//            $mer_data=Db::name('merchant')->where('mer_id',$data['mer_id'])->value('merchant_type');
//            if($mer_data==2){
//                try {
//                    $eb_user=Db::name('user')->where('account',$data['phone'])->find();
////                    Db::name('log')->insert(['data'=>'推荐人ID'.$eb_user['spread_uid']]);
//                    $users = app()->make(\app\controller\api\entropybarter\User::class);
//                    $users->bangding($eb_user['uid'],$eb_user['spread_uid'],276);
//                    $users->bangding($eb_user['uid'],$eb_user['spread_uid'],236);
//                }catch (Exception $exception){
//                    Db::name("log")->insert(array('data'=>$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】'));//日志记录
//                }
//            }
//        }
        if ($type == "marketing"){
            $spread = Db::name("User") -> alias("u") -> leftjoin("MarketingUser mu","u.uid = mu.uid") ->  where("u.uid",$data['spread']) -> field("u.uid,mu.spread_list") -> find();
            $spread_list = explode(',',$spread['spread_list']);
            if (!empty($spread_list)){
                $spread_list[] = "[" . $spread['uid'] . "]";
            }else{
                array_push($spread_list,"[".$spread['uid']."]");
            }
            $spread_list = array_filter($spread_list);
                    $data = [
                "uid" => $user->uid,
                "spread_uid" => $spread['uid'],
                "spread_list" => implode(",",$spread_list)
            ];
            Db::name("MarketingUser") -> insert($data);
        }

        $result = $repository->returnToken($user, $tokenInfo);
        $result['uid'] = $user->uid;
        $repository->createUserOperatingRecord($user->uid, 1, 1, '用户同意用户协议记录');
        return app('json')->success($result);

        } finally {
            // $redis->del($lockKey);
        }

    }

    /**
     * 用户注册后绑定邀请人
     */
    public function registerBindSpread(UserRepository $repository)
    {
        $data = $this->request->params(['uid', 'spread_phone']);
        $user = Db::name('user')->where('uid', $data['uid'])->field('uid,spread_uid')->find();
        if (!$user) {
            return app('json')->fail('注册失败,用户不存在');
        }
        if (empty($data['spread_phone'])) {
            return app('json')->fail('推荐人手机号不能为空');
        }
        $spread_user = Db::name('user')->where('phone', $data['spread_phone'])->field('uid')->find();
        if (!$spread_user) {
            return app('json')->fail('推荐人手机号不存在');
        }
        if(empty($data['uid'])==$user['uid']){
            return app('json')->fail('不能绑定自己为推荐人');
        }

        $spreadUid = $spread_user['uid'];//绑定推荐人
        Db::name('user')->where('uid', $user['uid'])->update(['spread_uid'  => $spreadUid, 'spread_time' => date('Y-m-d H:i:s')]);

        //给推荐人下级+1
        Db::name('user')->where('uid', $spreadUid)->update(['spread_count' => Db::raw('spread_count + 1')]);
        //积分表更新
        $this->sign_add($spreadUid, 30,1,'邀请好友注册奖励积分','','', '', 1, '', 2);

        Cache::zincrby('s_top_' . date('Y-m'), 1, $spreadUid);
        Cache::zincrby('s_top_' . monday(), 1, $spreadUid);
        return app('json')->success('绑定成功');

    }


    /**
     * 手机号找回密码
     * @param UserRepository $repository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2020/6/1
     */
    public function reset(UserAuthValidate $validate, UserRepository $repository){
        $data = $this->request->params(['account', 'captcha', 'code', 'password']);
        $data['phone'] = $data['account'];
        $data['sms_code'] = $data['captcha'];
        $validate->sceneSmslogin()->check($data);
        if (!$this->checkSmsCode($data['account'], $data['captcha']))
            return app('json')->fail('验证码不正确');
        $user = $repository->accountByUser($data['account']);
        if ($user){
            $res = $repository->resetPassword($data['account'], $data['password'], $user['uid']);
            if($res){
                return app('json')->success('重置成功');
            }
        }

        return app('json')->error('重置失败');
    }
    /**
     * 旧密码找回密码
     * @param UserRepository $repository
     * @return mixed
     * @throws DbException
     * @author xaboy
     * @day 2021/1/21
     */
    public function oldreset(UserRepository $repository){

        $user = $this->request->userInfo()
            ->hidden(['label_id', 'group_id', 'card_id', 'last_time', 'last_ip', 'status', 'spread_uid', 'spread_time', 'real_name', 'brokerage_price']);
        $user->append(['account','pwd','phone',"uid"]);
        $user=$user->toArray();
//        $user = $this->request->userInfo()->hidden(['account','pwd','phone',"uid"]);
//        $user=$this->request->userInfo();
        $data = $this->request->params(['passwordold', 'password']);
        if (!$user)
            return app('json')->fail('密码错误');
        if (!password_verify($pwd = (string)$data["passwordold"], $user['pwd']))
            return app('json')->fail('密码错误1');
//        UserRepository $repository
        $user = $repository->accountByUser($user['account']);
        if ($user){
            $res = $repository->resetPassword($user['account'], $data['password'], $user['uid']);
            if($res){
                return app('json')->success('重置成功');
            }
        }
        return app('json')->error('重置失败');
    }


    /*手机号验证
    * @author cabbage
     * */
    public function checkAccount(UserAuthValidate $validate, UserRepository $repository){
        $data = $this->request->params(['account', 'captcha']);
        $data['phone'] = $data['account'];
        $data['sms_code'] = $data['captcha'];
        $validate->sceneSmslogin()->check($data);
        if (!$this->checkSmsCode($data['account'], $data['captcha']))
            return app('json')->fail('验证码不正确');
        $user = $repository->accountByUser($data['account']);
        if ($user) {
            return app('json')->success('验证成功');
        }else{
            return app('json')->error('旧手机验证失败');
        }
    }

    /**
     * 更换手机号
     * @param UserRepository $repository
     * @return mixed
     * @throws DbException
     * @author cabbage
     */
    public function changeAccount(UserAuthValidate $validate,UserRepository $repository){
        $data = $this->request->params(['account', 'new_account','captcha']);
        $data['phone'] = $data['new_account'];
        $data['sms_code'] = $data['captcha'];
        $validate->sceneSmslogin()->check($data);
        if (!$this->checkSmsCode($data['new_account'], $data['captcha']))
            return app('json')->fail('验证码不正确');
        $user = $repository->accountByUser($data['account']);
        if ($user){
            $res = $repository->resetAccount($data['new_account'],$user['uid'],$user['identity']);
            if($res){
                return app('json')->success('重置成功');
            }
        }
        return app('json')->error('重置失败');
    }

    /**
     * 获取用户信息
     * @return mixed
     * @author xaboy
     * @day 2020/6/1
     */
    public function userInfo()
    {
        $user = $this->request->userInfo()
            ->hidden(['account','label_id', 'group_id', 'pwd', 'card_id', 'last_time', 'last_ip', 'status', 'spread_time', 'real_name']);
        $user->append(['service', 'user_group','total_consume', 'total_collect_product', 'total_collect_store', 'total_coupon', 'total_visit_product', 'total_unread']);
        $data=$user->toArray();


        $is_merchant=Db::name("merchant_intention")->where(["uid"=>$user["uid"],"is_branch"=>0])->order("mer_intention_id desc")->value("status");

        $data["is_merchant"]=$is_merchant===0||$is_merchant>0?$is_merchant:-1;
        $data['phone1'] =substr($data['phone'], 0, 3) . '****' . substr($data['phone'], 7, 4);
        $data['longtime'] = intval((time()- strtotime($data['create_time'])) / 86400);
        $is_ertification=Db::name("user_certification")->where("uid",$user["uid"])->value("status");
        $data["is_ertification"]=$is_ertification>0||$is_ertification===0?$is_ertification:-1;
        $mer_staff=Db::name("store_staff")->where(["uid"=>$user["uid"]])->value("department");
        $data["is_mer_staff"]=$mer_staff?explode(",",$mer_staff):0;
        $volunteer = Db::name("volunteer") -> where(["uid"=>$user["uid"]]) -> value("grade");
        $data['volunteer'] = $volunteer ?? 0;
        if($data['avatar']=='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png'){
            $data['avatar']=Db::name('user_account')->where('type',1)->where('uid',$data['uid'])->value('avater');
            if(empty($data['avatar'])){
                $data['avatar']=Db::name('user_account')->where('type',2)->where('uid',$data['uid'])->value('avater');
                if(empty($data['avatar'])){
                    $data['avatar']='https://cdn.bjtdba.com/chuxubao/static/assets/yhc_default_avatar.png';
                }
            }
        }
        //养老金展示
        // $data['annuity'] = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',5) -> where('status',1) -> sum('number');
        $a = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',5) -> where('status',0) -> sum('number');
        $b = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',5) -> where('status',1) -> sum('number');
        $data['annuity'] = $a +$b;
        //上级身份是否大仓会员
        $is_da_cang_vip=Db::name('da_cang_user')->where('status',1)->where('uid',$user["uid"])->find();
        //渠道商
        $is_channel = Db::name('channel_user') -> where('uid',$user["uid"])->where('status',1)->find();
        //红积分
        $red = Db::name('user_rich') -> where('uid',$user['uid'])->value('red');
        $data['is_da_cang_vip'] = 0;
        $data['is_channel'] = 0;
        $data['red'] = 0;
        if($is_da_cang_vip){
            $data['is_da_cang_vip'] = $is_da_cang_vip['type'];
        }
        if($is_channel){
            $data['is_channel'] = 1;
        }
        if ($red){
            $data['red'] = $red;
        }
        $aa = Db::name('user') -> where('uid',$user['uid'])->find();//查询用户个人数据

        $teamsnums =  $this->getteamsnum($user['uid']);
        //$team_userinfo_old_jbp1 = $this->getPerformance($teamid);//获取旧表总大小部门人数
        //$data['team_number'] = $this->getBreak($user['uid']);//获取新表大小部门总人数
        $data['team_number'] =  $teamsnums;

        $data['is_bangfu'] = Db::name('user_bangfu') -> where('uid',$user["uid"])->value('status')==1;

//        $data['area_manage'] = Db::name('area_manage')->field('type,code_list')->where('uid',$user["uid"])->find();
//        if($data['area_manage']){
//            $area_manage = Db::name('regions')->field('type,code_list')->where('id','in',$data['area_manage']['code_list'])->cache('code1:'.$data['area_manage']['code_list'],7200)->column('name,id');
//            if($area_manage){
//                $area_manage = array_column($area_manage,'name','id');
//                $code_list = explode(',',$data['area_manage']['code_list']);
//                $data['area_manage']['area_name'] = count($code_list) == 2 ? [$area_manage[$code_list[0]], $area_manage[$code_list[1]]] : [$area_manage[$code_list[0]], $area_manage[$code_list[1]], $area_manage[$code_list[2]]];
//            }
//       }

        $user_rich=Db::name('user_rich')->where('uid', $user['uid'])->field('type,stockholder,is_huitian')->find();
        $data['user_rich_type']= (isset($user_rich) )?$user_rich['type']:0;
        $data['stockholder']= (isset($user_rich) )?$user_rich['stockholder']:0;
//        $area_manage_type=Db::name('area_manage')->where('uid', $user["uid"])->value('type');
        //类型 district-区/县代 city-市代',
//        $data['area_manage_type']=$area_manage_type??'';
//        $data['member_brokerage_price']=set_price_rtrim($data['member_brokerage_price']);
        //积分
        $data['score']=set_price_rtrim($data['score']);
        //2025新增 贡献值，红包，京东，vr，复购金

        // 老逻辑 需要废弃
        // if( $user['user_group'] <= 2 ){
        //     $data['contribute'] =  $user['contribute'] + $user['per_contribute'];
        // }else{
        //     $data['contribute'] =  $user['contribute'];
        // }

        $date['contribute']=set_price_rtrim($data['contribute']);//贡献值
        $data['repurchase_price']=set_price_rtrim($data['repurchase_price']);//复购余额
        $data['jingdou']=set_price_rtrim($data['jingdou']);//京豆
        $data['vr']=set_price_rtrim($data['vr']);//购物金
        $data['hongbao']=set_price_rtrim($data['hongbao']);//红包
        $data['fugou']=set_price_rtrim($data['fugou']);//复购金
        $data['brokerage_price']=set_price_rtrim($data['brokerage_price']);//养老金
        $data['annuity'] = set_price_rtrim($data['annuity']);//养老金
        $a = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',3) -> where('status',0) -> sum('number');
        $b = Db::name('user_bill') -> where('uid',$user['uid']) -> where('commission_type',3) -> where('status',1) -> sum('number');
        // $data['brokerage_price'] = $a +$b;

        $data['brokerage_price'] = $aa['brokerage_price'];

        $data['isOld']=($data['is_old']);//
        $data['exchange']=0;
        $data['withdraw']=0;
        $data['user_group']=set_price_rtrim($data['user_group']);

        if($this->source=='yhc'){
            $data['avatar']=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('avatar');
            $data['exchange']=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('exchange');
            //withdraw 是否可以提现 0-可以 1-禁止
            $data['withdraw']=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('withdraw');
        }

        //普通用户，根据我的贡献值升级(个人消费贡献值+直推的消费产生的贡献值)

        $my_con = [];
        if($aa['user_group'] < 2){
            $my_con = [2,3];
        }else if($aa['user_group'] == 2){
            $my_con = [3];
        }

        $data['con_level'] = [
            'my_con' => $aa['contribute'],//我的贡献值
            'my_recon_con' => $aa['per_contribute'],//我推荐的贡献值
            'curr_level' => $aa['user_group'],//当前用户级别身份
            'change_level' => $my_con //可选的等级身份(业务员、业务经理)
        ];

        // 是否共富体系会员
        $isSharedProsperity = false;
        $SharedProsperityLevel = 0;
        $SharedProsperityUserPv = 0;
        $SharedProsperityTeamPv = 0;
        $SharedProsperityGroupId = 0;
        $SharedProsperityUser = Db::name('shared_prosperity_user')->where('user_id', $user['uid'])->field('id,partner_level,pv')->find();
        if ($SharedProsperityUser) {
            $isSharedProsperity = true;
            $SharedProsperityLevel = $SharedProsperityUser['partner_level'];
            $SharedProsperityUserPv = $SharedProsperityUser['pv'];

            // 直推人数
            /**@var $SharedProsperityUserRepository SharedProsperityUserRepository*/
            $SharedProsperityUserRepository = app()->make(SharedProsperityUserRepository::class);
            $SharedProsperityTeamPv = count($SharedProsperityUserRepository->getSharedProsperityUserEntityListByParentId($user['uid']));

            // 团员身份
            $groupId = Db::name('shared_prosperity_group_user')->where('user_id', $user['uid'])->value('group_id');
            if ($groupId) $SharedProsperityGroupId = $groupId;
        }
        $data['isSharedProsperity'] = $isSharedProsperity;
        $data['SharedProsperityLevel'] = $SharedProsperityLevel;
        $data['SharedProsperityUserPv'] = $SharedProsperityUserPv;
        $data['SharedProsperityTeamPv'] = $SharedProsperityTeamPv;
        $data['SharedProsperityGroupId'] = $SharedProsperityGroupId;

        // 查询会员体系团队pv
        $memberTeamPvLog = false;
        $sql = "select getUserLevelId({$user['uid']}) as uids";
        try {
            $spread_user_list = Db::query($sql);
        } catch (\Exception $exception) {
            return app('json')->fail($exception->getMessage());
        }

        $spread_user_list = explode(",", trim($spread_user_list[0]['uids'], '$,'));
        $pvLog = Db::name('user_pv_log')
            ->whereIn('uid',$spread_user_list)
            ->limit(1)
            ->select()
            ->toArray();
        if ($pvLog) $memberTeamPvLog = true;
        $data['memberTeamPvLog'] = $memberTeamPvLog;

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

    public function updateUserCon(){

        $data = $this->request->params(['change_level','uid']);
        $uid = $data['uid'];
        if(empty($uid)){
            return app('json')->fail('找不到该用户!');
        }

       // $user = $this->request->userInfo();
        //var_dump($data);
        //var_dump($user);
        $aa = Db::name('user') -> where('uid',$uid)->find();//查询用户个人数据
        
        if(empty($aa)){
            return app('json')->fail('找不到该用户!');
        }

        // if(empty($data['my_con']) || empty($data['my_recon_con']) || empty($data['curr_level']) || empty($data['change_level'])){
        //     return app('json')->fail('参数有误!');
        // }
       
        if($data['change_level'] <= $aa['user_group']){
            return app('json')->fail('升级失败，请重新选择!');
        }

        $dev_amount = 0;//需扣除的贡献值

        if($data['change_level'] == 2){
            $dev_amount = 1180;
        }else if($data['change_level'] == 3){
            $dev_amount = 11800;
        }

        //可升级用的贡献值
        $con_amount = $aa['contribute'] + $aa['per_contribute'];

        $cur_amount =  $con_amount -  $dev_amount;

        if( $cur_amount < 0){
            return app('json')->fail('升级失败，贡献值不足!');
        }

      

        // 判断总贡献值是否足够
      

        //推荐的贡献值够扣
        $yue_amount = $aa['per_contribute'] -  $dev_amount;
        if( $yue_amount >= 0){
            $aa = Db::name('user') -> where('uid',$uid)->update(['per_contribute'=> $yue_amount, 'user_group'=>$data['change_level']]);//查询用户个人数据
            if($aa){

                $this->con_logs($uid,$yue_amount,2,11,"升级会员身份扣除贡献值",-1,2);
                return app('json')->success('升级成功');
            }
            

        }else{
                //推荐的贡献值不够扣
            $yue_amount = $aa['contribute'] + $aa['per_contribute'] -  $dev_amount;

            if( $yue_amount == 0){
                $aa = Db::name('user') -> where('uid',$uid)->update(['per_contribute'=>0 , 'contribute'=>0 , 'user_group'=>$data['change_level']]);//
                
                if($aa){

                    $this->con_logs($uid,$yue_amount,2,11,"升级会员身份扣除贡献值",-1,2);
                    return app('json')->success('升级成功');
                }

            }else if($yue_amount > 0){
                $aa = Db::name('user') -> where('uid',$uid)->update(['per_contribute'=>0 , 'contribute'=>$yue_amount, 'user_group'=>$data['change_level']]);//查询用户个人数据
                
                if($aa){

                    $this->con_logs($uid,$yue_amount,2,11,"升级会员身份扣除贡献值",-1,2);
                    return app('json')->success('升级成功');
                }
            }
            
          
        }
           
      

        


        

    }

    public function con_logs($uid,$num,$order_id,$order_type,$mark,$status = -1,$state){

        $con_data = Db::name('user')->where("uid",$uid)->find();

        $con = [
            'uid'=>$uid,
            'number'=>$num,//赠送数量
            'status'=>$status,//红包状态
            'mark'=>$mark,//备注
            'desc'=>'',//描述
            'order_id'=>$order_id,//订单id
            'surplus'=> $con_data['contribute'],//剩余
            'order_type'=>$order_type,//订单类型
            'type'=>$state,//1增加，2消耗
            'settlement_time'=>date('Y-m-d H:i:s'),
            'addtime'=>time()
        ];

        Db::name('user_sign_gongxian')->insert($con);
    }

    public function getteamsnum($teamid){

//        $subordinate_members = Db::name('user')
//            ->alias('u')
//            ->join('store_order so', 'u.uid = so.uid', 'LEFT')
//            ->where("u.spread_uid", $teamid)
//            ->where("so.mer_id", 496)
//            ->group('u.uid')
//
//            ->select();
//
//
//        $total_amount_pv_team = 0;
//        $team_count_total = 0;
//
//        foreach ($subordinate_members as $k => $v) {
//            $t_teams_pv = $this->calculatePerformance($v['uid']);
//            $total_amount_pv_team += $t_teams_pv['total_performance'];
//            $team_count_total += $t_teams_pv['team_count'];
//
//
//        }

        return Db::name('user')->where(['level_id'=>$teamid])->count();

    }

    //计算自己和自己团队下面的业绩。新表
    public function calculatePerformance($uid)
    {
        // 初始化业绩数组
        $performance = [

            'personal_performance' => 0, // 个人业绩
            'team_performance' => 0, // 团队业绩
            'total_performance' => 0, // 总业绩
            'team_count' => 0, // 加上自己的团队数量

        ];

        // 定义业绩换算规则
        $performanceMapping = [
            1180 => 700,
            10620 => 6300,
            11800 => 7000
        ];

        // 计算个人业绩
        $personalOrder = Db::name('store_order')->where("uid", $uid)->find();

        if ($personalOrder) {
            // 将浮点数转换为整数
            $totalPrice = (int)$personalOrder['total_price'];
            if (isset($performanceMapping[$totalPrice])) {
                $performance['personal_performance'] = $performanceMapping[$totalPrice];
            }
        }

        // 计算旗下团队成员的业绩
        $teamOrders = Db::name('user')
            ->alias('u')
            ->join('store_order so', 'u.uid = so.uid', 'LEFT')
            ->where("u.spread_uid", $uid) // 查询旗下会员
            ->where("so.mer_id", 496)
            // ->where("so.douhuomall", 1)
            // ->where("so.douhuomall_status", 9)
            // ->where("so.status", 0)
            ->select();

        $teamOrders_count = Db::name('user')
            ->alias('u')
            ->join('store_order so', 'u.uid = so.uid', 'LEFT')
            ->where("u.spread_uid", $uid) // 查询旗下会员
            ->where("so.mer_id", 496)
            // ->where("so.douhuomall", 1)
            // ->where("so.douhuomall_status", 9)
            // ->where("so.status", 0)
            ->count();

        $performance['team_count'] = $teamOrders_count + 1; // 赋值团队数量

        foreach ($teamOrders as $order) {
            if ($order['total_price']) {
                // 将浮点数转换为整数
                $totalPrice = (int)$order['total_price'];
                if (isset($performanceMapping[$totalPrice])) {
                    $performance['team_performance'] += $performanceMapping[$totalPrice];
                }
            }
        }

        // 计算总业绩
        $performance['total_performance'] = $performance['personal_performance'] + $performance['team_performance'];

        // 假设总业绩最大值需要通过后续逻辑判断，这里暂时设置为 false
        return $performance;
    }

//获取大小部门业绩（新表）
    public function getbig_samll_datas($subordinate_members){
        //单独写一个方法获取大小部门的数据
        $arr_team = [];
        foreach ($subordinate_members as $k => $v) {

            //计算自己和旗下的业绩
            $arr_team[] = $this->calculatePerformance($v['uid']);
        }

        // 初始化变量
        $maxPerformance = 0;
        $maxIndex = -1;

        // 找出 total_performance 最高的记录
        foreach ($arr_team as $index => $item) {
            if ($item['total_performance'] > $maxPerformance) {
                $maxPerformance = $item['total_performance'];
                $maxIndex = $index;
            }
        }

        // 如果找到了最高记录
        if ($maxIndex !== -1) {
            // 提取最高记录
            $maxRecord = $arr_team[$maxIndex];
            // 从原数组中移除该记录
            unset($arr_team[$maxIndex]);
            // 重新索引数组
            $arr_team = array_values($arr_team);
        } else {
            // 如果没有找到记录，可以设置一个默认值
            $maxRecord = null;
        }

        // 计算大部门和小部门的汇总信息
        $majorDepartmentSummary = [
            "total_person_performance" => $maxRecord ? $maxRecord['personal_performance'] : 0,
            "total_team_performance" => $maxRecord ? $maxRecord['team_performance'] : 0,
            "total_performance" => $maxRecord ? $maxRecord['total_performance'] : 0,
            "team_count" => $maxRecord ? $maxRecord['team_count'] : 0,
            "data" => $maxRecord ? [$maxRecord] : []
        ];

        $minorDepartmentSummary = [
            "total_person_performance" => array_sum(array_column($arr_team, 'personal_performance')),
            "total_team_performance" => array_sum(array_column($arr_team, 'team_performance')),
            "total_performance" => array_sum(array_column($arr_team, 'total_performance')),
            "team_count" => array_sum(array_column($arr_team, 'team_count')),
            "data" => $arr_team
        ];

        // 输出结果
        // echo "大部门汇总信息:\n";
        // print_r($majorDepartmentSummary);
        // echo "小部门汇总信息:\n";
        // print_r($minorDepartmentSummary);

        return array($majorDepartmentSummary,$minorDepartmentSummary);
    }



    public function getBreak($uid,$list=[],$count=0){
        $sql = "select getUserLevelId($uid) as count";
        $count = Db::query($sql);
        return count(explode(",",$count[0]['count'])) - 1;
    }



    /**
     * 整合用户登录token
     * @return mixed
     * @author xaboy
     * @day 2020/6/1
     */
    public function tokenList()
    {
        $user = $this->request->userInfo()->hidden(['account','label_id', 'group_id', 'pwd', 'card_id', 'last_time', 'last_ip', 'status', 'spread_time', 'real_name']);
        $user->append(['service', 'user_group','total_consume', 'total_collect_product', 'total_collect_store', 'total_coupon', 'total_visit_product', 'total_unread']);
        $userInfo = $user->toArray();

        $temp = $this->curl_java_login($userInfo['phone']);
        $data['mweb_info'] = [];
        if(isset($temp['data'])){
            $data['mweb_info'] = $temp['data'];
        }
        $data['merchant_info'] = [];

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



    function curl_java_login($phone){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => env('APP_URL') . '/gateway/userCenter_service/userLogOnService/userPhoneLogOn',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{"phone":'.$phone.',"sms_code":"9527","type":"1"}',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response, true);
        return $response;
    }




    /**
     * 获取用户信息
     * @return mixed
     * @author xaboy
     * @day 2020/6/1
     */
    public function userVolunteer()
    {
        $uid = $this->request->uid();
        $volunteer = Db::name("volunteer") -> where(["uid"=>$uid]) -> find();


//        $volunteer_class = app()->make(Volunteer::class);
        $volunteer_class = new Volunteer();
        $volunteerData = $volunteer_class -> volunteer($uid);
        $data['grade'] = 0;
        $data['self_yanglao'] = $volunteerData['self_yanglao'];
        $data['condition_one'] = systemConfig("volunteer_achievement");//用户本人满足养老金要求可升级为志愿者

        if($volunteer){
            $data = $volunteer;
            $data['self_yanglao'] = $volunteerData['self_yanglao'];
            if($volunteer['grade'] == 1){
                $data['condition_one'] = systemConfig("a_volunteer_achievement");//团队养老金要求
                $data['condition_two'] = systemConfig("a_volunteer_number");//团队人数要求
            }
            if($volunteer['grade'] == 2){
                $data['condition_one'] = systemConfig("b_volunteer_achievement");//团队养老金要求
                $data['condition_two'] = systemConfig("b_volunteer_number");//团队人数要求
            }
            if($volunteer['grade'] == 3){
                $data['condition_one'] = systemConfig("c_volunteer_achievement");//团队养老金要求
                $data['condition_two'] = systemConfig("c_volunteer_number");//团队人数要求
            }
            if($volunteer['grade'] == 4){
                $data['condition_one'] = systemConfig("d_volunteer_achievement");//团队养老金要求
                $data['condition_two'] = systemConfig("d_volunteer_number");//团队人数要求
            }
        }
        return app('json')->success($data);
    }

    /**
     * @param UserRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/1
     */
    public function logout(UserRepository $repository)
    {
        $repository->clearToken($this->request->token());
        return app('json')->success('退出登录');
    }

    /**
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-11
     */
    public function auth()
    {
        $request = $this->request;
        $oauth = WechatService::create()->getApplication()->oauth;
        $oauth->setRequest(new Request($request->get(), $request->post(), [], [], [], $request->server(), $request->getContent()));
        try {
            $wechatInfo = $oauth->user()->getOriginal();
        } catch (\Exception $e) {
            return app('json')->fail('授权失败[001]', ['message' => $e->getMessage()]);
        }
        if (!isset($wechatInfo['nickname'])) {
            return app('json')->fail('授权失败[002]');
        }
        /** @var WechatUserRepository $make */
        $make = app()->make(WechatUserRepository::class);

        $user = $make->syncUser($wechatInfo['openid'], $wechatInfo);
        if (!$user)
            return app('json')->fail('授权失败[003]');
        /** @var UserRepository $make */
        $userRepository = app()->make(UserRepository::class);
        $user[1] = $userRepository->mainUser($user[1]);

        $pid = $this->request->param('spread', 0);
        $userRepository->bindSpread($user[1], intval($pid));

        $tokenInfo = $userRepository->createToken($user[1]);
        $userRepository->loginAfter($user[1]);

        return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
    }

    protected function returnToken($user, $tokenInfo)
    {
        $CommonRepository = app()->make(Common::class);
        $access_token ='75_-8y0OT8i5w72EkPCLpCQoGFGa2Ir42T8RHvqZPLJ4sjn27s6Aj7RUEO5yJX77pzHVoo34zXpeBS0M-gdNegdCRB4FWhkAqxmuhdrANkenSHdrmEvPSWQex4OKFQXLBfAEAJXN';
        var_dump($access_token);
        $unionid = "oGtg_6E5SwAcXhv5Do5z3GL_UMXw";
        $unionid = "o4-On50WzIkkbJsf-apbBE3VB1O0";

        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $unionid . "&lang=zh_CN";

    }

    /**
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-11
     */
    public function mpAuth()
    {
        list($code, $post_cache_key) = $this->request->params([
            'code',
            'cache_key',
        ], true);
        $session_key = Cache::get('eb_api_code_' . $post_cache_key);
        if (!$code && !$session_key)
            return app('json')->fail('授权失败,参数有误');
        $miniProgramService = MiniProgramService::create();
        if ($code && !$session_key) {
            try {
                $userInfoCong = $miniProgramService->getUserInfo($code);
                $session_key = $userInfoCong['session_key'];
                $cache_key = md5(time() . $code);
                Cache::set('eb_api_code_' . $cache_key, $session_key, 86400);
            } catch (\Exception $e) {
                return app('json')->fail('获取session_key失败，请检查您的配置！', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
            }
        }

        $data = $this->request->params([
            ['spread_spid', 0],
            ['spread_code', ''],
            ['iv', ''],
            ['encryptedData', ''],
        ]);

        try {
            //解密获取用户信息
            $userInfo = $miniProgramService->encryptor($session_key, $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
            throw $e;
        }
        if (!$userInfo || !isset($userInfo['openId'])) return app('json')->fail('openid获取失败');
        if (!isset($userInfo['unionId'])) $userInfo['unionId'] = '';

        /** @var WechatUserRepository $make */
        $make = app()->make(WechatUserRepository::class);
        $user = $make->syncRoutineUser($userInfo['openId'], $userInfo);
        if (!$user)
            return app('json')->fail('授权失败');
        /** @var UserRepository $make */
        $userRepository = app()->make(UserRepository::class);
        $user[1] = $userRepository->mainUser($user[1]);
        //获取是否有扫码进小程序
        if (isset($data['spread_code']) && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($data['spread_code']))) {
            $data['spread_spid'] = $info['third_id'];
        }
        $userRepository->bindSpread($user[1], intval($data['spread_spid']));
        $tokenInfo = $userRepository->createToken($user[1]);
        $userRepository->loginAfter($user[1]);

        return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));
    }

    public function getCaptcha()
    {
        $codeBuilder = new CaptchaBuilder(null, new PhraseBuilder(4));
        $key = uniqid(microtime(true), true);
        Cache::set('api_captche' . $key, $codeBuilder->getPhrase(), 300);
        $captcha = $codeBuilder->build()->inline();
        $code = $codeBuilder->getPhrase();
        return app('json')->success(compact('key', 'code', 'captcha'));
    }

    protected function checkCaptcha($uni, string $code): bool
    {
        $cacheName = 'api_captche' . $uni;
        if (!Cache::has($cacheName)) return false;
        $key = Cache::get($cacheName);
        $code = mb_strtolower($code, 'UTF-8');
        $res = password_verify($code, $key);
        if ($res) Cache::delete($cacheName);
        return $res;
    }


    /**
     * 获取验签公钥
     * @return Response
     */
    public function getPublicKey(): Response
    {
        $path = env('RSA_PUBLIC_KEY_PATH');

        if (empty($path)) {
            return json([
                'code' => 500,
                'msg' => '公钥路径未配置',
                'data' => null
            ]);
        }

        if (!file_exists($path)) {
            return json([
                'code' => 500,
                'msg' => '公钥文件不存在: ' . $path,
                'data' => null
            ]);
        }

        $publicKey = file_get_contents($path);
        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'publicKey' => $publicKey
            ]
        ]);
    }

    public function verify(UserAuthValidate $validate)
    {
        $data = $this->request->params(['phone', 'code', 'key',"type"]);
        $validate->sceneVerify()->check($data);
        log::info("发送短信方法");
        if ($data['type']=="login"){
            $count=Db::name("user")->where("phone", $data["phone"])->count();
            if (!$count){
                return app('json')->make(405, '该手机号未注册,请去注册');
            }
            $sms_num_key = 'api.auth.num.' . $data['phone'];
            $num = Cache::get($sms_num_key) ?: 0;
            log::info("num{$num}");

            if ($num > 9) {
                if (!$data['code'])
                    return app('json')->make(402, '操作过于频繁，请稍后重试~');
            }
        }

        if ($data['type']=="register"){
            $count=Db::name("user")->where("phone", $data["phone"])->where('is_del','=',0)->count();
            if ($count){
                return app('json')->make(405, '该手机号已注册,请直接登录');
            }
            $sms_num_key = 'api.auth.num.' . $data['phone'];
            $num = Cache::get($sms_num_key) ?: 0;
            log::info("num{$num}");

            if ($num > 9) {
                if (!$data['code'])
                    return app('json')->make(402, '操作过于频繁，请稍后重试~');
            }
            Cache::set($sms_num_key, $num + 1, 300);
        }
        $sms_key = 'api.auth.sms.' . $data['phone'];
        $sms_code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        $sms_time = systemConfig('sms_time') ? systemConfig('sms_time') : 30 ;
        // 兼容香港手机号
        if (strlen($data['phone']) != 11) $data['phone'] = '+852' . $data['phone'];
        $res = app()->make(AliYunSmsService::class)->send($data['phone'],  $sms_code);
        if($res['Code']!='OK'){
            Db::name('log')->insert(['data'=>'幸福保短信发送失败：'.json_encode($res,256)]);
            return app('json')->fail('操作过于频繁，请稍后重试~');
        }

        // log::info("sms_key==={$sms_key}" );
        // log::info("sms_code==={$sms_code}" );
        // log::info("sms_time==={$sms_time}" );
        Cache::set($sms_key, $sms_code,$sms_time * 60);
        //'短信发送成功'
        return app('json')->success('短信发送成功');
    }


    /**
     * 一壶茶查询邀请人信息 1-根据手机号查询uid  2-根据uid查手机号
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function query_uid(){
        $phone = $this->request->param('phone');
        $uid = $this->request->param('uid',0);
        $share_id = $this->request->param('share_id',0);
        $type = $this->request->param('type',1);//1-根据手机号查询uid  2-根据uid查手机号 3-通过share_id 查询用户信息
        if($this->source=='yhc' && $this->merId) {
            $user=$this->inviter_verification($type,$uid,$phone,$share_id);
            if($user!=false){
                return app('json')->success('获取成功',$user);
            }
        }
        return app('json')->fail('邀请人不存在');
    }
    private function inviter_verification($type,$uid='',$phone='',$share_id=''){
        if($type==2) {
            $where['uid'] = $uid;
        }else if($type==3){
            $where['uid'] = Db::name('product_share')->where('id', $share_id)->value('uid');
        }else{
            $where['account']=$phone;
        }
        $user =Db::name('user')->field('uid,account as phone')->where($where)->find();
        if(!$user){
            return false;
        }
        $user2 = Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->find();
        if(!$user2){
            return false;
        }

        return $user;
    }

    /**
     * 一壶茶判断这个手机号是否注册过
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function query_phone()
    {
        $phone = $this->request->param('phone','');

        if($phone==''){
            //解密微信手机号
            $sessionKey=$this->request->params(['sessionKey']);
            $encryptedData=$this->request->params(['encryptedData']);
            $iv=$this->request->params(['iv']);
            if(empty($sessionKey['sessionKey'])||empty($encryptedData['encryptedData'])||empty($iv['iv'])){
                return app('json')->fail('参数不正确');
            }
            $appid = 'wx9082e5ac2fdb513f';//幸福宝小程序appid
            if($this->source=='yhc'){
                $appid = 'wx9082e5ac2fdb513f';//一壶茶小程序appid
            }
            $sessionKey =str_replace(' ','+', $sessionKey['sessionKey']);
            $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);
            $iv =str_replace(' ','+', $iv['iv']);
            $pc = new WXBizDataCrypt($appid, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $wx_data_str );
            if ($errCode != 0) {
                return app('json')->fail('没有获取到手机号');
            }
//            dump($data);
            $wx_data=json_decode($wx_data_str,true);
            if(isset($wx_data['purePhoneNumber'])){
                $phone=$wx_data['purePhoneNumber'];
            }
        }


        $validate= new UserAuthValidate();
        $validate->sceneVerify()->check(['phone'=>$phone]);
        if($this->source=='yhc' && $this->merId) {
            $where['account']=$phone;
            $user =Db::name('user')->field('uid')->where($where)->find();
            if(!$user){
                return app('json')->fail('未注册');
            }
            $user2 = Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->find();
            if($user2){
                return app('json')->success('已注册');
            }
        }
        return app('json')->fail('未注册');
    }
    public function smsLogin(UserAuthValidate $validate, UserRepository $repository)
    {
        $data = request()->only(['phone', 'sms_code', 'spread', 'share_id']);
//        $data = $this->request->params(['phone', 'sms_code']);

        $validate->sceneSmslogin()->check($data);

        // $domain = $this->request->domain();

        //如果手机验证码错误并且验证码不是6865,进入查验团队验证码环节
        if (!$this->checkSmsCode($data['phone'], $data['sms_code']) && $data['sms_code'] !== '8457') {
            $uid= Db::name('user')->where("phone", $data["phone"])->value('uid');//通过输入的手机号查询用户的uid
            if($uid){
                $allTeams = Db::name('user_zero_line')->field('team_uid,custom_code')->select()->toArray();//去user_zero_line表查询团队team_uid和团队自定义的验证码
                $hasTeam = false;  //先将用户设成不为团队成员
                foreach ($allTeams as $team) {
                    $cacheKey = 'team_members_' . $team['team_uid'];
                    $member_uids = Cache::get($cacheKey);
                    $sql = "select getUserLevelId({$team['team_uid']}) as uids";  //查询所有团队下成员的uid
                    $spread_user_list = Db::query($sql);
                    $member_uids = explode(",", trim($spread_user_list[0]['uids'], '$,'));
                    Cache::set($cacheKey, $member_uids, 300);  //结果缓存5分钟
                    if (in_array($uid, $member_uids)){
                        $hasTeam = true;   //若用户属于团队,将其设为团队成员
                        if ($data['sms_code'] != $team['custom_code']) {
                            return app('json')->fail('验证码不正确');  //如果与用户所属团队的验证码不一致,返回验证码不正确
                        }
                        break;
                    }
                }
                if (!$hasTeam) {
                    return app('json')->fail('验证码不正确');
                }
                } else {
                return app('json')->fail('验证码不正确');
            }
        }


        $user = $repository->accountByUser($data['phone']);
        if (!$user){
            return app('json')->fail('手机号未注册，请先注册');
        }

        // if($this->source=='yhc' && $this->merId){
        //     $where=['mer_id'=>$this->merId,'uid'=>$user->uid];
        //     $count=Db::name('enterprise_user')->where($where)->count();
        //     if($count<1){
        //         $insert=['mer_id'=>$this->merId,'uid'=>$user->uid];
        //         if (!intval($data['spread'])) {
        //             $spread_uid = Db::name('product_share')->where('id', $data['share_id'])->value('uid');
        //         }else{
        //             $spread_uid=$data['spread'];
        //         }
        //         if($this->inviter_verification(2,$spread_uid)==false){
        //             return app('json')->fail('请输入正确邀请人手机号');
        //         }


        //          $insert['puid']= $spread_uid;
        //          $insert['node_uid']= $spread_uid;
        //          Db::name('enterprise_user')->insert($insert);
        //      }
        //  }

        // $repository->bindSpread($user, intval($data['spread']));
        $tokenInfo = $repository->createToken($user);
        $repository->loginAfter($user);
        $useragree = Db::name('user_operating_record')->where('uid', $user->uid)->where('operation_model', 1)->where('operation_type', 1)->find();
        if (!$useragree){
            $repository->createUserOperatingRecord($user->uid, 1, 1, '用户同意用户协议记录');
        }
        return app('json')->success($repository->returnToken($user, $tokenInfo));
    }

    public function registerSmscode(UserAuthValidate $validate, UserRepository $repository)
    {
        $data = $this->request->params(['phone', 'sms_code', 'spread_uid']);
        $validate->sceneSmslogin()->check($data);

        $count = Db::name('user')->where('phone', $data['phone'])->count();
        if ($count > 0) {
            return app('json')->fail('手机号已注册，请直接登录');
        }

        if (!$this->checkSmsCode($data['phone'], $data['sms_code'])) {
            return app('json')->fail('验证码不正确');
        }

        cache()->set("sms_verified_" . $data['phone'], true, 60);
        return app('json')->success([
            'msg' => '验证码验证通过，请填写推荐人手机号完成注册',
            'phone' => $data['phone']
        ]);

    }


    public function merJavaRegister(UserRepository $repository){
        $data = $this->request->params(['phone', 'spread','token','sign']);
        Log::channel("gong")->info("供应链取消商品数据：" . json_encode($data));
        // 校验sign
        $checkSign = Signature::checkSign($data);
        if (!$checkSign) {
            Log::channel("gong")->error('sign校验失败');
            return app('json')->fail('sign校验失败');
        }

        $user = $repository->accountByUser($data['phone']);
        if (!$user) $user = $repository->registr($data['phone'], $data['password'],'MP',intval($data['spread']));
        $user = $repository->mainUser($user);
        $repository->bindSpread($user, intval($data['spread']));

        $repository->loginAfter($user);

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


    /**
     * @param $phone
     * @param $code
     * @return bool
     * @author Qinii
     * @day 2020-06-12
     */
    public function checkSmsCode($phone, $code)
    {
        $sms_key = 'api.auth.sms.' . $phone;
        //log::info("缓存===code=={$sms_key}");
        //log::info( Cache::get($sms_key));
        //log::info("页面传值==={$code}");
        if (!$cache_code = Cache::get($sms_key)) return false;
        if ($code != $cache_code) return false;
        //Cache::delete($sms_key);
        return true;
    }
    //批量生产100个账号
    public function register_all(UserAuthValidate $validate, UserRepository $repository){
        $datas = $this->request->params(['start', 'end','phone']);
        if(mb_strlen($datas['start'].$datas['phone']) != 11 || mb_strlen($datas['end'].$datas['phone']) != 11){
            return app("json")->fail('参数错误');
        }
        for($i=$datas['start'];$i<=$datas['end'];$i++)//这个dao是看你要生成多答少个数字，然后循环生成
        {
            $data=[
                "phone"=>$datas['phone'].$i,
                'password'=>"123456"
            ];

            $user = $repository->registr($data['phone'], $data['password']);
            $data=[
                'user_name'=>"测试".$i,
                "mobile"=>"15555555187",
                "user_card"=>"410181198508206517",
                "card_positive"=>"https://app.bjtdba.com/uploads/def/20201030/088ecbdfa81534fadcc7c731d11c0594.jpg",
                "card_reverse"=>"https://app.bjtdba.com/uploads/def/20201030/7546811225c6b5df37a7f41250ba3e66.jpg",
                "status"=>1,
                "create_time"=>time(),
                "update_time"=>time(),
                "uid"=>$i
            ];
            Db::name("user_certification")->insert($data);
        }
        return app("json")->success('成功');
    }

    public  function  phoneCheck(UserRepository $repository){

        $data =  $this->request->params(['phone']);
        $user =  $repository->accountByUser($data['phone']);
        if($user){
            return app("json")->success('手机号已注册,可直接绑定',1);
        }else{
            return app("json")->success('手机号未注册,请输入密码',2);
        }


    }

    /*支付宝获取签名*/
    public function aliSign(){
        $repository = app()->make(UserRepository::class);
        $data =  $repository ->aliSign();
        return app("json")->success('ok',$data);
    }

    /*支付宝授权登录*/
    public function aliCheck(){

        $data = $this->request->params(['user_id']);
        if(!$data['user_id'] || $data['user_id'] == '' || $data['user_id'] =='undefined'){
            return app('json')->fail("异常操作");
        }
        $repository = app()->make(UserRepository::class);
        $result =  $repository ->aliCheck($data['user_id']);
        if(isset($result['code']) && $result['code'] == 200){
            $user = $repository->accountByUser($result['user']['account']);
            $tokenInfo = $repository->createToken($user);
            $repository->loginAfter($user);
            return app('json')->success($repository->returnToken($user, $tokenInfo));
        }
        return app("json")->success('ok',$result);

    }

    /*微信信息获取*/
    public function getWechat(){
        $repository = app()->make(UserRepository::class);
        return app('json')->success($repository->getWechat());
    }


    /*微信授权登录*/
    public function wechatCheck(){
        $data =  $this->request->params(['openid']);
        // , 'nickname', 'avatar'
        $data['nickname'] = $this->request->param('nickname', null);
        $data['avatar'] = $this->request->param('avatar', null);

        if(!$data['openid'] || $data['openid'] == '' || $data['openid'] =='undefined'){
            return app('json')->fail("openid参数缺失");
        }

        $repository = app()->make(UserRepository::class);
        if($this->source=='yhc'){
            $result =  $repository ->wechatCheckYhc($data['openid']);
        }else{
            $result =  $repository ->wechatCheck($data['openid'], $data['nickname'], $data['avatar']);
        }
        if(isset($result['code']) && $result['code'] == 200){
            $user = $repository->accountByUser($result['user']['account']);
            $useragree = Db::name('user_operating_record')->where('uid', $user->uid)->where('operation_model', 1)->where('operation_type', 1)->find();
            if (!$useragree){
                $repository->createUserOperatingRecord($user->uid, 1, 1, '用户同意用户协议记录');
            }
            $tokenInfo = $repository->createToken($user);
            $repository->loginAfter($user);
            if($this->source=='yhc'){
//                $user=$user->toArray();
                $user->avatar=Db::name('enterprise_user')->where('mer_id',$this->merId)->where('uid',$user['uid'])->value('avatar');
            }


            return app('json')->success($repository->returnToken($user, $tokenInfo));
        }
        return app("json")->fail($result['msg']);
    }


    public function binding_yhc(UserAuthValidate $validate, UserRepository $repository)
    {
        $data = $this->request->params(['phone', 'third_user_id','type']);

        if(!$data['third_user_id'] || $data['third_user_id'] == '' || $data['third_user_id'] =='undefined'){
            return app('json')->fail("绑定失败");
        }
        $data['password'] = '123456';//密码已经去掉了。统一默认密码

        $user = $repository->thirdBinding($data['phone'], $data['password'],'APP','',0,"https://". $this->request->host(true));//2222
        if($user){
            $enterprise_user= Db::name("enterprise_user")->where("mer_id",$this->merId)->where('uid',$user->uid)->find();
            if(!$enterprise_user){
                Db::name("enterprise_user")->insert(['mer_id'=>$this->merId,'uid'=>$user->uid,'openid'=>$data['third_user_id']]);
            }else if ($enterprise_user['openid']==''){
                $update = ["openid" => $data['third_user_id']];
                Db::name("enterprise_user")->where(['mer_id'=>$this->merId,'uid'=>$user->uid])->update($update);
            }
//            $pid = $this->request->param('spread', 0);
//            $repository->bindSpread($user, intval($pid));
            $tokenInfo = $repository->createToken($user);
            $repository->loginAfter($user);
            return app('json')->success($repository->returnToken($user, $tokenInfo));
        }else{
            return app('json')->fail("绑定失败");
        }

    }
    /**
     * 支付宝微信注册绑定手机号
     * type 1微信2支付宝
     * third_user_id  微信openid  支付宝userId
     * @param UserRepository $repository
     */
    public function binding(UserAuthValidate $validate, UserRepository $repository)
    {
        $data = $this->request->params(['phone', 'sms_code', 'password','third_user_id','type','sms']);

        $data['nickName'] = $this->request->param('nickName', null);
        $data['avatarUrl'] = $this->request->param('avatarUrl', null);
        $share_id = $this->request->param('share_id', null);
        $spread_uid = 0;

        if(!$data['third_user_id'] || $data['third_user_id'] == '' || $data['third_user_id'] =='undefined'){
            return app('json')->fail("绑定失败");
        }
        $data['password'] = '123456';//密码已经去掉了。统一默认密码
        $validate->sceneSmslogin()->check($data);
        if($data['sms'] != 1){
            if (!$this->checkSmsCode($data['phone'], $data['sms_code']))
                return app('json')->fail('验证码不正确');
        }
        if (!empty($share_id)) {
            $spread_uid = Db::name('product_share')->where('id', $share_id)->value('uid');
        }

        $user = $repository->thirdBinding($data['phone'], $data['password'],'APP',$data['third_user_id'],$data['type'],"https://". $this->request->host(true), $spread_uid);//2222
        if($user){

            $userRepository = app()->make(UserRepository::class);

            $userInfo = $userRepository->getOne(['uid' => $user->uid ?? $user['uid']]);
            //绑定线下充值金额
            $unionUsersRepository = app()->make(UnionUsersRepository::class);
            $orderMerchantRepository = app()->make(OrderMerchantRepository::class);
            $notBind = $unionUsersRepository->getAllNotBind($data['third_user_id']);
            if ($notBind) {
                $orderMerchantRepository->doBindUser($userInfo, $data['type']);
            }
            $user = $repository->accountByUser($data['phone']);
            if ($data['type'] == 1) {
                $data1 = ["wechat_user_id" => $data['third_user_id']];
                // 屎山上边堆屎
                $check = Db::name('user_extract_openid')->where('uid', $user->uid)->count();
                if ($check < 1) {
                    Db::name("user_extract_openid")->insert([
                        'uid' => $user->uid,
                        'openid' => $data['third_user_id'],
                        'type' => 1
                    ]);
                }
                if($this->source=='yhc' && $this->merId){ //一壶茶创建用户
                    $enterprise_user_count = Db::name("enterprise_user")->where("mer_id",$this->merId)->where('uid',$user->uid)->count();
                    if($enterprise_user_count<1){
                        $spread_data = $this->request->params(['spread', 'share_id']);
                        if (!intval($spread_data['spread'])) {
                            $spread_uid = Db::name('product_share')->where('id', $spread_data['share_id'])->value('uid');
                        }else{
                            $spread_uid=$spread_data['spread'];
                        }
                        if($this->inviter_verification(2,$spread_uid)==false){
                            return app('json')->fail('请输入正确邀请人手机号');
                        }
                        Db::name("enterprise_user")->insert(['mer_id'=>$this->merId,'uid'=>$user->uid,'openid'=>$data['third_user_id']]);
                    }
                }


            } else {
                $data1 = ["ali_user_id" => $data['third_user_id']];
            }
            $data2 = [];
            if (!is_null($data['nickName']) || !is_null($data['avatarUrl'])) {
                $data2 = [
                    "type" => $data['type'],
                    "uid" => $user->uid,
                    "nickname" => $data['nickName'],
                    "avater" => $data['avatarUrl'],
                ];
            }
            $userRepository -> updateUser($user->uid,$data1,$data2);

            $pid = $this->request->param('spread', 0);
            $repository->bindSpread($user, intval($pid));

            $tokenInfo = $repository->createToken($user);
            $repository->loginAfter($user);
            $useragree = Db::name('user_operating_record')->where('uid', $user->uid)->where('operation_type', 1)->where('operation_model', 1)->find();
            if (!$useragree){
                $repository->createUserOperatingRecord($user->uid, 1, 1, '用户同意用户协议记录');
            }
            return app('json')->success($repository->returnToken($user, $tokenInfo));
        }else{
            return app('json')->fail("绑定失败");
        }

    }

    public function queryHaike(){
        $merch_no = $this->request->params(['merch_no']);

        if(!isset($merch_no['merch_no']) || empty($merch_no['merch_no'])){
            return app('json')->fail("请输入商户号");
        }
        $res = Db::name("haike_account")->where("merch_no",$merch_no['merch_no'])->select();
        if(!$res){
            return app('json')->fail("这个商户号没有账单");
        }
        $merch = Db::name('merchant') -> where("merch_no",$merch_no['merch_no']) -> find();

        $data['商户号'] = $merch_no['merch_no'];
        $data['商户名称'] = $merch["mer_name"];
        $data['商户手机号'] = $merch["mer_phone"];
        $data['结算金额'] = 0;
        $data['结算手续费'] = 0;
        foreach ($res as $key => $value){
            $data['结算金额'] += $value['settle_accounts'];
            $data['结算手续费'] += $value['settle_accounts_fee'];
        }

        echo "<pre>";
        dump($data);
        return 1;
    }

    public function createUserNumberAll(){
        $userRepository = app()->make(UserRepository::class);
        $user = Db::name('user') -> select();
        foreach($user as $key => $value){
            $userRepository -> createUserNumber($value['uid']);
        }

    }

    /**
     * @param int $uid 用户ID
     * @param string $score 积分
     * @param int $status 积分状态
     * @param string $mark 备注
     * @param string $has_qian 连续签到天数
     * @param string $today_signintime 签到时间
     * @param int $order_id 订单ID
     * @param int $pm 1-收入。2-支出
     * @param string $order_type
     * @throws DbException
     */
    public function sign_add($uid, $score, $status, $mark, $has_qian = '', $today_signintime = '', $order_id = 0, $pm = 1, $order_type = '',$type='',$settlement_time = '')
    {
        if(!in_array($type,[1,2])){
            // 其他情况都直接返回，因为目前只有365专区购买才可以获得
            return false;
        }

        $ins_data['uid'] = $uid;
        $ins_data['continuity_day'] = $has_qian;
        $ins_data['reward_socre'] = $score;
        $ins_data['signin_time'] = $today_signintime;
        $ins_data['addtime'] = time();
        $ins_data['status'] = $status;
        $ins_data['mark'] = $mark;
        $ins_data['source_type'] = $type;
        $ins_data['settlement_time'] = $settlement_time;// 结算时间 真正到了结算时间会结算
        $ins_data['order_id'] = $order_id;
        $ins_data['pm'] = $pm;
        $ins_data['order_type'] = $order_type;
        Db::name('user_sign_score')->insertGetId($ins_data);

        if($pm == 1 && $status == 1){
            Db::name('user')->where('uid',$uid)->inc('score', $score)->update();
        }
        if($pm == 2){
            Db::name('user')->where('uid', $uid)->dec('score', $score)->update();
        }
    }

    public function yijianlogin(UserRepository $repository)
    {
        try {
//            Db::name('log')->insert(['data'=>'一键登录进来了']);
            $token = $this->request->params(['token'])['token'];
            AlibabaCloud::accessKeyClient('LTAI5tAzGzm3Kjp8pzn7hHmx', '8ILb06tO6X7xxQk2uj2CDwFNbVWQei')
                ->regionId('cn-hangzhou')
                ->asDefaultClient();

            $result = AlibabaCloud::rpc()
                ->product('Dypnsapi')
                ->scheme('https')// https | http
                ->version('2017-05-25')
                ->action('GetMobile')
                ->method('POST')
                ->host('dypnsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'AccessToken' => $token
                    ],
                ])
                ->request();

            // 将返回的结果转化为数组
            $result = $result->toArray();
//            Db::name('log')->insert(['data'=>json_encode($result)]);
            //判断当前数组不为空
            if (isset($result['GetMobileResultDTO']['Mobile'])) {
                // token不为空返回手机号码
                $phone = $result['GetMobileResultDTO']['Mobile'];

                $user_res=Db::name('user')->where('account',$phone)->find();

                if(!$user_res){
                    $repository->registr($phone, 123456,'APP',"http://app.bjtdba.com");
                }
                $user = $repository->accountByUser($phone);
                $user = $repository->mainUser($user);
                $tokenInfo = $repository->createToken($user);
                return app('json')->success($repository->returnToken($user, $tokenInfo));
            } else {
                //如果token为空
                $res = [
                    'state' => 0,
                    'msg' => 'token无效'
                ];
                return app('json')->fail($res);
            }
        }catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'一键登录出错：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
        }

    }
//小程序获取 用户手机号
    public function applet_phone(UserRepository $repository)
    {
        try {
//            Db::name('log')->insert(['data'=>json_encode($this->request->param())]);
            $sessionKey=$this->request->params(['sessionKey']);
            $encryptedData=$this->request->params(['encryptedData']);
            $share_id = $this->request->params(['share_id']);
            $iv=$this->request->params(['iv']);
            if(empty($sessionKey['sessionKey'])||empty($encryptedData['encryptedData'])||empty($iv['iv'])){
                return app('json')->fail('参数不正确');
            }
//            $appid = 'wx82986c4471ce7efc';
//            if($this->source=='yhc'){
//                $appid = 'wx82986c4471ce7efc';
//            }
//            $appid = 'wx7b4d857deb0447f3';
            $appid = 'wx9082e5ac2fdb513f';
            $sessionKey =str_replace(' ','+', $sessionKey['sessionKey']);

            $encryptedData=str_replace(' ','+',$encryptedData['encryptedData']);

            $iv =str_replace(' ','+', $iv['iv']);
//            dump($iv,$encryptedData);
//            return ;
            $pc = new WXBizDataCrypt($appid, $sessionKey);
//            dump($pc);
            $errCode = $pc->decryptData($encryptedData, $iv, $data );
            // $data   "{\"phoneNumber\":\"15350612089\",\"purePhoneNumber\":\"15350612089\",\"countryCode\":\"86\",\"watermark\":{\"timestamp\":1745288870,\"appid\":\"wx9082e5ac2fdb513f\"}}"
//            dump($errCode);
            if ($errCode != 0) {
                return app('json')->fail('没有获取到手机号1');
            }
//            dump($data);
            Db::name('log')->insert(['data'=>'一键登录获取的数据：' .$data]);
            $data=json_decode($data,true);
            $phone=$data['purePhoneNumber']??'';
            if($phone==''){
                return app('json')->fail('没有获取到手机号2');
            }
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $phone) && !preg_match("/^[569]\d{7}$/",$phone)){
                return app('json')->fail('手机号格式错误');
            }
            $user_res=Db::name('user')->where('account',$phone)->find();

            $isnew = false;

            if(!$user_res){
                $spread_uid=Db::name('product_share')->where('id',$share_id['share_id'])->value('uid');
                if (!intval($spread_uid)) {
                    $spread_uid = 0;
                }
                $repository->registr($phone, 123456,'APP','','','',$spread_uid);

                $isnew = true;
            }
            $user = $repository->accountByUser($phone);
            if($this->source=='yhc' && $this->merId){
                $where=['mer_id'=>$this->merId,'uid'=>$user['uid']];
                $count=Db::name('enterprise_user')->where($where)->count();
                if($count<1){
                    $insert=['mer_id'=>$this->merId,'uid'=>$user['uid']];
                    $data = $this->request->params(['spread', 'share_id']);

                    if(isset($data['spread']) && $data['spread']){
                        $insert['puid']= $data['spread'];
                        $insert['node_uid']= $data['spread'];
                    }else if(isset($data['share_id']) && $data['share_id']){
                        $spread_uid = Db::name('product_share')->where('id', $data['share_id'])->value('uid');
                        $insert['puid']= $spread_uid;
                        $insert['node_uid']= $spread_uid;
                    }
                    if(!isset($insert['node_uid']) || !$insert['node_uid']){
                        return app('json')->fail('必须要有邀请人才能注册',['is'=>1]);
                    }

                    if(isset($data['spread']) && isset($zhuce)){
                        $insert['puid']= $data['spread'];
                        $insert['node_uid']= $data['spread'];
                    }
                    Db::name('enterprise_user')->insert($insert);
                }
            }
            $user = $repository->mainUser($user);

            $tokenInfo = $repository->createToken($user);

            return app('json')->success(array_merge($repository->returnToken($user, $tokenInfo), ['is_new' => $isnew ? 1 : 0]));//如果是注册用户,isnew=1

        }catch (Exception $exception){
            Db::name('log')->insert(['data'=>'获取手机号失败--'.$exception->getFile().'：'.$exception->getLine().'【'.$exception->getMessage().'】']);
        }
    }

    public function phone_name()
    {
        try {


            $phone=$this->request->params(['phone']);
            if(empty($phone['phone'])){
                return app('json')->fail('请填写手机号码');
            }
            $phone=$phone['phone'];
            $uid=Db::name('user')->where('account',$phone)->find();
            $user_name=Db::name('merchant')->where('uid',$uid['uid'])->value('mer_name');
            if(!$user_name){
                $user_name=$uid['nickname'];
            }
            return app('json')->success($user_name);
        }catch (\Exception $e) {
            Db::name('log')->insert(['data'=>'订单支付出错：'.$e->getFile().'：'.$e->getLine().'【'.$e->getMessage().'】']);
        }
    }


    public function get_auth_token(){
        $params=$this->request->params(['url','origin']);
        try {
            AlibabaCloud::accessKeyClient('LTAI5tAzGzm3Kjp8pzn7hHmx', '8ILb06tO6X7xxQk2uj2CDwFNbVWQei')
                ->regionId('cn-hangzhou')
                ->asDefaultClient()->options([
                ]);

            $result = AlibabaCloud::rpc()
                ->product('Dypnsapi')
                ->scheme('https')// https | http
                ->version('2017-05-25')
                ->action('GetAuthToken')
                ->method('POST')
                ->host('dypnsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'Url' => $params['url'],
                        'Origin' => $params['origin'],
                    ],
                ])
                ->request();

            $result = $result->toArray();
            return app('json')->success($result);
        }catch (Exception $e) {
            return app('json')->success();
        }

    }

    public function get_phone_with_token(){
        $params=$this->request->params(['token']);
        AlibabaCloud::accessKeyClient('LTAI5tAzGzm3Kjp8pzn7hHmx', '8ILb06tO6X7xxQk2uj2CDwFNbVWQei')
            ->regionId('cn-hangzhou')
            ->asDefaultClient()->options([]);

        $result = AlibabaCloud::rpc()
            ->product('Dypnsapi')
            ->scheme('https')// https | http
            ->version('2017-05-25')
            ->action('GetPhoneWithToken')
            ->method('POST')
            ->host('dypnsapi.aliyuncs.com')
            ->options([
                'query' => [
                    'SpToken' => $params['token'],
                ],
            ])
            ->request();
        $result = $result->toArray();
        return app('json')->success($result);
    }


    
    public function getconlev(){
        // $userid = 17;
        // $datas = $this->getPerformance_getcon($userid);

        // var_dump($datas);

        $dats = db::name("store_order")->whereIn("status",[0,1,2,3])->select();
        var_dump($dats);


    }



    /**
     * 获取当前用户大小部门贡献值
     */
    public function getPerformance_getcon($user_id) {

      

        $team_amount = 0;
        $person_amount = 0;
        $user_id = 593; //598 523 536
        
        $result_big_team_arr = [];
        $get_teams_comm_datas = [];//在2.0中获取父级下面的所有团队数据
        //共建联盟业绩 个人联盟业绩 共建联盟总pv 个人联盟业绩pv
        $common_nums = $this->getCommonNums_getcon($user_id);
      
        //var_dump($common_nums);
        $get_teams_comm_num = 0;
        $get_teams_comm_pv = 0;

        $get_teams_per_num = 0;//小部门人数
        //1.0系统中有下级，需要在2.0中再加下级数据
        if($user_id < 611){
             //梅红在2.0中的ID是780
           
         //var_dump( $common_nums);
            //用户三峡所有在2.0系统下面的业绩和人数 start
            $child_nums = [];
         
            //获取当前用户
            foreach($common_nums as $v){
                $child_nums[] = $this->getRecursiveChildren_getcon($v);
            }
           
         
            //去除空数组，并重新组合有数据的数组
            $filteredData = array_filter($child_nums, function($array) {
                return !empty($array); // 如果数组不为空，则保留
            });

            // 合并所有非空数组
           
            foreach ($filteredData as $array) {
                $result_big_team_arr = array_merge($result_big_team_arr, $array);
            }
            //var_dump($result_big_team_arr);
            //获取当前用户下面在2.0中的下级所有PV
            //$get_teams_comm_pv = $this->getteampv($result_big_team_arr);
            $t_pv = $this->getteampv_getcon($result_big_team_arr);
            $get_teams_comm_pv = $t_pv;
            //var_dump($get_teams_comm_pv);echo "ttt";

            //用户伞下小部门所有在2.0系统下面的业绩和人数 end
        }else{
          
               //当前用户在1.0没有下级，那直接在新系统2.0找下级获取数据，并区分大小部门
              $child_nums = $this->getChildren_getcon($user_id);
             
              //获取父级子级下面的个人
              $num_teams = $this->getTeamSize_getcon($child_nums);
          
              //var_dump($num_teams);
              foreach($child_nums as $v){
                
                   $get_teams_comm_datas[] = $this->getTeamPv11_getcon($v);//如果有多个父级ID，需要获取他们伞下的子级，所有的业绩进行
              }

              //$s = $this->getparents_child_pv($user_id);

              //var_dump($get_teams_comm_datas);
              //如果只有一个部门，就是默认大部门
              if( count($get_teams_comm_datas) ==1 ){
                  
                  $get_teams_comm_pv =$get_teams_comm_datas[0];
                  $get_teams_comm_num = $num_teams[0]['total_count'];
                  
              }else if(count($get_teams_comm_datas) >1){

                    // var_dump( $get_teams_comm_datas);
                    //获取一个最大值，设为大部门，其他的加载一块是小部门
                    $getss = $this->processArray_getcon($get_teams_comm_datas);
                 //var_dump($getss);
                    $max_value_count = $num_teams[$getss['max_index']]['total_count'];

                    unset($num_teams[$getss['max_index']]);

                       //获取小部门的人数
                       $per_num = 0;
                       foreach($num_teams as $k=>$v){
                        $per_num +=$v['total_count'];
                       }
        
                    //找到最大值的(大部门)
                    //$get_teams_comm_num = $max_value_count;
                    //小部门的数量
                   // $get_teams_per_num =  $per_num;
                    //var_dump($getss['max_value']);
                    $person_amount = $getss['remaining_sum'];
                    $get_teams_comm_pv = $getss['max_value'];
              }
          
        }
        //var_dump($get_teams_comm_pv);
        //合并业绩和人数
        $team_amount += $get_teams_comm_pv;
           
        //var_dump($team_amount);
        //1.0获取小区业绩
        $person_nums = $this->getPersonageNums_getcon($user_id);
        //var_dump($person_nums);
        $result_small_team_arr = [];
          //1.0系统中有下级，需要在2.0中再加下级数据
     
      
      
           //用户三峡所有在2.0系统下面的业绩和人数 start
            $child_nums_mix = [];

              //获取当前用户
            foreach($person_nums as $v){
                $child_nums_mix[] = $this->getRecursiveChildren_getcon($v);
            }
       
            //去除空数组，并重新组合有数据的数组
            $filteredData_1 = array_filter($child_nums_mix, function($array) {
                return !empty($array); // 如果数组不为空，则保留
            });
            
            // 合并所有非空数组
            $result_small_team_arr = [];
            foreach ($filteredData_1 as $array) {
                $result_small_team_arr = array_merge($result_small_team_arr, $array);
            }


            //var_dump($result_small_team_arr);
            //获取当前用户下面在2.0中的下级所有PV
           // $get_teams_per_pv = $this->getteampv($result_small_team_arr);
           $t_pv = $this->getteampv_getcon($result_small_team_arr);
           $get_teams_per_pv =$t_pv;
           //var_dump(  $get_teams_per_pv);
          
       
        
        
          //获取当前用户下面在2.0中的下级所有人数
           // $get_teams_per_num += count($result_small_team_arr);
            //合并业绩和人数
            $person_amount += $get_teams_per_pv;

      
        //当前会员直属的业绩（1.0大部门）
        $t_pv = $this->getteampv_getcon($common_nums);
        $team_amount += $t_pv;

         //当前会员直属的业绩（1.0大部门）
        $p_pv = $this->getteampv_getcon($person_nums);
        $person_amount += $p_pv;
    

      
    //var_dump($team_amount,$person_amount);
        //如果当前用户是1.0用户，找到其直推所有的业绩，根据业绩找到大小部门的同时，还要比对1.0中大小部门的业绩，摘出一个最大业绩的部门是大部门，其余都是小部门()
        if($user_id < 611){
        
            //获取当前用户直属下级(查询在2.0中直接推荐人和伞下的业绩。并比对大小部门)
            //例子:17所有下面uid是speard_uid都是17的，和所有伞下的业绩。分出大小部门，加到1.0的大小部门中
            $b_s = $this->getparents_child_pv11_getcon($user_id,$team_amount,$person_amount);
         
            $team_amount = $b_s[0];
          
            $person_amount = $b_s[1];

        }



        $return_data = [
           
            'common_nums_pv'=> $team_amount,
            'person_nums_pv'=> $person_amount,
          
        ];

        return $return_data;

    }

     /**
     * 获取该用户共建联盟
     */
    public function getCommonNums_getcon($user_id){



        //先获取共建联盟下用户的id
        $son_ids = Db::name("old_user_jbp")->where("spread",$user_id)->where("is_team",1)->select()->toArray();
        $new_array_ids =[];
        foreach ($son_ids as $key => $value) {
            # code...
            $son_id = $value['id'];
            $new_array_ids = array_merge($new_array_ids,[$son_id]);
            $son_value_ids = Db::name("old_user_jbp")->whereRaw("FIND_IN_SET('$son_id',parent_ids)")->field("id")->select()->toArray();

            if(count($son_value_ids) > 0) {
                $son_value_ids = array_column($son_value_ids,"id");
                $new_array_ids = array_merge($new_array_ids,$son_value_ids);
            }

        }
        return $new_array_ids;
    }
    /**
     * 获取该用户个人联盟
     */
    public function getPersonageNums_getcon($user_id){

        $son_ids = Db::name("old_user_jbp")->where("spread",$user_id)->where("is_team",0)->field("id")->select();
        $new_array_ids =[];
        // return 3343;
        foreach ($son_ids as $key => $value) {
            # code...
            $son_id = $value['id'];
            $new_array_ids = array_merge($new_array_ids,[$son_id]);
            $son_value_ids = Db::name("old_user_jbp")->whereRaw("FIND_IN_SET('$son_id',parent_ids)")->field("id")->select()->toArray();

            if(count($son_value_ids) > 0) {
                $son_value_ids = array_column($son_value_ids,"id");
                $new_array_ids = array_merge($new_array_ids,$son_value_ids);
            }

        }
        return $new_array_ids;
    }

        // 根据父级uid,递归获取所有子级UID数组
    public function getRecursiveChildren_getcon($parentUid) {
        $result = []; // 用于存储所有子级的 uid

        // 定义递归函数
        $recursion = function ($parentUid) use (&$result, &$recursion) {
            // 查询当前父级的所有直接子级
            $children = Db::name("user")
                        ->where("spread_uid", $parentUid)
                        ->column("uid"); // 获取子级的 uid 列表

            // 如果没有子级，直接返回
            if (empty($children)) {
                return;
            }

            // 遍历每个子级
            foreach ($children as $childUid) {
                $result[] = $childUid; // 将子级的 uid 添加到结果数组
                $recursion($childUid); // 递归查询子级的子级
            }
        };

        // 从初始父级开始递归查询
        $recursion($parentUid);

        return array_unique($result); // 返回结果数组，并去重
    }

    //只获取数组中的业绩
    public function getteampv_getcon($common_nums) {

         // // 查询当前用户及其子级的所有订单
        $orders_gongxian = Db::name("user_sign_gongxian")
                    ->whereIn('status', [1])
                    ->whereIn("uid", $common_nums)
                  
                    ->select();
        //var_dump( $common_nums);

        $total_gongxian = 0;
        // // 遍历订单计算业绩
         foreach ($orders_gongxian as $order) {
            if (strpos($order['mark'], "购买") !== false) {
                $total_gongxian += $order['number'];
            }
        }    

         return $total_gongxian;

        // // // 查询当前用户及其子级的所有订单
        // $orders = Db::name("store_order")
        //             ->whereIn('status', [0, 1, 2, 3])
        //             ->whereIn("uid", $common_nums)
        //             ->whereIn("total_price", [1180, 11800, 10620, 2360, 9440])
        //             ->select();

        // // 初始化业绩和人数
        // $totalPv = 0;
        // $totalUsers = count($common_nums); // 初始化人数为子级总数

        // // 遍历订单计算业绩
        // foreach ($orders as $order) {
        //     if ($order['total_price'] == 1180) {
        //         $totalPv += 700;
        //     } else if ($order['total_price'] == 11800) {
        //         $totalPv += 7000;
        //     } else if ($order['total_price'] == 10620) {
        //         $totalPv += 6300;
        //     } else if ($order['total_price'] == 2360) {
        //         $totalPv += 1400;
        //     } else if ($order['total_price'] == 9440) {
        //         $totalPv += 5600;
        //     }
        // }

        // // 返回业绩和人数
        // return [
        //     'totalPv' => $totalPv,
        //     'totalUsers' => $totalUsers
        // ];
    }


        // 2.0 根据父级uid,找到当前用户下面的UID
    public function getChildren_getcon($parentUid) {
        $result = []; // 用于存储所有子级的 uid

    
            $children = Db::name("user")
                        ->where("spread_uid", $parentUid)
                        ->column("uid"); // 获取子级的 uid 列表

        
        return $children; // 返回结果数组，并去重
    }


      // 递归获取所有子级 UID 的业绩
    public function getTeamPv11_getcon($parentUid) {
    
        $getRecursiveChildren = function ($parentUid) use (&$getRecursiveChildren) {
            $children = Db::name("user")
                        ->where("spread_uid", $parentUid)
                        ->column("uid");
            $allChildren = [];
            foreach ($children as $childUid) {
                $allChildren[] = $childUid;
                $allChildren = array_merge($allChildren, $getRecursiveChildren($childUid));
            }
            return $allChildren;
        };

        // 获取当前用户及其所有子级的 UID
        $allUids = array_merge([$parentUid], $getRecursiveChildren($parentUid));


        $orders_gongxian = Db::name("user_sign_gongxian")
                    ->whereIn('status', [1])
                    ->whereIn("uid", $allUids)
                  
                    ->select();


        $total_gongxian = 0;
        // // 遍历订单计算业绩
        foreach ($orders_gongxian as $order) {
            if (strpos($order['mark'], "购买") !== false) {
                $total_gongxian += $order['number'];
            }
           
        }    

        return $total_gongxian;
        // // 查询当前用户及其子级的所有订单
        // $orders = Db::name("store_order")
        //             ->whereIn('status', [0, 1, 2, 3])
        //             ->whereIn("uid", $allUids)
        //             ->whereIn("total_price", [1180, 11800, 10620, 2360, 9440])
        //             ->select();

        // // 计算总业绩
        // $totalPv = 0;
        // foreach ($orders as $order) {
        //     switch ($order['total_price']) {
        //         case 1180:
        //             $totalPv += 700;
        //             break;
        //         case 11800:
        //             $totalPv += 7000;
        //             break;
        //         case 10620:
        //             $totalPv += 6300;
        //             break;
        //         case 2360:
        //             $totalPv += 1400;
        //             break;
        //         case 9440:
        //             $totalPv += 5600;
        //             break;
        //     }
        // }

       // return $totalPv;
    }

    //根据传递的父级数组，返回他的对应子级的个数
    public function getTeamSize_getcon($parentUids) {
        // 初始化结果数组
        $result = [];

        // 遍历每个父级ID
        foreach ($parentUids as $parentUid) {
            // 递归获取所有子级 UID
            $getRecursiveChildren = function ($parentUid) use (&$getRecursiveChildren) {
                $children = Db::name("user")
                            ->where("spread_uid", $parentUid)
                            ->column("uid");

                // 确保返回的是数组
                if (!is_array($children)) {
                    return [];
                }

                $allChildren = [];
                foreach ($children as $childUid) {
                    $allChildren[] = $childUid;
                    $allChildren = array_merge($allChildren, $getRecursiveChildren($childUid));
                }
                return $allChildren;
            };

            // 获取当前父级及其所有子级的 UID
            $allUids = array_merge([$parentUid], $getRecursiveChildren($parentUid));

            // 计算总个数（包括父级自身）
            $totalUids = count($allUids);

            // 将结果存入数组
            $result[] = [
                'parent_uid' => $parentUid,
                'total_count' => $totalUids
            ];
        }

        return $result;
    }

    public function processArray_getcon($array) {
        // 初始化结果数组
        $result = [
            'max_value' => null,     // 最大值
            'max_index' => null,     // 最大值的下标
            'remaining_sum' => 0     // 剩余值的总和
        ];
    
        // 检查数组是否为空
        if (empty($array)) {
            return $result;
        }
    
        // 找出最大值及其下标
        $maxValue = $array[0];
        $maxIndex = 0;
        for ($i = 1; $i < count($array); $i++) {
            if ($array[$i] > $maxValue) {
                $maxValue = $array[$i];
                $maxIndex = $i;
            }
        }
    
        // 计算剩余值的总和
        $remainingSum = 0;
        for ($i = 0; $i < count($array); $i++) {
            if ($i != $maxIndex) {
                $remainingSum += $array[$i];
            }
        }
    
        // 将结果存入数组
        $result['max_value'] = $maxValue;
        $result['max_index'] = $maxIndex;
        $result['remaining_sum'] = $remainingSum;
    
        return $result;
    }

       /**
     * 获取流水信息
     */
    public function getPerformance1_getcon($user_id) {
        // $amount = Db::name("old_user_of_goods")->where("node_id",$user_id)->where("status",1)->sum("money");

        // $amount = isset($amount) ? round($amount*0.7,2) : 0;
        // return $amount;

        $money1180Records = Db::name("old_user_of_goods")->where("node_id",$user_id)->where("money",1180)->where("status",1)->select();

        $money1180Sum = 0;

        foreach ($money1180Records as $record) {
            $money1180Sum += $record['money'] - 300 - 180;
        }
        // var_dump($money1180Sum);
        $money11800Records = Db::name("old_user_of_goods")->where("node_id",$user_id)->where("money",11800)->where("status",1)->select();

        //var_dump($person_nums);
        //计算个人的11800单价的业绩 集合
        $money11800Sum = 0;

        foreach ($money11800Records as $record) {
            $money11800Sum += $record['money'] - 3000 - 1800;
        }

        $money10620Records = Db::name("old_user_of_goods")->where("node_id",$user_id)->where("money",10620)->where("status",1)->select();

        //var_dump($person_nums);
        //计算个人的11800单价的业绩 集合
        $money10620Sum = 0;

        foreach ($money10620Records as $record) {
            $money10620Sum += $record['money'] - 2700 - 1620;
        }

        // 计算除去特定值后的总和
        $otherMoneyRecords = Db::name("old_user_of_goods")->where("node_id",$user_id)->where('status', 1)->whereNotIn('money', [1180, 11800 ,10620])->select();
        $otherMoneySum = 0;
        foreach ($otherMoneyRecords as $record) {
            $otherMoneySum += $record['money'];
        }

        // 分别处理特定值的情况并加上其他值的总和
        $user_person_amount = $money1180Sum + $money11800Sum + $money10620Sum + round($otherMoneySum * 0.7,2);

        return $user_person_amount;


    }

        //1.0用户直属的部门和2.0直属的部门，进行比较，获取大部门和小部门数据
        public function getparents_child_pv11_getcon($user_id, $bigamount, $smallamount) {

            // 获取直接下级的 UID 列表
            $get_childs = Db::name("user")
            ->where("spread_uid", $user_id)
            ->column("uid");

            // 初始化变量
            $all_departments = []; // 用于存储所有直属下级的业绩

            // 遍历每个直属下级
            foreach ($get_childs as $child) {
                // 获取当前下级及其子级
                $child_group = [$child];
                $recursive_children = $this->getRecursiveChildren_getcon($child);
                $child_group = array_merge($child_group, $recursive_children);

                // 获取当前分组的业绩
                $result = $this->getteampv_getcon($child_group);

                // 将直属下级的业绩加入数组
                $all_departments[] = $result;
            }

            // 将传入的 $bigamount 和 $smallamount 加入数组
            $all_departments[] = $bigamount;
            $all_departments[] = $smallamount;

            // 检查是否所有业绩都是 0
            if (count(array_filter($all_departments, function($value) { return $value != 0; })) == 0) {
                return [0, 0];
            }

            // 初始化最大部门和小部门
            $max_department = 0;
            $small_department = 0;

            // 遍历 $all_departments，找出最大值并累加小部门的值
            foreach ($all_departments as $department) {
                if ($department > $max_department) {
                    // 如果当前部门的业绩大于最大部门的业绩，更新最大部门
                    if ($max_department != 0) {
                        $small_department += $max_department; // 将旧的最大值累加到小部门
                    }
                    $max_department = $department; // 更新最大部门
                } else {
                    // 如果当前部门的业绩小于或等于最大部门的业绩，累加到小部门
                    $small_department += $department;
                }
            }

            // 返回结果
            return [
                $max_department, // 大部门业绩
                $small_department // 小部门业绩
            ];
            //拿$bigamount, $smallamount业绩和get_childs产生的result业绩去对比。如果都是0.说明没有大小部门了，直接返回0，0如果只有一个数组有数据，
            // 说明只有大部门，默认返回大部门数据，小部门返回0，如果有多条数组数据是一样的，那么就是选一个，设为大部门。剩下的数据叠加设为小部门
          
        }

        //获取当前uesr_id下面在2.0中是否还有直接下级，并计算她的大部门和小部门
        public function getparents_child_pv_getcon($user_id){
        // 获取直接下级的 UID 列表
        //$user_id = 593;
        // $get_childs = $this->getRecursiveChildren($user_id);
        $get_childs = Db::name("user")
        ->where("spread_uid", $user_id)
        ->column("uid"); // 获取子级的 uid 列表
        //根据获得的直接推荐下级2.0，来获取他们和她伞下的子级PV。对比拿一个最大的值，设为大部门，其余的是小部门

        //获取直接下级
        $children_group = []; // 用于存储每个直接下级及其子级的分组

        // 遍历每个直接下级
        foreach ($get_childs as $child) {
            $child_group = [$child]; // 将直接下级加入分组
            $recursive_children = $this->getRecursiveChildren($child); // 获取直接下级的所有子级
            $child_group = array_merge($child_group, $recursive_children); // 将子级加入分组
            $children_group[] = $child_group; // 将分组加入最终结果
        }


        $get_teams_comm_datas = [];
        foreach($children_group as $v){
                    
            $get_teams_comm_datas[] = $this->getteampv($v);//如果有多个父级ID，需要获取他们伞下的子级，所有的业绩进行
        }

        if(count($get_teams_comm_datas)  > 0){


            // 找到最大值作为大部门
            $max_value = max($get_teams_comm_datas);
            $total_sum = array_sum($get_teams_comm_datas); // 计算数组的总和

            // 小部门为总和减去最大值
            $small_department = $total_sum - $max_value;

            //返回大部门和小部门
            return [
                $max_value,
                $small_department
            ];

        }else{
        return [
        0,
        0
        ];
        }
    
    }

    /**
     * 将 所有用户 令牌设置为失效
     * @return \think\response\Json
     */
    public function invalidateAllTokens(): \think\response\Json
    {
        // 获取所有用户token键（可能需要使用Redis的keys命令或scan）
        $userTokens = Cache::store('redis')->keys('user_*');
        $javaTokens = Cache::store('redis')->keys('java_*');

        // 批量删除所有token
        foreach ($userTokens as $token) {
            Cache::delete($token);
        }
        foreach ($javaTokens as $token) {
            Cache::delete($token);
        }

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

    /**
     * @return mixed
     * @author 史晨
     * @date 2025/11/3 09:22
     * 注册是否显示邀请码
     */
    public function isInviteCode()
    {
        $data['show'] = 0;
        return app('json')->success($data);
    }
}
