<?php

namespace App\Http\Controllers;

use App\Models\Address;
use App\Models\DwbsUser;
use App\Models\Inventory;
use App\Models\User;
use App\Models\See;
use App\Models\Goods;
use App\Models\GoodSku;
use App\Models\ShopCar;
use App\Models\Verify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class GoodsController extends Controller
{
    //获取商品详情
    public function getGoodsInfos(Request $request){
        $goods_id=$request->input('goods_id');
        $store_id=$request->input('store_id');
        $goods=Goods::where('id',$goods_id)->first();
        $inventory=Inventory::where('store_id',$store_id)->pluck('num',DB::raw("CONCAT(store_id,'_',goods_id,'_',sku_id)"))->toArray();
        if(empty($goods)){
            return $this->error('450001','没有获取到商品信息');
        }
        $time=Carbon::now()->subMinute(10);
        if($request->has('sku_id')){
            $sku_id=$request->input('sku_id');
            $goods->goods_sku=GoodSku::where('id',$sku_id)->first();
            $goods->type=1;//商品详情（单一规格）
            $is_see=See::where('store_id',$store_id)->where('goods_id',$goods_id)
                ->where('user_id',Auth::user()->id)->where('created_at','>',$time)->doesntExist();
            if($is_see){
                See::create([
                    'user_id'=>Auth::user()->id,
                    'store_id'=>$store_id,
                    'goods_id'=>$goods_id,
                    'size'=>1,
                    'type'=>2
                ]);
            }
        }else{
            $sku=GoodSku::where('goods_id',$goods_id)->groupBy('type')->pluck('type');
            $size=[];
            foreach($sku as $key=>$val){
                $sizes=GoodSku::where('goods_id',$goods_id)->where('type',$val)->orderBy('sort')->get();
                foreach($sizes as $k=>$v){
                    $size[$val][$v->size]=$v->id;
                }
            }
            $goods->sku=$sku;
            $goods->size=$size;
            $goods->type=2;//商品详情(全规格)
            $is_see=See::where('store_id',$store_id)->where('goods_id',$goods_id)
                ->where('user_id',Auth::user()->id)->where('created_at','>',$time)->doesntExist();
            if($is_see){
                See::create([
                    'user_id'=>Auth::user()->id,
                    'store_id'=>$store_id,
                    'goods_id'=>$goods_id
                ]);
            }
        }
        return $this->success($goods);
    }
    //获取商品详情
    public function getGoodsInfo(Request $request){
        $goods_id=$request->input('goods_id');
        $store_id=$request->input('store_id');
        $goods=Goods::where('id',$goods_id)->first();
        $inventory=Inventory::where('store_id',$store_id)->pluck('num',DB::raw("CONCAT(store_id,'_',goods_id,'_',sku_id)"))->toArray();
        if(empty($goods)){
            return $this->error('450001','没有获取到商品信息');
        }
        $sku=GoodSku::where('goods_id',$goods_id)->groupBy('type')->pluck('type');
        $size=[];
        foreach($sku as $key=>$val){
            $sizes=GoodSku::where('goods_id',$goods_id)->where('type',$val)->orderBy('sort')->get();
            foreach($sizes as $k=>$v){
                $size[$val][$v->size]['size']=$v->size;
                $size[$val][$v->size]['size_desc']=$v->size_desc;
                $size[$val][$v->size]['id']=$v->id;
                if(empty($inventory[$store_id.'_'.$goods_id.'_'.$v->id])){
                    $size[$val][$v->size]['num']=0;
                }else{
                    $size[$val][$v->size]['num']=$inventory[$store_id.'_'.$goods_id.'_'.$v->id];
                }
            }
        }
        $goods->sku=$sku;
        $goods->size=$size;
        $time=Carbon::now()->subMinute(10);
        $is_see=See::where('store_id',$store_id)->where('goods_id',$goods_id)
            ->where('user_id',Auth::user()->id)->where('created_at','>',$time)->doesntExist();
        if($is_see){
            See::create([
                'user_id'=>Auth::user()->id,
                'store_id'=>$store_id,
                'goods_id'=>$goods_id
            ]);
        }
        return $this->success($goods);
    }
    //添加购物车
    public function addShopCar(Request $request){
        $user_id=Auth::user()->id;
        $user=User::where('id',$user_id)->first();
        if(empty($user->phone)){
            return $this->error('450001','客户没有绑定手机号');
        }
        $dwbsUser = DwbsUser::where('mobile',$user->phone)->first();
        if($dwbsUser){
            return $this->error('450001','该账号不能添加购物车');
        }
        $arr=$request->input('arr');
        DB::beginTransaction();
        try {
            foreach ($arr as $key => $val) {
                $sku = GoodSku::with(['goods'])->where('id', $val[0])->first();
                $where['user_id'] = $user_id;
                $where['goods_id'] = $sku->goods_id;
                $where['sku_id'] = $val[0];
                $where['type'] = $sku->type;
                $where['size'] = $sku->size;
                $skuInfo = ShopCar::where($where)->first();
                if($val[1]>0){
                    if ($skuInfo) {
                        $skuInfo->price = $sku->goods->price;
                        $skuInfo->num += $val[1];
                        $skuInfo->amount = $skuInfo->price * $skuInfo->num;
                        $skuInfo->is_true = 1;
                        $skuInfo->save();
                    } else {
                        $amount = $sku->goods->price * $val[1];
                        $flight = new ShopCar();
                        $flight->user_id = $user_id;
                        $flight->goods_id = $sku->goods_id;
                        $flight->price = $sku->goods->price;
                        $flight->num = $val[1];
                        $flight->sku_id = $val[0];
                        $flight->amount = $amount;
                        $flight->size = $sku->size;
                        $flight->type = $sku->type;
                        $flight->is_true = 1;
                        $flight->save();
                    }
                }
            }
            DB::commit();
            return $this->success([]);
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error();
        }
    }
    //获取用户购物车
    public function getShopCar()
    {
        $user=Auth::user();
        $goodsIds=ShopCar::where('user_id',$user->id)->groupBy('goods_id')->pluck('goods_id');
        $goods=[];
        foreach($goodsIds as $key=>$val){
            $goods[$key]=Goods::where('id',$val)->first();
            $goods[$key]->sku=ShopCar::where('user_id',$user->id)->where('goods_id',$val)->get();
        }
        return $this->success($goods);
    }
    //选中| 不选 购物车
    public function checkedShopCar(Request $request)
    {
        $ids=$request->input('ids');
        $is_true=$request->input('type') ? 1:0;
        $res=ShopCar::whereIn('id',$ids)->update(['is_true'=>$is_true]);
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //删除购物车商品
    public function destroyShopCar(Request $request)
    {
        $res=ShopCar::where('goods_id',$request->input('goods_id'))->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //删除购物车商品规格
    public function destroyShopCarSku(Request $request)
    {
        $res=ShopCar::where('id',$request->input('shopCar_id'))->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //购物车商品数量变更
    public function updateShopCarNum(Request $request)
    {
        $shopCar_id=$request->input('shopCar_id');
        $num=$request->input('num');
        $shopCar=ShopCar::with(['goods'])->where('id',$shopCar_id)->first();
        if(empty($shopCar)){
            return $this->error('450001','购物车数据有误');
        }
        $shopCar->num = $num;
        $shopCar->price= $shopCar->goods->price;
        $shopCar->amount=$shopCar->num * $shopCar->price;
        $res=$shopCar->save();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //获取所有收货地址
    public function getAllAddress()
    {
        $user=Auth::user();
        $address=Address::where('user_id',$user->id)->orderByDesc('is_default')->orderByDesc('created_at')->get();
        return $this->success($address);
    }
    //获取默认收货地址
    public function getAddress()
    {
        $user=Auth::user();
        $address=Address::where('user_id',$user->id)->where('is_default',1)->first();
        return $this->success($address);
    }
    //添加收货地址
    public function addAddress(Request $request)
    {
        $user=Auth::user();
        $input=$request->all();
        $regex=Verify::where('code',$request->input('areaCode','+86'))->value('preg');
        $rules=[
            'name'=>'required|max:32',
            'phone'=>['required','regex:'.$regex],
            'province'=>'required',
            'city'=>'required',
            'area'=>'required',
            'address'=>'required|max:255',
        ];
        $message=[
            'name.required'=>'收货人姓名不能为空.',
            'name.max'=>'收货人姓名不能大于32个字符.',
            'phone.required'=>'手机号不能为空.',
            'phone.regex'=>'手机号格式有误.',
            'province.required'=>'省不能为空.',
            'city.required'=>'市不能为空.',
            'area.required'=>'区/县不能为空.',
            'address.required'=>'详细地址不能为空.',
            'address.max'=>'详细地址不能大于255个字符.'
        ];
        $validator = Validator::make($input,$rules,$message);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $count=Address::where('user_id',$user->id)->count();
        if($count>=10){
            return $this->error('450001','用户地址数量已达上限');
        }
        try{
            DB::transaction(function()use($request,$input,$user){
                if($input['is_default']==1){
                    Address::where('user_id',$user->id)->update(['is_default'=>0]);
                }
                Address::create([
                    'name'=>$input['name'],
                    'area_code'=>$request->input('areaCode','+86'),
                    'phone'=>$input['phone'],
                    'user_id'=>$user->id,
                    'province'=>$input['province'],
                    'city'=>$input['city'],
                    'area'=>$input['area'],
                    'address'=>$input['address'],
                    'is_default'=>$input['is_default']??0,
                    'type'=>1,
                    'remark'=>$input['remark'],
                ]);
            },5);
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    //修改收货地址
    public function updateAddress(Request $request)
    {
        $input=$request->all();
        $regex=Verify::where('code',$request->input('areaCode','+86'))->value('preg');
        $rules=[
            'name'=>'required|max:32',
            'phone'=>['required','regex:'.$regex],
            'province'=>'required',
            'city'=>'required',
            'area'=>'required',
            'address'=>'required|max:255',
        ];
        $message=[
            'name.required'=>'收货人姓名不能为空.',
            'name.max'=>'收货人姓名不能大于32个字符.',
            'phone.required'=>'手机号不能为空.',
            'phone.regex'=>'手机号格式有误.',
            'province.required'=>'省不能为空.',
            'city.required'=>'市不能为空.',
            'area.required'=>'区/县不能为空.',
            'address.required'=>'详细地址不能为空.',
            'address.max'=>'详细地址不能大于255个字符.'
        ];
        $validator = Validator::make($input,$rules,$message);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }

        try{
            DB::transaction(function()use($request,$input){
                $address_id=$input['address_id'];
                $address=Address::where('id',$address_id)->first();
                if($input['is_default']==1){
                    Address::where('user_id',$address->user_id)->update(['is_default'=>0]);
                }
                Address::where('id',$address_id)->update([
                    'name'=>$input['name'],
                    'area_code'=>$request->input('areaCode','+86'),
                    'phone'=>$input['phone'],
                    'province'=>$input['province'],
                    'city'=>$input['city'],
                    'area'=>$input['area'],
                    'address'=>$input['address'],
                    'is_default'=>$input['is_default'],
                    'type'=>1,
                    'remark'=>$input['remark'],
                ]);
            },5);
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    //删除收货地址
    public function destroyAddress(Request $request)
    {
        $res=Address::where('id',$request->input('id'))->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //设为 | 取消 默认地址
    public function setDefaultAddress(Request $request)
    {
        $id=$request->input('id');
        $address=Address::where('id',$id)->first();
        try{
            DB::transaction(function()use($address){
                if($address->is_default == 1) {
                    $address->is_default = 0;
                    $address->save();
                }else{
                    $address->is_default = 1;
                    $address->save();

                    Address::where('user_id',$address->user_id)->whereNotIn('id',[$address->id])->update(['is_default'=>0]);
                }
            },5);
            return $this->success([]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
    }
}
