<?php

namespace App\Http\Controllers;

use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CancelController extends Controller
{
    //获取所有取消订单信息
    public function getCancelOrderList(Request $request){
        $user_id=Auth::user()->id;
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $order_no=$request->input('order_no');
        $num=$page_size*($page_index-1);
        $data= Order::with(['cancel'=>function($query){$query->where('using',1);},'refund','store:id,name,img,phone'])
            ->select('id','order_no','store_id','is_tip_send','account','address_id','apply_cancel','is_refund','is_pay','pay_at','total','user_id','created_at','remark','signature','status')
            ->where('user_id',$user_id)
            ->whereIn('apply_cancel',[1,2,3]);
        if($order_no){
            $data->where('order_no','like','%'.$order_no.'%');
        }
        $count= $data->count();
        $orders= $data->orderByDesc('cancel_at')->skip($num)->take($page_size)->get();
        foreach($orders as $key=>$val){
            $goods_ids=OrderDetail::where('order_no',$val->order_no)->groupBy('goods_id')->pluck('goods_id');
            $goods=[];
            foreach($goods_ids as $k=>$v){
                $goods[$k]=Goods::select('id','name','img','main_attr')->where('id',$v)->first();
                $goods[$k]->sku=OrderDetail::where('order_no',$val->order_no)->where('goods_id',$v)->get();
                if(count($goods[$k]->sku)>0){
                    $goods[$k]->price=$goods[$k]->sku[0]->price;
                }
            }
            $orders[$key]->goods=$goods;
        }
        return $this->success_list($orders,'成功',$count);
    }

    //删除订单
    public function deleteOriginOrder(Request $request){
        $order_id=$request->input('order_id');
        $res=Order::where('id',$order_id)->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
}
