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

namespace app\admin\controller\bbfxshop;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use think\Cache;

class Index extends Base
{
    protected $initConfigFlag = false;

    public function _initialize(){
        parent::_initialize();
    }
    
    public function getStatisticsdays($type=0){
        $params = $this->param();
        
        $activeIndex = intval($params['activeIndex']);
        
        $days = [];
        $days_list = [];
        for($i = 0;$i < 29;$i++){
            $days[] = date("m-d",strtotime("-".(29-$i)." day"));
            $days_list[] = date("Y-m-d",strtotime("-".(29-$i)." day"));
        }
        $days[] = date("m-d");
        $days_list[] = date("Y-m-d");
        
        
        $list = [];
        if($activeIndex == 1){
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'status'=>['>',0],'createtime'=>['<=',strtotime($val." 23:59:59")]])->count();
            }
        }
        else if($activeIndex == 2){
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'createtime'=>['<=',strtotime($val." 23:59:59")]])->count();
            }
        }
        else if($activeIndex == 3){
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'createtime'=>['>=',strtotime($val." 00:00:00")]])->where(['createtime'=>['<=',strtotime($val." 23:59:59")]])->count();
            }
        }
        else if($activeIndex == 4){
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'is_distributor'=>1,'become_distributor_time'=>['<=',strtotime($val." 23:59:59")]])->count();
            }
        }
        else if($activeIndex == 5){
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'is_distributor'=>1,'become_distributor_time'=>['between',[strtotime($val." 00:00:00"),strtotime($val." 23:59:59")]]])->count();
            }
        }
        else if($activeIndex == 6){
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'createtime'=>['>=',strtotime($val." 00:00:00")]])->where(['createtime'=>['<=',strtotime($val." 23:59:59")]])->count();
            } 
        }
        else if($activeIndex == 7){
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'status'=>['>',0],'createtime'=>['>=',strtotime($val." 00:00:00")]])->where(['createtime'=>['<=',strtotime($val." 23:59:59")]])->count();
            }
        }
        else{
            foreach ($days_list as $val) {
                $list[] = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'createtime'=>['<=',strtotime($val." 23:59:59")]])->count();
            }
        }

        $result = ['days'=>$days,'list'=>$list];

        if($type == 1){
            return $result;
        }
        
        __success("操作成功",$result);
    }
    
    public function statistics(){
        $params = $this->param();
        
        $type = intval($params['type']);
        
        $params1 = ['uniacid'=>UNIACID];
        $params2 = $params1;
        $params2['is_pay'] = 1;
        
        $start_time = 0;
        if($type == 1){
            $start_time = strtotime(date("Y-m-d 00:00:00"));
        }
        else if($type == 2){
            $start_time = strtotime(date("Y-m-d 00:00:00")) - 7*86400;
        }
        else if($type == 3){
            $start_time = strtotime(date("Y-m-d 00:00:00")) - 15*86400;
        }
        else if($type == 4){
            $start_time = strtotime(date("Y-m-d 00:00:00")) - 30*86400;
        }
        else if($type == 5){
            $start_time = strtotime(date("Y-m-d 00:00:00")) - 90*86400;
        }
        
        
        $params1['createtime'] = ['>',$start_time];
        $params2['createtime'] = ['>',$start_time];
      	
        $goods_num = Db::name("bbfx_goods")->where($params1)->count();
        $order_num = Db::name("bbfx_order")->where($params2)->count();
        
        $user_num = Db::name("bbfx_user")->where($params1)->count();
        
        $order_price = Db::name("bbfx_order")->where($params2)->sum('price');
        $refund_price = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'refund_status'=>1])->sum('price');
        $order_price -= $refund_price;
        $order_price = max(0,$order_price);
        $order_profit = 0;
        $express_fee = Db::name("bbfx_order")->where($params2)->sum('express_fee');
        $cost_price = Db::name("bbfx_order")->where($params2)->sum('cost_price');
        $order_list = Db::name("bbfx_order")->where($params2)->where(['refund_status'=>['in',[-1,2]]])->field("id,price,cost_price,express_fee,profit_amount")->select();
        if(!empty($order_list)){
            if(empty($order_list)) $order_list = [];
            $oids = array_column($order_list,"id");
            $order_commissions = Db::name("bbfx_fenxiao_order")->alias("a")->join("bbfx_order b","a.order_id=b.id","LEFT")->where(['a.uniacid'=>UNIACID,'a.user_id'=>['>',0],'a.money_type'=>['in',[1,3]],'a.order_id'=>['in',$oids],'a.status'=>['in',[1]]])->group("a.order_id")->field("a.id,a.order_id,sum(a.money) as money")->select();
            $order_commissions = array_skey($order_commissions,"order_id");
            
            foreach ($order_list as $key => $val){
                $order_commission = 0;
                if(!empty($order_commissions[$val['id']])){
                    $order_commission = $order_commissions[$val['id']]['money'];
                }
                if($val['profit_amount'] > 0){
                    $order_profit += $val['profit_amount'];
                }
                else{
                    $order_profit1 = $val['price'] - $val['cost_price'] - $order_commission;
                    $order_profit += max(0,round($order_profit1,2));
                }
            }
            
        }
        
        $today_order_price = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->sum('price');
        $today_profit = $today_order_price;
        
        $total_order_price = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1])->sum('price');
        
        
        $activity_num = Db::name("bbfx_activity_list")->where(['uniacid'=>UNIACID,'status'=>1,'createtime'=>['>',$start_time]])->count();
        $activity_baoming_num = Db::name("bbfx_activity_baoming")->where(['uniacid'=>UNIACID,'is_pay'=>1,'createtime'=>['>',$start_time]])->count();
        
        
        $shop_profit = $total_order_price;
        if($today_profit < 0){
            $today_profit = 0;
        }
        if($shop_profit < 0){
            $shop_profit = 0;
        }
        
        // $today_balance_withdrawal_count = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'withdrawal_type'=>1,'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->count();
        // $today_balance_withdrawal_money = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'withdrawal_type'=>1,'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->sum("money");
        
        // $today_commission_withdrawal_count = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'withdrawal_type'=>2,'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->count();
        // $today_commission_withdrawal_money = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'withdrawal_type'=>2,'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->sum("money");
        
        // $today_score_withdrawal_count = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'withdrawal_type'=>3,'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->count();
        // $today_score_withdrawal_money = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID,'withdrawal_type'=>3,'createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->sum("money");
        
        $todaytime = strtotime(date("Y-m-d 00:00:00"));
        $withdrawal_info = Db::name("bbfx_withdrawal_log")->where(['uniacid'=>UNIACID])
            ->field("
                COUNT(CASE WHEN withdrawal_type = 1 AND createtime > {$todaytime} THEN 1 END) AS today_balance_withdrawal_count,
                SUM(CASE WHEN withdrawal_type = 1 AND createtime > {$todaytime} THEN money ELSE 0 END) AS today_balance_withdrawal_money,
                COUNT(CASE WHEN withdrawal_type = 2 AND createtime > {$todaytime} THEN 1 END) AS today_commission_withdrawal_count,
                SUM(CASE WHEN withdrawal_type = 2 AND createtime > {$todaytime} THEN money ELSE 0 END) AS today_commission_withdrawal_money,
                COUNT(CASE WHEN withdrawal_type = 3 AND createtime > {$todaytime} THEN 1 END) AS today_score_withdrawal_count,
                SUM(CASE WHEN withdrawal_type = 3 AND createtime > {$todaytime} THEN money ELSE 0 END) AS today_score_withdrawal_money
            ")
            ->find();
        $today_balance_withdrawal_count = $withdrawal_info['today_balance_withdrawal_count'];
        $today_balance_withdrawal_money = $withdrawal_info['today_balance_withdrawal_money'];
        $today_commission_withdrawal_count = $withdrawal_info['today_commission_withdrawal_count'];
        $today_commission_withdrawal_money = $withdrawal_info['today_commission_withdrawal_money'];
        $today_score_withdrawal_count = $withdrawal_info['today_score_withdrawal_count'];
        $today_score_withdrawal_money = $withdrawal_info['today_score_withdrawal_money'];
        


        $cumulative_fanhuan_surplus = Db::name("bbfx_cumulative_fanhuan_user")->where(['uniacid'=>UNIACID])->value("surplus");
        $cumulative_fanhuan_total = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'item_type'=>26])->sum("money");

        // $result = $this->getStatisticsdays(1);

        $goods_data = $this->goods();
        $user_data = $this->user();
        $order_data = $this->order();
        
      	$pdata = array(
            // 'days'=>$result['days'],
            // 'list'=>$result['list'],
            'goods_data'=>$goods_data,
            'user_data'=>$user_data,
            'order_data'=>$order_data,
      	    "activity_num"=>intval($activity_num),
      	    "activity_baoming_num"=>intval($activity_baoming_num),
      	    "goods_num"=>intval($goods_num),
      	    "order_num"=>intval($order_num),
      	    "order_price"=>round($order_price,2),
      	    "user_num"=>intval($user_num),
      	    "today_profit"=>round($today_profit,2),
      	    "shop_profit"=>round($shop_profit,2),
      	    "today_balance_withdrawal_count"=>intval($today_balance_withdrawal_count),
      	    "today_balance_withdrawal_money"=>round($today_balance_withdrawal_money,2),
      	    "today_commission_withdrawal_count"=>intval($today_commission_withdrawal_count),
      	    "today_commission_withdrawal_money"=>round($today_commission_withdrawal_money,2),
      	    "today_score_withdrawal_count"=>intval($today_score_withdrawal_count),
      	    "today_score_withdrawal_money"=>round($today_score_withdrawal_money,2),
      	    "cumulative_fanhuan_surplus"=>round($cumulative_fanhuan_surplus,2),
      	    "cumulative_fanhuan_total"=>round($cumulative_fanhuan_total,2),
      	    "refund_price"=>round($refund_price,2),
      	    "order_profit"=>round($order_profit,2),
      	 );
      	 
      	 __success('操作成功',$pdata);
    }

    protected function goods(){
        
        $params = $this->param(['sdate/s','edate/s','goods_id/d']);
        $stime = strtotime(date("Y-m-d 00:00:00")." -29 day");
        $etime = strtotime(date("Y-m-d 23:59:59"));
        if(!empty($params['sdate'])){ 
            $stime = strtotime($params['sdate']." 00:00:00");
        }
        if(!empty($params['edate'])){
            $etime = strtotime($params['edate']." 23:59:59");
        }
         
        $goods_where = ['>',0];
        if($params['goods_id'] > 0){
            $goods_where = $params['goods_id'];
        }
        // print_r(date('Y-m-d H:i:s',$stime)."----".date('Y-m-d H:i:s',$etime));die;
        // 浏览数
        $where = ['a.uniacid'=>UNIACID,'a.type'=>0,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where];
        $browse_list = Db::name("bbfx_goods_log")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->where($where)->order("a.createtime asc")->field("a.id,a.createtime")->select();
        $browse_num = count($browse_list);
        // 访问数
        $where = ['a.uniacid'=>UNIACID,'a.type'=>1,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where];
        $visitor_list = Db::name("bbfx_goods_log")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->where($where)->group("a.user_id,a.utk")->order("a.createtime asc")->field("a.id,a.createtime")->select();
        $visitor_num = count($visitor_list);

        // 浏览数
        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where];
        $collection_list = Db::name("bbfx_goods_collection")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->where($where)->order("a.createtime asc")->field("a.id,a.createtime")->select();
        $collection_num = count($collection_list);
        
        // 下单数
        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where];
        $order_goods_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->where($where)->sum("a.total");
        // 支付数
        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where,'c.is_pay'=>1];
        $pay_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->sum("a.total");
        // 订单总金额（包含未支付，已退款）
        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where];
        $order_list = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->field("a.id,a.price,a.createtime")->order("a.createtime asc")->select();
        $order_price = 0;
        foreach ($order_list as $val){
            $order_price += $val['price'];
        }
        // 订单成交金额（已支付金额-退款金额）
        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where,'c.is_pay'=>1];
        $pay_list = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>['in',[-1,0,2]]])->field("a.id,a.price,a.createtime")->order("a.createtime asc")->select();
        $pay_price = 0;
        foreach ($pay_list as $val){
            $pay_price += $val['price'];
        }
        // 成本金额
        $cost_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->sum("a.cost_price");
        // 退款金额
        $refund_list = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->field("a.id,a.price,a.createtime")->order("a.createtime asc")->select();
        $refund_price = 0;
        foreach ($refund_list as $val){
            $refund_price += $val['price'];
        }
        // 退款数量
        $refund_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->sum("a.total");
        // 支付转化率
        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where,'c.is_pay'=>1];
        $pay_user_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->group("c.user_id")->count();
        $pay_rate = 0;
        $visitor_num1 = $visitor_num;
        if($visitor_num <= $pay_user_num){
            $visitor_num1 = $pay_user_num;
        }
        if($visitor_num1 > 0){
            $pay_rate = round($pay_user_num / $visitor_num1,2) * 100;
        }
        

        $result = [
            'browse_num'=>intval($browse_num),
            'visitor_num'=>intval($visitor_num),
            'order_goods_num'=>intval($order_goods_num),
            'collection_num'=>intval($collection_num),
            'pay_num'=>intval($pay_num),
            'refund_num'=>intval($refund_num),
            'cost_price'=>round($cost_price,2),
            'order_price'=>round($order_price,2),
            'pay_price'=>round($pay_price,2),
            'pay_rate'=>round($pay_rate,2),
            'refund_price'=>round($refund_price,2),
        ];

        $list = [];
        $time = $stime;
        while(true){
            $st = $time;
            $et = strtotime(date('Y-m-d 23:59:59',$time));

            // $where = ['a.uniacid'=>UNIACID,'a.type'=>0,'a.createtime'=>['between',[$st,$et]],'b.id'=>$goods_where];
            // $browse_num = Db::name("bbfx_goods_log")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->where($where)->count();
            $browse_num = 0;
            $datas = [];
            foreach ($browse_list as $key => $val){
                if($st < $val['createtime'] && $et >= $val['createtime']){
                    $browse_num++;
                }
                if($val['createtime'] > $et){
                    $datas[] = $val;
                }
            }
            $browse_list = $datas;

            // $where = ['a.uniacid'=>UNIACID,'a.type'=>1,'a.createtime'=>['between',[$st,$et]],'b.id'=>$goods_where];
            // $visitor_num = Db::name("bbfx_goods_log")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->where($where)->group("a.user_id,a.utk")->count();
            $visitor_num = 0;
            $datas = [];
            foreach ($visitor_list as $key => $val){
                if($st < $val['createtime'] && $et >= $val['createtime']){
                    $visitor_num++;
                }
                if($val['createtime'] > $et){
                    $datas[] = $val;
                }
            }
            $visitor_list = $datas;
            
            // GMV、订单总金额（包含未支付，已退款）
            // $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$st,$et]],'b.id'=>$goods_where];
            // $order_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->sum("a.price");
            $order_price = 0;
            $datas = [];
            foreach ($order_list as $key => $val){
                if($st < $val['createtime'] && $et >= $val['createtime']){
                    $order_price += $val['price'];
                }
                if($val['createtime'] > $et){
                    $datas[] = $val;
                }
            }
            $order_list = $datas;
            
            // GMV（净）、支付金额（已支付金额-退款金额）
            // $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$st,$et]],'b.id'=>$goods_where,'c.is_pay'=>1];
            // $pay_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>['in',[-1,0,2]]])->sum("a.price");
            $pay_price = 0;
            $datas = [];
            foreach ($pay_list as $key => $val){
                if($st < $val['createtime'] && $et >= $val['createtime']){
                    $pay_price += $val['price'];
                }
                if($val['createtime'] > $et){
                    $datas[] = $val;
                }
            }
            $pay_list = $datas;
            
            // 退款金额
            // $refund_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->sum("a.price");
            $refund_price = 0;
            $datas = [];
            foreach ($refund_list as $key => $val){
                if($st < $val['createtime'] && $et >= $val['createtime']){
                    $refund_price += $val['price'];
                }
                if($val['createtime'] > $et){
                    $datas[] = $val;
                }
            }
            $refund_list = $datas;
            
            $list[] = [
                'date'=>date('m-d',$time),
                'browse_num'=>intval($browse_num),
                'visitor_num'=>intval($visitor_num),
                'pay_price'=>round($pay_price,2),
                'order_price'=>round($order_price,2),
                'refund_price'=>round($refund_price,2)
            ];

            $time = strtotime(date('Y-m-d 00:00:00',$time)." +1 day");
            
            if($time > $etime){
                break;
            }
            
        }

        $result['list'] = $list;

        return $result;
    }

    protected function user(){
        $params = $this->param(['sdate/s','edate/s','platform/s']);
        $stime = strtotime(date("Y-m-d 00:00:00")." -29 day");
        $etime = strtotime(date("Y-m-d 23:59:59"));
        if(!empty($params['sdate'])){ 
            $stime = strtotime($params['sdate']." 00:00:00");
        }
        if(!empty($params['edate'])){
            $etime = strtotime($params['edate']." 23:59:59");
        }

        $platform = ['in',['wxapp','WXAPP','H5','GZH','APP','PC']];
        if(!empty($params['platform'])){
            $platform = $params['platform'];
        }

        // 访客数
        $visitor_num = Db::name("bbfx_user_log")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$stime,$etime]],'platform'=>$platform])->group("user_id,utk")->count();
        // 用户数
        $user_num = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$stime,$etime]],'platform'=>$platform])->count();
        // 成交用户数
        $order_user_num = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$stime,$etime]],'is_pay'=>1,'platform'=>$platform])->group("user_id")->count();
        // 支付转化率
        $pay_rate = 0;
        $visitor_num1 = $visitor_num;
        if($order_user_num > $visitor_num){
            $visitor_num1 = $order_user_num;
        }
        if($visitor_num1 > 0){
            $pay_rate = round($order_user_num / $visitor_num1,2) * 100;
        }
        // 分销商用户数
        $fenxiao_user_num = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'platform'=>$platform,'become_distributor_time'=>['between',[$stime,$etime]],'is_distributor'=>1,'distributor_status'=>1])->count();
        // 充值用户数
        $recharge_user_num = Db::name("bbfx_recharge_order")->where(['uniacid'=>UNIACID,'platform'=>$platform,'createtime'=>['between',[$stime,$etime]],'is_pay'=>1])->group("user_id")->count();
        // 累计用户数
        $user_total = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'platform'=>$platform])->count();
        // 累计分销商用户数
        $fenxiao_user_total = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'platform'=>$platform,'is_distributor'=>1,'distributor_status'=>1])->count();
        // 累计充值用户数
        $recharge_user_total = Db::name("bbfx_recharge_order")->where(['uniacid'=>UNIACID,'platform'=>$platform,'is_pay'=>1])->group("user_id")->count();
        // 累计成交用户数
        $order_user_total = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'platform'=>$platform])->group("user_id")->count();
        // 访客总数
        // $visitor_total = Db::name("bbfx_user_log")->where(['uniacid'=>UNIACID,'platform'=>$platform])->group("user_id,utk")->count();
        $visitor_total_sql = Db::name('bbfx_user_log')->where(['uniacid'=>UNIACID,'platform'=>$platform])->field('DISTINCT user_id,utk')->buildSql();
        // 嵌套子查询统计数量
        $visitor_total = Db::table($visitor_total_sql.' a')->count();

        $result = [
            'visitor_num'=>intval($visitor_num),
            'user_num'=>intval($user_num),
            'order_user_num'=>intval($order_user_num),
            'pay_rate'=>round($pay_rate,2),
            'fenxiao_user_num'=>intval($fenxiao_user_num),
            'recharge_user_num'=>intval($recharge_user_num),
            'user_total'=>intval($user_total),
            'fenxiao_user_total'=>intval($fenxiao_user_total),
            'recharge_user_total'=>intval($recharge_user_total),
            'order_user_total'=>intval($order_user_total),
            'visitor_total'=>intval($visitor_total)
        ];

        $visitor_num_list = Db::name("bbfx_user_log")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$stime,$etime]],'platform'=>$platform])->group("user_id,utk")->field("createtime")->select();
        $user_num_list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$stime,$etime]],'platform'=>$platform])->field("createtime")->select();
        $order_user_num_list = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$stime,$etime]],'is_pay'=>1,'platform'=>$platform])->group("user_id")->field("createtime")->select();
        $fenxiao_user_num_list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'become_distributor_time'=>['between',[$stime,$etime]],'platform'=>$platform,'is_distributor'=>1,'distributor_status'=>1])->field("createtime")->select();
        $recharge_user_nums_list = Db::name("bbfx_recharge_order")->where(['uniacid'=>UNIACID,'platform'=>$platform,'createtime'=>['between',[$stime,$etime]],'is_pay'=>1])->group("user_id")->field("createtime")->select();
        $visitor_nums = [];
        $user_nums = [];
        $order_user_nums = [];
        $fenxiao_user_nums = [];
        $recharge_user_nums = [];
        foreach($visitor_num_list as $val){
            $date = date('Y-m-d',$val['createtime']);
            if(empty($visitor_nums[$date])) $visitor_nums[$date] = 0;
            $visitor_nums[$date]++;
        }
        foreach($user_num_list as $val){
            $date = date('Y-m-d',$val['createtime']);
            if(empty($user_nums[$date])) $user_nums[$date] = 0;
            $user_nums[$date]++;
        }
        foreach($order_user_num_list as $val){
            $date = date('Y-m-d',$val['createtime']);
            if(empty($order_user_nums[$date])) $order_user_nums[$date] = 0;
            $order_user_nums[$date]++;
        }
        foreach($fenxiao_user_num_list as $val){
            $date = date('Y-m-d',$val['createtime']);
            if(empty($fenxiao_user_nums[$date])) $fenxiao_user_nums[$date] = 0;
            $fenxiao_user_nums[$date]++;
        }
        foreach($recharge_user_nums_list as $val){
            $date = date('Y-m-d',$val['createtime']);
            if(empty($recharge_user_nums[$date])) $recharge_user_nums[$date] = 0;
            $recharge_user_nums[$date]++;
        }
        
        $list = [];
        $time = $stime;
        while(true){
            $st = $time;
            $et = strtotime(date('Y-m-d 23:59:59',$time));
            $date = date('Y-m-d',$time);
            // 访客数
            // $visitor_num = Db::name("bbfx_user_log")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$st,$et]],'platform'=>$platform])->group("user_id,utk")->count();
            // 用户数
            // $user_num = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$st,$et]],'platform'=>$platform])->count();
            // 成交用户数
            // $order_user_num = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$st,$et]],'is_pay'=>1,'platform'=>$platform])->group("user_id")->count();
            // 分销商用户数
            // $fenxiao_user_num = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'become_distributor_time'=>['between',[$st,$et]],'platform'=>$platform,'is_distributor'=>1,'distributor_status'=>1])->count();
            // 充值用户数
            // $recharge_user_num = Db::name("bbfx_recharge_order")->where(['uniacid'=>UNIACID,'platform'=>$platform,'createtime'=>['between',[$st,$et]],'is_pay'=>1])->group("user_id")->count();
            
            $visitor_num = intval($visitor_nums[$date]);
            $user_num = intval($user_nums[$date]);
            $order_user_num = intval($order_user_nums[$date]);
            $fenxiao_user_num = intval($fenxiao_user_nums[$date]);
            $recharge_user_num = intval($recharge_user_nums[$date]);
            
            $list[] = [
                'date'=>date('m-d',$time),
                'visitor_num'=>intval($visitor_num),
                'user_num'=>intval($user_num),
                'order_user_num'=>intval($order_user_num),
                'fenxiao_user_num'=>intval($fenxiao_user_num),
                'recharge_user_num'=>intval($recharge_user_num),
            ];

            $time = strtotime(date('Y-m-d 00:00:00',$time)." +1 day");
            
            if($time > $etime){
                break;
            }
            
        }
        
        $result['list'] = $list;
        
        return $result;
    }

    protected function order(){
        $params = $this->param(['sdate/s','edate/s','goods_id/d','type/d']);
        $stime = strtotime(date("Y-m-d 00:00:00")." -29 day");
        $etime = strtotime(date("Y-m-d 23:59:59"));
        if(!empty($params['sdate'])){ 
            $stime = strtotime($params['sdate']." 00:00:00");
        }
        if(!empty($params['edate'])){
            $etime = strtotime($params['edate']." 23:59:59");
        }
        // $type = $params['type'];
        // if($type == 1){
        //     $stime = strtotime(date("Y-m-d 00:00:00"));
        //     $etime = strtotime(date("Y-m-d 23:59:59"));
        // }
        // else if($type == 2){
        //     $stime = strtotime(date("Y-m-d 00:00:00")." -1 day");
        //     $etime = strtotime(date("Y-m-d 23:59:59",$stime));
        // }
        // else if($type == 3){
        //     $stime = strtotime(date("Y-m-d 00:00:00")." -6 day");
        //     $etime = strtotime(date("Y-m-d 23:59:59"));
        // }
        // else if($type == 4){
        //     $stime = strtotime(date("Y-m-d 00:00:00")." -29 day");
        //     $etime = strtotime(date("Y-m-d 23:59:59"));
        // }
        // else if($type == 5){
        //     $stime = strtotime(date("Y-m-01 00:00:00"));
        //     $etime = strtotime(date("Y-m-d 23:59:59"));
        // }
        // else if($type == 6){
        //     $stime = strtotime(date("Y-01-01 00:00:00"));
        //     $etime = strtotime(date("Y-m-d 23:59:59"));
        // }
         
        $goods_where = ['>',0];
        if($params['goods_id'] > 0){
            $goods_where = $params['goods_id'];
        }

        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where,'c.is_pay'=>1];
        $order_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->group("a.order_id")->count();
        $order_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->sum("a.price");
        $refund_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->group("a.order_id")->count();
        $refund_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->sum("a.price");
        

        $order_platform = [
            ['title'=>'小程序','value'=>['wxapp','WXAPP']],
            ['title'=>'H5','value'=>['H5']],
            ['title'=>'公众号','value'=>['GZH']],
            ['title'=>'APP','value'=>['APP']],
            ['title'=>'PC','value'=>['PC']],
        ];
        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where,'c.is_pay'=>1];
        foreach($order_platform  as $key => &$val){
            $where['c.platform'] = ['in',$val['value']];
            $price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->sum("a.price");
            $val['price'] = round($price,2);
            $val['rate'] = 0;
            if($order_price > 0){
                $val['rate'] = round($price / $order_price,2) * 100;
            }
            
        }
        unset($val);

        $pay_plugin = \app\common\model\bbfxshop\Plugin::getPayPlugin();
        
        $order_source = [
            ['title'=>'普通订单','value'=>0],
            ['title'=>'后台录单','value'=>7],
        ];
        if(in_array('seckill',$pay_plugin)){
            $order_source[] = ['title'=>'秒杀订单','value'=>1];
        }
        if(in_array('cloud_warehouse',$pay_plugin)){
            $order_source[] = ['title'=>'云仓提货订单','value'=>2];
            $order_source[] = ['title'=>'云仓进货订单','value'=>8];
        }
        if(in_array('pintuan',$pay_plugin)){
            $order_source[] = ['title'=>'拼团订单','value'=>3];
        }
        if(in_array('crazy',$pay_plugin)){
            $order_source[] = ['title'=>'疯狂卖货模式复购单','value'=>4];
        }
        if(in_array('super_maihuo',$pay_plugin)){
            $order_source[] = ['title'=>'超级卖货模式复购单','value'=>5];
        }
        if(in_array('gift',$pay_plugin)){
            $order_source[] = ['title'=>'礼品订单','value'=>6];
        }

        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where,'c.is_pay'=>1];
        foreach($order_source  as $key => &$val){
            $where['c.order_source'] = $val['value'];
            $price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->sum("a.price");
            $val['price'] = round($price,2);
            $val['rate'] = 0;
            if($order_price > 0){
                $val['rate'] = round($price / $order_price,2) * 100;
            }
        }
        unset($val);
        
        // 成交用户数
        $order_user_num = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'createtime'=>['between',[$stime,$etime]],'is_pay'=>1])->group("user_id")->count();
        // 累计用户数
        $user_total = Db::name("bbfx_user")->where(['uniacid'=>UNIACID])->count();
        $pay_rate = 0;
        if($user_total > 0){
            $pay_rate = round($order_user_num / $user_total,2) * 100;
        }
        
        
        $result = [
            'order_num'=>intval($order_num),
            'refund_num'=>intval($refund_num),
            'order_price'=>round($order_price,2),
            'refund_price'=>round($refund_price,2),
            'order_platform'=>$order_platform,
            'order_source'=>$order_source,
            'pay_rate'=>round($pay_rate,2),
        ];

        $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$stime,$etime]],'b.id'=>$goods_where,'c.is_pay'=>1];
        $order_list = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->group("a.order_id")->field("a.id,sum(a.price) as price,a.createtime")->order("a.createtime asc")->select();
        $refund_list = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->group("a.order_id")->field("a.id,sum(a.price) as price,a.createtime")->order("a.createtime asc")->select();
        
        $list = [];
        $time = $stime;
        while(true){
            $st = $time;
            $et = strtotime(date('Y-m-d 23:59:59',$time));

            // $where = ['a.uniacid'=>UNIACID,'a.createtime'=>['between',[$st,$et]],'b.id'=>$goods_where,'c.is_pay'=>1];
            // $order_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->group("a.order_id")->count();
            // $order_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->sum("a.price");
            // $refund_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->group("a.order_id")->count();
            // $refund_price = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id","LEFT")->join("bbfx_order c","a.order_id=c.id","LEFT")->where($where)->where(['c.refund_status'=>1])->sum("a.price");
            
            $order_num = 0;
            $order_price = 0;
            foreach ($order_list as $val){
                if($val['createtime'] >= $st && $val['createtime'] < $et){
                    $order_num++;
                    $order_price += $val['price'];
                }
                if($val['createtime'] > $et){
                    break;
                }
            }
            $refund_num = 0;
            $refund_price = 0;
            foreach ($refund_list as $val){
                if($val['createtime'] >= $st && $val['createtime'] < $et){
                    $refund_num++;
                    $refund_price += $val['price'];
                }
                if($val['createtime'] > $et){
                    break;
                }
            }

            $list[] = [
                'date'=>date('m-d',$time),
                'order_num'=>intval($order_num),
                'refund_num'=>intval($refund_num),
                'order_price'=>round($order_price,2),
                'refund_price'=>round($refund_price,2)
            ];

            $time = strtotime(date('Y-m-d 00:00:00',$time)." +1 day");
            
            if($time > $etime){
                break;
            }
            
        }

        $result['list'] = $list;

        return $result;
    }
}