<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GoodSku;
use App\Models\OrderDetail;
use Illuminate\Http\Request;
use App\Models\Goods;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class GoodsController 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);
        $count=Goods::count();
        $list=Goods::orderBy('id','desc')->skip($num)->take($page_size)->get();
        foreach($list as $key=>$val){
            $list[$key]->good_sku=GoodSku::where('goods_id',$val->id)->orderBy('sort','asc')->get();
        }
        return $this->success_list($list,'成功',$count);
    }
    //添加商品
    public function addGoods(Request $request){
        try{
            DB::transaction(function()use($request){
                //添加商品基本信息
                $goods=Goods::create([
                    'name'=>$request->input('name'),
                    'price'=>$request->input('price'),
                    'vip_price'=>$request->input('vip_price'),
                    'content'=>$request->input('content'),
                    'img'=>$request->input('img'),
                    'main_attr'=>$request->input('main_attr'),
                    'banner'=>json_encode($request->input('banner')),
                    'is_delete'=>0,
                    'is_shelves'=>0,
                ]);
                $sku=$request->input('sku');
                $data=[];
                foreach($sku as $key=>$val){
                    $data[$key]=$val;
                    $data[$key]['goods_id']=$goods->id;
                    $data[$key]['num']=1000;
                    $data[$key]['sale_num']=0;
                    $data[$key]['created_at']=date("Y-m-d H:i:s");
                    $data[$key]['updated_at']=date("Y-m-d H:i:s");
                }
                GoodSku::insert($data);
            });
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    //编辑商品
    public function editGoods(Request $request){
        $sku_old=GoodSku::where('goods_id',$request->input('id'))
            ->select(DB::raw("CONCAT(type,'-',size,'-',sort) as string"))->pluck('string')->toArray();
        $sku_new=[];

        foreach($request->input('sku') as $key=>$val){
            $sku_new[$key]=$val['type'].'-'.$val['size'].'-'.$val['sort'];
        }
        Log::info(json_encode($sku_new));
        try{
            DB::transaction(function()use($request,$sku_new,$sku_old){
                //添加商品基本信息
                $goods=Goods::where('id',$request->input('id'))->update([
                    'name'=>$request->input('name'),
                    'price'=>$request->input('price'),
                    'vip_price'=>$request->input('vip_price'),
                    'content'=>$request->input('content'),
                    'img'=>$request->input('img'),
                    'main_attr'=>$request->input('main_attr'),
                    'banner'=>json_encode($request->input('banner')),
                    'is_delete'=>0,
                    'is_shelves'=>0,
                ]);
                $increase=array_diff($sku_new,$sku_old);
                Log::info('2222'.json_encode($increase));
                $increase_data=[];
                foreach($increase as $k=>$v){
                    $increase_data[$k]['type']=explode('-',$v)[0];
                    $increase_data[$k]['size']=explode('-',$v)[1];
                    $increase_data[$k]['sort']=explode('-',$v)[2];
                    $increase_data[$k]['goods_id']=$request->input('id');
                    $increase_data[$k]['num']=1000;
                    $increase_data[$k]['sale_num']=0;
                    $increase_data[$k]['created_at']=date("Y-m-d H:i:s");
                    $increase_data[$k]['updated_at']=date("Y-m-d H:i:s");
                }
                GoodSku::insert($increase_data);
                $decrease=array_diff($sku_old,$sku_new);
                foreach($decrease as $k=>$v){
                    $type=explode('-',$v)[0];
                    $size=explode('-',$v)[1];
                    GoodSku::where('size',$size)->where('type',$type)->delete();
                }
            },5);
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    //编辑尺码备注
    public function editSizeDesc(Request $request){
        $id=$request->input('id');
        $sizes=$request->input('sizes');
        $size_img=$request->input('size_img');
        foreach($sizes as $key=>$val){
            GoodSku::where('id',$val[0])->update([
                'size_desc'=>$val[1]
            ]);
        }
        Goods::where('id',$id)->update(['size_img'=>json_encode($size_img)]);
        return $this->success([]);
    }
    //商品上下架
    public function shelves(Request $request){
        $goods=Goods::where('id',$request->input('id'))->first();
        $goods->is_shelves = $goods->is_shelves ? 0 : 1;
        $res=$goods->save();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //商品删除
    public function destroy(Request $request){
        $res=Goods::where('id',$request->input('id'))->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //上传图片
    public function uploadImg(Request $request){
        $path_url = 'public/goods';
        $path = $request->file('img')->store($path_url);
        if($path){
            $url = env('APP_URL').Storage::url($path);
            return $this->success($url);
        }
        return $this->error();
    }
    //获取当日商品单规格销量
    public function getGoodsSkuSalesValue(Request $request){

        if($request->has('date') && !empty($request->input('date'))){
            $date=$request->input('date');
        }else{
            $date=date("Y-m-d");
        }
        $where=function($query)use($date){
            $query->whereDate('created_at',$date);
        };
        $goods_sku=OrderDetail::whereHas('order',function($query){
            $query->where('is_pay',1)->whereIn('apply_cancel',[0,1,3])->whereIn('is_refund',[0,1]);
        })->where($where)
            ->select('goods_id','type','size',DB::raw('sum(num) as total'),DB::raw('sum(account) as amount'))
            ->groupBy('goods_id','type','size')->get();
        $list=GoodSku::whereHas('goods',function($query){
            $query->where('is_shelves',1);
        })->select('goods_id','type','size')->with(['goods:id,name,main_attr'])->get();
        foreach($list as $k=>$v){
            $list[$k]->sale_num=0;
            $list[$k]->sale_money=0;
            foreach($goods_sku as $key=>$val){
                if($v->goods_id==$val->goods_id && $v->type==$val->type && $v->size==$val->size){
                    $list[$k]->sale_num=$val->total;
                    $list[$k]->sale_money=$val->amount;
                }
            }
        }
        return $this->success($list);
    }
}
