<?php
namespace App\Http\Controllers\Api\ProductManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\ProductManage\VerifyGiftListsController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use \PhpOffice\PhpSpreadsheet\IOFactory;

class GiftListsController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGiftListsController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        $page_size = $request->input('show_count', 10);
        $search_data = $request->all();
        $list_data = DB::table('goods as a')
                        ->leftJoin('goods_affiliate as b', 'a.goo_id', '=', 'b.goaf_goo_id')
                        ->where('a.goo_cid', $user_info->adm_cid)
                        ->where('a.goo_superior_shop_id', $shop_id)
                        ->where('a.goo_delete', 1)
                        ->where('a.goo_type', 2)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_name'])) {
                                $query->where('a.goo_name', 'like', $search_data['goo_name'].'%' );
                            }
                        })//商品名称
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goaf_another_name'])) {
                                $query->where('b.goaf_another_name', 'like', $search_data['goaf_another_name'].'%' );
                            }
                        })//别名
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_goods_encode'])) {
                                $query->where('a.goo_goods_encode', 'like', $search_data['goo_goods_encode'].'%' );
                            }
                        })//检索编码
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_goods_code'])) {
                                $query->where('a.goo_goods_code', 'like', $search_data['goo_goods_code'].'%' );
                            }
                        })//商品编号
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_state'])) {
                                $query->where('a.goo_state', $search_data['goo_state']);
                            }
                        })//状态
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_bra_id'])) {
                                $query->where('a.goo_bra_id', $search_data['goo_bra_id']);
                            }
                        })//品牌id
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_cate_id'])) {
                                $query->where('a.goo_cate_id', $search_data['goo_cate_id']);
                            }
                        })//品类id
                        ->select('a.goo_id', 'a.goo_name', 'a.goo_bra_name', 'a.goo_state', 'a.goo_goods_encode', 
                            'a.goo_price', 'a.goo_cate_name', 'a.goo_attribute', 'b.goaf_another_name','a.goo_wholesale_price','a.goo_purchase_price','a.goo_goods_code')
                        ->orderBy('a.goo_id', 'desc')
                        ->paginate($page_size);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $page_size;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据

        // 商品下架数量
        $data_info['stop_number'] = DB::table('goods as a')
                        ->leftJoin('goods_affiliate as b', 'a.goo_id', '=', 'b.goaf_goo_id')
                        ->where('a.goo_cid', $user_info->adm_cid)
                        ->where('a.goo_superior_shop_id', $shop_id)
                        ->where('a.goo_delete', 1)
                        ->where('a.goo_type', 2)
                        ->where('goo_state', 2)
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_name'])) {
                                $query->where('a.goo_name', 'like', $search_data['goo_name'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goaf_another_name'])) {
                                $query->where('b.goaf_another_name', 'like', $search_data['goaf_another_name'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_goods_encode'])) {
                                $query->where('a.goo_goods_encode', 'like', $search_data['goo_goods_encode'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_goods_code'])) {
                                $query->where('a.goo_goods_code', 'like', $search_data['goo_goods_code'].'%' );
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_state'])) {
                                $query->where('a.goo_state', $search_data['goo_state']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_bra_id'])) {
                                $query->where('a.goo_bra_id', $search_data['goo_bra_id']);
                            }
                        })
                        ->where(function($query) use($search_data) {
                            if (!empty($search_data['goo_cate_id'])) {
                                $query->where('a.goo_cate_id', $search_data['goo_cate_id']);
                            }
                        })
                        ->count();

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info, 'list_button'=>$list_button]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGiftListsController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 商品属性
        if (!empty($request['info_name'])) {
            // 处理商品属性数组数据
            foreach ($request['info_name'] as $key => $value) {
                if (empty($value) || empty($request['info_content'][$key])) {
                    return response()->json(['code'=>500,'msg'=>'error','data'=>'信息项存在空项']);
                }
                $goo_attribute[$key]['key'] = $value;//名称
                $goo_attribute[$key]['value'] = $request['info_content'][$key];//内容
            }
            $goo_add_data['goo_attribute'] = json_encode($goo_attribute);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 1. 判断商品名称是否存在
        $find_goo = DB::table('goods')
            ->where('goo_delete', 1)
            ->where('goo_type', 2)
            ->where('goo_cid', $user_info->adm_cid)
            ->where('goo_superior_shop_id', $shop_id)
            ->where('goo_name', $request['goo_name'])
            ->select('goo_id')
            ->first();
        if ($find_goo) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'商品名称已存在']);
        }

        // 判断检索编码是否存在
        if (!empty($request['goo_goods_encode'])) {
            $find_goo = DB::table('goods')
                ->where('goo_delete', 1)
            	->where('goo_type', 2)
                ->where('goo_cid', $user_info->adm_cid)
                ->where('goo_superior_shop_id', $shop_id)
                ->where('goo_goods_encode', $request['goo_goods_encode'])
                ->select('goo_id')
                ->first();
            if ($find_goo) {
                return response()->json(["code"=>500,'msg'=>'error','data'=>'检索编码已存在']);
            }
        }

        // 判断商品编号是否存在
        if (!empty($request['goo_goods_code'])) {
            $find_goo = DB::table('goods')
                ->where('goo_delete', 1)
            	->where('goo_type', 2)
                ->where('goo_cid', $user_info->adm_cid)
                ->where('goo_superior_shop_id', $shop_id)
                ->where('goo_goods_code', $request['goo_goods_code'])
                ->select('goo_id')
                ->first();
            if ($find_goo) {
                return response()->json(["code"=>500,'msg'=>'error','data'=>'商品编号已存在']);
            }
        }

        DB::beginTransaction();
        // 2 新增一个商品数据
        $goo_add_data['goo_cid'] = $user_info->adm_cid;
        $goo_add_data['goo_shop_id'] = $user_info->adm_shop_id;
        $goo_add_data['goo_superior_shop_id'] = $shop_id;
        $goo_add_data['goo_name'] = $request['goo_name'];   //商品名称
        $goo_add_data['goo_goods_code'] = $request['goo_goods_code'] ? $request['goo_goods_code'] : '';   //商品编号
        $goo_add_data['goo_goods_encode'] = $request['goo_goods_encode'] ? $request['goo_goods_encode'] : '';   //检索编码
        $goo_add_data['goo_cate_id'] = $request['goo_cate_id']; //所属品类id
        $goo_add_data['goo_cate_name'] = $request['goo_cate_name']; //品类名称
        $goo_add_data['goo_price'] = $request['goo_price'] * 100;   //商品零售价格
        $goo_add_data['goo_wholesale_price'] = $request['goo_wholesale_price'] * 100;   //批发价
        $goo_add_data['goo_purchase_price'] = $request['goo_purchase_price'] * 100; //采购价
        $goo_add_data['goo_type'] = 2; //商品类型 1正常商品2赠品

        // 判断是否选择商品品牌
        if ($request['goo_bra_id']) {
            $goo_add_data['goo_bra_id'] = $request['goo_bra_id'];
            $goo_add_data['goo_bra_name'] = $request['goo_bra_name'];
        }
        // 新增商品
        $goo_id =  DB::table('goods')->insertGetId($goo_add_data);

        // 3. 判断是否有商品别名
        if ($request['goaf_another_name']) {
            $goaf_add_data = [
                'goaf_goo_id'=>$goo_id,
                'goaf_shop_id'=>$user_info->adm_shop_id,
                'goaf_another_name'=>$request['goaf_another_name'],
                'goaf_update_time'=>date('Y-m-d H:i:s'),
            ];
            // 新增商品别名
            $goaf_res =  DB::table('goods_affiliate')->insert($goaf_add_data);
        } else {
            $goaf_res = true;
        }

        // 4.商品所属品类数量更改
        $res_cate = DB::table('category')
                    ->where('cate_id',$request['goo_cate_id'])
                    ->increment('cate_goods_number');

        // 5.商品所属品牌数量更改
        if ($request['goo_bra_id']) {
            $res_brand = DB::table('brand')
            ->where('bra_id',$request['goo_bra_id'])
            ->increment('bra_goods_number');
        }else{
            $res_brand = true;
        }

        if ($goo_id && $goaf_res && $res_cate && $res_brand) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '赠品','新增','新增赠品：'.$request['goo_name'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'新增赠品：成功']);
        }else{
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'新增赠品：失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGiftListsController;
        $error_message = $verify_data->editShowValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        if ($request['type'] == 1) {
            // 获取编辑页面数据
            $find_data = DB::table('goods as a')
                ->leftJoin('goods_affiliate as b', 'a.goo_id', '=', 'b.goaf_goo_id')
                ->where('a.goo_id', $request['goo_id'])
                ->select('goo_bra_name', 'goo_bra_id', 'goo_cate_name', 'goo_cate_id', 'goo_name', 'goo_goods_encode', 
                    'goo_price', 'goo_attribute', 'goaf_id', 'goaf_another_name','goo_wholesale_price','goo_purchase_price','goo_goods_code')
                ->first();
            return response()->json(['code'=> 200, 'msg'=>'success', 'data'=>$find_data]);
        }
        // 提交编辑数据
        // 验证数据
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 商品属性
        if (!empty($request['info_name'])) {
            // 处理商品属性数组数据
            foreach ($request['info_name'] as $key => $value) {
                if (empty($value) || empty($request['info_content'][$key])) {
                    return response()->json(['code'=>500,'msg'=>'error','data'=>'信息项存在空项']);
                }
                $goo_attribute[$key]['key'] = $value;//名称
                $goo_attribute[$key]['value'] = $request['info_content'][$key];//内容
            }
            $goo_edit_data['goo_attribute'] = json_encode($goo_attribute);
        }else{
            $goo_edit_data['goo_attribute'] = '';
        }

        // 1. 判断商品名称是否存在
        $find_goo = DB::table('goods')
            ->where('goo_cid', $user_info->adm_cid)
            ->where('goo_superior_shop_id', $shop_id)
            ->where('goo_id', '<>', $request['goo_id'])
            ->where('goo_delete', 1)
            ->where('goo_type', 2)
            ->where('goo_name', $request['goo_name'])
            ->value('goo_id');
        if ($find_goo) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'商品名称已存在']);
        }

        // 1. 判断检索编码是否存在
        if (!empty($request['goo_goods_encode'])) {
            $find_goo = DB::table('goods')
                ->where('goo_cid', $user_info->adm_cid)
                ->where('goo_superior_shop_id', $shop_id)
                ->where('goo_id', '<>', $request['goo_id'])
                ->where('goo_delete', 1)
                ->where('goo_type', 2)
                ->where('goo_goods_encode', $request['goo_goods_encode'])
                ->value('goo_id');
            if ($find_goo) {
                return response()->json(["code"=>500,'msg'=>'error','data'=>'检索编码已存在']);
            }
        }

        // 判断商品编号是否存在
        if (!empty($request['goo_goods_code'])) {
            $find_goo = DB::table('goods')
                ->where('goo_delete', 1)
                ->where('goo_type', 2)
                ->where('goo_cid', $user_info->adm_cid)
                ->where('goo_superior_shop_id', $shop_id)
                ->where('goo_id', '!=', $request['goo_id'])
                ->where('goo_goods_code', $request['goo_goods_code'])
                ->select('goo_id')
                ->first();
            if ($find_goo) {
                return response()->json(["code"=>500,'msg'=>'error','data'=>'商品编号已存在']);
            }
        }

        // 查询出商品未编辑前的商品品类/商品所属品牌数量更改
        $goods_info = DB::table('goods')
                        ->where('goo_id', $request['goo_id'])
                        ->select('goo_bra_id','goo_cate_id')
                        ->first();

        // 2 编辑一个商品数据
        $goo_edit_data['goo_cid'] = $user_info->adm_cid;
        $goo_edit_data['goo_shop_id'] = $user_info->adm_shop_id;
        $goo_edit_data['goo_superior_shop_id'] = $shop_id;
        $goo_edit_data['goo_name'] = $request['goo_name'];  //商品名称
        $goo_edit_data['goo_goods_encode'] = $request['goo_goods_encode'] ? $request['goo_goods_encode'] : '';  //检索编码
        $goo_edit_data['goo_goods_code'] = $request['goo_goods_code'] ? $request['goo_goods_code'] : '';  //商品编号
        $goo_edit_data['goo_cate_id'] = $request['goo_cate_id'];    //所属品类id
        $goo_edit_data['goo_cate_name'] = $request['goo_cate_name'];    //品类名称
        $goo_edit_data['goo_price'] = $request['goo_price'] * 100;  //商品零售价格
        $goo_edit_data['goo_wholesale_price'] = $request['goo_wholesale_price'] * 100;  //批发价
        $goo_edit_data['goo_purchase_price'] = $request['goo_purchase_price'] * 100;    //采购价
        $goo_edit_data['goo_update_time'] = date('Y-m-d H:i:s');

        // 判断是否选择商品品牌
        if ($request['goo_bra_id']) {
            $goo_edit_data['goo_bra_id'] = $request['goo_bra_id'];
            $goo_edit_data['goo_bra_name'] = $request['goo_bra_name'];
        }else{
            $goo_edit_data['goo_bra_id'] = 0;
            $goo_edit_data['goo_bra_name'] = '';
        }

        DB::beginTransaction();
        // 编辑商品
        $goo_res =  DB::table('goods')
                    ->where('goo_id', $request['goo_id'])
                    ->update($goo_edit_data);

        // 3. 判断是否有商品别名
        if ($request['goaf_id']) {
            // 3.1 已经添加了商品别名，就编辑商品别名
            $goaf_data['goaf_another_name'] = $request['goaf_another_name'];
            $goaf_data['goaf_update_time'] = date('Y-m-d H:i:s');
            $goaf_res =  DB::table('goods_affiliate')
                        ->where('goaf_id', $request['goaf_id'])
                        ->update($goaf_data);
        } else {
            // 3.2 没有添加商品别名的，就直接添加数据
            if ($request['goaf_another_name']) {
                $goaf_add_data = [
                    'goaf_goo_id'=>$request['goo_id'],
                    'goaf_shop_id'=>$user_info->adm_shop_id,
                    'goaf_another_name'=>$request['goaf_another_name'],
                    'goaf_update_time'=>date('Y-m-d H:i:s'),
                ];
                // 新增商品别名
                $goaf_res =  DB::table('goods_affiliate')->insert($goaf_add_data);
            } else {
                $goaf_res = true;
            }
        }

        // 4.判断是否更改商品所属品类
        if ($request['goo_cate_id'] != $goods_info->goo_cate_id) {
            // 更改商品所属品类
            $save_cate_add = DB::table('category')
                        ->where('cate_id',$request['goo_cate_id'])
                        ->increment('cate_goods_number');//商品所属品类+1

            $save_cate_subtract = DB::table('category')
                                ->where('cate_id',$goods_info->goo_cate_id)
                                ->decrement('cate_goods_number');//商品所属品类-1
            if ($save_cate_add && $save_cate_subtract) {
                $save_cate = true;
            }else{
                $save_cate = false;
            }
        }else{
            $save_cate = true;
        }

        // 5.判断是否更改商品所属品牌
        if ($request['goo_bra_id'] != $goods_info->goo_bra_id) {
            // 更改商品所属品牌
            if ($request['goo_bra_id']) {
                $save_bra_add = DB::table('brand')
                            ->where('bra_id',$request['goo_bra_id'])
                            ->increment('bra_goods_number');//商品所属品类+1
            }else{
                $save_bra_add = true;
            }

            if ($goods_info->goo_bra_id) {
                $save_bra_subtract = DB::table('brand')
                                    ->where('bra_id',$goods_info->goo_bra_id)
                                    ->decrement('bra_goods_number');//商品所属品类-1
            }else{
                $save_bra_subtract = true;
            }
            if ($save_bra_add && $save_bra_subtract) {
                $save_bra = true;
            }else{
                $save_bra = false;
            }
        }else{
            $save_bra = true;
        }
        if ($goo_res && $goaf_res && $save_cate && $save_bra) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '赠品','编辑','编辑赠品：'.$request['goo_name'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'编辑赠品：成功']);
        }else{
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'编辑赠品：失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGiftListsController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_sepr = DB::table('goods')
                    ->whereIn('goo_id', $request['goo_id'])
                    ->select('goo_name')
                    ->get();
        foreach ($find_sepr as $key => $value) {
            $goo_name[] = $value->goo_name;
        }

        // 启用
        $update_data['goo_state'] = 1;//状态1启用2停用
        $update_data['goo_update_time'] = date('Y-m-d H:i:s');
        $goo_res = DB::table('goods')
                    ->whereIn('goo_id', $request['goo_id'])
                    ->update($update_data);

        if($goo_res) {
            Common::addLog($user_info, getRealIp($request), '赠品', '启用', '赠品：（'.implode(',', $goo_name).'）启用成功');
            return response()->json(["code"=>200, 'msg'=>'success', 'data'=>'启用成功']);
        }else{
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'启用失败']);
        }
    }

    // 停用
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGiftListsController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_sepr = DB::table('goods')
                    ->whereIn('goo_id',$request['goo_id'])
                    ->select('goo_name')
                    ->get();
        foreach ($find_sepr as $key => $value) {
            $goo_name[] = $value->goo_name;
        }

        // 启用
        $update_data['goo_state'] = 2;//状态1启用2停用
        $update_data['goo_update_time'] = date('Y-m-d H:i:s');
        $goo_res = DB::table('goods')
                    ->whereIn('goo_id', $request['goo_id'])
                    ->update($update_data);

        if($goo_res) {
            Common::addLog($user_info, getRealIp($request), '赠品','停用','赠品：（'.implode(',', $goo_name).'）停用成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'停用成功']);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'停用失败']);
        }
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGiftListsController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 商品有库存不得删除
        $stock_number = DB::table('warehouse_goods')
                        ->whereIn('wago_goo_id',$request['goo_id'])
                        ->sum('wago_stock_number');
        if($stock_number > 0){
           return response()->json(["code"=>500,'msg'=>'error','data'=>'商品下有库存不得删除']); 
        }

        // 查询信息
        $find_sepr = DB::table('goods')
                    ->whereIn('goo_id',$request['goo_id'])
                    ->select('goo_name','goo_cate_id','goo_bra_id')
                    ->get();
        $goo_bra_id = [];
        foreach ($find_sepr as $key => $value) {
            $goo_name[] = $value->goo_name;
            $goo_cate_id[] = $value->goo_cate_id;
            if ($value->goo_bra_id) {
                // 商品选择了品牌id
                $goo_bra_id[] = $value->goo_bra_id;
            }
        }

        DB::beginTransaction();
        // 1. 商品所属品类数量更改
        $goo_cate_id = array_count_values($goo_cate_id);
        $cate_ids = '';
        $cate_del_sql = '';
        if (count($goo_cate_id) > 1 ) {
            $cate_del_sql = 'UPDATE `faster_category` SET `cate_goods_number`=  CASE `cate_id` ';
            foreach ($goo_cate_id as $key => $value) {
                $cate_del_sql = $cate_del_sql . ' WHEN ' .$key;
                $cate_del_sql = $cate_del_sql . ' THEN `cate_goods_number`-' .$value;
                $cate_ids = $cate_ids . $key.',';
            }
            $cate_del_sql = $cate_del_sql . ' END WHERE `cate_id` IN ('.trim($cate_ids,',').')';
        } else {
            $cate_del_sql = 'UPDATE `faster_category` SET  `cate_goods_number`= `cate_goods_number`-'.end($goo_cate_id).'  WHERE  `cate_id` ='.key($goo_cate_id);
        }
        $save_cate = DB::update($cate_del_sql);// 商品所属品类数量更改

        // 2. 商品所属品牌数量更改
        if ($goo_bra_id) {
            $goo_bra_id = array_count_values($goo_bra_id);
            $bra_ids = '';
            $bra_del_sql = '';
            if (count($goo_bra_id) > 1 ) {
                $bra_del_sql = 'UPDATE `faster_brand` SET `bra_goods_number`=  CASE `bra_id` ';
                foreach ($goo_bra_id as $key => $value) {
                    $bra_del_sql = $bra_del_sql . ' WHEN ' .$key;
                    $bra_del_sql = $bra_del_sql . ' THEN `bra_goods_number`-' .$value;
                    $bra_ids = $bra_ids . $key.',';
                }
                $bra_del_sql = $bra_del_sql . ' END WHERE `cate_id` IN ('.trim($bra_ids,',').')';
            } else {
                $bra_del_sql = 'UPDATE `faster_brand` SET  `bra_goods_number`= `bra_goods_number`-'.end($goo_bra_id).'  WHERE  `bra_id` ='.key($goo_bra_id);
            }
            $save_bra = DB::update($bra_del_sql);// 商品所属品牌数量更改
        }else{
            $save_bra = true;
        }

        // 3. 删除商品
        $update_data['goo_delete'] = 2;//是否删除：1正常2已删除
        $update_data['goo_update_time'] = date('Y-m-d H:i:s');
        $goo_res = DB::table('goods')
                    ->whereIn('goo_id', $request['goo_id'])
                    ->update($update_data);
        if($goo_res && $save_cate && $save_bra) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '赠品','删除','赠品：（'.implode(',', $goo_name).'）删除成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'删除成功']);
        }else{
            DB::rollBack();
            return response()->json(["code"=>500,'msg'=>'error','data'=>'删除失败']);
        }
    }

    // 搜索库存
    public function searchStock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGiftListsController;
        $error_message = $verify_data->searchStockValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 查询信息
        $find_data = DB::table('warehouse as a')
                    ->leftJoin('warehouse_goods as b', 'b.wago_ware_id', '=', 'a.ware_id')
                    ->where('wago_goo_id', $request['goo_id'])
                    ->where('ware_superior_shop_id', $shop_id)
                    ->where('wago_stock_number', '>',0)
                    ->select('ware_name','wago_stock_number')
                    ->orderBy('wago_stock_number', 'desc')
                    ->get();
        return response()->json(["code"=>200,'msg'=>'success','data'=>$find_data]);
    }

    // 下拉搜索数据
    public function pulldownSearch(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        $search_data = $request->all();
        $list_data = DB::table('goods')
                    ->where('goo_cid', $user_info->adm_cid)
                    ->where('goo_superior_shop_id', $shop_id)
                    ->where('goo_delete', 1)
                    ->where('goo_type', 2)
                    ->where('goo_state', 1)
                    ->where(function($query) use($search_data) {
                        if (!empty($search_data['goo_name'])) {
                            $query->where('goo_name', 'like', '%'.$search_data['goo_name'].'%' )
                                  ->orwhere('goo_goods_encode', 'like', '%'.$search_data['goo_name'].'%' );
                        }
                    })
                    ->select('goo_id', 'goo_name')
                    ->orderBy('goo_id', 'desc')
                    ->limit(10)
                    ->get();
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$list_data]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }
}
