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

namespace app\admin\controller\bbfxshop\user;

use app\admin\controller\bbfxshop\Base;
use app\common\model\bbfxshop\Fenxiao;
use think\Db;
use app\common\model\bbfxshop\FenxiaoUpgrade;

use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;

class User extends Base
{

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\User;
    }

    public function initSupPath(){

        $this->model->initSupPath();
        $this->model->initOriginalSupPath();

        __success("操作成功");
    }
    
    public function search(){
        $params = $this->param();
        
        $uids = trim($params['uids']);
        $uids = explode(",",$uids);
        
        
        $where = ['uniacid'=>UNIACID,'id'=>['in',$uids]];
        $keyword = $params['keyword'];
        if(!empty($keyword)){
            $where['title'] = ['like','%'.$keyword.'%'];
        }
        
        $list = Db::name("bbfx_user")->where($where)->field(['id','nickname','avatar'])->select();
        
        foreach ($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
        }
        unset($val);
        
        if(empty($list)){
            __error("未查询到数据");
        }
        else{
            __success("操作成功",$list);
        }
    }

    public function refreshLevel(){


        $list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID])->field("id,sup_uid,status,level,is_distributor,distributor_status,become_distributor_time,upgrade_distributor_time,commission_total,commission_ok,freeze_commission,is_transfer,first_sup_uid,transfer_sup_uid")->select();
        foreach($list as $key => $val){
            FenxiaoUpgrade::upgrade($val);
        }
        
        __success("操作成功");
    }
    
    public function post(){
        global $_W;
        $params = $this->param();
        $id = intval($params['id']);
        $user = Db::name("bbfx_user")->where("id",$id)->find();
        
        $avatar = $params['avatar'];
        $nickname = $params['nickname'];
        $mobile = $params['mobile'];
        $password = $params['password'];
        $pay_password = $params['pay_password'];
        $region = $params['region'];
        $weixin = $params['weixin'];
        $realname = $params['realname'];
        $username = $params['username'];
        $agent_level = intval($params['agent_level']);
        
        $platform = "H5";
        if(!empty($user)){
            $platform = $user['platform'];
        }
        
        if(empty($user)){
            if((empty($user) || $platform == 'H5' || $platform == 'APP') && (empty($username) && empty($mobile))){
                __error("手机号或登录账号必须设置一个");
            }
        }
        
        if(!empty($mobile)){
            $mobile_user = Db::name("bbfx_user")->where(["uniacid"=>UNIACID,"mobile"=>$mobile])->find();
            if(!empty($mobile_user) && (empty($user) || (!empty($user) && $mobile_user['id'] != $user['id'])) ){
                // __error("该手机号已被使用");
            }
        }
        
        if(empty($password) && empty($user)){
            __error("请输入登录密码"); 
        } 
        
        if(!empty($password) && mb_strlen($password, 'UTF-8') < 6){
            __error("密码长度不足，最低6位字符");
        }
        
        if(!empty($pay_password) && (mb_strlen($pay_password, 'UTF-8') != 6 || !is_numeric($pay_password))){
            __error("请输入6位数字支付密码");
        }
        
         
        if(empty($nickname)){
            if(!empty($mobile)){
                $nickname = secret($mobile,true,3,4);
            }
            else{
                $nickname = "用户".random(8,true);
            }
        }

        if(empty($avatar)){
            $avatar = request()->domain()."/assets/images/avatar.jpg";
        }

        if(!empty($username)){
            $username_user = Db::name("bbfx_user")->where(["uniacid"=>UNIACID,"username"=>$username])->find();
            if(!empty($username_user) && (empty($user) || (!empty($user) && $user['id'] != $username_user['id']))){
                __error("登录账号已存在");
            }
        }

        

        $data = array(
            "uniacid"=>UNIACID,
            "sup_uid"=>intval($params['sup_uid']),
            "avatar"=>$avatar,
            "nickname"=>$nickname,
            "username"=>$username,
            "mobile"=>$mobile,
            "weixin"=>$weixin,
            "realname"=>$realname,
            "upgrade_score"=>max(0,intval($params['upgrade_score'])),
            "team_upgrade_score"=>max(0,intval($params['team_upgrade_score'])),
            "level"=>intval($params['level']),
            "is_distributor"=>intval($params['is_distributor']),
            "distributor_status"=>intval($params['distributor_status']),
            "agent_status"=>intval($params['agent_status']),
            "strikeout_multiple"=>intval($params['strikeout_multiple']),
            "agent_level"=>$agent_level
        );
        if(empty($data['username'])){
            $data['username'] = null;
        }
        
        $data['avatar'] = replaceSiteroot($data['avatar']);
        
        $salt = random(8);
        
        if(empty($user)){
            if($data['sup_uid']){
                $data['bindtime'] = time();
            }
        }
        else{
            // $data['uid'] = $user['uid'];
            if(empty($user['sup_uid']) && $data['sup_uid']){
                $data['bindtime'] = time();
            }
        }
        
        if(!empty($password)){
            $password = md5(md5($password).$salt);
            $data['salt'] = $salt;
            $data['password'] = $password;
        }
        
        if(!empty($pay_password)){
            $data['pay_password'] = md5($pay_password);
        }
        
        $uid = 0;
        $sup_path = "0";
        $o_sup_path = "0";
        if($data['sup_uid'] > 0){
            $sup_user = Db::name("bbfx_user")->where(['id'=>$data['sup_uid']])->find();
            if(!empty($sup_user)){
                $uid = $sup_user['id'];
                $sup_path = $sup_user['sup_path'];
                if(!empty($sup_user['sup_path'])){
                    if(empty($user) || ($user['first_sup_uid'] === 0)){
                        $o_sup_path = $sup_user['o_sup_path'];
                    }
                    
                }
            }
            else{
                __error("推荐人信息错误");
            }
        }
        $success = false;
        try {
            Db::startTrans();

            if(!empty($user)){
                if($data['is_distributor'] == 1 && $data['distributor_status'] == 1){
                    if($user['level'] != $data['level'] || empty($user['upgrade_distributor_time']) || $user['is_distributor'] != 1 || $user['distributor_status'] != 1){
                        $data['upgrade_distributor_time'] = time();
                    }
                    if(empty($user['become_distributor_time'])){
                        $data['become_distributor_time'] = time();
                    }
                }
                if($data['agent_status'] == 1 && $user['agent_status'] != 1){
                    $data['become_agent_time'] = time();
                }
                
                if($data['sup_uid'] > 0){
                    if($data['sup_uid'] == $user['id']){
                        __error("推荐人不能是自己");
                    }

                    if($data['sup_uid'] != $user['sup_uid']){
                        $isSupUser = $this->model->isSupUser($data['sup_uid'],$user['id']);
                        if(empty($isSupUser)){
                            __error("推荐关系存在死循环，请重新选择推荐人");
                        }
                    }
                }

                $data['loginfailure'] = 0;
                
                $res = Db::name("bbfx_user")->where(['id'=>$user['id']])->update($data);
                $user_id = $user['id'];
            }
            else{
                if($data['agent_status'] == 1){
                    $data['become_agent_time'] = time();
                }
                if($data['is_distributor'] == 1 && $data['distributor_status'] == 1){
                    $data['upgrade_distributor_time'] = time();
                    $data['become_distributor_time'] = time();
                }
                $data['platform'] = $platform;
                
                $data['createtime'] = time();
                $data['code'] = random_int(100000,999999);
                $data['id'] = $this->model->uuid();
                $user_id = $data['id'];
                Db::name("bbfx_user")->insert($data);
            }

            if($user_id){
                $success = true;
            }
            else{
                throw new \Exception("操作失败");
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            __error($e->getMessage());
        }

        echo toJsonen(__json(1,"操作成功"));

        bbfx_finish_request();

        if($success){

            $data['id'] = $user_id;
            if(empty($user)){
                $user = [];
            }
            $changed = $this->getChangedData($user,$data);
            \app\admin\model\AdminLog::record("","",$changed,"bbfx_user");

            $sup_path .= "-".$user_id;
            $uudata = ['sup_path'=>$sup_path];
            if($o_sup_path != ''){
                $uudata['o_sup_path'] = $o_sup_path."-".$user_id;
            }
            Db::name("bbfx_user")->where(['id'=>$user_id])->update($uudata);
            if(empty($user) || (!empty($user) && $user['sup_uid'] != $data['sup_uid'])){
                $this->model->initSupPath($user_id,$sup_path);
                if(!empty($uudata['o_sup_path'])){
                    $this->model->initOriginalSupPath($user_id,$uudata['o_sup_path']);
                }
            }
            
            // 升级记录
            $is_up = true;
            $ulevel = $data['level'];
            if(empty($user)){
                if($data['is_distributor'] != 1 || $data['distributor_status'] != 1){
                    $is_up = false;
                }
                $before_level = -1;
                $sup_uid = $data['sup_uid'];
            }
            else{
                if($data['is_distributor'] != 1 || $data['distributor_status'] != 1){
                    $ulevel = -1;
                }
                if($user['is_distributor'] != 1 || $user['distributor_status'] != 1){
                    $before_level = -1;
                }
                else{
                    $before_level = $user['level'];
                }
                $sup_uid = $user['sup_uid'];
            }
            if($is_up){
                FenxiaoUpgrade::addUpgradeRecord(1,$user_id,$ulevel,$before_level,$sup_uid); 
            }
            
            
            if($data['agent_status'] == 1){
            
                $agent_user_log = Db::name("bbfx_agent_log")->where(['uniacid'=>UNIACID,'user_id'=>$user_id])->select();
                $log_oks = [];
                foreach ($region as $key => $val){
                    if(empty($val['province'])){
                        continue;
                    } 
                    if(!empty($val['id'])){
                        $log_oks[$val['id']] = true;
                    }
                }
                if(!empty($agent_user_log)){
                    foreach ($agent_user_log as $key => $val){
                        if(empty($log_oks[$val['id']])){
                            Db::name("bbfx_agent_log")->where(['id'=>$val['id']])->delete();
                        }
                    } 
                } 
                foreach ($region as $key => $val){
                    $agent_params = ['id'=>$val['id']];
                    $agent_params['province'] = $val['province'];
                    $agent_params['city'] = $val['city'];
                    $agent_params['area'] = $val['area'];
                    $agent_params['street'] = $val['street'];
                    
                    $result = \app\common\model\bbfxshop\Agent::setRegion($user_id,$agent_params);
                    if($result['code'] != 1 && $result['code'] != 2){
                        __error($result['message'],['user_id'=>$user_id]);
                    }
                }
            }

            
        }
    }
    
    public function detail(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        $params = $this->param();
        $id = intval($params['id']);
        
        $user = Db::name("bbfx_user")->where("id",$id)->find();
        $where = ['uniacid'=>UNIACID];
        if($base['fenxiao']['ordinary_user_share'] == 1){
            $where['is_distributor'] = 1;
            $where['distributor_status'] = 1;
        }
        if(!empty($user)){
            $where['id'] = ['neq',$user['id']];
        }
        $user_list = Db::name("bbfx_user")->where($where)->field(['id','nickname','mobile','avatar','sup_uid'])->order("id desc")->select();
        if(empty($user_list)){
            $user_list = [];
        }
        foreach ($user_list as $key => &$val){
            $val['nickname'] = "【ID:".$val['id']."】".$val['nickname'];
        }
        unset($val);
        
        
        $result = ['user_list'=>$user_list];
        if(!empty($user)){


            $user['password'] = "";
            $user['pay_password'] = "";
            $user['avatar'] = cdnurl($user['avatar']);

            $agent_user_log = Db::name("bbfx_agent_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'level'=>$user['agent_level']])->select();
            $user['region'] = $agent_user_log;


            $zs_upgrade_score_total = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id = o.id")->where(['o.uniacid'=>UNIACID,'o.user_id'=>$user['id'],'o.status'=>['in',[1,2,3]],'o.refund_status'=>['in',[-1,2]]])->sum("og.upgrade_score");
            $upgrade_score_total = $zs_upgrade_score_total + $user['upgrade_score'];
            $user['upgrade_score_total'] = intval($upgrade_score_total);
            $user['zs_upgrade_score_total'] = intval($zs_upgrade_score_total);

            $alldown = \app\common\model\bbfxshop\FenxiaoUser::getAllDown($user['id']);
            $uids = [];
            if(!empty($alldown['ids'])){
                $uids = $alldown['ids'];
            }

            if($base['fenxiao']['selfbuy_achievement'] == 1){
                $uids[] = $user['id'];
            }
            $where = ['o.uniacid'=>UNIACID,'o.user_id'=>['in',$uids],'o.status'=>['in',[1,2,3]],'o.refund_status'=>['in',[-1,2]]];
            $zs_team_upgrade_score_total = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id = o.id")->where($where)->sum("og.upgrade_score");
            $zs_team_upgrade_score_total = intval($zs_team_upgrade_score_total);
            // $user_upgrade_score = Db::name("bbfx_user")->where(['id'=>['in',$uids]])->sum("upgrade_score");
            $user_upgrade_score = $user['team_upgrade_score'];
            $team_upgrade_score_total = $user_upgrade_score + $zs_team_upgrade_score_total;
            $user['team_upgrade_score_total'] = intval($team_upgrade_score_total);
            $user['zs_team_upgrade_score_total'] = intval($zs_team_upgrade_score_total);

            if(!empty($user['ip_gs'])) $user['ip_gs'] = iunserializer($user['ip_gs']);

            $result['user'] = $user;
        }
        
        __success("操作成功",$result);
    }

    public function info(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        $params = $this->param();
        $id = intval($params['id']);
        
        $user = Db::name("bbfx_user")->where("id",$id)->find();
 
        if(empty($user)){ 
            __error("用户不存在");
        }

        if(!empty($user['ip_gs'])) $user['ip_gs'] = iunserializer($user['ip_gs']);

        $user['createtime'] = date('Y-m-d H:i:s',$user['createtime']);
        $agent_user_log = Db::name("bbfx_agent_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'level'=>$user['agent_level']])->select();
        $user['region'] = $agent_user_log;
        $user['password'] = "";
        $user['pay_password'] = "";
        $user['avatar'] = cdnurl($user['avatar']);
        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'] = "普通用户";
            }
        }
        if(!empty($user['last_login_time'])){
            $user['last_login_time'] = date("Y-m-d H:i:s",$user['last_login_time']);
        }
        else{
            $user['last_login_time'] = "";
        }
        $sup_user = Db::name('bbfx_user')->where(['id'=>$user['sup_uid']])->field("id,nickname,avatar")->find();
        // $sup_user = Db::name('bbfx_user')->where(['id'=>$val['sup_uid'],'is_distributor'=>1,'distributor_status'=>1])->field("id,nickname,avatar")->find();
        if(!empty($sup_user)){
            $sup_user['avatar'] = cdnurl($sup_user['avatar']);
            $user['sup_user'] = $sup_user;
        }
        $CloudWarehouse_set = \app\common\model\bbfxshop\CloudWarehouse::getSet();
    	$cw_goods = [-1];
        if(!empty($CloudWarehouse_set['cw_goods'])){
            $cw_goods = explode(",",(string)$CloudWarehouse_set['cw_goods']);
        }
        $cloud_warehouse_goods = Db::name("bbfx_cloud_warehouse_goods")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'goods_id'=>['in',$cw_goods]])->order("id desc")->select();
        $stock = Db::name("bbfx_cloud_warehouse_goods")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'goods_id'=>['in',$cw_goods]])->order("id desc")->sum("stock");
        $user['cloud_warehouse_stock'] = intval($stock);
        $user['cloud_warehouse_goods'] = $cloud_warehouse_goods;

        $zs_upgrade_score_total = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id = o.id")->where(['o.uniacid'=>UNIACID,'o.user_id'=>$user['id'],'o.status'=>['in',[1,2,3]],'o.refund_status'=>['in',[-1,2]]])->sum("og.upgrade_score");
        
        $upgrade_score_total = $zs_upgrade_score_total + $user['upgrade_score'];

        $user['upgrade_score_total'] = intval($upgrade_score_total);
        $user['zs_upgrade_score_total'] = intval($zs_upgrade_score_total);

        $alldown = \app\common\model\bbfxshop\FenxiaoUser::getAllDown($user['id']);
        $uids = [];
        if(!empty($alldown['ids'])){
            $uids = $alldown['ids'];
        }

        if($base['fenxiao']['selfbuy_achievement'] == 1){
            $uids[] = $user['id'];
        }
        $where = ['o.uniacid'=>UNIACID,'o.user_id'=>['in',$uids],'o.status'=>['in',[1,2,3]],'o.refund_status'=>['in',[-1,2]]];
        $zs_team_upgrade_score_total = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id = o.id")->where($where)->sum("og.upgrade_score");
        $zs_team_upgrade_score_total = intval($zs_team_upgrade_score_total);
        // $user_upgrade_score = Db::name("bbfx_user")->where(['id'=>['in',$uids]])->sum("upgrade_score");
        $user_upgrade_score = $user['team_upgrade_score'];
        $team_upgrade_score_total = $user_upgrade_score + $zs_team_upgrade_score_total;
        $user['team_upgrade_score_total'] = intval($team_upgrade_score_total);
        $user['zs_team_upgrade_score_total'] = intval($zs_team_upgrade_score_total);


        $order_price = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'user_id'=>$user['id']])->sum("price");
        $order_count = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'user_id'=>$user['id']])->count();

        $user['order_price'] = round($order_price,2);
        $user['order_count'] = intval($order_count);
        

        $where = ["a.uniacid"=>UNIACID,'a.user_id'=>$user['id']];
        $coupon_list = Db::name("bbfx_user_coupon")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where($where)->order('a.createtime desc')->field("a.*,b.nickname,b.avatar")->select();
        foreach($coupon_list as $key => &$val){
            $val['createtime'] = date('Y-m-d H:i:s',$val['createtime']);
            $val['avatar'] = cdnurl($val['avatar']);
            if($val['endtime'] > 0){
                $val['endtime'] = date('Y-m-d H:i:s',$val['endtime']);
            }
            else{
                $val['endtime'] = "长期有效";
            }
        }
        unset($val);

        $address_list = Db::name("bbfx_user_address")->where(['uniacid'=>UNIACID,'user_id'=>$user['id']])->order("id desc")->select();
        $txaccount = Db::name("bbfx_user_txaccount")->where(['uniacid'=>UNIACID,'user_id'=>$user['id']])->find();

        $result = [
            'user'=>$user,
            'coupon_list'=>$coupon_list,
            'address_list'=>$address_list,
            'txaccount'=>$txaccount,
        ];
        
        __success("操作成功",$result);
    }
    
    public function delete(){
        $this->commonDelete('bbfx_user');
    }

    public function getShareQrcode(){
        $id = $this->param("id/d");
        $platform = $this->param("platform/s");
        $user = Db::name("bbfx_user")->where("id",$id)->find();
        if(empty($user)){
            __error("用户不存在");
        }
        $page = "pages/index/index";

        if($platform == 'wxapp'){
            $result = \app\common\model\bbfxshop\Weixin::getUnlimitedQRCode("{$page}?sup_uid={$user['id']}", "share_{$user['uniacid']}_".$user['id'],1);
         }
        else{
            $result = \app\common\model\QRcode::create(request()->domain()."/mobile/#/{$page}?sup_uid={$user['id']}&i=".UNIACID,"qrcodeshare_{$user['uniacid']}_".$user['id']);
        }
        if($result['code'] == 1){
            $result['data']['url'] = cdnurl($result['data']['url'],true);
        }
        __result($result);
    }
    
    public function list(){
        global $_W;
        // echo "<pre>";
        // print_r($_W);die;
        $params = $this->param(['page/d','limit/d','keyword/s','startTime/s','endTime/s','type/d','export/d']);
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        
        
        $where = ["uniacid"=>UNIACID];
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $type = max(1,intval($params['type']));
        $export = intval($params['export']);
        if($keyword){
            if($type == 1){
                $where['nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['realname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['mobile'] = ['like',$keyword];
            }
            else if($type == 4){
                $where['id'] = intval($keyword);
            }
            else if($type == 5){
                $uids = \app\common\model\bbfxshop\User::getLevel1UserIds(intval($keyword));
                $where['id'] = ['in',$uids];
            }
        }
        
        $whereTime = [];
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['createtime'] = ['>=',$startTime];
        }
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['createtime'] = ['<=',$endTime];
        }
        if($export == 1){
            $pindex = 1;
            $psize = 999999;
        }
    	$list = Db::name('bbfx_user')->where($where)->where($whereTime)->order("createtime desc")->limit(($pindex - 1) * $psize,$psize)->select();
    	
    	$levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
    	
    	$CloudWarehouse_set = \app\common\model\bbfxshop\CloudWarehouse::getSet();
    	$cw_goods = [-1];
        if(!empty($CloudWarehouse_set['cw_goods'])){
            $cw_goods = explode(",",(string)$CloudWarehouse_set['cw_goods']);
        }
        
        $export_list = [];
    	foreach($list as $key=>&$val){
    	    $val['levelname'] = "普通用户";
    	    if($val['is_distributor'] == 1 && $val['distributor_status'] == 1){
    	        $val['levelname'] = $levels[$val['level']]['title'];
    	    }
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    if(!empty($val['last_login_time'])){
    	        $val['last_login_time'] = date("Y-m-d H:i:s",$val['last_login_time']);
    	    }
    	    else{
    	        $val['last_login_time'] = "";
    	    }
    	    $sup_user = Db::name('bbfx_user')->where(['id'=>$val['sup_uid']])->field("id,nickname,avatar")->find();
    	   // $sup_user = Db::name('bbfx_user')->where(['id'=>$val['sup_uid'],'is_distributor'=>1,'distributor_status'=>1])->field("id,nickname,avatar")->find();
    	    if(!empty($sup_user)){
    	        $sup_user['avatar'] = cdnurl($sup_user['avatar']);
    	        $val['sup_user'] = $sup_user;
    	    }
            
    	    $cloud_warehouse_goods = Db::name("bbfx_cloud_warehouse_goods")->where(['uniacid'=>UNIACID,'user_id'=>$val['id'],'goods_id'=>['in',$cw_goods]])->order("id desc")->select();
    	    $stock = Db::name("bbfx_cloud_warehouse_goods")->where(['uniacid'=>UNIACID,'user_id'=>$val['id'],'goods_id'=>['in',$cw_goods]])->order("id desc")->sum("stock");
            $val['cloud_warehouse_stock'] = intval($stock);
            $val['cloud_warehouse_goods'] = $cloud_warehouse_goods;

            $val['fanhuan_score'] = round(Db::name("bbfx_cumulative_fanhuan_user")->where(['uniacid'=>UNIACID,'type'=>2,'user_id'=>$val['id']])->value("surplus"),2);
            $val['fanhuan_balance'] = round(Db::name("bbfx_cumulative_fanhuan_user")->where(['uniacid'=>UNIACID,'type'=>1,'user_id'=>$val['id']])->value("surplus"),2);
            
            $val['sabonus_part'] = \app\common\model\bbfxshop\Sabonus::getUserAbonusPart($val['id']);
            if($export == 1){
                
                $sup_name = "";
                $sup_uid = "";
                if(!empty($sup_user)){
                    // $sup_name = "【ID:".$sup_user['id']."】".$sup_user['nickname'];
                    $sup_name = $sup_user['nickname'];
                    $sup_uid = $sup_user['id'];
                }

                $openid = '';
                $unionid = '';
                if($val['platform'] == 'wxapp' || $val['platform'] == 'WXAPP' || $val['platform'] == 'GZH'){
                    $openid = $val['openid'];
                    $unionid = $val['unionid'];
                }
                
                
                $export_list[] = [
                    $val['id'],
                    $val['nickname'],
                    $val['realname'],
                    $sup_name,
                    $sup_uid,
                    $val['levelname'],
                    $val['balance'],
                    $val['score'],
                    $val['repurchase_currency'],
                    $val['mobile'],
                    $openid,
                    $unionid,
                    $val['createtime']
                ];
            }
    	}
    	unset($val);
    	if($export == 1){
    	    $headArr = ["ID","昵称","姓名","推荐人","推荐人ID","分销等级","余额","积分","复购金","手机号","微信OpenID","UnionID","注册时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("user-".date("Y-m-d"),$headArr,$export_list);
    	}
    	$total = Db::name('bbfx_user')->where($where)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
      
    }
    
    public function status(){
        
        $params = $this->param(['id/d','status/d']);
        
        $status = 1;
        if($params['status'] != 1){
            $status = 0;
        }
        
    	$res = Db::name("bbfx_user")->where(["id"=>$params['id']])->update(["status"=>$status]);
        if($res){
            __success("操作成功");
        }
        else{
            __error("操作失败");
        }
    }
    
    public function getMoneyLog(){
        $params = $this->param();
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = array("a.uniacid"=>UNIACID,'a.type'=>1);
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $type = max(1,intval($params['type']));
        if($keyword){
            
            if($type == 1){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.realname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['b.mobile'] = $keyword;
            }
            else if($type == 4){
                $where['b.id'] = intval($keyword);
            }
            else if($type == 5){
                $where['a.remarks'] = ['like','%'.$keyword.'%'];
            }
            
        }
        
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        }
        
        $whereTime = [];
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        $export = intval($params['export']);
        if($export == 1){
            $pindex = 1;
            $psize = 999999;
        }
        
        $list = Db::name("bbfx_money_log")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->field('a.*,b.nickname,b.avatar,b.mobile')->order('a.createtime desc,a.id desc')->limit(($pindex-1)*$psize,$psize)->select();
    	foreach($list as $key=>&$val){
    	    if($val['item_type'] == 3){
    	        $info = iunserializer($val['info']);
    	        $val['remarks'] .= "-".$info['notes'];
    	    }
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    $val['money'] = bd_number($val['money']);
    	    $val['befores'] = bd_number($val['befores']);
    	    $val['afters'] = bd_number($val['afters']);
    	    if($export == 1){
    	        $export_list[] = array(
    	            $val['id'],
    	            "【".$val['user_id']."】".$val['nickname'],
    	            $val['money'],
    	            $val['befores'],
    	            $val['afters'],
    	            $val['remarks'],
    	            $val['createtime']
    	        );
    	    }
    	}
    	unset($val);
    	
    	if($export == 1){
    	    $headArr = ["ID","用户信息","变动金额","变动前","变动后","备注","操作时间"];
    	    \app\common\model\PhpOffice::excelExport("money-".date("Y-m-d"),$headArr,$export_list);
    	}
    	
    	$total = Db::name("bbfx_money_log")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function getEepurchaseCurrencyLog(){
        $params = $this->param();
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = array("a.uniacid"=>UNIACID,'a.type'=>4);
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $type = max(1,intval($params['type']));
        if($keyword){
            
            if($type == 1){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.realname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['b.mobile'] = $keyword;
            }
            else if($type == 4){
                $where['b.id'] = intval($keyword);
            }
            else if($type == 5){
                $where['a.remarks'] = ['like','%'.$keyword.'%'];
            }
            
        }
        
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        }
        
        $whereTime = [];
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        
        $export = intval($params['export']);
        if($export == 1){
            $pindex = 1;
            $psize = 999999;
        }
        $list = Db::name("bbfx_money_log")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->field('a.*,b.nickname,b.avatar,b.mobile')->order('a.createtime desc,a.id desc')->limit(($pindex-1)*$psize,$psize)->select();
    	foreach($list as $key=>&$val){
    	    if($val['item_type'] == 3){
    	        $info = iunserializer($val['info']);
    	        $val['remarks'] .= "-".$info['notes'];
    	    }
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    $val['money'] = bd_number($val['money']);
    	    $val['befores'] = bd_number($val['befores']);
    	    $val['afters'] = bd_number($val['afters']);
    	    if($export == 1){
    	        $export_list[] = array(
    	            $val['id'],
    	            "【".$val['user_id']."】".$val['nickname'],
    	            $val['money'],
    	            $val['befores'],
    	            $val['afters'],
    	            $val['remarks'],
    	            $val['createtime']
    	        );
    	    }
    	}
    	unset($val);
    	
    	if($export == 1){
    	    $headArr = ["ID","用户信息","变动金额","变动前","变动后","备注","操作时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("money-".date("Y-m-d"),$headArr,$export_list);
    	}
    	
    	$total = Db::name("bbfx_money_log")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function getScoreLog(){
        $params = $this->param();
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = array("a.uniacid"=>UNIACID,'a.type'=>2);
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $type = max(1,intval($params['type']));
        if($keyword){
            
            if($type == 1){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.realname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['b.mobile'] = $keyword;
            }
            else if($type == 4){
                $where['b.id'] = intval($keyword);
            }
            else if($type == 5){
                $where['a.remarks'] = ['like','%'.$keyword.'%'];
            }
            
        }
        
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        }
        
        $whereTime = [];
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        
        $export = intval($params['export']);
        if($export == 1){
            $pindex = 1;
            $psize = 999999;
        }
        $list = Db::name("bbfx_money_log")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->field('a.*,b.nickname,b.avatar,b.mobile')->order('a.createtime desc,a.id desc')->limit(($pindex-1)*$psize,$psize)->select();
    	foreach($list as $key=>&$val){
    	    if($val['item_type'] == 3){
    	        $info = iunserializer($val['info']);
    	        $val['remarks'] .= "-".$info['notes'];
    	    }
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    $val['money'] = bd_number($val['money']);
    	    $val['befores'] = bd_number($val['befores']);
    	    $val['afters'] = bd_number($val['afters']);
    	    if($export == 1){
    	        $export_list[] = array(
    	            $val['id'],
    	            "【".$val['user_id']."】".$val['nickname'],
    	            $val['money'],
    	            $val['befores'],
    	            $val['afters'],
    	            $val['remarks'],
    	            $val['createtime']
    	        );
    	    }
    	}
    	unset($val);
    	
    	if($export == 1){
    	    $headArr = ["ID","用户信息","变动积分","变动前","变动后","备注","操作时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("money-".date("Y-m-d"),$headArr,$export_list);
    	}
    	
    	$total = Db::name("bbfx_money_log")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->count();
    	__success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function getCommissionLog(){
        $params = $this->param();
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = array("a.uniacid"=>UNIACID);
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $type = max(1,intval($params['type']));
        if($keyword){
            
            if($type == 1){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.realname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['b.mobile'] = $keyword;
            }
            else if($type == 4){
                $where['b.id'] = intval($keyword);
            }
            else if($type == 5){
                $where['a.remarks'] = ['like','%'.$keyword.'%'];
            }
            
        }
        
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        }
        
        $whereTime = [];
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        $export = intval($params['export']);
        if($export == 1){
            $pindex = 1;
            $psize = 999999;
        }
        $list = Db::name("bbfx_fenxiao_commission")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->field('a.*,b.nickname,b.avatar,b.mobile')->order('a.createtime desc,a.id desc')->limit(($pindex-1)*$psize,$psize)->select();
    	foreach($list as $key=>&$val){
    	    $info = iunserializer($val['info']);
    	    if($val['type'] == 0 && !empty($info['notes'])){
    	        $val['remarks'] .= "-".$info['notes'];
    	    }
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    if($export == 1){
    	        $export_list[] = array(
    	            $val['id'],
    	            "【".$val['user_id']."】".$val['nickname'],
    	            $val['money'],
    	            $val['befores'],
    	            $val['afters'],
    	            $val['remarks'],
    	            $val['createtime']
    	        );
    	    }
    	}
    	unset($val);
    	
    	if($export == 1){
    	    $headArr = ["ID","用户信息","变动金额","变动前","变动后","备注","操作时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("commission-".date("Y-m-d"),$headArr,$export_list);
    	}
    	
    	$total = Db::name("bbfx_fenxiao_commission")->alias("a")->join("bbfx_user b","a.user_id = b.id")->where($where)->where($whereTime)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function query(){
        $params = $this->param(['type/d','keyword/s']);
        
        $where = ['uniacid'=>UNIACID];
        if($params['type'] == 2){
            $where['realname'] = $params['keyword'];
        }
        else if($params['type'] == 3){
            $where['id'] = $params['keyword'];
        }
        else{
            $where['mobile'] = $params['keyword'];
        }
        
        $list = Db::name("bbfx_user")->where($where)->field("id,nickname,realname,avatar,mobile")->select();
        if(empty($list)){
            __error("未查询到用户",$where);
        }
        
        foreach ($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
        }
        unset($val);
        
        __success("操作成功",$list);
    }

    public function import(){
        $file = $this->param('file/s');
        if (!$file) {
            __error("请上传文件");
        }
        $filePath = ROOT_PATH . 'public' . replaceSiteroot($file);
        
        if (!is_file($filePath)) {
            __error("未找到文件");
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            __error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                __error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            $fields_key = ['ID'=>'id','昵称'=>'nickname','用户名'=>'username','微信OpenID'=>'openid','UnionID'=>'unionid','手机号'=>'mobile','推荐人ID'=>'sup_uid','分销等级'=>'levelname','余额'=>'balance','佣金'=>'commission_ok','积分'=>'score','会员密码'=>'password','注册时间'=>'createtime'];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = ['title'=>$val,'field'=>$fields_key[$val]];
                }
            }
            // unlink($filePath);
            // print_r($fields);die;
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                
                if(!empty($values)){
                    
                    // 日期转换 \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($values[5])->format('Y-m-d')
                    
                    $item = [];
                    
                    foreach($values as $k => $v){
                        $item[$fields[$k]['field']] = $v;
                    }

                    $insert[] = $item;
                }
                else{
                    $insert[] = [];
                }
            }
        } catch (Exception $exception) {
            __error($exception->getMessage());
        }
        if (!$insert) {
            __error(__('No rows were updated'));
        }
        // unlink($filePath);
        // echo "<pre>";
        // print_r($insert);die;
        
        $log = "";
        $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels();
        $success = 0;
        $user_uids = [];
        $sup_users = Db::name("bbfx_user")->where(['uniacid'=>UNIACID])->field("id,sup_path")->select();
        if(!empty($sup_users)){
            $sup_users = array_skey($sup_users,"id");
        }

        $user_list = [];

        foreach ($insert as $key => $val){
            if(empty($val['id'])){
                $log .= "第".($key+2)."行，ID缺失<br>";
                continue;
            }

            if(empty($val['mobile']) && empty($val['username']) && empty($val['openid'])){
                $log .= "第".($key+2)."行，手机号、登录账号、微信OpenID缺失<br>";
                continue;
            }
            if(empty($val['nickname']) && !empty($val['mobile'])){
                $val['nickname'] = secret($val['mobile'],true,3,4);
            }
            if(empty($val['nickname'])){
                $val['nickname'] = "用户".random(8,true);
            }

            if(!empty($val['mobile'])){
                $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'mobile'=>$val['mobile'],'nickname'=>$val['nickname']])->find();
                if(!empty($user)){
                    $log .= "第".($key+2)."行，手机号和昵称已被其他用户绑定<br>";
                    continue;
                }
            }
            

            if(!empty($val['username'])){
                $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'username'=>$val['username']])->find();
                if(!empty($user)){
                    $log .= "第".($key+2)."行，登录账号已存在<br>";
                    continue;
                }
            }
            else{
                $val['username'] = "8".random(9,true);
            }

            if(!empty($val['openid'])){
                $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'openid'=>$val['openid']])->find();
                if(!empty($user)){
                    $val['openid'] = '';
                    $val['unionid'] = '';
                }
            }

            
            $avatar = request()->domain()."/assets/images/avatar.jpg";

            $id = intval($val['id']);
            if($id <= 0){
                $id = $this->model->uuid();
            }
            else{
                if($id > 999999999){
                    $log .= "第".($key+2)."行，ID不得超出9位数<br>";
                    continue;
                }
            }

            $commission_ok = round($val['commission_ok'],2);
            
            $data = [
                'id'=>$id,
                'uniacid'=>UNIACID,
                'avatar'=>$avatar,
                'nickname'=>$val['nickname'],
                'username'=>$val['username'],
                'mobile'=>$val['mobile'],
                'openid'=>$val['openid'],
                'unionid'=>$val['unionid'],
                'commission_ok'=>$commission_ok,
                'commission_total'=>$commission_ok,
                'balance'=>max(0,round($val['balance'],2)),
                'score'=>max(0,round($val['score'],2)),
                'repurchase_currency'=>max(0,round($val['repurchase_currency'],2)),
                'status'=>1,
                'platform'=>'H5',
                'code'=>random_int(100000,999999),
                'createtime'=>time()
            ];
            
            if(!empty($val['levelname'])){
                foreach($levels as $k => $v){
                    if($v['title'] == $val['levelname']){
                        $data['level'] = $v['id'];
                        $data['is_distributor'] = 1;
                        $data['distributor_status'] = 1;
                        $data['become_distributor_time'] = time();
                        $data['upgrade_distributor_time'] = time();
                    }
                }
            }

            if(!empty($val['password'])){
                $salt = random(8);
                $password = md5(md5($val['password']).$salt);
                $data['salt'] = $salt;
                $data['password'] = $password;
            }

            
            $sup_uid = intval($val['sup_uid']);
            if($sup_uid > 0 && !empty($sup_users[$sup_uid])){
                $data['sup_uid'] = $sup_uid;
                $data['sup_path'] = $sup_users[$sup_uid]['sup_path']."-".$data['id'];
            }
            else{
                $data['sup_path'] = "0-".$data['id'];
                if($sup_uid > 0){
                    $user_list[] = ['id'=>$data['id'],'sup_uid'=>$sup_uid,'sup_path'=>$data['sup_path']];
                }
            }

            $commission_data = array(
                "uniacid"=>UNIACID,
                "user_id"=>$data['id'],
                "money"=>$commission_ok,
                "befores"=>0,
                "afters"=>$commission_ok,
                "remarks"=>"后台充值",
                "type"=>0,
                "createtime"=>time()
            );
            
            
            try {
                Db::startTrans();
                Db::name("bbfx_user")->insert($data);
                $user_uids[$val['id']] = $data['id'];
                $sup_users[$data['id']] = ['id'=>$data['id'],'sup_path'=>$data['sup_path']];
                if($commission_ok > 0){ 
                    Db::name("bbfx_fenxiao_commission")->insert($commission_data);
                }
                Db::commit();
                $success++;
            } catch (Exception $e) {
                Db::rollback();
                $log .= "第".($key+2)."行，导入失败：".$e->getMessage()."<br>";
            }
        }

        if($success > 0){
            
            /*
            foreach ($insert as $key => $val){
                $user_id = intval($user_uids[$val['id']]);
                $oid_sup_uid = intval($val['sup_uid']);
                if($oid_sup_uid > 0){
                    $sup_uid = intval($user_uids[$oid_sup_uid]);
                    if($sup_uid > 0){
                        Db::name("bbfx_user")->where(['id'=>$user_id])->update(['sup_uid'=>$sup_uid]);
                    }
                }
            }

            $this->model->initSupPath();

            */

            // if(!empty($user_list)){
            //     foreach($user_list as $key => $user){
            //         $sup_uid = intval($sup_users[$user['sup_uid']]);
            //         if($sup_uid > 0){
            //             $sup_path = $sup_users[$sup_uid]['sup_path']."-".$user['id'];
            //             Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['sup_uid'=>$sup_uid,'sup_path'=>$sup_path]);
            //         }
            //     }
            // }
            $this->model->initSupPath();
            $this->model->initOriginalSupPath();
        }
        $data = [
            "uniacid"=>UNIACID,
            "type"=>1,
            "content"=>$log,
            "admin_id"=>$this->auth->id,
            "createtime"=>time()
        ];
        
        Db::name("bbfx_import_log")->insert($data);
        // 删除表格
        unlink($filePath);
        
        if($success == 0){
            __error("导入失败",['log_content'=>$log]);
        }
        if(empty($log)){
            $log = '已成功导入：'.$success.'条';
        }

        __success("导入成功",['log_content'=>$log]);
    }
}
