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

namespace app\common\model\bbfxshop;

use think\Db;
use think\Model;


class User extends Model
{
    protected $name = 'bbfx_user';


    public static function uuid(){
        global $_W;
        $uid_prefix = intval($_W['base']['uid_prefix']);
        if($uid_prefix > 0 && $uid_prefix < 1000){
            if($uid_prefix < 10){
                $min = 10000000;
                $max = 99999999;
            }
            else if($uid_prefix < 99 && $uid_prefix > 9){
                $min = 1000000;
                $max = 9999999;
            }
            else{
                $min = 100000;
                $max = 999999;
            }
        }
        else{
            $uid_prefix = "";
            $min = 100000000;
            $max = 999999999;
        }
        $uid = 0;
        while(true){
            $uid = $uid_prefix.random_int($min, $max);
            
            $user = Db::name("bbfx_user")->where(['id'=>$uid])->count();
            if(empty($user)){
                break;
            }
        }
        
        return $uid;
    }
    
    public static function isSupUser($user_id,$uid){
        $user = Db::name("bbfx_user")->where(['id'=>$user_id])->field("id,sup_uid")->find();
        if(empty($user)){
            return true;
        }
        if($user['sup_uid'] == $uid){
            return false;
        }
        
        return self::isSupUser($user['sup_uid'],$uid);
    }
    
    public static function initSupPath($user_id=0,$sup_path="0",$user_list=[]){

        try{
            Db::startTrans();
            $users = self::getChildrenSupPathData($user_id,$sup_path,$user_list);

            if(!empty($users) && $user_id == 0){

                $num = 0;
                $sql = "";
                $uids = [];
                foreach($users as $key => $val){
                    if($num == 0){
                        $sql = "UPDATE ".tablename("bbfx_user")."\r\n";
                        $sql .= "SET sup_path = CASE id"."\r\n";
                    }
                    $uids[] = intval($val['id']);
                    $sql .= "WHEN ".intval($val['id'])." THEN '".$val['sup_path']."'"."\r\n";
                    $num++;

                    if($num >= 499 || $key == count($users)-1){
                        $sql .= "END"."\r\n";
                        $sql .= "WHERE id IN (".implode(',',$uids).");";
                        // file_put_contents("sql111.txt",$sql);
                        Db::execute($sql);
                        $uids = [];
                        $sql = "";
                        $num = 0;
                    }
                }
                
                $users = [];
            }
            Db::commit();
        }
        catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }

        return __json(1,"操作成功");
    }

    public static function getChildrenSupPathData($user_id=0,$sup_path="0",$user_list=[]){

        $users = [];

        try{

            if(($user_id > 0 && empty($user_list)) || $user_id == 0){
                $user_all = Db::name("bbfx_user")->where(['uniacid'=>UNIACID])->field("id,sup_uid")->select();
                if(!empty($user_all)){
                    if(empty($user_all)) $user_all = [];
                    $uids = array_column($user_all,"id");
                    foreach($user_all as $key => $val){

                        if($val['sup_uid'] > 0 && in_array($val['sup_uid'],$uids)){
                            $sup_uid = $val['sup_uid'];
                        }
                        else{
                            $sup_uid = 0;
                        }

                        if(empty($user_list[$sup_uid])){
                            $user_list[$sup_uid] = [];
                        }
                        $user_list[$sup_uid][] = $val;
                    }
                }
            }
            
            $list = $user_list[$user_id];

            if(!empty($list)){
                unset($user_list[$user_id]);
                foreach ($list as $key => $val){
                    $new_sup_path = $sup_path."-".intval($val['id']);
                    $users[] = [
                        'id'=>$val['id'],
                        'sup_path'=>$new_sup_path,
                    ];
                    if(!empty($user_list)){
                        $children_users = self::getChildrenSupPathData($val['id'],$new_sup_path,$user_list);
                        $users = array_merge($users,$children_users);
                    }
                }
            }
        }
        catch(\Exception $e){
            // print_r($e->getMessage());die;
        }

        return $users;
    }
    

    public static function initOriginalSupPath($user_id=0,$sup_path="0",$user_list=[]){

        try{
            Db::startTrans();
            $users = self::getChildrenOriginalSupPathData($user_id,$sup_path,$user_list);

            if(!empty($users) && $user_id == 0){

                $num = 0;
                $sql = "";
                $uids = [];
                foreach($users as $key => $val){
                    if($num == 0){
                        $sql = "UPDATE ".tablename("bbfx_user")."\r\n";
                        $sql .= "SET o_sup_path = CASE id"."\r\n";
                    }
                    $uids[] = intval($val['id']);
                    $sql .= "WHEN ".intval($val['id'])." THEN '".$val['sup_path']."'"."\r\n";

                    $num++;

                    if($num >= 499 || $key == count($users)-1){
                        $sql .= "END"."\r\n";
                        $sql .= "WHERE id IN (".implode(',',$uids).");";
                        // file_put_contents("sql222.txt",$sql);
                        Db::execute($sql);
                        $uids = [];
                        $sql = "";
                        $num = 0;
                    }
                }

            }
            Db::commit();
        }
        catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }

        return __json(1,"操作成功");
    }

    public static function getChildrenOriginalSupPathData($user_id=0,$sup_path="0",$user_list=[]){

        $users = [];

        try{

            if(($user_id > 0 && empty($user_list)) || $user_id == 0){
                $user_all = Db::name("bbfx_user")->where(['uniacid'=>UNIACID])->field('id,sup_uid,first_sup_uid')->select();
                if(!empty($user_all)){
                    if(empty($user_all)) $user_all = [];
                    $uids = array_column($user_all,"id");
                    foreach($user_all as $key => $val){

                        $sup_uid = $val['sup_uid'];
                        if($val['first_sup_uid'] > 0){
                            $sup_uid = $val['first_sup_uid'];
                        }

                        if($sup_uid > 0 && !in_array($sup_uid,$uids)){
                            $sup_uid = 0;
                        }
                        
                        if(empty($user_list[$sup_uid])){
                            $user_list[$sup_uid] = [];
                        }
                        $user_list[$sup_uid][] = $val;
                    }
                }
            }

            $list = $user_list[$user_id];

            if(!empty($list)){
                unset($user_list[$user_id]);
                foreach ($list as $key => $val){
                    $new_sup_path = $sup_path."-".intval($val['id']);
                    $users[] = [
                        'id'=>intval($val['id']),
                        'sup_path'=>$new_sup_path,
                    ];
                    
                    if(!empty($user_list)){
                        $children_users = self::getChildrenOriginalSupPathData($val['id'],$new_sup_path,$user_list);
                        $users = array_merge($users,$children_users);
                    }
                }
            }
        }
        catch(\Exception $e){
            // print_r($e->getMessage());die;
        }

        return $users;
    }
    
    public static function getLevel1UserIds($user_id){
        $list = Db::name("bbfx_user")->where(['sup_uid'=>$user_id,'uniacid'=>UNIACID])->field("id")->select();
        
        $ids = [-1];
        
        if(!empty($list)){
            $ids = array_column($list,"id");
        }
        
        return $ids;
    }
    
    public static function getSupUser($user_id){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        
        $where = ['id'=>intval($user_id)];
        if($base['fenxiao']['ordinary_user_share'] == 1){
            $sup_user = Db::name("bbfx_user")->where($where)->find();
            return $sup_user;
        }
        else if($base['fenxiao']['ordinary_user_share'] == 2){
            $sup_user = Db::name("bbfx_user")->where($where)->find();
            if(empty($sup_user)){
                return false;
            }
            if($sup_user['is_distributor'] == 1 && $sup_user['distributor_status'] == 1){
                return $sup_user;
            }
            return self::getSupUser($sup_user['sup_uid']);
        }
        else{
            $where['is_distributor'] = 1;
            $where['distributor_status'] = 1;
            $sup_user = Db::name("bbfx_user")->where($where)->find();
            return $sup_user;
        }
    }
    
    public static function getUserDiscount($user,$levels = []){
        if(empty($levels)){
            $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
        }
        
        if(!is_array($user)){
            $user = self::getInfo($user);
        }
        
        $discount = 10;
        if($user['is_distributor'] == 1 && $user['distributor_status'] == 1){
            $discount = floatval($levels[$user['level']]['discount']);
            if($discount > 10 || $discount <= 0){
                $discount = 10;
            }
        }
        
        return $discount;
    }
    
    public static function getTypeText($type){
        $list = [
            "1"=>"商品支付",
            "2"=>"积分商品兑换",
            "3"=>"后台充值",
            "4"=>"订单退款",
            "5"=>"余额/积分提现",
            "6"=>"拒绝提现",
            "7"=>"充值余额",
            "8"=>"充值积分",
            "9"=>"佣金提现打款",
            "10"=>"余额/积分返还",
            "11"=>"佣金结算",
            "12"=>"资金转账",
            "21"=>"会员卡赠送",
            "22"=>"收益冻结",
            "23"=>"收益解冻",
            "24"=>"复购赠送",
            "25"=>"订单关闭退回(复购金)",
            "26"=>"累计返还",
            "27"=>"云仓进货返还",
            "28"=>"排队免单",
            "29"=>"轮盘抽奖",
            "30"=>"红包发放",
            "31"=>"资产分红",
            "32"=>"预存款存入",
            "33"=>"预存款释放",
            "34"=>"签到奖励",
            "35"=>"储值利息", 
            "36"=>"拼团未拼中奖励",
            "37"=>"佣金结算奖励",
            "38"=>"消费金额贡献",
            "39"=>"直推业绩贡献",
            "40"=>"团队业绩贡献",
            "41"=>"礼品金额提现",
            "42"=>"推荐用户贡献",
            "43"=>"贡献值转换积分",
            "44"=>"报名费结算",
            "45"=>"扫码支付结算",
            "46"=>"转盘抽奖",
            "47"=>"消费金额获得抽奖次数",
            "48"=>"AI舌诊诊断",
            "49"=>"购买赠送",
            "50"=>"项目分红",
            "51"=>"分享奖励",
            "52"=>"直推加速返还奖",
            "53"=>"见单加速返还奖",
            "54"=>"平级加速返还奖",
            "55"=>"团队层数返还奖",
            "56"=>"直推加速返还奖",
            "57"=>"兑换优惠券",
            "58"=>"消费增加次数",
            "59"=>"抽奖扣除次数",
            "60"=>"现金抽奖提现",
            "61"=>"购买赠送",
            "62"=>"生成数字人视频",
            "63"=>"佣金结算",
            "64"=>"激励广告奖励",
            "65"=>"静态返还",
            "66"=>"直推加速静态返还奖",
            "67"=>"见单加速静态返还奖",
            "68"=>"平级加速静态返还奖",
            "69"=>"直推加速静态返还奖",
            "70"=>"购买舌诊次数"
        ];
        
        return $list[$type];
    }
    
    public static function setUserMoney($user_id,$money,$type=0,$item_type=0,$remarks = "",$info = [],$createtime=0){
        // 操作类型:1=商品支付,2=积分商品兑换,3=后台充值,4=订单退款,5=余额/积分提现,6=拒绝提现,7=充值余额,8=充值积分,9=佣金提现打款,10=余额/积分返还,11=佣金结算,12=资金转账,21=会员卡赠送,22=收益冻结,23=收益解冻,24=复购赠送,25=订单关闭退回(复购金),26=累计返还,27=云仓进货返还,28=排队免单,29=轮盘抽奖,30=红包发放,31=资产分红,32=预存款存入,33=预存款释放,34=签到奖励,35=储值利息,36=拼团未拼中奖励,37=佣金结算奖励,38=消费金额贡献,39=直推业绩贡献,40=团队业绩贡献,41=礼品金额提现,42=推荐用户贡献
        // 金额类型:1=余额,2=积分,3=创业基金（2+1模式）,4=复购金,5=红包金额,6=预存款,7=冻结收益,8=贡献值,9=收款码余额,10=发展基金,11=抽奖次数,12=AI舌诊次数
        $user = self::getInfo($user_id); 
        if(empty($user)){
            return false;
        }
        
        $money = floatval($money);
        
        if(intval($createtime) <= 0){
            $createtime = time();
        }

        if($type == 1){
            $money_key = "balance";
            $money_text = "余额";
        } 
        else if($type == 2){
            $money_key = "score";
            $money_text = "积分";
        }
        else if($type == 3){
            $money_key = "freeze_money";
            $money_text = "创业基金";
        }
        else if($type == 4){
            $money_key = "repurchase_currency";
            $money_text = "复购金";
        }
        else if($type == 5){
            $money_key = "redpacket_money";
            $money_text = "红包金额";
        }
        else if($type == 6){
            $money_key = "deposit_money";
            $money_text = "预存款";
        }
        else if($type == 7){
            $money_key = "freeze_commission";
            $money_text = "冻结收益";
        }
        else if($type == 8){
            $money_key = "contribution_value";
            $money_text = "贡献值";
        }
        else if($type == 9){
            $money_key = "sk_balance";
            $money_text = "收款码余额";
        }
        else if($type == 10){
            $money_key = "fund_money";
            $money_text = "发展基金";
        }
        else if($type == 11){
            $money_key = "lottery_num";
            $money_text = "抽奖次数";
        }
        else if($type == 12){
            $money_key = "tongue_diagnosis_num";
            $money_text = "AI舌诊次数";
        }
        else if($type == 13){
            $money_key = "cashlottery_lottery_num";
            $money_text = "现金抽奖次数";
        }
        else if($type == 14){
            $money_key = "shuziren_num";
            $money_text = "生成数字人次数";
        }
        else if($type == 15){
            $money_key = "contribute_vadded";
            $money_text = "贡献分";
        }
        else{
            return false;
        }
        
        $success = true;
        try {
            Db::startTrans();

            if(empty($money_key)){
                throw new \Exception("类型错误");
            }

            if($money > 0){
                $res = Db::name("bbfx_user")->where(['id'=>$user_id])->setInc($money_key,$money);
                if($type == 8){
                    Db::name("bbfx_user")->where(['id'=>$user_id])->setInc("contribution_value_total",$money);
                }
            }
            else{
                $pmoney = abs($money);
                if($user[$money_key] < $pmoney){
                    throw new \Exception($money_text."不足");
                }
                $res = Db::name("bbfx_user")->where(['id'=>$user_id])->setDec($money_key,$pmoney);
            }
            if(empty($res)){
                throw new \Exception($money_text."不足");
            }
            $nuser = self::getInfo($user_id);
            $befores = $user[$money_key];
            $afters = $nuser[$money_key];

            $data = array(
                "uniacid"=>UNIACID,
                "user_id"=>$user_id,
                "money"=>$money,
                "befores"=>$befores,
                "afters"=>$afters,
                "remarks"=>$remarks,
                "info"=>iserializer($info),
                "type"=>$type,
                "item_type"=>$item_type,
                "createtime"=>$createtime
            );
            
            if(!empty($info['id'])){
                $data['item_id'] = $info['id'];
            }
            if(!empty($info['extend'])){
                $data['extend'] = $info['extend'];
            }
            
            $id = Db::name("bbfx_money_log")->insertGetId($data);
            
            Db::commit();
        } 
        catch (\Exception $e) {
            $success = false;
            Db::rollback();
            // print_r($msg = $e->getMessage());die;
            addFileLog("money_1",json_encode($e->getMessage()));
        }
        
         
        if(empty($success)){
            return false;
        }
        
        if($type == 2 || $type == 1){
            $data['id'] = $id;
            $extend = $data;
            $content = $remarks;
            if($type == 1){
                $ntype = 3;
                $unit = "元";
                $title = "余额变动通知";
            }
            else{
                $ntype = 5;
                $unit = "积分";
                $title = "积分变动通知";
            }
            
            if($money > 0){
                $content .= "增加".$money.$unit."。";
            }
            else{
                $content .= "减少".abs($money).$unit."。";
            }
            $params = ['type'=>$ntype,'itype'=>$ntype,'user_id'=>$user_id,'title'=>$title,'content'=>$content,'extend'=>$extend];
            $result = \app\common\model\bbfxshop\Notice::send($params);
        }
        
        return $id;
    }
    
    public static function getInfo($openid){
        if(empty($openid)){
            return [];
        }
        if(intval($openid)){
            $user = Db::name("bbfx_user")->where(['id'=>intval($openid)])->find();
        }
        else{
            $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'openid'=>$openid])->find();
        }
        
        if(!empty($user)){
            $user['contribute_vadded'] = floatval($user['contribute_vadded']);
            if(empty($user['avatar'])){
                $user['avatar'] = "/assets/images/avatar.jpg";
            }

            if(empty($user['chat_uuid'])){
                $user['chat_uuid'] = \fast\Random::uuid();
                Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['chat_uuid'=>$user['chat_uuid']]);
            }
        }
        
        return $user;
    }
    
    public static function getUser($openid,$all=true){
        global $_W;
        if(empty($openid)){
            return false;
        }
        $base = $_W['base'];
        $user = self::getInfo($openid);
        
        if(!empty($user)){
            
            
            $udata = ['last_login_time'=>time(),'login_ip'=>request()->ip()];
            $is_ip_gs = false;
            if(!empty($user['ip_gs'])){
                $user['ip_gs'] = iunserializer($user['ip_gs']);
                if(time() - $user['time'] > 600){
                    $is_ip_gs = true;
                }
            }
            else{
                $is_ip_gs = true;
            }
            if($is_ip_gs){
                // $result = ihttp_get("https://api.asilu.com/ip/?ip=".$udata['login_ip']);
                // $result = json_decode($result['content'],true);
                // if(!empty($result['dz'])){
                //     $dz = explode(" ",$result['dz']);
                //     $user['ip_gs'] = [
                //         'p'=>$dz[0],
                //         'c'=>$dz[1],
                //         'a'=>$dz[2],
                //         'wl'=>$result['wl'],
                //         'ip'=>$udata['login_ip']
                //     ];
                //     $udata['ip_gs'] = iserializer($user['ip_gs']);
                // }
            }

            Db::name("bbfx_user")->where(['id'=>$user['id']])->update($udata);
            
            $base = $_W['base'];
            
            $user['avatar'] = cdnurl($user['avatar']);
            $user['skqrcode_attach'] = cdnurl($user['skqrcode']);
            $user['skqrcode'] = cdnurl($user['skqrcode']);
            $user['commission_total'] = round($user['commission_total'],2);
            $user['commission_ok'] = round($user['commission_ok'],2);
            if($user['is_distributor'] == 1 && $user['distributor_status'] == 1){
                $leveldata = \app\common\model\bbfxshop\FenxiaoLevel::getLevel($user['level']);
                $user['levelname'] = $leveldata['title'];
                $user['level_icon'] = cdnurl($leveldata['thumb']);
            }
            else{
                $user['levelname'] = $base['fenxiao']['texts']['mlevel'];
                
                if(empty($user['levelname'])){
                    $user['levelname'] = "普通用户";
                }
            }
            
            $user['withdrawal_info'] = iunserializer($user['withdrawal_info']);
            
            $card = \app\common\model\bbfxshop\Card::getUserCard($user['id']);
            
            if(!empty($card)){
                if($card['endtime'] != -1){
                    $vip_endtime = date("Y-m-d",$card['endtime']); 
                    $user['vip_endtime'] = $vip_endtime;
                    $user['vip_endday'] = round(($card['endtime'] - time()) / 86400);
                }
                else{
                    $user['vip_endtime'] = "永久有效";
                    $user['vip_endday'] = "永久有效";
                }
                $user['card'] = $card;
            }
            
            if($user['agent_status'] == 1 && $user['agent_level'] > 0){
                $log_count = Db::name("bbfx_agent_log")->where(["uniacid"=>UNIACID,'user_id'=>$user['id']])->count();
                if($log_count == 0){
                    $agent_params = ['agent_province'=>$user['agent_province'],'agent_city'=>$user['agent_city'],'agent_area'=>$user['agent_area'],'agent_street'=>$user['agent_street']];
                    \app\common\model\bbfxshop\Agent::setRegion($user,$agent_params);
                }
            }
            
            if($all){

                $user['txaccount_rz_status'] = -1;
                $dg_huifu_id = Db::name("platform")->where(['id'=>$user['uniacid']])->value("dg_huifu_id");
                if(!empty($dg_huifu_id)){
                    $txaccount = Db::name("bbfx_user_txaccount")->where(['uniacid'=>UNIACID,'dg_huifu_id'=>$dg_huifu_id,'user_id'=>$user['id']])->field("id,kh_status,rz_status")->find();
                    if(!empty($txaccount)){
                        $user['txaccount_rz_status'] = $txaccount['rz_status'];
                    }
                }
                

                if($user['sup_uid'] > 0){
                    $sup_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$user['sup_uid']])->field("id,nickname,avatar")->find();
                    if(!empty($sup_user)){
                        $sup_user['avatar'] = cdnurl($sup_user['avatar']);
                        $user['sup_user'] = $sup_user;
                    }
                }

                $user['coupon_num'] = intval(Db::name("bbfx_user_coupon")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'status'=>0])->where(function($query){
                    $query->whereOr(function($query){
                        $query->where(['endtime'=>0]);
                    });
                    $query->whereOr(function($query){
                        $query->where(['endtime'=>['>',time()]]);
                    });
                })->count());
                
                $user['createtime'] = date("Y-m-d H:i:s",$user['createtime']);
                $user['last_login_time'] = date("Y-m-d H:i:s",$user['last_login_time']);
                
                $yajin_money = Db::name("bbfx_yajin_record")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'status'=>1])->sum("money");
                $user['yajin_money'] = $yajin_money;
                
                $nextLevels = \app\common\model\bbfxshop\FenxiaoLevel::getUplevels($user);
                if(!empty($nextLevels)){
                    $nextLevel = $nextLevels[0];
                    $conditions = iunserializer($nextLevel['conditions']);
                    if($conditions['apply'] == 1 && in_array(14,$base['fenxiao']['up_type'])){
                        $nextLevel['apply'] = 1;
                    }
                    else{
                        $nextLevel['apply'] = 0;
                    }
                    
                    if($nextLevel['id'] == 0 && $base['fenxiao']['become_agent'] == 4){
                        $nextLevel['apply'] = 1;
                    }
                    
                    if($nextLevel['apply'] == 1 && in_array(14,$base['fenxiao']['up_type']) && $base['fenxiao']['user_shenhe_apply'] == 1){
                        $sup_user = self::getInfo($user['sup_uid']);
                        if(!empty($sup_user)){
                            $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
                            if($levels[$sup_user['level']]['user_shenhe_apply'] == 1){
                                $level_ids = [];
                                $sort = $levels[$sup_user['level']]['sort'];
                                foreach ($levels as $key => $val){
                                    if($sort > $val['sort']){
                                        $level_ids[] = intval($val['id']);
                                    }
                                }
                                
                                if(in_array(intval($nextLevel['id']),$level_ids)){
                                    $nextLevel['apply'] = 1;
                                }
                                else{
                                    $nextLevel['apply'] = 0;
                                }
                            }
                            else{
                                $nextLevel['apply'] = 0;
                            }
                        }
                    }
                    
                    
                    
                    $user['nextLevel'] = $nextLevel;
                }
                $user['max_balance'] =$user['balance'];
                $user['max_score'] =$user['score'];
                if($base['cumulative_fanhuan']['status'] == 1){
                    $surplus = Db::name("bbfx_cumulative_fanhuan_user")->where(['uniacid'=>UNIACID,'user_id'=>$user['id']])->value("surplus");
                    $surplus = floatval($surplus);
                    
                    if($base['cumulative_fanhuan']['settlement_currency'] == 1){
                        $user['max_balance'] = round($user['balance'] + $surplus,2);
                    }
                    else{
                        $user['max_score'] = round($user['score'] + $surplus,2);
                    }
                }

                // 返还模式
                $user['return_total'] = 0;
                $user['return_ok'] = 0;
                $user['return_wait'] = 0;
                $user['return_today'] = 0;
                if($base['return']['status'] == 1){
                    $return_total = Db::name("bbfx_return_item")->where(['uniacid'=>UNIACID,'user_id'=>$user['id']])->sum("total");
                    $user['return_total'] = round($return_total,2);
                    $return_ok = Db::name("bbfx_return_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id']])->sum("money");
                    $user['return_ok'] = round($return_ok,2);
                    $user['return_wait'] = max(0,round($user['return_total'] - $user['return_ok'],2));
                    $return_today = Db::name("bbfx_return_item")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->sum("total");
                    $user['return_today'] = round($return_today,2);
                }
                
                // 累计返还
                $user['cumulative_fanhuan_total'] = 0;
                $user['cumulative_fanhuan_ok'] = 0;
                $user['cumulative_fanhuan_wait'] = 0;
                $user['cumulative_fanhuan_score_total'] = 0;
                $user['cumulative_fanhuan_score_ok'] = 0;
                $user['cumulative_fanhuan_score_wait'] = 0;
                if($base['cumulative_fanhuan']['status'] == 1){
                    $where = ['uniacid'=>UNIACID,'user_id'=>$user['id'],'item_type'=>['in',[26,52,53,54]],'money'=>['>',0]];
                    $fanhuan_user = Db::name("bbfx_cumulative_fanhuan_user")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>1])->find();
                    if(!empty($fanhuan_user)){
                        $user['cumulative_fanhuan_total'] = $fanhuan_user['total'];
                        // $user['cumulative_fanhuan_wait'] = $fanhuan_user['surplus'];
                        // $user['cumulative_fanhuan_ok'] = round($fanhuan_user['total'] - $fanhuan_user['surplus'],2);
                        $user['cumulative_fanhuan_ok'] = Db::name("bbfx_money_log")->where($where)->where(['type'=>1])->sum("money");
                        $user['cumulative_fanhuan_ok'] = round($user['cumulative_fanhuan_ok'],2);
                        $user['cumulative_fanhuan_wait'] = round($fanhuan_user['total'] - $user['cumulative_fanhuan_ok'],2);
                    }

                    $fanhuan_score_user = Db::name("bbfx_cumulative_fanhuan_user")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>2])->find();
                    if(!empty($fanhuan_score_user)){
                        $user['cumulative_fanhuan_score_total'] = $fanhuan_score_user['total'];
                        // $user['cumulative_fanhuan_score_wait'] = $fanhuan_score_user['surplus'];
                        // $user['cumulative_fanhuan_score_ok'] = round($fanhuan_score_user['total'] - $fanhuan_score_user['surplus'],2);
                        $user['cumulative_fanhuan_score_ok'] = Db::name("bbfx_money_log")->where($where)->where(['type'=>2])->sum("money");
                        $user['cumulative_fanhuan_score_ok'] = round($user['cumulative_fanhuan_score_ok'],2);
                        $user['cumulative_fanhuan_score_wait'] = round($fanhuan_score_user['total'] - $user['cumulative_fanhuan_score_ok'],2);
                    }
                }

                // 静态返还
                $user['sreturn_total'] = 0;
                $user['sreturn_ok'] = 0;
                $user['sreturn_wait'] = 0;
                $user['sreturn_score_total'] = 0;
                $user['sreturn_score_ok'] = 0;
                $user['sreturn_score_wait'] = 0;
                if($base['sreturn']['status'] == 1){
                    $where = ['uniacid'=>UNIACID,'user_id'=>$user['id'],'item_type'=>['in',[65,66,67,68]],'money'=>['>',0]];
                    $sreturn_user = Db::name("bbfx_sreturn_user")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>1])->find();
                    if(!empty($sreturn_user)){
                        $user['sreturn_total'] = $sreturn_user['total'];
                        $user['sreturn_wait'] = $sreturn_user['surplus'];
                        $user['sreturn_ok'] = round($sreturn_user['total'] - $sreturn_user['surplus'],2);
                        // $user['sreturn_ok'] = Db::name("bbfx_money_log")->where($where)->where(['type'=>1])->sum("money");
                        // $user['sreturn_ok'] = round($user['sreturn_ok'],2);
                        // $user['sreturn_wait'] = round($sreturn_user['total'] - $user['sreturn_ok'],2);
                    }

                    $sreturn_score_user = Db::name("bbfx_sreturn_user")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'type'=>2])->find();
                    if(!empty($sreturn_score_user)){
                        $user['sreturn_score_total'] = $sreturn_score_user['total'];
                        $user['sreturn_score_wait'] = $sreturn_score_user['surplus'];
                        $user['sreturn_score_ok'] = round($sreturn_score_user['total'] - $sreturn_score_user['surplus'],2);
                        // $user['sreturn_score_ok'] = Db::name("bbfx_money_log")->where($where)->where(['type'=>2])->sum("money");
                        // $user['sreturn_score_ok'] = round($user['sreturn_score_ok'],2);
                        // $user['sreturn_score_wait'] = round($sreturn_score_user['total'] - $user['sreturn_score_ok'],2);
                    }
                }
                
                // 代理区域
                $user['agent_regions'] = [];
                if($base['agent']['status'] == 1){
                    $agent_regions = [];
                    if($base['agent']['status'] == 1 && $base['agent']['level'] >= 1){
                        $agent_level = intval($user['agent_level']);
                        
                        $agent_log = Db::name("bbfx_agent_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id']])->select();
                        
                        foreach ($agent_log as $key => $val){
                            if($agent_level >= 1 && !empty($val['province'])){
                                $region = "";
                                $region .= $val['province'];
                                if($agent_level >= 2){
                                    $region .= "-".$val['city'];
                                }
                                if($agent_level >= 3){
                                    $region .= "-".$val['area'];
                                }
                                if($agent_level >= 4){
                                    $region .= "-".$val['street'];
                                }
                                $agent_regions[] = ['name'=>$region,'level'=>$agent_level];
                            }
                        }
                        
                        $user['agent_regions'] = $agent_regions;
                    }
                }
        
                
                if($base['fenxiao']['is_ladder_abonus'] == 1){
                    $is_rule = false;
                    if($base['fenxiao']['ladder_abonus_mode'] == 2){
                        $ladder_abonus_multiple = $base['fenxiao']['ladder_abonus_multiple'];
                        foreach ($ladder_abonus_multiple as $key => $val){
                            if(empty($val['users']) || (!empty($val['users']) && in_array($user['id'],$val['users']))){
                                $is_rule = true;
                                break;
                            }
                        }
                    }
                    else{
                        $ladder_abonus = $base['fenxiao']['ladder_abonus'];
                        $is_rule = true;
                    }
                    
                    
                    if($is_rule){
                        $alldown = \app\common\model\bbfxshop\FenxiaoUser::getAllDown($user['id']);
                        $team_uids = [];
                        if(!empty($alldown['ids'])){
                            $team_uids = $alldown['ids'];
                        }
                        $team_achievement = Db::name("bbfx_order")->where(['uniacid'=>$user['uniacid'],'user_id'=>['in',$team_uids],'status'=>['in',[1,2,3]]])->sum("price");
                        $ladder_abonus_levelname = "";
                        if($base['fenxiao']['ladder_abonus_mode'] == 2){
                            foreach ($ladder_abonus_multiple as $key => $val){
                                foreach ($val['rules'] as $k => $v){
                                    if($team_achievement >= intval($v['achievement'])){
                                        $ladder_abonus_levelname = $v['name'];
                                    }
                                }
                                if(!empty($ladder_abonus_levelname)){
                                    break;
                                }
                            }
                        }
                        else{
                            foreach ($ladder_abonus as $key => $val){
                                if($team_achievement >= intval($val['achievement'])){
                                    $ladder_abonus_levelname = $val['name'];
                                }
                            }
                        }
                        $user['ladder_abonus_levelname'] = $ladder_abonus_levelname;
                    }
                    
                }
                
                $stock = Db::name("bbfx_cloud_warehouse_goods")->where(['uniacid'=>$user['uniacid'],'user_id'=>$user['id']])->order("id desc")->value("stock");
                $user['cloud_warehouse_stock'] = intval($stock);
                $user['is_pay_password'] = 0;
                if(!empty($user['pay_password'])){
                   $user['is_pay_password'] = 1; 
                }
          	    $user['isAdmin'] = 0;
          	    if($base['admin']){
          	        $admin = explode(",",$base['admin']);
          	        foreach ($admin as $key => $val){
          	            if($val == $user['id']){
          	                $user['isAdmin'] = 1;
          	            }
          	        }
          	    }
            }
        }
        
        return $user;
    }

    // 支付密码验证
    public static function checkPayPassword($user_id,$password){
        $is_pay_password = Db::name("bbfx_base")->where(['uniacid'=>UNIACID])->value("is_pay_password");
        if($is_pay_password != 1){
            return __json(1,"未开启支付密码");
        }
        $user = Db::name("bbfx_user")->where(['id'=>$user_id])->field("id,status,pay_password,payfailure,paytime")->find();
        if(empty($user)){
            return __json(0,"用户信息错误");
        }

        if($user['status'] != 1){
            return __json(0,"账户已被冻结");
        }

        $time = strtotime(date('Y-m-d 00:00:00'));
        if($user['payfailure'] >= 5 && $user['paytime'] > $time){
            return __json(0,"支付已锁定，请于1天后尝试");
        }
        
        $password = md5($password);

        if($password !== $user['pay_password']){
            if($user['paytime'] > $time){
                $payfailure = $user['payfailure'] + 1;
            }
            else{
                $payfailure = 1;
            }

            Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['payfailure'=>$payfailure,'paytime'=>time()]);

            return __json(0,"密码错误");
        }
        else{
            Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['payfailure'=>0,'paytime'=>time()]);
        }

        return __json(1,"操作成功");
    }
    
    public function bind($user,$sup_uid){
        global $_W;
        $fenxiao = $_W['base']['fenxiao'];
        $rebind_day = max(0,intval($fenxiao['rebind_day']));
        $sup_uid = intval($sup_uid);
        if($fenxiao['is_rebind'] != 1 || $sup_uid <= 0 || $user['is_distributor'] == 1 || $user['distributor_status'] == 1 || $sup_uid == $user['sup_uid']){
            return false;
        }
        
        $time = time() - $user['bindtime'];
        if($time / 86400 < $rebind_day){
            return false;
        }
        
        $sup_user = Db::name("bbfx_user")->where(['is_distributor'=>1,'distributor_status'=>1,'id'=>$sup_uid])->find();
        if(empty($sup_user)){
            return false;
        }
        
        $order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'user_id'=>$user['id']])->find();
        if(!empty($order)){
            return false;
        }
        
        $res = Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['sup_uid'=>$sup_uid]);
        if($res){
            Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['bindtime'=>time()]);
            self::initSupPath();
        }
        return $res;
    }
     
    public static function checkTxdateLimit($type = 1){
        global $_W;
        $base = $_W['base'];
        
        if($type == 2){
            $tx_date_limit = $base['fenxiao']['tx_date_limit']['status'];
            $tx_date_type = $base['fenxiao']['tx_date_limit']['tx_date_type'];
            $tx_day = $base['fenxiao']['tx_date_limit']['tx_day'];
            $tx_week = $base['fenxiao']['tx_date_limit']['tx_week'];
        }
        else if($type == 3){
            $tx_date_limit = $base['withdrawal']['score_tx_date_limit'];
            $tx_date_type = $base['withdrawal']['score_tx_date_type'];
            $tx_day = $base['withdrawal']['score_tx_day'];
            $tx_week = $base['withdrawal']['score_tx_week'];
        }
        else if($type == 9){
            $tx_date_limit = $base['contribute_vadded']['withdrawal']['tx_date_limit'];
            $tx_date_type = $base['contribute_vadded']['withdrawal']['tx_date_type'];
            $tx_day = $base['contribute_vadded']['withdrawal']['tx_day'];
            $tx_week = $base['contribute_vadded']['withdrawal']['tx_week'];
        }
        else{
            $tx_date_limit = $base['withdrawal']['tx_date_limit'];
            $tx_date_type = $base['withdrawal']['tx_date_type'];
            $tx_day = $base['withdrawal']['tx_day'];
            $tx_week = $base['withdrawal']['tx_week'];
        }
        if($tx_date_limit == 1){
            if($tx_date_type == 1){
                if(!empty($tx_day) && !in_array(intval(date("d")),$tx_day)){
                    __error("每月".implode(",",$tx_day)."日等日期可提现");
                }
            }
            else{ 
                $w = date("w");
                if($w == 0) $w = 7;
                if(!in_array($w,$tx_week)){
                    __error("每周".implode(",",$tx_week)."等日期可提现");
                }
            }
        }
    } 
    
    public static function checkStatus($user){
        if(!is_array($user)){
            $user = self::getInfo($user);
        }
        
        if(!empty($user) && $user['status'] != 1){
            __error("您的账号已被冻结，请联系管理员");
        }
    }

    public static function getOpenidKey($platform){
        $openid_keys = [
            'GZH'=>'gzh_openid',
            'wxapp'=>'wxapp_openid',
            'WXAPP'=>'wxapp_openid',
            'dyapp'=>'dyapp_openid',
        ];

        if(empty($openid_keys[$platform])){
            return false;
        }
        $openid_key = $openid_keys[$platform];
        return $openid_key;
    }

    public static function getUserId($openid,$platform){
        if(empty($openid)){
            return false;
        }

        $openid_key = self::getOpneidKey($platform);
        if(empty($openid_key)){
            return false;
        }

        $uid = Db::name("bbfx_user")->where(["uniacid"=>UNIACID,"{$openid_key}"=>$openid])->value("id");
        
        return $uid;
    }

    public static function login($code,$platform){
        if($platform == 'dyapp'){
            $result = \app\common\model\bbfxshop\Douyin::login($code);
        }
        else{
            $result = \app\common\model\bbfxshop\Weixin::login($code);
        }

        return $result;
    }

    public static function getPhoneNumber($code,$platform){
        if($platform == 'dyapp'){
            $result = \app\common\model\bbfxshop\Douyin::getPhoneNumber($code);
        }
        else{
            $result = \app\common\model\bbfxshop\Weixin::getPhoneNumber($code);
        }

        return $result;
    }

    public static function getUnionidUser($openid,$unionid,$platform){
        if(empty($unionid)){
            return $openid;
        }
        
        $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'unionid'=>$unionid])->field("id,platform")->select();
        if(empty($user)){
            return $openid;
        }
        $uid = 0;
        foreach ($user as $key => $val){
            if($platform == 'GZH' && $val['platform'] == 'GZH'){
                $uid = $val['id'];
                break;
            }
            else if(($platform == 'wxapp' || $platform == 'WXAPP') && ($val['platform'] == 'wxapp' || $val['platform'] == 'WXAPP')){
                $uid = $val['id'];
                break;
            }
        }
        
        if(empty($uid) && count($user) == 1){
            $openid_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'openid'=>$openid])->field("id,platform")->select();
            if(empty($openid_user)){
                $uid = $user[0]['id'];
            }
        }
        
        if(empty($uid)){
            return $openid;
        }
        
        return $uid;
    }
    
    public static function getUserUnionid(){
        $page = 26;
        $limit = 100;
        $result = \app\common\model\bbfxshop\Weixin::getWxAccessToken();
        if($result['code'] != 1){
            return $result;
        }
        $access_token = $result['data'];
        $unionids = [];
        
        $where = ['uniacid'=>UNIACID,'platform'=>'GZH'];
        // $where['id'] = ['in',[288229811,288274017]];
        
        $list = Db::name('bbfx_user')->where($where)->field("id,unionid,openid,gzh_openid")->limit(($page-1)*$limit,$limit)->order("id asc")->select();
        if(empty($list)){
            return __json(0,"用户不存在");
        }
        
        $openids = [];
        $user_list = [];
        foreach($list as $key => $val){
            if(!empty($val['unionid'])){
                $unionids[] = $val['unionid'];
            }
            if($val['openid'] != $val['gzh_openid'] || !empty($val['unionid'])){
                continue;
            }
            $openids[$val['openid']] = $val;
            $user_list[] = ['openid'=>$val['openid']];
        }
        
        if(!empty($user_list)){
            $url = 'https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token='.$access_token;
            $data = ['user_list'=>$user_list];
            $result = ihttp_post($url,toJsonen($data));
            $result = toJsonde($result['content']);
            // echo "<pre>";
            // print_r($result);die;
            if(!empty($result['user_info_list'])){
                $user_info_list = $result['user_info_list'];
                foreach ($user_info_list as $k => $v){
                    
                    $unionid = $v['unionid'];
                    if(!in_array($unionid,$unionids) && !empty($unionid)){
                        $user = $openids[$v['openid']];
                        $unionids[] = $unionid;
                        // print_r($user);
                        // print_r($unionid);die;
                        Db::name('bbfx_user')->where(['id'=>$user['id']])->update(['unionid'=>$unionid]);
                    }
                }
            }
        }
        
        return __json(1,"操作成功");
    }

    public static function visitor($user_id,$utk,$platform){

        $data = [
            'uniacid'=>UNIACID,
            'type'=>0,
            'user_id'=>intval($user_id),
            'utk'=>$utk,
            'platform'=>$platform,
            'createtime'=>time()
        ];

        if(!empty($data['user_id']) && !empty($data['utk'])){
            $where = ['uniacid'=>$data['uniacid'],'type'=>$data['type'],'user_id'=>$data['user_id'],'utk'=>$data['utk']];
        }
        else if(empty($data['user_id'])  && !empty($data['utk'])){
            $where = ['uniacid'=>$data['uniacid'],'type'=>$data['type'],'utk'=>$data['utk']];
        }
        else{
            return __json(0,"参数缺失");
        }

        $where['createtime'] = ['>',strtotime(date('Y-m-d 00:00:00'))];
        $log = Db::name("bbfx_user_log")->where($where)->find();
        if(!empty($log)){
            return __json(0,"已记录");
        }

        try {
            Db::name("bbfx_user_log")->insert($data);
        } catch (\Exception $e) {
            return __json(0,$e->getMessage());
        }

        return __json(1,"操作成功");
    }

    public static function addShareLog($user_id,$type){
        $user = self::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户不存在");
        }

        $log = Db::name("bbfx_user_share_log")->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'type'=>$type,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->find();
        if(!empty($log)){

            \app\common\model\bbfxshop\CumulativeFanhuan::signRelease($user_id,2);
            \app\common\model\bbfxshop\ReturnMode::signRelease($user_id,2);

            return __json(0,"已记录");
        }

        $data = [
            'uniacid'=>UNIACID,
            'user_id'=>$user_id,
            'type'=>$type,
            'createtime'=>time()
        ];

        try {
            Db::name("bbfx_user_share_log")->insert($data);
        } catch (\Exception $e) {
            return __json(0,$e->getMessage());
        }

        \app\common\model\bbfxshop\CumulativeFanhuan::signRelease($user_id,2);
        \app\common\model\bbfxshop\ReturnMode::signRelease($user_id,2);

        return __json(1,"操作成功");
    }

    public static function isTodayShare($user_id){
        $log = Db::name("bbfx_user_share_log")->where(['uniacid'=>UNIACID,'type'=>['in',[1,2]],'user_id'=>$user_id,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->count();
        if(!empty($log)){
            return true;
        }
        else{
            return false;
        }
    }

    public static function addSeeVideoLog($user_id){
        $user = self::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户不存在");
        }
        $type = 3;
        $log = Db::name("bbfx_user_share_log")->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'type'=>$type,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->find();
        if(!empty($log)){

            \app\common\model\bbfxshop\ReturnMode::signRelease($user_id,4);

            return __json(0,"已记录");
        }

        $data = [
            'uniacid'=>UNIACID,
            'user_id'=>$user_id,
            'type'=>$type,
            'createtime'=>time()
        ];

        try {
            Db::name("bbfx_user_share_log")->insert($data);
        } catch (\Exception $e) {
            return __json(0,$e->getMessage());
        }

        \app\common\model\bbfxshop\ReturnMode::signRelease($user_id,4);

        return __json(1,"操作成功");
    }

    public static function isTodaySeeVideo($user_id){
        $log = Db::name("bbfx_user_share_log")->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'type'=>3,'createtime'=>['>',strtotime(date('Y-m-d 00:00:00'))]])->count();
        if(!empty($log)){
            return true;
        }
        else{
            return false;
        }
    }

    public static function setSchievement($user_id,$achievement,$time){
        if(empty($user_id)){
            return __json(0,"用户不存在");
        }
        if(empty($achievement)){
            return __json(0,"业绩金额错误");
        }
        if(empty($time)){
            return __json(0,"时间格式错误");
        }

        $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$user_id])->field("id,today_achievement,month_achievement,smonth_achievement,total_achievement")->find();
        if(empty($user)){
            return __json(0,"用户不存在");
        }

        $date = date("Y-m-d",$time);
        
        try {
            $user_achievement_where1 = ['uniacid'=>UNIACID,'user_id'=>$user_id,'type'=>1,'date'=>$date];
            $user_achievement = Db::name("bbfx_user_achievement")->where($user_achievement_where1)->find();
            if(empty($user_achievement)){
                $data = [
                    'uniacid'=>UNIACID,
                    'user_id'=>$user_id,
                    'type'=>1,
                    'date'=>$date
                ];
                $user_achievement = Db::name("bbfx_user_achievement")->where($user_achievement_where1)->find();
            }

            $user_achievement_where1 = ['uniacid'=>UNIACID,'user_id'=>$user_id,'type'=>1,'date'=>$date];
            $user_achievement = Db::name("bbfx_user_achievement")->where($user_achievement_where1)->find();
            if(empty($user_achievement)){
                $data = [
                    'uniacid'=>UNIACID,
                    'user_id'=>$user_id,
                    'type'=>1,
                    'date'=>$date
                ];
                $user_achievement = Db::name("bbfx_user_achievement")->where($user_achievement_where1)->find();
            }

            $data = [];
            if($achievement > 0){
                $data['total_achievement'] = $user['total_achievement'] + $achievement;
                if(date('Y-m-d') == $date){
                    $data['today_achievement'] = $user['today_achievement'] + $achievement;
                    $data['month_achievement'] = $user['month_achievement'] + $achievement;
                }
                else if(date('Y-m',strtotime("-1 month")) == date("Y-m",$time)){
                    $data['smonth_achievement'] = $user['smonth_achievement'] + $achievement;
                }
                else if(date('Y-m') == date("Y-m",$time)){
                    $data['month_achievement'] = $user['month_achievement'] + $achievement;
                }
            }
            else{
                $data['total_achievement'] = $user['total_achievement'] - $achievement;
                if(date('Y-m-d') == $date){
                    $data['today_achievement'] = $user['today_achievement'] - $achievement;
                    $data['month_achievement'] = $user['month_achievement'] - $achievement;
                }
                else if(date('Y-m',strtotime("-1 month")) == date("Y-m",$time)){
                    $data['smonth_achievement'] = $user['smonth_achievement'] - $achievement;
                }
                else if(date('Y-m') == date("Y-m",$time)){
                    $data['month_achievement'] = $user['month_achievement'] - $achievement;
                }
            }
            Db::name("bbfx_user")->where(['id'=>$user_id])->update($data);
        } catch (\Exception $e) {
            return __json(0,$e->getMessage());
        }
        return __json(1,"操作成功");
    }
}
