<?php

namespace App\Http\Controllers\Admin;

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


class OrderController extends Controller
{
    public function list(Request $request){
        $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();
        Log::info('02获取数据时间'.microtime());
        if($admin && in_array($admin->role_id,[22,24])){//超级管理员
            $data=Order::with(['user'=>function($qa){$qa->select('id','phone','name','nickname');},'store'=>function($qq){$qq->with('warea:id,admin_name')
                ->select('warea_id','id','name','phone');},'address'=>function($q){$q->select('province','city','area','name','phone','id');},'cancel'=>function($query){$query->where('using',1);}]);
        }else{
            $warea_ids=DwbsWarea::where('admin_id',$admin_id)->pluck('id');
//            $agent_ids=DwbsUser::withTrashed()->whereIn('warea_id',$warea_ids)->pluck('id');
//            $store_ids=Store::withTrashed()->whereIn('warea_id',$warea_ids)->pluck('id');//->whereIn('user_id',$agent_ids)
//            $data=Order::whereIn('store_id',$store_ids)
//                ->with(['user','store','address','cancel'=>function($query){$query->where('using',1);}]);
            $data=Order::whereHas('store',function($query)use($warea_ids){
                $query->withTrashed()->whereIn('warea_id',$warea_ids);
            })->with(['user','store:id,warea_id,name,phone','address'=>function($q){$q->select('province','city','area','name','phone','id');},'cancel'=>function($query){$query->where('using',1);}]);
        }
        //筛选订单号
        if($request->has('order_no') && !empty($request->input('order_no'))){
            $data->where('order_no',"like","%".$request->input('order_no')."%");
        }
        //店铺名称手机号筛选
        if($request->has('agent_phone') && !empty($request->input('agent_phone'))){
            $store_ids=Store::withTrashed()->where('phone','like',"%".$request->input('agent_phone')."%")
                ->orWhere('name','like',"%".$request->input('agent_phone')."%")->pluck('id');
            $data->whereIn('store_id',$store_ids);
        }
        //客户信息筛选
        if($request->has('user_phone') && !empty($request->input('user_phone'))){
            $user_ids=User::withTrashed()->where('phone','like',"%".$request->input('user_phone')."%")
                ->orWhere('nickname','like',"%".$request->input('user_phone')."%")->pluck('id');
            $data->whereIn('user_id',$user_ids);
        }
        //状态筛选
        if($request->input('status')!='all'){
            if(!empty($request->input('status')) || $request->input('status')==0){
                $data->where('status',$request->input('status'));
            }
        }
        //筛选订单类型
        if($request->has('type') && !empty($request->input('type'))){
            switch($request->input('type')){
                case 1:
                    $data->where('is_pay',1);
                    $data->where('is_help',1);
                    $data->where('self_pay',1);
                break;
                case 2:
                    $data->where('is_pay',1);
                    $data->where('is_help',1);
                    $data->where('self_pay',0);
                    break;
                case 3:
                    $data->where('is_pay',1);
                    $data->where('is_help',0);
                    $data->where('self_pay',0);
                    break;
                case 4:
                    $data->where('is_pay',1);
                    $data->where('is_help',0);
                    $data->where('self_pay',1);
                    break;
                default:
                    $data->where([]);
            }
        }
        //日期时间筛选
        if($request->input('start_time') && $request->input('end_time')){
            $data->whereBetween('created_at',[$request->input('start_time'),$request->input('end_time')]);
        }
        $count=$data->count();
        $list=$data->select('id','user_id','store_id','self_receive','address_id','total','order_no','account','status',
            'apply_cancel','is_help','op_name','is_pay','pay_money','pay_at','order_status','is_finish','signature','express_no',
            'express_company','express_code','express_state','express_info','express_time','pay_type','created_at')
            ->orderBy('id','desc')->skip($num)->limit($page_size)->get();
        Log::info('12获取数据时间'.microtime());
        foreach($list as $key=>$val){
//            $list[$key]->store->phone='';
            $list[$key]->address->phone=mb_substr($val->address->phone,0,3).'********';;
            $list[$key]->address->address='****';
            $list[$key]->user->phone=mb_substr($val->user->phone,0,3).'********';
        }
        return $this->success_list($list,'成功',$count);
    }

    public function export(Request $request){
        return $this->success([]);
    }
    //获取订单详情
    public function getOrderDetails(Request $request){
        $order_no=$request->input('order_no');
        $goods_ids = OrderDetail::where('order_no', $order_no)->groupBy('goods_id')->pluck('goods_id');
        $goods = [];
        foreach ($goods_ids as $key => $val) {
            $goods[$key] = Goods::where('id', $val)->first();
            $goods[$key]->sku = OrderDetail::where('order_no', $order_no)->where('goods_id', $val)->get();
        }
        $list['goods']=$goods;
        $order=Order::with('refund:id,order_no')->where('order_no',$order_no)->first();
        if($order->apply_cancel > 1){
            $order_cancel=OrderCancel::where('order_id',$order->id)->OrderBy('created_at')->get();
            $list['cancel']=$order_cancel;
        }
        if(count($order->refund) >= 1){
            $refund=OrderRefund::where('order_no',$order->order_no)->OrderBy('created_at')->get();
            $list['refund']=$refund;
        }
        return $this->success($list);
    }
    //获取门店、订单日销售额对比
    public function getOrderDailySales(Request $request){
        $store_id=$request->input('store_id');
        $startdate=$request->input('startdate');
        $enddate=$request->input('enddate');
        $where=$wheres=[];
        if($store_id){
            $where['store_id']=$store_id;
        }
        if($startdate && $enddate){
            $start=date("Y-m-d",strtotime($startdate));
            $end=date("Y-m-d",strtotime($enddate));
        }else{
            $start=date("Y-m-d",strtotime('-7 days'));
            $end=date("Y-m-d");
        }
        $dates=$this->getDateFromRange($start,$end);
        $list=[];
        foreach($dates as $key=>$val){
            $list[$val]=Order::whereDate('created_at',$val)->where($where)
                ->select(DB::raw('ifnull(sum(total),0) as total'),DB::raw('ifnull(sum(account),0) as money'))
                ->where('is_pay',1)->where('apply_cancel',[0,1,3])->where('is_refund',[0,1])->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;
    }
    //获取店铺销售额前10
    public function getStoreTop10(){
        $list=Order::with('store:id,name')->select('store_id',DB::raw('sum(account) as money'))
            ->where('is_pay',1)->groupBy('store_id')
            ->orderByDesc('money')->limit(10)->get();
        return $this->success($list);
    }
    //查询订单物流信息
    public function getOrderExpress(Request $request){
        $order_no=$request->input('order_no');
        $order=Order::with('address')->where('order_no',$order_no)->first();
        if(empty($order)){
            return $this->error('450001','订单信息有误');
        }
        if($order->express_state==3){  //已签收
            $express=json_decode($order->express_info,true);
        }else{ //未签收
            $express=new ExpressHandler();
            $CustomerName = null;
            if($order->express_code=='SF'){
                $CustomerName = substr($order->express_phone,-4);
            }
            $express=$express->getExpress($order->express_no, $order->express_code, $order->order_no, $CustomerName);
        }
        $data['express']=$express;
        $data['express_state']=$order->express_state;
        $data['express_company']=$order->express_company;
        $data['express_no']=$order->express_no;
        $data['express_time']=$order->express_time;
        return $this->success($data);
    }

    public function getAbnormalOrder(Request $request){
        $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();
        $date180 = Carbon::today()->subDays(180)->toDateTimeString();
        $date15 =  Carbon::today()->subDays(15)->toDateTimeString();

        if($admin && in_array($admin->role_id,[22,24])){//超级管理员
            $data=Order::with(['user:id,nickname,phone','store:id,name,phone','cancel'=>function($query){$query->where('using',1);}]);
        }else{
            $warea_ids=DwbsWarea::where('admin_id',$admin_id)->pluck('id');
            $agent_ids=DwbsUser::withTrashed()->whereIn('warea_id',$warea_ids)->pluck('id');
            $store_ids=Store::withTrashed()->whereIn('user_id',$agent_ids)->pluck('id');
            $data=Order::whereIn('store_id',$store_ids)
                ->with(['user:id,nickname,phone','store:id,name,phone','cancel'=>function($query){$query->where('using',1);}]);
        }
        //筛选订单号
        if($request->has('order_no') && !empty($request->input('order_no'))){
            $data->where('order_no',"like","%".$request->input('order_no')."%");
        }
        //店铺名称手机号筛选
        if($request->has('agent_phone') && !empty($request->input('agent_phone'))){
            $store_ids=Store::withTrashed()->where('phone','like',"%".$request->input('agent_phone')."%")
                ->orWhere('name','like',"%".$request->input('agent_phone')."%")->pluck('id');
            $data->whereIn('store_id',$store_ids);
        }
        //客户信息筛选
        if($request->has('user_phone') && !empty($request->input('user_phone'))){
            $user_ids=User::withTrashed()->where('phone','like',"%".$request->input('user_phone')."%")
                ->orWhere('nickname','like',"%".$request->input('user_phone')."%")->pluck('id');
            $data->whereIn('user_id',$user_ids);
        }
        //状态筛选
        if($request->input('status')!='all'){
            if(!empty($request->input('status')) || $request->input('status')==0){
                $data->where('status',$request->input('status'));
            }
        }
        $data->where('is_pay',1)->where('is_finish',0)->whereIn('apply_cancel',[0,1,3])
            ->whereBetween('pay_at',[$date180,$date15]);
//            ->where('pay_at','<',$date15);
        $total=$data->count();
        $list=$data->select('id','user_id','store_id','self_receive','address_id','total','order_no','account','status',
            'apply_cancel','is_help','op_name','is_pay','pay_money','pay_at','order_status','is_finish','signature','express_no',
            'express_company','express_code','express_state','express_info','express_time','pay_type','created_at')
            ->orderBy('store_id')->orderByDesc('pay_at')->skip($num)->take($page_size)->get();
        return $this->success_list($list,'',$total);
    }
}
