<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\GoodSku;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Models\User;
use App\Models\Store;
use App\Models\Order;
use App\Models\Goods;
use App\Models\DwbsUser;
use App\Models\DwbsWarea;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class IndexController extends Controller
{
    //获取首页信息
    public function index()
    {
        $user_count = User::whereNotNull('openId')->orWhereNotNull('phone')->count();
        $store_count = Store::where('is_apply', 3)->count();
        $goods_count = Goods::where('is_shelves', 1)->count();
        $order_sale = Order::where('is_pay', 1)->sum('account');
        $refund_no_auth = OrderRefund::where('status', 0)->count();
        $list['user_count'] = $user_count;
        $list['store_count'] = $store_count;
        $list['goods_count'] = $goods_count;
        $list['order_sale'] = $order_sale;
        $list['refund_no_auth'] = $refund_no_auth;

        $list['expire']=date("YmdHis",strtotime('+120 second'));
        $list['ccc']=Order::where('apply_cancel',2)->whereColumn('cancel_at','<','pay_at')->get();
        return $this->success($list);
    }

    //支付比例
    public function getAgentPayRate(Request  $request)
    {
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
//        $store_ids = Order::where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->pluck('store_id');
        $total=Store::where('status', 0)->where('is_test','0')->whereHas('order',function($query){
            $query->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1]);
        })->count();
        $stores = Store::where('status', 0)->where('is_test','0')->whereHas('order',function($query){
            $query->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1]);
        })->select('id', 'user_id','name','phone')->orderBy('id')->skip($num)->take($page_size)->get();
        foreach ($stores as $key => $val) {
//            $stores[$key]->total = Order::where('store_id', $val->id)->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->sum('total');
            $stores[$key]->pay_total = Order::where('store_id', $val->id)->where('self_pay',0)->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->sum('total');
            $stores[$key]->no_self_pay_total = Order::where('store_id', $val->id)->where('self_pay', 1)->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->sum('total');
//            $stores[$key]->agent = DwbsUser::where('id', $val->user_id)->select('nickname', 'mobile')->first();
        }
        return $this->success_list($stores,'',$total);
    }

    //总销量排名
    public function getSaleOrderByAll(Request $request)
    {
        $page_index = $request->input('page_index');
        $page_size = $request->input('page_size');
        $num = $page_size * ($page_index - 1);
        $search_name = $request->input('search_name');
        $startime = $request->input('startime');
        $endtime = $request->input('endtime');
        $sort = $request->input('sort');
        $desc = $request->input('desc');
        $admin_id = Auth::user()->id;
        $admin = Admin::where('id', $admin_id)->first();
        $store_where=[];
        if($admin){
            if (!in_array($admin->role_id, [22, 24])) {
                $warea_ids = DwbsWarea::where('admin_id', $admin_id)->pluck('id');
                $store_where[]=[function($query)use($warea_ids){
                    $query->whereIn('warea_id',$warea_ids);
                }];
            }
        }

        if ($search_name) {
            $store_where[]=[function($query)use($search_name){
                $query->where('name', 'like', '%' . $search_name . '%')
                    ->orWhere('phone', 'like', '%' . $search_name . '%');
            }];
        }
        $where=[];
        if ($startime && $endtime) {
            $where=function($query)use($startime, $endtime){
                $query->whereBetween('created_at', [$startime, $endtime]);
            };
        }

        $data = Order::where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->where($where);
        $data->whereHas('store',function($query)use($store_where){
            $query->where($store_where);
        });
        Log::info('2---'.microtime());
        $data1 = clone $data;
        $order = $data->with([
            'store'=>function($query){
                $query->select('id','name','img','phone','province','city','area','user_id');
            }])
            ->groupBy('store_id')
            ->select('store_id',DB::raw('ifnull(sum(total),0) as total'), DB::raw('ifnull(sum(account),0) as account'));
//        $list = $data->orderBy($sort,'desc')->orderBy('store_id')->skip($num)->limit($page_size)->get();
        Log::info('2-1-0-'.microtime());
        $count = $order->get()->count();
        if($desc==1){
            $desc='asc';
        }else{
            $desc='desc';
        }
        $list = $order->orderBy($sort,$desc)->orderBy('store_id')->skip($num)->limit($page_size)->get();
        Log::info('3---'.microtime());
        $account_num = $data1->select(DB::raw('sum(account) as account'),DB::raw('sum(total) as num'))->first();
        $all['all_account'] = $account_num->account;
        $all['all_num'] = $account_num->num;
        Log::info('3.1---'.microtime());
        $num_data = OrderDetail::whereHas('order',function($query){
            $query->where('is_pay',1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1]);
        });
        if($store_where) {
            $num_data->whereHas('store', function ($query) use ($store_where) {
                $query->where($store_where);
            });
        }
        $nums = $num_data->where($where)->groupBy('goods_id')->select(DB::raw('sum(num) as num'),'goods_id')->pluck('num','goods_id')->toArray();

        $all['hard_num'] =array_key_exists(1,$nums)?$nums[1]:null;
        $all['simple_num'] = array_key_exists(2,$nums)?$nums[2]:null;
        $all['old_num'] = array_key_exists(3,$nums)?$nums[3]:null;
        $all['cotton_num'] = array_key_exists(4,$nums)?$nums[4]:null;
        $all['young_num'] = array_key_exists(25,$nums)?$nums[25]:null;
        Log::info('4---'.microtime());
        foreach ($list as $key => $val) {
            if($val->total==0 && $val->account==0){
                $list[$key]->goods =[];
            }else{
                $list[$key]->goods = OrderDetail::with('goods:id,name,main_attr')
                    ->where('store_id', $val->store_id)->where($where)
                    ->whereHas('order',function($query)use($where){
                        $query->has('store')->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->where($where);
                    })
                    ->groupBy('goods_id')
                    ->select('goods_id', DB::raw('ifnull(sum(num),0) as num'), DB::raw('ifnull(sum(account),0) as account'))->get();
            }
        }
        Log::info('6---'.microtime());
        $all['list'] = $list;
//        $all['num'] = $nums;
        return $this->success_list($all, '', $count);
    }

    //总销量排名
    public function exportSaleOrderByAll(Request $request)
    {
        return $this->success([]);
    }

    //获取昨日销量排名
    public function yesterdayOrderBy(Request  $request)
    {
        $page_index=$request->input('page_index')??1;
        $page_size=$request->input('page_size')??20;
        $num=$page_size*($page_index-1);
        $data['super_info'] = $this->orderDetail(1,$num,$page_size);
        $data['simple_info'] = $this->orderDetail(2,$num,$page_size);
        $data['old_info'] = $this->orderDetail(3,$num,$page_size);
        $data['cotton_info'] = $this->orderDetail(4,$num,$page_size);
        return $this->success($data);
    }

    public function orderDetail($id,$num,$index)
    {
        $date = date("Y-m-d", strtotime('-1 days'));
        $order_nos = Order::has('store')->where('is_pay', 1)
            ->whereDate('created_at', $date)
            ->whereIn('apply_cancel', [0, 1, 3])
            ->whereIn('is_refund', [0, 1])->pluck('order_no');
        $stores=Order::has('store')->where('is_pay', 1)
            ->whereDate('created_at', $date)
            ->whereIn('apply_cancel', [0, 1, 3])
            ->whereIn('is_refund', [0, 1])->pluck('store_id');
        $count = $order_details = Store::where('status', 0)->where('is_apply', 3)->whereIn('store_id',$stores)
            ->leftJoin('order_detail as od', function ($query) use ($order_nos, $id) {
                $query->on('od.store_id', '=', 'store.id')
                    ->whereIn('od.order_no', $order_nos)
                    ->where('od.goods_id',$id);
            })->groupBy('store.id')->get()->count();
        $order_details = Store::where('status', 0)->where('is_apply', 3)->whereIn('store_id',$stores)
            ->leftJoin('order_detail as od', function ($query) use ($order_nos, $id) {
                $query->on('od.store_id', '=', 'store.id')
                    ->whereIn('od.order_no', $order_nos)
                    ->where('od.goods_id',$id);
            })
            ->groupBy('store.id')
            ->select('store.id as store_id', 'store.name', 'store.phone', 'store.img', DB::raw('ifnull(sum(num),0) as total'), DB::raw('ifnull(sum(store.account),0) as accounts'))
            ->orderByDesc('total')
            ->orderByDesc('accounts')
            ->orderBy('store.id')
            ->skip($num)->limit($index)
            ->get();
        $data['total']=$count;
        $data['list']=$order_details;
        return $data;
    }

    //总销售数据排名
    public function allOrderBy(Request  $request)
    {
        $page_index=$request->input('page_index')??1;
        $page_size=$request->input('page_size')??20;
        $num=$page_size*($page_index-1);
        $count =  Order::query()->whereHas('store')
            ->with(['store:id,name,phone,img'])
            ->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])
            ->groupBy('store_id')
            ->get()->count();
        $order = Order::query()->whereHas('store')
            ->with(['store:id,name,phone,img'])
            ->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])
            ->select('store_id',DB::raw('ifnull(sum(total),0) as total'), DB::raw('ifnull(sum(account),0) as account'))
            ->groupBy('store_id')
            ->orderByDesc('total')
            ->orderByDesc('account')
            ->skip($num)->limit($page_size)
            ->get();
        return $this->success_list($order,'',$count);
    }

    //各款式每日销量变化曲线图
    public function getSaleInfo(Request $request)
    {
        if ($request->input('startdate') && $request->input('enddate')) {
            $startdate = $request->input('startdate');
            $enddate = $request->input('enddate');
        } else {
            $startdate = date("Y-m-d", strtotime('-7 days'));
            $enddate = date("Y-m-d");
        }
        $dates = $this->getDateFromRange($startdate, $enddate);
        $list = [];
        foreach ($dates as $key => $val) {
            $order_nos = Order::whereDate('created_at', $val)->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->pluck('order_no');
            $list['super'][$val] = OrderDetail::whereIn('order_no', $order_nos)->where('goods_id', 1)
                ->select(DB::raw('ifnull(sum(num),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        }
        foreach ($dates as $key => $val) {
            $order_nos = Order::whereDate('created_at', $val)->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->pluck('order_no');
            $list['simple'][$val] = OrderDetail::whereIn('order_no', $order_nos)->where('goods_id', 2)
                ->select(DB::raw('ifnull(sum(num),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        }
        foreach ($dates as $key => $val) {
            $order_nos = Order::whereDate('created_at', $val)->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->pluck('order_no');
            $list['old'][$val] = OrderDetail::whereIn('order_no', $order_nos)->where('goods_id', 3)
                ->select(DB::raw('ifnull(sum(num),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        }
        foreach ($dates as $key => $val) {
            $order_nos = Order::whereDate('created_at', $val)->where('is_pay', 1)->whereIn('apply_cancel', [0, 1, 3])->whereIn('is_refund', [0, 1])->pluck('order_no');
            $list['cotton'][$val] = OrderDetail::whereIn('order_no', $order_nos)->where('goods_id', 4)
                ->select(DB::raw('ifnull(sum(num),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        }
        return $this->success($list);
    }

    function getDateFromRange($startdate, $enddate)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();

        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
        }
        return $date;
    }

    //获取每日新增人数
    public function getEveryAddAgent(Request $request)
    {
        if ($request->input('startdate') && $request->input('enddate')) {
            $startdate = $request->input('startdate');
            $enddate = $request->input('enddate');
        } else {
            $startdate = date("Y-m-d", strtotime('-7 days'));
            $enddate = date("Y-m-d");
        }
        $dates = $this->getDateFromRange($startdate, $enddate);
        $list = [];
        foreach ($dates as $key => $val) {
            $list[$val] = Store::whereDate('created_at', $val)->where('is_apply',3)->count();
        }
        return $this->success($list);
    }

    //获取每日新增人数
    public function getEveryAddAgentSort(Request $request)
    {
        $date=$request->input('date');
        $user_ids=Store::whereDate('created_at', $date)->where('is_apply',3)->pluck('user_id');
        $list=DwbsUser::with('warea:id,name')->whereIn('id',$user_ids)->groupBy('warea_id')
            ->select('warea_id',DB::raw('count(id) as count'))->orderByDesc('count')->get();
        return $this->success($list);
    }

    //获取政委每日新增人数变化曲线图
    public function getEveryAddAgentLine(Request $request)
    {
        if ($request->input('startdate') && $request->input('enddate')) {
            $startdate = $request->input('startdate');
            $enddate = $request->input('enddate');
        } else {
            $startdate = date("Y-m-d", strtotime('-7 days'));
            $enddate = date("Y-m-d");
        }
        $dates = $this->getDateFromRange($startdate, $enddate);
        $list = [];
        $warea=DwbsWarea::all();
        foreach($warea as $k=>$v){
            foreach ($dates as $key => $val) {
                $user_ids=Store::whereDate('created_at', $val)->where('is_apply',3)->pluck('user_id');
                $list[$v->name][$val]=DwbsUser::whereIn('id',$user_ids)->where('warea_id',$v->id)->count();
            }
        }
        return $this->success($list);
    }

    public function getHistoryTotal(Request $request)
    {
        $startime = $request->input('start_time');
        $endtime = $request->input('end_time');
        $where = $wheres = [];
        if ($startime && $endtime) {
            $where = function ($query) use ($startime, $endtime) {
                $query->whereBetween('created_at', [$startime, $endtime]);
            };
            $wheres = function ($query) use ($startime, $endtime) {
                $query->whereBetween('cancel_at', [$startime, $endtime]);
            };
        }
        $data['all'] = Order::where('is_pay', 1)->where($where)
            ->select(DB::raw('ifnull(sum(total),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        $data['refund'] = OrderRefund::where($where)->where('status', 1)
            ->select(DB::raw('ifnull(sum(total),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        $data['cancel'] = Order::where($wheres)->where('apply_cancel', 2)
            ->select(DB::raw('ifnull(sum(total),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        return $this->success($data);
    }

    public function getSkuHistoryNum(Request $request)
    {
        $startdate = $request->input('startdate');
        $enddate = $request->input('enddate');

        $where = $wheres = [];
        if ($startdate && $enddate) {
            $startime = date("Y-m-d 00:00:00", strtotime($startdate));
            $endtime = date("Y-m-d 23:59:59", strtotime($enddate));
            $where = function ($query) use ($startime, $endtime) {
                $query->whereBetween('created_at', [$startime, $endtime]);
            };
        }
        $data = OrderDetail::has('goods')->whereHas('order', function ($query) {
            $query->where('is_pay', 1);
        })->with('goods:id,name,main_attr')->where($where)
            ->select('goods_id', DB::raw('ifnull(sum(num),0) as total'), DB::raw('ifnull(sum(account),0) as account'))
            ->groupBy('goods_id')->orderBy('goods_id')->get();
        return $this->success($data);
    }

    //获取款式排行
    public function getSkuOrderBy()
    {
        $goods_sku=GoodSku::whereHas('goods',function($query){$query->where('is_shelves', 1);})->with('goods:id,name,main_attr')->get();
        foreach($goods_sku as $key=>$val){
            $goods_sku[$key]->detail=OrderDetail::where('sku_id',$val->id)->whereHas('order',function($query){
                $query->where('is_pay', 1)->whereIn('is_refund', [0, 1])->whereIn('apply_cancel', [0, 1, 3]);
            })->select(DB::raw('ifnull(sum(num),0) as total'), DB::raw('ifnull(sum(account),0) as account'))->first();
        }
        return $this->success($goods_sku);
    }

    //三天销量为0
    public function get3DaysSales0(Request $request)
    {
        $start_time = date("Y-m-d 00:00:00", strtotime('-3 days'));
        $end_time = date("Y-m-d H:i:s");
        $page_index = $request->input('page_index');
        $page_size = $request->input('page_size');
        $num = $page_size * ($page_index - 1);

        $admin_id = Auth::user()->id;
        $admin = Admin::where('id', $admin_id)->first();
        if ($admin && in_array($admin->role_id, [22, 24])) {//超级管理员
            $where = [];
        } else {
            $warea_ids = DwbsWarea::where('admin_id', $admin_id)->pluck('id');
            $agent_ids = DwbsUser::whereIn('warea_id', $warea_ids)->pluck('id');
            $store_ids = Store::whereIn('user_id', $agent_ids)->pluck('id');
            $where = function ($query) use ($store_ids) {
                $query->whereIn('store.id', $store_ids);
            };
        }
        $count = Store::where('store.status', 0)->where($where)
            ->leftJoin('order as o', function ($query) use ($start_time, $end_time) {
                $query->on('store.id', '=', 'o.store_id')->where('o.is_pay', 1)
                    ->whereIn('o.apply_cancel', [0, 1, 3])->whereIn('o.is_refund', [0, 1])
                    ->whereBetween('o.created_at', [$start_time, $end_time]);
            })->select('store.id', 'store.name', 'store.img', 'store.phone', DB::Raw('sum(ifnull(o.total,0)) as total'))
            ->groupBy('store.id')
            ->having('total', '=', 0)->get()->count();
        $list = Store::where('store.status', 0)->where($where)
            ->leftJoin('order as o', function ($query) use ($start_time, $end_time) {
                $query->on('store.id', '=', 'o.store_id')->where('o.is_pay', 1)
                    ->whereIn('o.apply_cancel', [0, 1, 3])->whereIn('o.is_refund', [0, 1])
                    ->whereBetween('o.created_at', [$start_time, $end_time]);
            })->select('store.id', 'store.name', 'store.img', 'store.phone', DB::Raw('sum(ifnull(o.total,0)) as total'))
            ->groupBy('store.id')
            ->having('total', '=', 0)
            ->orderBy('store.id')
            ->skip($num)->take($page_size)
            ->get();
        return $this->success_list($list, '', $count);
    }

    //三天销量为0
    public function export3DaysSales0(Request $request)
    {
        return $this->success([]);
    }
}
