<?php

namespace App\Http\Controllers\Api\ProductManage;

use App\Http\Controllers\Common\CommonController;
use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\ProductManage\VerifyGoodsListController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use App\Http\Models\Api\Export;
use App\Http\Models\Services\ProductManage\GoodsList;

// 基础管理 -- 产品列表
class GoodsListController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $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);
        $post['string'] = 'goo_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        DB::connection()->enableQueryLog();#开启执行日志
        $list_data = DB::table('goods as a')
            ->leftJoin('goods_affiliate as b', 'a.goo_id', '=', 'b.goaf_goo_id')
            ->where('a.goo_type', $search_data['goo_type'])
            ->where('a.goo_delete', 1)
            ->where(function ($query) use ($shop_id, $where_data) {
                $query->whereIn($where_data['string'], $where_data['shop_id']); //门店id为0的是系统数据
            })
            ->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_cate_id'])) { //品类id
                    $query->where('a.goo_cate_id', $search_data['goo_cate_id']);
                }
                if (!empty($search_data['goo_bra_id'])) { //品牌id
                    $query->where('a.goo_bra_id', $search_data['goo_bra_id']);
                }
                if (!empty($search_data['goo_brse_id'])) { //品牌系列id
                    $query->where('a.goo_brse_id', $search_data['goo_brse_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_class'])) {
                    $query->where('goo_class', $search_data['goo_class']);
                }
            }) //类型1自营商品2系统商品
            ->select('a.goo_id', 'a.goo_name', 'a.goo_bra_name', 'a.goo_state', 'a.goo_goods_encode', 'a.goo_cate_name', 'a.goo_attribute', 'b.goaf_another_name', 'a.goo_wholesale_price as goo_price', 'a.goo_brse_id', 'a.goo_unit', 'a.goo_guarantee', 'goo_system_code', 'a.goo_class', 'goo_commodity_propert', 'goo_shop_id')
            ->orderBy('a.goo_id', 'desc')
            ->paginate($page_size);
        $data['sqls'] = DB::getQueryLog()[0];
        $sqls = $data['sqls'];
        $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;       //一页显示多少个
        $list_items = $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('b.goaf_shop_id', $shop_id)
            ->where('a.goo_type', $search_data['goo_type'])
            ->where('a.goo_delete', 1)
            ->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']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('a.goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_class'])) {
                    $query->where('goo_class', $search_data['goo_class']);
                }
            }) //类型1自营商品2系统商品
            ->count();
        $brse_data = []; //品牌系列数据
        if ($list_items) {
            foreach ($list_data as $k => $v) {
                if ($v->goo_class == 2) {
                    $where['gosa_goo_id'] = $v->goo_id;
                    $where['gosa_shop_id'] = $shop_id;
                    $find_gosa_data = DB::table('goods_system_affiliate')
                        ->where($where)
                        ->select('gosa_wholesale_price', 'gosa_another_name')
                        ->first();
                    if ($find_gosa_data) {
                        $list_data[$k]->goo_price = $find_gosa_data->gosa_wholesale_price;
                        $list_data[$k]->goaf_another_name = $find_gosa_data->gosa_another_name;
                    } else {
                        $list_data[$k]->goaf_price = 0;
                        $list_data[$k]->goaf_another_name = '';
                    }
                }
            }
            // 查询品牌系列数据
            $goo_brse_id = array_filter(array_unique(array_column($list_items, 'goo_brse_id')));
            if ($goo_brse_id) {
                $brse_data = DB::table('brand_serie')
                    ->whereIn('brse_id', $goo_brse_id)
                    ->select('brse_id', 'brse_name')
                    ->get();
            }
            // 门店版 查询门店版本
            $shop_versions = DB::table('shop')
                ->where('shop_id', $shop_id)
                ->value('shop_versions');
            if ($shop_versions == 1) {
                foreach ($list_items as $key => $value) {
                    $gocs_goods_state = DB::table('goods_correlation_system')
                        ->where('goco_goo_id', $value->goo_id)
                        ->value('goco_state');
                    if ($gocs_goods_state) {
                        $list_items[$key]->goco_state = $gocs_goods_state;
                    } else {
                        $list_items[$key]->goco_state = 1;
                    }
                }
            } else {
                foreach ($list_items as $key => $value) {
                    $gocs_goods_state = DB::table('goods_correlation_system')
                        ->where('goco_parent_goo_id', $value->goo_id)
                        ->value('goco_state');
                    if ($gocs_goods_state) {
                        $list_items[$key]->goco_state = $gocs_goods_state;
                    } else {
                        $list_items[$key]->goco_state = 1;
                    }
                }
            }
        }
        $data_info['data'] = $list_items; //返回数据
        $data_info['brse_data'] = $brse_data;
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //获取top按钮
        $sea_button_data = 'add,start,stop';
        $sea_button_data = CommonService::getTopButton('lead,exportGoods',$sea_button_data,$list_button);
        if ($list_items) {
            if ($list_button) {
                foreach ($list_items as $key => $value) {
                    foreach ($list_button as $key_b => $value_b) {
                        if ($value_b['pri_operate_method'] == 'info') {//详情
                            $list_items[$key]->list_button_one[] = $value_b;
                        }
                        if ($user_info->adm_shop_id == $value->goo_shop_id) {
                            if ($value_b['pri_operate_method'] == 'edit') {//编辑
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'stop' && $value->goo_state == 1) {//停用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'start' && $value->goo_state == 2) {//启用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'bindList') {//绑定列表
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            $list_items[$key]->edit = 1;
                        }
                    }
                    if ($user_info->adm_shop_id != $value->goo_shop_id) {
                        $list_items[$key]->edit = 2;
                    }
                }
            }
            $data_info['data'] = $list_items; //返回数据
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info, 'list_button' => $list_button, 'sea_button_data'=>$sea_button_data]);
        } else {
            return response()->json(['code' => 200, 'msg' => '暂无数据', 'data' => $data_info, 'list_button' => $list_button, 'sea_button_data'=>$sea_button_data]);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            $error_message = CommonService::validatorToString($error_message);
            return response()->json(['code' => 500, 'msg' => 'error', 'data' => $error_message, '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' => '信息项存在空项', '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(function ($query) use ($user_info) {
                $query->where('goo_shop_id', 0)
                    ->orwhere('goo_shop_id', $user_info->adm_shop_id);
            })
            ->where('goo_name', $request['goo_name'])
            ->select('goo_id')
            ->first();
        if ($find_goo) {
            return response()->json(['code' => 500, 'msg' => '商品名称已存在', 'data' => '商品名称已存在']);
        }

        // 判断检索编码是否存在
        if (!empty($request['goo_goods_encode'])) {
            $find_goo = DB::table('goods')
                ->where('goo_delete', 1)
                ->where(function ($query) use ($user_info) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                })
                ->where('goo_goods_encode', $request['goo_goods_encode'])
                ->select('goo_id')
                ->first();
            if ($find_goo) {
                return response()->json(['code' => 500, 'msg' => '检索编码已存在', 'data' => '检索编码已存在']);
            }
        }

        // 判断商品编号是否存在
        if (!empty($request['goo_goods_code'])) {
            $find_goo = DB::table('goods')
                ->where('goo_delete', 1)
                ->where(function ($query) use ($user_info) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                })
                ->where('goo_goods_code', $request['goo_goods_code'])
                ->select('goo_id')
                ->first();
            if ($find_goo) {
                return response()->json(['code' => 500, 'msg' => '商品编号已存在', '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_type'] = $request['goo_type'];   //1正常商品2赠品商品3活动商品4旧货商品5无库存商品
        $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_assign_state'] = $request->input('goo_assign_state', 1); //商品派单状态：1不允许派单2允许派单
        $goo_add_data['goo_system_code'] = str_pad($user_info->adm_cid, '4', '0', STR_PAD_RIGHT) . str_pad($user_info->adm_shop_id, '5', '0', STR_PAD_RIGHT) . rand(10, 99) . rand(100000000, 999999999); //系统编码
        $goo_add_data['goo_unta_id'] = $request['goo_unta_id']; //商品单位id
        if ($request['goo_unta_id'] == 1) {
            $goo_level = 1;
        } elseif ($request['goo_unta_id'] == 4) {
            $goo_level = 2;
        } else {
            $goo_level = 3;
        }
        $goo_add_data['goo_level'] = $goo_level; //商品单位id
        if ($request['goo_unta_id'] == 1) {//卷
            if (empty($request['goo_unit_conversion'])) {
                return response()->json(['code' => 500, 'msg' => '请输入每卷长度', 'data' => '请输入每卷长度']);
            }
            $goo_add_data['goo_unit_conversion'] = isset($request['goo_unit_conversion']) ? $request['goo_unit_conversion'] : ''; //商品单位换算每卷多少米
        }
        $goo_add_data['goo_unit'] = $request['goo_unit']; //商品单位名称
        $goo_add_data['goo_commodity_propert'] = $request['goo_commodity_propert']; //商品属性：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'];
        }
        // 判断是否选择品牌系列
        if ($request['goo_brse_id']) {
            $goo_add_data['goo_brse_id'] = $request['goo_brse_id'];
        }
        if ($request['goo_pic']) {
            $goo_add_data['goo_pic'] = $request['goo_pic'];
        } else {
            $goo_add_data['goo_pic'] = config('apisystem.server_name_https').'/storage/image/default_goo_img.png';
        }
        // 新增商品
        $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.商品所属品类数量更改
        $find_caco_id = DB::table('category_correlation')
            ->where('caco_cate_id', $request['goo_cate_id'])
            ->where('caco_shop_id', $user_info->adm_shop_id)
            ->value('caco_id');
        if ($find_caco_id) {
            if ($request['goo_unta_id'] == 1) {
                $res_cate = DB::table('category_correlation')
                    ->where('caco_cate_id', $request['goo_cate_id'])
                    ->where('caco_shop_id', $user_info->adm_shop_id)
                    ->increment('caco_goods_number', 2);
            } else {
                $res_cate = DB::table('category_correlation')
                    ->where('caco_cate_id', $request['goo_cate_id'])
                    ->where('caco_shop_id', $user_info->adm_shop_id)
                    ->increment('caco_goods_number', 1);
            }
        } else {
            // 没有数据，新增数据
            $add_caco_data['caco_shop_id'] = $user_info->adm_shop_id;
            $add_caco_data['caco_cate_id'] = $request['goo_cate_id'];
            $add_caco_data['caco_goods_number'] = $request['goo_unta_id'] == 1?2:1;
            $add_caco_data['caco_update_time'] = date('Y-m-d H:i:s');
            $res_cate = DB::table('category_correlation')->insert($add_caco_data);
        }

        // 5.商品所属品牌数量更改
        if ($request['goo_bra_id']) {
            // 查询关联表是否有数据
            $find_brco_id = DB::table('brand_correlation')
                ->where('brco_bra_id', $request['goo_bra_id'])
                ->where('brco_shop_id', $user_info->adm_shop_id)
                ->value('brco_id');
            if ($find_brco_id) {
                // 有数据增加数量
                if ($request['goo_unta_id'] == 1) {
                    $res_brand = DB::table('brand_correlation')
                        ->where('brco_bra_id', $request['goo_bra_id'])
                        ->where('brco_shop_id', $user_info->adm_shop_id)
                        ->increment('brco_goods_number', 2);
                } else {
                    $res_brand = DB::table('brand_correlation')
                        ->where('brco_bra_id', $request['goo_bra_id'])
                        ->where('brco_shop_id', $user_info->adm_shop_id)
                        ->increment('brco_goods_number', 1);
                }
            } else {
                // 没有数据，新增数据
                $add_brco_data['brco_shop_id'] = $user_info->adm_shop_id;
                $add_brco_data['brco_bra_id'] = $request['goo_bra_id'];
                $add_brco_data['brco_goods_number'] = $request['goo_unta_id'] == 1?2:1;
                $add_brco_data['brco_update_time'] = date('Y-m-d H:i:s');
                $res_brand = DB::table('brand_correlation')->insert($add_brco_data);
            }
        } else {
            $res_brand = true;
        }

        // 商品所属品牌系列数量更改
        if ($request['goo_brse_id']) {
            // 查询系列关联表是否有数据
            $find_brsc_id = DB::table('brand_serie_correlation')
                ->where('brsc_brse_id', $request['goo_brse_id'])
                ->where('brsc_shop_id', $user_info->adm_shop_id)
                ->value('brsc_id');
            if ($find_brsc_id) {
                // 有数据增加数量
                if ($request['goo_unta_id'] == 1) {
                    $res_brand_serie = DB::table('brand_serie_correlation')
                        ->where('brsc_brse_id', $request['goo_brse_id'])
                        ->where('brsc_shop_id', $user_info->adm_shop_id)
                        ->increment('brsc_goods_number', 2);
                } else {
                    $res_brand_serie = DB::table('brand_serie_correlation')
                        ->where('brsc_brse_id', $request['goo_brse_id'])
                        ->where('brsc_shop_id', $user_info->adm_shop_id)
                        ->increment('brsc_goods_number', 1);
                }
            } else {
                // 没有数据，新增数据
                $add_brsc_data['brsc_shop_id'] = $user_info->adm_shop_id;
                $add_brsc_data['brsc_brse_id'] = $request['goo_brse_id'];
                $add_brsc_data['brsc_goods_number'] = $request['goo_unta_id'] == 1?2:1;
                $add_brsc_data['brsc_update_time'] = date('Y-m-d H:i:s');
                $res_brand_serie = DB::table('brand_serie_correlation')->insert($add_brsc_data);
            }
        } else {
            $res_brand_serie = true;
        }
        // 新增单位字数限制
        if ($request['goo_unit']) {
            if (strlen($request['goo_unit']) > 40) {
                return response()->json(['code' => 500, 'msg' => '单位最多20个字符', 'data' => '单位最多20个字符']);
            }
            // $goo_add_data['goo_unit'] = $request['goo_unit'];
        }
        if ($request['goo_unta_id'] == 1) {//卷
            $post['goo_add_data'] = $goo_add_data;
            $add_res = $this->addAffiliatedGood($user_info, $post,$goo_id,$request['goaf_another_name']);
        }

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


    // 新增卷的附属商品
    public function addAffiliatedGood($user_info,$request,$goo_id,$goaf_another_name) {
        $goods = $request['goo_add_data'];
        $goods['goo_unta_id'] = 4;
        $goods['goo_fid'] = $goo_id;
        $goods['goo_unit'] = '米';
        $goods['goo_price'] = isset($goods['goo_price']) ? round($goods['goo_price']/$goods['goo_unit_conversion']) : 0;
        $goods['goo_wholesale_price'] = round($goods['goo_wholesale_price']/$goods['goo_unit_conversion']);
        $goods['goo_purchase_price'] = round($goods['goo_purchase_price']/$goods['goo_unit_conversion']);
        $goods['goo_level'] = $goods['goo_level'] + 1;
        $goods['goo_unit_conversion'] = 0;
        // $goods['goo_system_code'] = str_pad($user_info->adm_cid, '4', '0', STR_PAD_RIGHT) . str_pad($user_info->adm_shop_id, '5', '0', STR_PAD_RIGHT) . rand(10, 99) . rand(100000000, 999999999); //系统编码
        $col_goo_id = DB::table('goods')->insertGetId($goods);
        // 3. 判断是否有商品别名
        if ($goaf_another_name) {
            $goaf_add_data = [
                'goaf_goo_id' => $col_goo_id,
                'goaf_shop_id' => $user_info->adm_shop_id,
                'goaf_another_name' => $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;
        }
    }

    /**
     * 根据卷的商品id转换成米的
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-06-21
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function searchColGoods(Request $request) {
        $find_goods = DB::table('goods')
            ->where('goo_id', $request['goo_id'])
            ->first();
        $return_goods = [];
        if ($find_goods->goo_level == 1) {
            $return_goods = DB::table('goods')
                ->where('goo_fid', $find_goods->goo_id)
                ->where('goo_level', 2)
                ->first();
        } elseif ($find_goods->goo_level == 2) {
            $return_goods = DB::table('goods')
                ->where('goo_id', $find_goods->goo_fid)
                ->where('goo_level', 1)
                ->first();
        }
        if (!empty($return_goods)) {
            $return_goods->goo_price = $return_goods->goo_wholesale_price;
            if ($return_goods->goo_level == 1 ||($return_goods->goo_level == 2 && !empty($return_goods->goo_fid))) {
                $return_goods->goo_change = 1;
            } else {
                $return_goods->goo_change = 2;
            }
            $goo_brse_name = DB::table('brand_serie')
                ->where('brse_id', $return_goods->goo_brse_id)
                ->value('brse_name');
            $return_goods->goo_brse_name = !empty($goo_brse_name) ? $goo_brse_name:'';

        }
        if ($return_goods) {
            if ($request['ware_id']) {
                // 仓库商品表数据
                $stock_data = DB::table('warehouse as a')
                    ->leftJoin('warehouse_goods as b', 'b.wago_ware_id', '=', 'a.ware_id')
                    ->where('ware_state', 1) //  状态1启用2停用3撤仓
                    ->where('wago_class', 1)
                    ->where('ware_id', $request['ware_id'])
                    ->where('wago_goo_id', $return_goods->goo_id)
                    ->select('wago_id', 'wago_goo_id', 'ware_id', 'ware_name', 'wago_stock_number', 'wago_lock_quantity', 'wago_priority_stock_number', 'wago_priority_lock_quantity')
                    ->orderBy('wago_stock_number', 'desc')
                    ->get()->toArray();
                $return_goods->stock_data = $stock_data;
            } else {
                $return_goods->stock_data = [];
            }
        }
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $return_goods]);
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $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) {
            // 查询无库存商品数据
            if ($request['goo_type'] == 5) {
                $goods_list = new GoodsList;
                $return_data = $goods_list->edit($user_info, $request->all());
                return response()->json($return_data);
            }

            // 获取编辑页面数据
            $find_data = DB::table('goods as a')
                ->leftJoin('goods_affiliate as b', 'a.goo_id', '=', 'b.goaf_goo_id')
                ->leftJoin('brand_serie as bs', 'bs.brse_id', '=', 'a.goo_brse_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', 'goo_ampere_hour', 'goo_assign_price', 'goo_direct_accounting_price', 'goo_assign_state', 'goo_brse_id', 'brse_name', 'goo_class', 'goo_recycle_price', 'goo_unit', 'goo_unta_id', 'goo_commodity_propert', 'goo_unit_conversion', 'goo_pic')
                ->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]);
        }

        // 1. 判断商品名称是否存在
        $find_goo = DB::table('goods')
            ->where('goo_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('goo_shop_id', 0)
                    ->orwhere('goo_shop_id', $user_info->adm_shop_id);
            })
            ->where('goo_name', $request['goo_name'])
            ->where('goo_id', '!=', $request['goo_id'])
            ->select('goo_id', 'goo_fid', 'goo_level')
            ->first();
        $goo_info = DB::table('goods')
            ->where('goo_id', $request['goo_id'])
            ->first();
        if ($find_goo) {
            if ($find_goo->goo_id != $goo_info->goo_fid && $goo_info->goo_id != $find_goo->goo_fid) {
                return response()->json(['code' => 500, 'msg' => '商品名称已存在', 'data' => '商品名称已存在']);
            }
        }
        if ($goo_info->goo_class == 2) {
            return response()->json(['code' => 500, 'msg' => '系统商品不允许修改', 'data' => '系统商品不允许修改']);
        }

        // 商品属性
        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' => '信息项存在空项', '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. 判断检索编码是否存在
        if (!empty($request['goo_goods_encode'])) {
            $find_goo = DB::table('goods')
                ->where(function ($query) use ($user_info) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                })
                ->where('goo_id', '<>', $request['goo_id'])
                ->where('goo_delete', 1)
                ->where('goo_type', 1)
                ->where('goo_goods_encode', $request['goo_goods_encode'])
                ->select('goo_id', 'goo_fid')
                ->first();
            if ($find_goo) {
                if ($find_goo->goo_id != $goo_info->goo_fid && $goo_info->goo_id != $find_goo->goo_fid) {
                    return response()->json(['code' => 500, 'msg' => '检索编码已存在', 'data' => '检索编码已存在']);
                }
            }
        }

        // 判断商品编号是否存在
        if (!empty($request['goo_goods_code'])) {
            $find_goo = DB::table('goods')
                ->where('goo_delete', 1)
                ->where('goo_type', 1)
                ->where(function ($query) use ($user_info) {
                    $query->where('goo_shop_id', 0)
                        ->orwhere('goo_shop_id', $user_info->adm_shop_id);
                })
                ->where('goo_id', '!=', $request['goo_id'])
                ->where('goo_goods_code', $request['goo_goods_code'])
                ->select('goo_id', 'goo_fid')
                ->first();
            if ($find_goo) {
                if ($find_goo->goo_id != $goo_info->goo_fid && $goo_info->goo_id != $find_goo->goo_fid) {
                    return response()->json(['code' => 500, 'msg' => '商品编号已存在', 'data' => '商品编号已存在']);
                }
            }
        }

        // 查询出商品未编辑前的商品品类/商品所属品牌数量更改
        $goods_info = DB::table('goods')
            ->where('goo_id', $request['goo_id'])
            ->select('goo_bra_id', 'goo_brse_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_recycle_price'] = $request->input('goo_recycle_price', 0) * 100; //回收金额
        // $goo_edit_data['goo_assign_price'] = $request->input('goo_assign_price', 0) * 100; //接单价
        // $goo_edit_data['goo_direct_accounting_price'] = $request->input('goo_direct_accounting_price', 0) * 100; //直营核算价
        // $goo_edit_data['goo_assign_state'] = $request->input('goo_assign_state', 1); //商品派单状态：1不允许派单2允许派单
        // $goo_edit_data['goo_ampere_hour'] = $request['goo_ampere_hour'] ?: '';    //安时
        $goo_edit_data['goo_unta_id'] = $request['goo_unta_id']; //商品单位id
        if ($request['goo_unta_id'] == 1) {
            $goo_edit_data['goo_unit_conversion'] = isset($request['goo_unit_conversion']) ? $request['goo_unit_conversion'] : ''; //商品单位换算每卷多少米
        }
        $goo_edit_data['goo_unit'] = $request['goo_unit']; //商品单位名称
        $goo_edit_data['goo_commodity_propert'] = $request['goo_commodity_propert']; //商品属性：1成品2原材料
        $goo_edit_data['goo_pic'] = !empty($request['goo_pic']) ? $request['goo_pic'] : config('apisystem.server_name_https').'/storage/image/default_goo_img.png'; //商品属性：1成品2原材料
        $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'] = '';
        }
        // 判断是否选择品牌系列
        if ($request['goo_brse_id']) {
            if (empty($request['goo_bra_id'])) {
                return response()->json(['code' => 500, 'msg' => '请选择所属品牌', 'data' => '请选择所属品牌']);
            }
            $goo_edit_data['goo_brse_id'] = $request['goo_brse_id'];
        } else {
            $goo_edit_data['goo_brse_id'] = 0;
        }
        //商品数量
        $num = 1;

        DB::beginTransaction();
        // 编辑商品
        $goo_res =  DB::table('goods')
            ->where('goo_id', $request['goo_id'])
            ->update($goo_edit_data);
        if ($goo_info->goo_level == 1 || $goo_info->goo_level == 2) {
            $new_update['goo_name'] = $goo_edit_data['goo_name'];
            $new_update['goo_goods_encode'] = $goo_edit_data['goo_goods_encode'];
            $new_update['goo_goods_code'] = $goo_edit_data['goo_goods_code'];
            $new_update['goo_cate_id'] = $goo_edit_data['goo_cate_id'];
            $new_update['goo_cate_name'] = $goo_edit_data['goo_cate_name'];
            $new_update['goo_commodity_propert'] = $goo_edit_data['goo_commodity_propert'];
            $new_update['goo_pic'] = $goo_edit_data['goo_pic'];
            $new_update['goo_bra_id'] = $goo_edit_data['goo_bra_id'];
            $new_update['goo_bra_name'] = $goo_edit_data['goo_bra_name'];
            $new_update['goo_brse_id'] = $goo_edit_data['goo_brse_id'];
            $new_update['goo_update_time'] = date('Y-m-d H:i:s');
            if ($goo_info->goo_level == 1) {
                $goo_res =  DB::table('goods')
                    ->where('goo_fid', $request['goo_id'])
                    ->update($new_update);
            } elseif ($goo_info->goo_level == 2) {
                $goo_res =  DB::table('goods')
                    ->where('goo_id', $goo_info->goo_fid)
                    ->update($new_update);
            }
            $num = 2;
        }

        // 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) {
            // 更改商品所属品类
            $find_cc = DB::table('category_correlation')
                ->where('caco_cate_id', $request['goo_cate_id'])
                ->where('caco_shop_id', $user_info->adm_shop_id)
                ->select('caco_id')
                ->first();
            if (empty($find_cc)) {
                DB::rollBack();
                return response()->json(['code' => 500, 'msg' => '请先创建品类', 'data' => '请先创建品类']);
            }
            $save_cate_add = DB::table('category_correlation')
                ->where('caco_cate_id', $request['goo_cate_id'])
                ->where('caco_shop_id', $user_info->adm_shop_id)
                ->increment('caco_goods_number', $num); //商品所属品类+1

            $save_cate_subtract = DB::table('category_correlation')
                ->where('caco_cate_id', $goods_info->goo_cate_id)
                ->where('caco_shop_id', $user_info->adm_shop_id)
                ->decrement('caco_goods_number', $num); //商品所属品类-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) {
            // 更改商品所属品牌
            $find_bc = DB::table('brand_correlation')
                ->where('brco_bra_id', $request['goo_bra_id'])
                ->where('brco_shop_id', $user_info->adm_shop_id)
                ->select('brco_id')
                ->first();
            if ($find_bc) {
                if ($request['goo_bra_id']) {
                    $save_bra_add = DB::table('brand_correlation')
                        ->where('brco_bra_id', $request['goo_bra_id'])
                        ->where('brco_shop_id', $user_info->adm_shop_id)
                        ->increment('brco_goods_number', $num); //商品所属品类+1
                } else {
                    $save_bra_add = true;
                }
            } else {
                DB::rollBack();
                return response()->json(['code' => 500, 'msg' => '请先创建品牌', 'data' => '请先创建品牌']);
            }


            if ($goods_info->goo_bra_id) {
                $save_bra_subtract = DB::table('brand_correlation')
                    ->where('brco_bra_id', $goods_info->goo_bra_id)
                    ->where('brco_shop_id', $user_info->adm_shop_id)
                    ->decrement('brco_goods_number', $num); //商品所属品类-1
            } else {
                $save_bra_subtract = true;
            }
            if ($save_bra_add && $save_bra_subtract) {
                $save_bra = true;
            } else {
                $save_bra = false;
            }
        } else {
            $save_bra = true;
        }

        // 6.判断是否更改商品所属品牌系列
        if ($request['goo_brse_id'] != $goods_info->goo_brse_id) {
            // 更改商品所属品牌
            $find_bsc = DB::table('brand_serie_correlation')
                ->where('brsc_brse_id', $request['goo_brse_id'])
                ->where('brsc_shop_id', $user_info->adm_shop_id)
                ->select('brsc_id')
                ->first();
            if (empty($find_bsc)) {
                DB::rollBack();
                return response()->json(['code' => 500, 'msg' => '请先创建品牌系列', 'data' => '请先创建品牌系列']);
            }
            if ($request['goo_brse_id']) {
                $save_brse_add = DB::table('brand_serie_correlation')
                    ->where('brsc_brse_id', $request['goo_brse_id'])
                    ->where('brsc_shop_id', $user_info->adm_shop_id)
                    ->increment('brsc_goods_number', $num);
            } else {
                $save_brse_add = true;
            }

            if ($goods_info->goo_brse_id) {
                $save_brse_dec = DB::table('brand_serie_correlation')
                    ->where('brsc_brse_id', $goods_info->goo_brse_id)
                    ->where('brsc_shop_id', $user_info->adm_shop_id)
                    ->decrement('brsc_goods_number', $num);
            } else {
                $save_brse_dec = true;
            }
            if ($save_brse_add && $save_brse_dec) {
                $save_brse = true;
            } else {
                $save_brse = false;
            }
        } else {
            $save_brse = true;
        }
        if ($goo_res && $goaf_res && $save_cate && $save_bra /*&& $goo_res_three && $goaf_res_three*/ && $save_brse) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '商品列表', '编辑', '编辑商品：' . $request['goo_name'] . '成功');
            return response()->json(['code' => 200, 'msg' => '编辑商品：成功', 'data' => '编辑商品：成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => '编辑商品：失败', 'data' => '编辑商品：失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => '参数错误', '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', 'goo_class')
            ->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);
        //修改其他类型状态
        $goo_count = DB::table('goods')
            ->whereIn('goo_fid', $request['goo_id'])
            ->count();
        if ($goo_count > 0) {
            $goo_fid_res = DB::table('goods')
                ->whereIn('goo_fid', $request['goo_id'])
                ->update($update_data);
        } else {
            $goo_fid_res = true;
        }

        if ($goo_res && $goo_fid_res) {
            Common::addLog($user_info, getRealIp($request), '商品列表', '上架', '商品：（' . implode(',', $goo_name) . '）上架成功');
            return response()->json(['code' => 200, 'msg' => '上架成功', 'data' => '上架成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => '上架失败', 'data' => '上架失败']);
        }
    }

    // 停用
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => '参数错误', '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', 'goo_id', 'goo_class', 'goo_goods_encode')
            ->get();
        $stock_number = '';
        foreach ($find_sepr as $key => $value) {
            $goo_name[] = $value->goo_name;
            $find_stock_number = DB::table('warehouse_goods as wg')
                ->leftjoin('warehouse as w', 'w.ware_id', '=', 'wg.wago_ware_id')
                ->where('ware_type', '<>', 2)
                ->where('wago_goo_id', $value->goo_id)
                ->where(function ($query) use ($user_info) {
                    $query->where('wago_stock_number', '>', 0)
                        ->orWhere('wago_lock_quantity', '>', 0)
                        ->orWhere('wago_priority_stock_number', '>', 0)
                        ->orWhere('wago_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_stock_number', '>', 0)
                        ->orWhere('wago_freight_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_priority_stock_number', '>', 0)
                        ->orWhere('wago_freight_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_unchecked_stock_number', '>', 0);
                })
                ->value('wago_id');
            if ($find_stock_number) {
                if (!empty($value->goo_goods_encode)) {
                    $stock_number .= $value->goo_goods_encode . '，';
                } else {
                    $stock_number .= $value->goo_name . '，';
                }
            }
        }
        if (!empty($stock_number)) {
            return response()->json(['code' => 500, 'msg' => $stock_number . '当前商品有库存数量，无法下架', 'data' => $stock_number . '当前商品有库存数量，无法下架']);
        }
        // 商品其他类型数据
        $find_other_type_data = DB::table('goods')
            ->whereIn('goo_fid', $request['goo_id'])
            ->select('goo_name', 'goo_id', 'goo_goods_encode')
            ->get()->toArray();
        $other_stock_number = '';
        foreach ($find_other_type_data as $key => $value) {
            $find_stock_number = DB::table('warehouse_goods as wg')
                ->leftjoin('warehouse as w', 'w.ware_id', '=', 'wg.wago_ware_id')
                ->where('ware_type', '<>', 2)
                ->where('wago_goo_id', $value->goo_id)
                ->where(function ($query) use ($user_info) {
                    $query->where('wago_stock_number', '>', 0)
                        ->orWhere('wago_lock_quantity', '>', 0)
                        ->orWhere('wago_priority_stock_number', '>', 0)
                        ->orWhere('wago_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_stock_number', '>', 0)
                        ->orWhere('wago_freight_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_priority_stock_number', '>', 0)
                        ->orWhere('wago_freight_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_unchecked_stock_number', '>', 0);
                })
                ->value('wago_id');
            if ($find_stock_number) {
                if (!empty($value->goo_goods_encode)) {
                    $other_stock_number .= $value->goo_goods_encode . '，';
                } else {
                    $other_stock_number .= $value->goo_name . '，';
                }
            }
        }
        if (!empty($other_stock_number)) {
            return response()->json(['code' => 500, 'msg' => $other_stock_number . '当前旧货商品有库存数量，无法删除', 'data' => $other_stock_number . '当前旧货商品有库存数量，无法删除']);
        }

        // 停用
        $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);

        // 修改其他类型状态
        $goo_count = DB::table('goods')
            ->whereIn('goo_fid', $request['goo_id'])
            ->count();
        if ($goo_count > 0) {
            $goo_fid_res = DB::table('goods')
                ->whereIn('goo_fid', $request['goo_id'])
                ->update($update_data);
        } else {
            $goo_fid_res = true;
        }

        if ($goo_res && $goo_fid_res) {
            Common::addLog($user_info, getRealIp($request), '商品列表', '下架', '商品：（' . implode(',', $goo_name) . '）下架成功');
            return response()->json(['code' => 200, 'msg' => '下架成功', 'data' => '下架成功']);
        } else {
            return response()->json(['code' => 500, 'msg' => '下架失败', 'data' => '下架失败']);
        }
    }

    // 删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => '参数错误', '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', 'goo_class', 'goo_cate_id', 'goo_bra_id', 'goo_brse_id', 'goo_id', 'goo_goods_encode')
            ->get();
        $goo_bra_id = []; //商品品牌
        $goo_brse_id = []; //商品系列
        $goo_cate_id = []; //商品品类
        $stock_number = '';
        foreach ($find_sepr as $key => $value) {
            if ($value->goo_class == 2) {
                return response()->json(['code' => 500, 'msg' => $value->goo_goods_encode . ' 系统商品无法删除', 'data' => $value->goo_goods_encode . ' 系统商品无法删除']);
            }
            $goo_name[] = $value->goo_name;
            // 品类id，删除商品所属品类数量
            if (isset($goo_cate_id[$value->goo_cate_id])) {
                $goo_cate_id[$value->goo_cate_id]++;
            } else {
                $goo_cate_id[$value->goo_cate_id] = 1;
            }
            if ($value->goo_bra_id) {
                // 商品选择了品牌id，删除商品所属品牌数量
                if (isset($goo_bra_id[$value->goo_bra_id])) {
                    $goo_bra_id[$value->goo_bra_id]++;
                } else {
                    $goo_bra_id[$value->goo_bra_id] = 1;
                }
            }

            if ($value->goo_brse_id) {
                // 商品选择了系列id，删除商品所属系列数量
                if (isset($goo_brse_id[$value->goo_brse_id])) {
                    $goo_brse_id[$value->goo_brse_id]++;
                } else {
                    $goo_brse_id[$value->goo_brse_id] = 1;
                }
            }

            $find_stock_number = DB::table('warehouse_goods as wg')
                ->leftjoin('warehouse as w', 'w.ware_id', '=', 'wg.wago_ware_id')
                ->where('ware_type', '<>', 2)
                ->where('wago_goo_id', $value->goo_id)
                ->where(function ($query) use ($user_info) {
                    $query->where('wago_stock_number', '>', 0)
                        ->orWhere('wago_lock_quantity', '>', 0)
                        ->orWhere('wago_priority_stock_number', '>', 0)
                        ->orWhere('wago_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_stock_number', '>', 0)
                        ->orWhere('wago_freight_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_priority_stock_number', '>', 0)
                        ->orWhere('wago_freight_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_unchecked_stock_number', '>', 0);
                })
                ->value('wago_id');
            if ($find_stock_number) {
                if (!empty($value->goo_goods_encode)) {
                    $stock_number .= $value->goo_goods_encode . '，';
                } else {
                    $stock_number .= $value->goo_name . '，';
                }
            }
        }
        if (!empty($stock_number)) {
            return response()->json(['code' => 500, 'msg' => $stock_number . '当前商品有库存数量，无法删除', 'data' => $stock_number . '当前商品有库存数量，无法删除']);
        }

        //商品其他类型数据
        $find_other_type_data = DB::table('goods')
            ->whereIn('goo_fid', $request['goo_id'])
            ->select('goo_name', 'goo_cate_id', 'goo_bra_id', 'goo_brse_id', 'goo_id', 'goo_goods_encode')
            ->get()->toArray();
        $other_stock_number = '';
        $other_goods = [];
        foreach ($find_other_type_data as $key => $value) {
            $other_goods[] = $value->goo_id;
            // 品类id，删除商品所属品类数量
            if (isset($goo_cate_id[$value->goo_cate_id])) {
                $goo_cate_id[$value->goo_cate_id]++;
            } else {
                $goo_cate_id[$value->goo_cate_id] = 1;
            }
            if ($value->goo_bra_id) {
                // 商品选择了品牌id，删除商品所属品牌数量
                if (isset($goo_bra_id[$value->goo_bra_id])) {
                    $goo_bra_id[$value->goo_bra_id]++;
                } else {
                    $goo_bra_id[$value->goo_bra_id] = 1;
                }
            }

            if ($value->goo_brse_id) {
                // 商品选择了系列id，删除商品所属系列数量
                if (isset($goo_brse_id[$value->goo_brse_id])) {
                    $goo_brse_id[$value->goo_brse_id]++;
                } else {
                    $goo_brse_id[$value->goo_brse_id] = 1;
                }
            }

            $find_stock_number = DB::table('warehouse_goods as wg')
                ->leftjoin('warehouse as w', 'w.ware_id', '=', 'wg.wago_ware_id')
                ->where('ware_type', '<>', 2)
                ->where('wago_goo_id', $value->goo_id)
                ->where(function ($query) use ($user_info) {
                    $query->where('wago_stock_number', '>', 0)
                        ->orWhere('wago_lock_quantity', '>', 0)
                        ->orWhere('wago_priority_stock_number', '>', 0)
                        ->orWhere('wago_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_stock_number', '>', 0)
                        ->orWhere('wago_freight_lock_quantity', '>', 0)
                        ->orWhere('wago_freight_priority_stock_number', '>', 0)
                        ->orWhere('wago_freight_priority_lock_quantity', '>', 0)
                        ->orWhere('wago_unchecked_stock_number', '>', 0);
                })
                ->value('wago_id');
            if ($find_stock_number) {
                if (!empty($value->goo_goods_encode)) {
                    $other_stock_number .= $value->goo_goods_encode . '，';
                } else {
                    $other_stock_number .= $value->goo_name . '，';
                }
            }
        }
        if (!empty($other_stock_number)) {
            return response()->json(['code' => 500, 'msg' => $other_stock_number . '当前旧货商品有库存数量，无法删除', 'data' => $other_stock_number . '当前旧货商品有库存数量，无法删除']);
        }

        DB::beginTransaction();
        // 1. 商品所属品类数量更改
        if ($goo_cate_id) {
            foreach ($goo_cate_id as $cate_id => $amount) {
                $caco_res = DB::table('category_correlation')
                    ->where('caco_cate_id', $cate_id)
                    ->where('caco_shop_id', $user_info->adm_shop_id)
                    ->decrement('caco_goods_number', $amount);
                if (!$caco_res) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => '删除失败010', 'data' => '删除失败010']);
                }
            }
        }

        // 2. 商品所属品牌数量更改
        if ($goo_bra_id) {
            foreach ($goo_bra_id as $bra_id => $amount) {
                $bra_res = DB::table('brand_correlation')
                    ->where('brco_bra_id', $bra_id)
                    ->where('brco_shop_id', $user_info->adm_shop_id)
                    ->decrement('brco_goods_number', $amount);
                if (!$bra_res) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => '删除失败011', 'data' => '删除失败011']);
                }
            }
        }

        // 商品所属系列数量更改
        if ($goo_brse_id) {
            foreach ($goo_brse_id as $brse_id => $amount) {
                $brse_res = DB::table('brand_serie_correlation')
                    ->where('brsc_brse_id', $brse_id)
                    ->where('brsc_shop_id', $user_info->adm_shop_id)
                    ->decrement('brsc_goods_number', $amount);
                if (!$brse_res) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => '删除失败012', 'data' => '删除失败012']);
                }
            }
        }

        // 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 (count($other_goods) > 0) {
            $goo_fid_res = DB::table('goods')
                ->whereIn('goo_id', $other_goods)
                ->update($update_data);
        } else {
            $goo_fid_res = true;
        }
        if ($goo_res && $goo_fid_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '商品列表', '删除', '商品：（' . implode(',', $goo_name) . '）删除成功');
            return response()->json(['code' => 200, 'msg' => '删除成功', 'data' => '删除成功']);
        } else {
            DB::rollBack();
            return response()->json(['code' => 500, 'msg' => '删除失败', 'data' => '删除失败']);
        }
    }

    // 搜索库存
    public function searchStock(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->searchStockValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => '参数错误', '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 downTemplate(Request $request)
    {
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/Template/GoodsList.xlsx']);
    }

    // 批量新增导入
    public function lead(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->leadValidator($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;

        $file = $request->file('file');

        $res = $this->verifyLead($request);
        if (empty($res)) {
            if ($file->isValid()) {
                // 获取表格的大小，限制上传表格的大小5M
                $file_size = $_FILES['file']['size'];
                if ($file_size > 5 * 1024 * 1024) {
                    return response()->json(['code' => 500, 'msg' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M']);
                }

                // 限制上传表格类型
                $ext = $file->getClientOriginalExtension(); //文件拓展名
                if ($ext != 'xlsx') {
                    return response()->json(['code' => 500, 'msg' => '仅允许上传以xlsx结尾的后缀文件', 'data' => '仅允许上传以xlsx结尾的后缀文件']);
                }

                // 有Xls和Xlsx格式两种
                $objReader = IOFactory::createReader('Xlsx');
                $filename = $_FILES['file']['tmp_name'];
                $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                if ($highestRow < 3) {
                    return response()->json(['code' => 500, 'msg' => '未获取到商品数据', 'data' => '未获取到商品数据']);
                }
                if ($highestRow > 2503) {
                    return response()->json(['code' => 500, 'msg' => '一次最多导入1500条数据', 'data' => '一次最多导入1500条数据']);
                }

                // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
                $usersExits = [];
                $encode_arr = []; //系统编码
                $encode = []; //已存在的编码
                DB::beginTransaction();
                for ($j = 3; $j <= $highestRow; $j++) {
                    $goo_add['goo_cid'] = $user_info->adm_cid; //所属企业id
                    $goo_add['goo_shop_id'] = $user_info->adm_shop_id; //所属门店id
                    $goo_add['goo_superior_shop_id'] = $shop_id; //所属门店id

                    // 商品名称
                    $goo_add['goo_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                    if (empty($goo_add['goo_name'])) {
                        continue;
                        return response()->json(['code' => 500, 'msg' => '商品名称必填1', 'data' => '商品名称必填1']);
                    }
                    if (strlen($goo_add['goo_name']) > 240) {
                        return response()->json(['code' => 500, 'msg' => '商品名称最多80个字', 'data' => '商品名称最多80个字']);
                    }
                    // 单位
                    $goo_add['goo_unit'] = trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());
                    if (empty($goo_add['goo_unit'])) {
                        $goo_add['goo_unit'] = '';
                    } else {
                        if ($goo_add['goo_unit'] == '卷') {
                            $goo_add['goo_unta_id'] = 1;
                            $goo_add['goo_level'] = 1;
                        }
                        if ($goo_add['goo_unit'] == '厘米') {
                            $goo_add['goo_unta_id'] = 2;
                            $goo_add['goo_level'] = 3;
                        }
                        if ($goo_add['goo_unit'] == '个') {
                            $goo_add['goo_unta_id'] = 3;
                            $goo_add['goo_level'] = 3;
                        }
                        if ($goo_add['goo_unit'] == '米') {
                            $goo_add['goo_unta_id'] = 4;
                        }
                        if ($goo_add['goo_unit'] == '次') {
                            $goo_add['goo_unta_id'] = 5;
                            $goo_add['goo_level'] = 3;
                        }
                        if ($goo_add['goo_unit'] == '套') {
                            $goo_add['goo_unta_id'] = 6;
                            $goo_add['goo_level'] = 3;
                        }
                        if ($goo_add['goo_unit'] == '张') {
                            $goo_add['goo_unta_id'] = 7;
                            $goo_add['goo_level'] = 3;
                        }
                        if ($goo_add['goo_unit'] == '车') {
                            $goo_add['goo_unta_id'] = 8;
                            $goo_add['goo_level'] = 3;
                        }
                    }

                    // 商品别名
                    $goaf_add['goaf_another_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                    if (empty($goaf_add['goaf_another_name'])) {
                        $goaf_add['goaf_another_name'] = '';
                    }
                    // 检索编码
                    $goo_add['goo_goods_encode'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                    if (empty($goo_add['goo_goods_encode'])) {
                        $goo_add['goo_goods_encode'] = '';
                        $goo_goods_encode = false;
                    } else {
                        // 根据检索编号判断商品是否存在,不存在就新增
                        $goo_goods_encode = DB::table('goods')
                            ->where(function ($query) use ($user_info) {
                                $query->where('goo_cid', $user_info->adm_cid)
                                    ->orWhere('goo_cid', 0);
                            })
                            ->where(function ($query) use ($user_info) {
                                $query->where('goo_shop_id', $user_info->adm_shop_id)
                                    ->orWhere('goo_shop_id', 0);
                            })
                            ->where('goo_goods_encode', $goo_add['goo_goods_encode'])
                            ->where('goo_type', 1)
                            ->where('goo_delete', 1)
                            ->select('goo_goods_encode', 'goo_id', 'goo_class', 'goo_fid', 'goo_level')
                            ->orderBy('goo_id', 'desc')
                            ->first();
                        if (!$goo_goods_encode) {
                        } else {
                            if (!empty($goo_add['goo_goods_encode'])) {
                                $encode[] = $goo_add['goo_goods_encode'];
                            } else {
                                $encode[] = $goo_add['goo_name'];
                            }
                        }
                    }
                    // 商品品类
                    $goo_add['goo_cate_name'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                    if (empty($goo_add['goo_cate_name'])) {
                        return response()->json(['code' => 500, 'msg' => '商品品类必填', 'data' => '商品品类必填']);
                    }
                    // 查询商品品类是否存在
                    $cate_id = DB::table('category')
                        ->where(function ($query) use ($user_info) {
                            $query->where('cate_cid', $user_info->adm_cid)
                                ->orWhere('cate_cid', 0);
                        })
                        ->where(function ($query) use ($shop_id) {
                            $query->where('cate_shop_id', $shop_id)
                                ->orWhere('cate_shop_id', 0);
                        })
                        ->where('cate_name', $goo_add['goo_cate_name'])
                        ->where('cate_delete', 1)
                        ->where('cate_state', 1)
                        ->value('cate_id');
                    if ($goo_add['goo_unit'] == '卷') {
                        $num = 2;
                    } else {
                        $num = 1;
                    }
                    if (empty($cate_id)) {
                        $cate_data['cate_cid'] = $user_info->adm_cid;
                        $cate_data['cate_shop_id'] = $user_info->adm_shop_id;
                        $cate_data['cate_superior_shop_id'] = $shop_id;
                        $cate_data['cate_name'] = $goo_add['goo_cate_name'];
                        $cate_data['cate_create_time'] = date('Y-m-d H:i:s');
                        $cate_data['cate_goods_number'] = $num;
                        $cate_id = DB::table('category')->insertGetId($cate_data);
                        $caco_add['caco_shop_id'] = $user_info->adm_shop_id;
                        $caco_add['caco_cate_id'] = $cate_id;
                        $caco_add['caco_goods_number'] = $num;
                        $caco_id = DB::table('category_correlation')->insert($caco_add);
                        if (!$cate_id || !$caco_id) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '品类添加失败', 'data' => '品类添加失败']);
                        }
                        unset($cate_data);
                        unset($caco_add);
                    } else {
                        $category_addnum = DB::table('category_correlation')
                            ->where('caco_shop_id', $user_info->adm_shop_id)
                            ->where('caco_cate_id', $cate_id)
                            ->increment('caco_goods_number', $num);
                        if (!$category_addnum) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '品类数量更新失败', 'data' => '品类数量更新失败']);
                        }
                    }
                    $goo_add['goo_cate_id'] = $cate_id;

                    // 商品品牌
                    $goo_add['goo_bra_name'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                    if (empty($goo_add['goo_bra_name'])) {
                        $goo_add['goo_bra_name'] = ''; //品牌名称
                        $goo_add['goo_bra_id'] = 0; //品牌id
                        $goo_add['goo_brse_id'] = 0; //品牌系列id
                    } else {
                        // 查询商品品牌是否存在
                        $bra_id = DB::table('brand')
                            ->where(function ($query) use ($user_info) {
                                $query->where('bra_cid', $user_info->adm_cid)
                                    ->orWhere('bra_cid', 0);
                            })
                            ->where(function ($query) use ($user_info) {
                                $query->where('bra_shop_id', $user_info->adm_shop_id)
                                    ->orWhere('bra_shop_id', 0);
                            })
                            ->where('bra_name', $goo_add['goo_bra_name'])
                            ->where('bra_delete', 1)
                            ->where('bra_state', 1)
                            ->value('bra_id');
                        if (empty($bra_id)) {
                            $bra_data['bra_cid'] = $user_info->adm_cid;
                            $bra_data['bra_shop_id'] = $user_info->adm_shop_id;
                            $bra_data['bra_superior_shop_id'] = $shop_id;
                            $bra_data['bra_name'] = $goo_add['goo_bra_name'];
                            $bra_data['bra_create_time'] = date('Y-m-d H:i:s');
                            $bra_data['bra_goods_number'] = $num;
                            $bra_id = DB::table('brand')->insertGetId($bra_data);
                            $brco_add['brco_bra_id'] = $bra_id;
                            $brco_add['brco_shop_id'] = $shop_id;
                            $brco_add['brco_goods_number'] = $num;
                            $brco_id = DB::table('brand_correlation')->insertGetId($brco_add);
                            if (!$bra_id || !$brco_id) {
                                DB::rollBack();
                                return response()->json(['code' => 500, 'msg' => '新品牌添加失败', 'data' => '新品牌添加失败']);
                            }
                            unset($bra_data);
                            unset($brco_add);
                        } else {
                            $brand_addnum = DB::table('brand_correlation')
                                ->where('brco_shop_id', $user_info->adm_shop_id)
                                ->where('brco_bra_id', $bra_id)
                                ->increment('brco_goods_number', $num);
                            if (!$brand_addnum) {
                                DB::rollBack();
                                return response()->json(['code' => 500, 'msg' => '品牌数量更新失败', 'data' => '品牌数量更新失败']);
                            }
                        }
                        $goo_add['goo_bra_id'] = $bra_id;
                        if ($goo_add['goo_bra_id']) {
                            // 品牌系列
                            $brse_name = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                            if (!empty($brse_name)) {
                                $brse_id = DB::table('brand_serie')
                                    ->where(function ($query) use ($user_info) {
                                        $query->where('brse_cid', $user_info->adm_cid)
                                            ->orWhere('brse_cid', 0);
                                    })
                                    ->where(function ($query) use ($user_info) {
                                        $query->where('brse_shop_id', $user_info->adm_shop_id)
                                            ->orWhere('brse_shop_id', 0);
                                    })
                                    ->where('brse_bra_id', $goo_add['goo_bra_id'])
                                    ->where('brse_name', $brse_name)
                                    ->where('brse_delete', 1)
                                    ->where('brse_state', 1)
                                    ->value('brse_id');
                                if (empty($brse_id)) {
                                    $brse_data['brse_cid'] = $user_info->adm_cid;
                                    $brse_data['brse_shop_id'] = $user_info->adm_shop_id;
                                    $brse_data['brse_superior_shop_id'] = $shop_id;
                                    $brse_data['brse_bra_id'] = $goo_add['goo_bra_id'];
                                    $brse_data['brse_cate_id'] = $cate_id;
                                    $brse_data['brse_name'] = $brse_name;
                                    $brse_data['brse_create_time'] = date('Y-m-d H:i:s');
                                    $brse_data['brse_goods_number'] = $num;
                                    $brse_id = DB::table('brand_serie')->insertGetId($brse_data);
                                    $brsc_add['brsc_shop_id'] = $user_info->adm_shop_id;
                                    $brsc_add['brsc_brse_id'] = $brse_id;
                                    $brsc_add['brsc_goods_number'] = $num;
                                    $brsc_id = DB::table('brand_serie_correlation')->insertGetId($brsc_add);
                                    if (!$brse_id || !$brsc_id) {
                                        DB::rollBack();
                                        return response()->json(['code' => 500, 'msg' => '系列添加失败', 'data' => '系列添加失败']);
                                    }
                                } else {
                                    $brand_serie_addnum = DB::table('brand_serie_correlation')
                                        ->where('brsc_shop_id', $shop_id)
                                        ->where('brsc_brse_id', $brse_id)
                                        ->increment('brsc_goods_number', $num);
                                    if (!$brand_serie_addnum) {
                                        DB::rollBack();
                                        return response()->json(['code' => 500, 'msg' => '系列数量更新失败', 'data' => '系列数量更新失败']);
                                    }
                                }
                                $goo_add['goo_brse_id'] = $brse_id;
                            } else {
                                $goo_add['goo_brse_id'] = 0; //品牌系列id
                            }
                        } else {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '请选择所属品牌', 'data' => '请选择所属品牌']);
                        }
                    }

                    // 零售价
                    // $goo_add['goo_price'] = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                    // if (empty($goo_add['goo_price'])) {
                    //     $goo_add['goo_price'] = 0;
                    // } else {
                    //     $goo_add['goo_price'] = trim($goo_add['goo_price']) * 100;
                    // }

                    // 零售价
                    $goo_add['goo_wholesale_price'] = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                    if (empty($goo_add['goo_wholesale_price'])) {
                        $goo_add['goo_wholesale_price'] = 0;
                    } else {
                        $goo_add['goo_wholesale_price'] = trim($goo_add['goo_wholesale_price']) * 100;
                    }

                    // 采购价
                    $goo_add['goo_purchase_price'] = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                    if (empty($goo_add['goo_purchase_price'])) {
                        $goo_add['goo_purchase_price'] = 0;
                    } else {
                        $goo_add['goo_purchase_price'] = trim($goo_add['goo_purchase_price']) * 100;
                    }

                    // 商品属性：1成品2原材料
                    $goo_commodity_propert = trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue());
                    if (empty($goo_commodity_propert)) {
                        return response()->json(['code' => 500, 'msg' => '商品属性必填', 'data' => '商品属性必填']);
                    }
                    if ($goo_commodity_propert == '成品') {
                        $goo_add['goo_commodity_propert'] = 1;
                    } elseif ($goo_commodity_propert == '原料') {
                        $goo_add['goo_commodity_propert'] = 2;
                    }

                    if (strlen($goo_add['goo_unit']) > 60) {
                        return response()->json(['code' => 500, 'msg' => '单位最多20个字', 'data' => '单位最多20个字']);
                    }

                    // 商品信息
                    $supplier = [];
                    $goo_attribute = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue();
                    if (!empty($goo_attribute)) {
                        $goo_attribute = explode(',', trim($goo_attribute));
                        foreach ($goo_attribute as $key => $value) {
                            if ($value) {
                                if (strpos($value, '：') === false) {
                                    DB::rollBack();
                                    return response()->json(['code' => 500, 'msg' => '商品属性格式不正确1', 'data' => '']);
                                }
                                $goo_attributes = explode('：', $value);
                                $supplier[] = ['key' => $goo_attributes[0], 'value' => $goo_attributes[1]];
                                $goo_add['goo_attribute'] = json_encode($supplier);
                                unset($goo_attributes);
                            }
                        }
                    } else {
                        $goo_add['goo_attribute'] = '';
                    }

                    $goo_add['goo_unit_conversion'] = $objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue();
                    if (empty($goo_add['goo_unit_conversion'])) {
                        $goo_add['goo_unit_conversion'] = '';
                    }
                    if ($goo_goods_encode) {
                    } else {
                        $goo_add['goo_type'] = 1;   //1正常商品2赠品商品3活动商品4旧货商品
                        $goo_add['goo_fid'] = 0;

                        $goo_add['goo_system_code'] = str_pad($user_info->adm_cid, '4', '0', STR_PAD_RIGHT) . str_pad($user_info->adm_shop_id, '5', '0', STR_PAD_RIGHT) . rand(10, 99) . rand(100000000, 999999999); //系统编码
                        $goo_id = DB::table('goods')->insertGetId($goo_add);
                        if ($goo_add['goo_unit'] == '卷') {
                            $post['goo_add_data'] = $goo_add;
                            $add_res = $this->addAffiliatedGood($user_info, $post,$goo_id,$goaf_add['goaf_another_name']);
                        }
                        if (!empty($goaf_add['goaf_another_name'])) {
                            $goaf_add['goaf_shop_id'] = $user_info->adm_shop_id;
                            // 查询正常商品是否存在
                            $goaf_id = DB::table('goods_affiliate')
                                ->where('goaf_goo_id', $goo_id)
                                ->where('goaf_shop_id', $user_info->adm_shop_id)
                                ->value('goaf_id');
                            if ($goaf_id) {
                                $goaf_add['goaf_goo_id'] = $goo_id;
                                $goaf_add['goaf_update_time'] = date('Y-m-d H:i:s');
                                $goaf_res = DB::table('goods_affiliate')
                                    ->where('goaf_goo_id', $goo_id)
                                    ->where('goaf_shop_id', $user_info->adm_shop_id)
                                    ->update($goaf_add);
                            } else {
                                $goaf_add['goaf_goo_id'] = $goo_id;
                                $goaf_res = DB::table('goods_affiliate')->insert($goaf_add);
                            }
                        } else {
                            $goaf_res = true;
                        }
                        if (!$goo_id || !$goaf_res) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '上传失败03', 'data' => '上传失败03']);
                        }
                    }
                    unset($goo_add);
                }
                if (!empty($encode_arr)) {
                    $data['time'] = date('Y-m-d H:i:s');
                    $data['user_info'] = $user_info;
                    $data['encode'] = $encode_arr;
                    logRecord($data, 'goods_lead_log', 2);
                }
                Common::addLog($user_info, getRealIp($request), '商品列表', '导入', '导入商品成功');
                DB::commit();
                return response()->json(['code' => 200, 'msg' => '上传成功', 'data' => '上传成功', 'num' => $highestRow - 2, 'encode' => $encode]);
            } else {
                return response()->json(['code' => 500, 'msg' => '上传有误，请重新上传！', 'data' => '上传有误，请重新上传！']);
            }
        } else {
            return response()->json(['code' => 500, 'msg' => $res, 'data' => $res]);
        }
    }

    // 批量新增验证
    public function verifyLead($request)
    {
        $file = $request->file('file');

        if ($file->isValid()) {
            // 获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return response()->json(['code' => 500, 'msg' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M']);
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return response()->json(['code' => 500, 'msg' => '仅允许上传以xlsx结尾的后缀文件', 'data' => '仅允许上传以xlsx结尾的后缀文件']);
            }

            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow < 3) {
                return response()->json(['code' => 500, 'msg' => '未获取到商品数据', 'data' => '未获取到商品数据']);
            }
            if ($highestRow > 2503) {
                return response()->json(['code' => 500, 'msg' => '一次最多导入2500条数据', 'data' => '一次最多导入2500条数据']);
            }

            // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
            $hint = '';
            for ($j = 3; $j <= $highestRow; $j++) {
                // 商品名称
                $goo_add['goo_name'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());

                if (empty($goo_add['goo_name'])) {
                    $hint .= '商品名称必填1，';
                }
                if (strlen($goo_add['goo_name']) > 240) {
                    $hint .= '商品名称最多80个字，';
                }
                // 商品品类
                $goo_add['goo_cate_name'] = trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue());
                if (empty($goo_add['goo_cate_name'])) {
                    $hint .= '商品品类必填2，';
                }
                $goo_add['goo_unit'] = trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());
                if (strlen($goo_add['goo_unit']) > 60) {
                    $hint .= '单位最多20个字，';
                }
                if (empty($goo_add['goo_unit'])) {
                    $hint .= '单位必填3，';
                }
                if ($goo_add['goo_unit'] == '卷') {
                    $goo_add['goo_unit_conversion'] = trim($objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue());
                    if (empty($goo_add['goo_unit_conversion'])) {
                        $hint .= '商品单位为卷时，单位长度必填，';
                    }
                } else {
                    $goo_add['goo_unit_conversion'] = '';
                }
                // 商品属性
                $goo_attribute = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue();
                if (!empty($goo_attribute)) {
                    $goo_attribute = explode(',', trim($goo_attribute));
                    foreach ($goo_attribute as $key => $value) {
                        if ($value) {
                            if (strpos($value, '：') === false) {
                                $hint .= '商品属性格式不正确3，';
                            }
                        }
                    }
                } else {
                    $goo_add['goo_attribute'] = '';
                }
            }
            return $hint;
        } else {
            return '上传有误,请重新上传';
        }
    }

    // 下拉搜索数据
    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', $request['goo_type'])
            ->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' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    // 订单外派-搜索商品
    public function assignSearch(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->assignSearchValidator($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;

        $search_data = $request->all();
        $list_data = DB::table('goods as goo')
            ->join('warehouse_goods as wago', 'wago.wago_goo_id', '=', 'goo.goo_id')
            ->join('warehouse as war', 'war.ware_id', '=', 'wago.wago_ware_id')
            ->where('goo_shop_id', $request['shop_id'])
            ->where('goo_delete', 1)
            ->where('goo_type', $request['goo_type'])
            ->where('goo_state', 1)
            ->where('goo_assign_state', 2) //商品派单状态：1不允许派单2允许派单
            ->where('ware_state', 1)
            ->where('ware_type', 1) //类型：1固定仓2移动仓
            ->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'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            }) //品牌id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            }) //品类id
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goo_type', 'goo_price', 'goo_assign_price', 'goo_ampere_hour')
            ->orderBy('goo_goods_encode', 'asc')
            ->groupBy('goo_id')
            ->paginate($this->show_count);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据
        if ($data_info['data']) {
            $goo_id = array_column($data_info['data'], 'goo_id');
            $stock_data = DB::table('warehouse as a')
                ->leftJoin('warehouse_goods as b', 'b.wago_ware_id', '=', 'a.ware_id')
                ->where('ware_shop_id', $request['shop_id'])
                ->where('ware_state', 1) //  状态1启用2停用3撤仓
                ->where('ware_type', 1) //类型：1固定仓2移动仓
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['waon_class'])) {
                        $query->where('wago_class', $search_data['waon_class']);
                    }
                }) //商品编码
                ->whereIn('wago_goo_id', $goo_id)
                ->select('wago_id', 'wago_goo_id', 'ware_id', 'ware_name', 'wago_stock_number', 'wago_priority_stock_number')
                ->orderBy('wago_stock_number', 'desc')
                ->get()->toArray();
            if (!empty($stock_data)) {
                $data_info['stock_data'] = $stock_data;
            } else {
                $data_info['stock_data'] = [];
            }
        } else {
            $data_info['stock_data'] = [];
        }
        if ($list_data) {
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => $data_info]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    // 导出
    public function exportGoods(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;

        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }
        $post['string'] = 'goo_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        DB::connection()->enableQueryLog();#开启执行日志
        $list_data = DB::table('goods as goo')
            ->leftJoin('goods_affiliate as goaf', 'goo.goo_id', '=', 'goaf.goaf_goo_id')
            ->where(function ($query) use ($shop_id, $where_data) {
                $query->whereIn($where_data['string'], $where_data['shop_id']); //门店id为0的是系统数据
            })
            ->where('goo_delete', 1)
            ->where('goo_type', $request['goo_type'])
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_name'])) {
                    $query->where('goo_name', 'like', '%' . $search_data['goo_name'] . '%');
                }
            }) //商品名称
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goaf_another_name'])) {
                    $query->where('goaf_another_name', 'like', '%' . $search_data['goaf_another_name'] . '%');
                }
            }) //别名
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_goods_encode'])) {
                    $query->where('goo_goods_encode', 'like', '%' . $search_data['goo_goods_encode'] . '%');
                }
            }) //检索编码
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_goods_code'])) {
                    $query->where('goo_goods_code', 'like', '%' . $search_data['goo_goods_code'] . '%');
                }
            }) //商品编号
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_state'])) {
                    $query->where('goo_state', $search_data['goo_state']);
                }
            }) //状态
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_bra_id'])) {
                    $query->where('goo_bra_id', $search_data['goo_bra_id']);
                }
            }) //品牌id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_cate_id'])) {
                    $query->where('goo_cate_id', $search_data['goo_cate_id']);
                }
            }) //品类id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_brse_id'])) {
                    $query->where('goo_brse_id', $search_data['goo_brse_id']);
                }
            }) //品牌系列id
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['goo_class'])) {
                    $query->where('goo_class', $search_data['goo_class']);
                }
            }) //类型：1自营商品2系统商品
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goaf_another_name', 'goo_cate_name', 'goo_bra_name', 'goo_brse_id', 'goo_ampere_hour', 'goo_price', 'goo_wholesale_price', 'goo_purchase_price', 'goo_assign_price', 'goo_recycle_price', 'goo_direct_accounting_price', 'goo_unit', 'goo_attribute', 'goo_class', 'goo_unit_conversion')
            ->orderBy('goo_id', 'desc')
            ->get()->toArray();
        $data['sqls'] = DB::getQueryLog()[0];
        $sqls = $data['sqls'];
        $excel = new CommonController();
        $amp_id = $search_data['amp_id']??0;
        return $excel->getExcelOut($amp_id,$user_info,$search_data['pri_id'], $sqls, $search_data['api_token']);
        // ini_set("memory_limit", "1024M");  // 根据电脑配置不够继续增加
        if (!empty($list_data)) {
            // 将对象转化为数组
            $list_data = json_decode(json_encode($list_data), true);
            $goo_id = [];
            $brse_id = [];
            foreach ($list_data as $key => $value) {
                if ($value['goo_brse_id']) {
                    $brse_id[] = $value['goo_brse_id'];
                }
            }
            $brse_id = array_unique($brse_id);
            // 查找系列id对应的系列名称
            $admin = DB::table('brand_serie')->whereIn('brse_id', $brse_id)->pluck('brse_name', 'brse_id');
            $goods_id = array_column($list_data, 'goo_id');
            // 查询系统商品属性表信息
            $gosa_data = DB::table('goods_system_affiliate')
                ->where('gosa_shop_id', $user_info->adm_shop_id)
                ->whereIn('gosa_goo_id', $goods_id)
                ->select('gosa_another_name', 'gosa_price', 'gosa_wholesale_price', 'gosa_purchase_price', 'gosa_recycle_price', 'gosa_assign_price', 'gosa_direct_accounting_price', 'gosa_goo_id')
                ->get()->toArray();
            $gosa_data = array_column($gosa_data, null, 'gosa_goo_id');
            foreach ($list_data as $key => $value) {
                $goo_id[] = $value['goo_id'];

                if (isset($admin[$value['goo_brse_id']])) {
                    $list_data[$key]['goo_brse_id'] = $admin[$value['goo_brse_id']];
                } else {
                    $list_data[$key]['goo_brse_id'] = '';
                }
                $list_data[$key]['goo_price'] = $value['goo_price'] / 100;
                $list_data[$key]['goo_wholesale_price'] = $value['goo_wholesale_price'] / 100;
                $list_data[$key]['goo_purchase_price'] = $value['goo_purchase_price'] / 100;
                $list_data[$key]['goo_assign_price'] = $value['goo_assign_price'] / 100;
                $list_data[$key]['goo_recycle_price'] = $value['goo_recycle_price'] / 100;
                $list_data[$key]['goo_direct_accounting_price'] = $value['goo_direct_accounting_price'] / 100;

                // 系统商品
                if ($value['goo_class'] == 2 && isset($gosa_data[$value['goo_id']]) && !empty($gosa_data[$value['goo_id']])) {
                    $list_data[$key]['goaf_another_name'] = $gosa_data[$value['goo_id']]->gosa_another_name;
                    $list_data[$key]['goo_price'] = $gosa_data[$value['goo_id']]->gosa_price / 100;
                    $list_data[$key]['goo_wholesale_price'] = $gosa_data[$value['goo_id']]->gosa_wholesale_price / 100;
                    $list_data[$key]['goo_purchase_price'] = $gosa_data[$value['goo_id']]->gosa_purchase_price / 100;
                    $list_data[$key]['goo_assign_price'] = $gosa_data[$value['goo_id']]->gosa_assign_price / 100;
                    $list_data[$key]['goo_recycle_price'] = $gosa_data[$value['goo_id']]->gosa_recycle_price / 100;
                    $list_data[$key]['goo_direct_accounting_price'] = $gosa_data[$value['goo_id']]->gosa_direct_accounting_price / 100;
                } else {
                    $list_data[$key]['goaf_another_name'] = '';
                }

                if (!empty($value['goo_attribute'])) {
                    $goo_attribute = json_decode($value['goo_attribute'], true);
                    $t = '';
                    foreach ($goo_attribute as $k => $v) {
                        $v = join("：", $v); // 可以用implode将一维数组转换为用逗号连接的字符串，join是别名
                        $temp[] = $v;
                    }
                    foreach ($temp as $a) {
                        $t .= $a . ", ";
                    }
                    $t = substr($t, 0, -1); // 利用字符串截取函数消除最后一个逗号
                    $list_data[$key]['goo_attribute'] = $t;
                    unset($temp);
                    unset($t);
                }
                $list_data[$key]['goo_unit_conversion'] = $value['goo_unit_conversion'];
                unset($list_data[$key]['goo_class']);
            }
            $pathName = storage_path() . "/app/public/excel"; //获取上传excel路径
            // 创建文件夹
            if (!file_exists($pathName)) {
                mkdir($pathName, 0775, true);
                chmod($pathName, 0775);
            }

            $streamFileRand = time() . rand(10000, 99999) . '.xlsx';
            // 产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
            $streamFilename = $pathName . '/' . $streamFileRand;

            $where['action_name'] = '商品表';
            $where['field_name'] = ['序列码', '商品名称', '检索编号', '商品别名', '商品品类', '商品品牌', '品牌系列',  '商品安时', '零售价', '批发价', '采购价', '接单价', '回收价', '直营核算价', '单位', '商品属性', '单位长度'];
            // 调用导出的公共方法
            export::publicExport(
                $streamFilename, //路径
                $where,    //sheet名及其每一行的标题
                $list_data      //导出数据
            );
            Common::addLog($user_info, getRealIp($request), '商品列表', '导出', '导出成功');
            return response()->json(['code' => 200, 'msg' => 'success', 'data' => 'storage/excel/' . $streamFileRand]);
        } else {
            return response()->json(['code' => 500, 'msg' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    // 系统编码
    public function importGoods(Request $request)
    {
        // 查询商品数据
        $goo_id = DB::table('goods')
            ->where('goo_system_code', '')
            ->select('goo_id', 'goo_cid', 'goo_shop_id')
            ->get()->toArray();

        foreach ($goo_id as $key => $value) {
            $device_name = str_pad($value->goo_cid, '4', '0', STR_PAD_RIGHT) . str_pad($value->goo_shop_id, '5', '0', STR_PAD_RIGHT);
            $str = $device_name . rand(1000, 9999) . rand(1000000, 9999999);
            $update_data['goo_system_code'] = $str;
            $update_data['goo_update_time'] = date('Y-m-d H:i:s');
            $res = DB::table('goods')
                ->where('goo_id', $value->goo_id)
                ->update($update_data);
            unset($device_name);
            unset($str);
            unset($update_data);
        }
    }

    // 获取品牌系列数据
    public function getBrandSerie(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();

        $shop_state = true;
        if (in_array($shop_id, config('apisystem.NO_SHOPID'))) {
            $shop_state = false;
        }

        $list_data  =  DB::table('brand_serie')
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('brse_cid', 0)
                        ->orwhere('brse_cid', $user_info->adm_cid);
                } else {
                    $query->where('brse_cid', $user_info->adm_cid);
                }
            })
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('brse_shop_id', 0)
                        ->orwhere('brse_shop_id', $user_info->adm_shop_id);
                } else {
                    $query->where('brse_shop_id', $user_info->adm_shop_id);
                }
            })
            ->where('brse_state', 1)
            ->where('brse_delete', 1)
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['brse_name'])) { //品牌系列名称
                    $query->where('brse_name', 'like', '%' . $search_data['brse_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bra_id'])) { //品牌id
                    $query->where('brse_bra_id', $search_data['bra_id']);
                }
            })
            ->orderBy('brse_sequence', 'asc')
            ->select('brse_id', 'brse_name', 'brse_cate_id', 'brse_second_cate_id')
            ->paginate($this->show_count);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $list_items = $list_data->items();
        $cate_data = []; //品类数据
        $cate_second_data = [];
        if ($list_items) {
            // 查询一级品类数据
            $brse_cate_id = array_filter(array_unique(array_column($list_items, 'brse_cate_id')));
            $brse_second_cate_id = array_filter(array_unique(array_column($list_items, 'brse_second_cate_id')));
            if ($brse_cate_id) {
                $cate_data = DB::table('category')
                    ->whereIn('cate_id', $brse_cate_id)
                    ->select('cate_id', 'cate_name', 'cate_parent_id')
                    ->get();
            }
            if ($brse_second_cate_id != '0') {
                $cate_second_data = DB::table('category')
                    ->whereIn('cate_id', $brse_second_cate_id)
                    ->select('cate_id', 'cate_name', 'cate_parent_id')
                    ->get();
            } else {
                $cate_second_data = [];
            }
        }
        $data_info['data'] = $list_items; //返回数据
        $data_info['cate_data'] = $cate_data;
        $data_info['cate_second_data'] = $cate_second_data;
        return response()->json(['code' => 200, 'msg' => 'success', 'data_info' => $data_info]);
    }

    // 详情
    public function info(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $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;

        $goods_data = DB::table('goods as a')
            ->leftJoin('goods_affiliate as b', 'a.goo_id', '=', 'b.goaf_goo_id')
            ->where('goo_id', $request['goo_id'])
            ->select('goo_id', 'goo_name', 'goo_goods_encode', 'goo_goods_code', 'goaf_another_name', 'goo_bra_name', 'goo_cate_name', 'goo_ampere_hour', 'goo_price', 'goo_wholesale_price', 'goo_purchase_price', 'goo_assign_price', 'goo_recycle_price', 'goo_direct_accounting_price', 'goo_assign_state', 'goo_state', 'goo_attribute', 'goo_brse_id', 'goo_unit', 'goo_system_code', 'goo_class', 'goo_commodity_propert', 'goo_unit_conversion', 'goo_unta_id')
            ->first();

        if ($goods_data->goo_unta_id == 1) {
            $goods_data->goo_unit = $goods_data->goo_unit . '(每卷' . $goods_data->goo_unit_conversion . '米)';
        }

        // 判断是否是系统商品
        if ($goods_data->goo_class == 2) {
            $where['gosa_shop_id'] = $shop_id;
            $where['gosa_goo_id'] = $goods_data->goo_id;
            $gosa_info = DB::table('goods_system_affiliate')
                ->where($where)
                ->select('gosa_price', 'gosa_wholesale_price', 'gosa_purchase_price', 'gosa_assign_price', 'gosa_recycle_price', 'gosa_direct_accounting_price', 'gosa_another_name')
                ->first();
            if ($gosa_info) {
                $goods_data->goo_price = $gosa_info->gosa_price; //零售价金额
                $goods_data->goo_wholesale_price = $gosa_info->gosa_wholesale_price; //批发价
                $goods_data->goo_purchase_price = $gosa_info->gosa_purchase_price; //采购价
                $goods_data->goo_recycle_price = $gosa_info->gosa_recycle_price; //回收价
                $goods_data->goo_assign_price = $gosa_info->gosa_assign_price; //接单价
                $goods_data->goo_direct_accounting_price = $gosa_info->gosa_direct_accounting_price; //直营核算价
                $goods_data->goaf_another_name = $gosa_info->gosa_another_name; //商品别名
            }
        }
        $goods_data->goo_brse_name = DB::table('brand_serie')
            ->where('brse_id', $goods_data->goo_brse_id)
            ->value('brse_name');
        return response()->json(['code' => 200, 'msg' => 'success', 'data' => $goods_data]);
    }

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

        ignore_user_abort();
        set_time_limit(0);

        // 获取当前操作账号信息
        $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;

        $file = $request->file('file');

        $res = $this->verifyEditGoods($request);
        if (empty($res)) {
            if ($file->isValid()) {
                // 获取表格的大小，限制上传表格的大小5M
                $file_size = $_FILES['file']['size'];
                if ($file_size > 5 * 1024 * 1024) {
                    return response()->json(['code' => 500, 'msg' => '文件大小不能超过5M', 'data' => '文件大小不能超过5M']);
                }

                // 限制上传表格类型
                $ext = $file->getClientOriginalExtension(); //文件拓展名
                if ($ext != 'xlsx') {
                    return response()->json(['code' => 500, 'msg' => '仅允许上传以xlsx结尾的后缀文件', 'data' => '仅允许上传以xlsx结尾的后缀文件']);
                }

                // 有Xls和Xlsx格式两种
                $objReader = IOFactory::createReader('Xlsx');
                $filename = $_FILES['file']['tmp_name'];
                $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                if ($highestRow < 2) {
                    return response()->json(['code' => 500, 'msg' => '未获取到商品数据', 'data' => '未获取到商品数据']);
                }
                if ($highestRow > 2502) {
                    return response()->json(['code' => 500, 'msg' => '一次最多导入2500条数据', 'data' => '一次最多导入2500条数据']);
                }

                // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
                $usersExits = [];
                $encode_arr = []; //系统编码
                $encode = []; //已存在的编码
                DB::beginTransaction();
                for ($j = 2; $j <= $highestRow; $j++) {
                    $goo_add['goo_cid'] = $user_info->adm_cid; //所属企业id
                    $goo_add['goo_shop_id'] = $user_info->adm_shop_id; //所属门店id
                    $goo_add['goo_superior_shop_id'] = $shop_id; //所属门店id

                    // 商品id
                    $goo_adds['goo_id'] = trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue());
                    // if (empty($goo_adds['goo_id'])) {
                    //     continue;
                    //     // return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'序列码不能为空！']);
                    // }

                    // 商品名称
                    $goo_add['goo_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                    if (empty($goo_add['goo_name'])) {
                        return response()->json(['code' => 500, 'msg' => '商品名称必填', 'data' => '商品名称必填']);
                    }
                    if (strlen($goo_add['goo_name']) > 240) {
                        return response()->json(['code' => 500, 'msg' => '商品名称最多80个字', 'data' => '商品名称最多80个字']);
                    }

                    // 检索编码
                    $goo_add['goo_goods_encode'] = trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue());
                    if (empty($goo_add['goo_name'])) {
                        $goo_add['goo_name'] = '';
                        $goo_goods_encode = false;
                    } else {
                        // 根据检索编号判断商品是否存在,不存在就新增,存在编辑
                        $goo_goods_encode = DB::table('goods')
                            ->where(function ($query) use ($user_info) {
                                $query->where('goo_cid', $user_info->adm_cid)
                                    ->orWhere('goo_cid', 0);
                            })
                            ->where(function ($query) use ($user_info) {
                                $query->where('goo_shop_id', $user_info->adm_shop_id)
                                    ->orWhere('goo_shop_id', 0);
                            })
                            ->where('goo_name', $goo_add['goo_name'])
                            ->where('goo_type', 1)
                            ->where('goo_delete', 1)
                            ->select('goo_goods_encode', 'goo_id', 'goo_class', 'goo_name')
                            ->orderBy('goo_id', 'desc')
                            ->first();
                        if (!$goo_goods_encode) {
                            continue;
                        } else {
                            $goo_name_arr[] = $goo_add['goo_name'];
                        }
                    }


                    // 商品品类
                    $goo_add['goo_cate_name'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                    if (empty($goo_add['goo_cate_name'])) {
                        return response()->json(['code' => 500, 'msg' => '商品品类必填', 'data' => '商品品类必填']);
                    }
                    // 查询商品品类是否存在
                    $cate_id = DB::table('category')
                        ->where(function ($query) use ($user_info) {
                            $query->where('cate_cid', $user_info->adm_cid)
                                ->orWhere('cate_cid', 0);
                        })
                        ->where(function ($query) use ($shop_id) {
                            $query->where('cate_shop_id', $shop_id)
                                ->orWhere('cate_shop_id', 0);
                        })
                        ->where('cate_name', $goo_add['goo_cate_name'])
                        ->where('cate_delete', 1)
                        ->where('cate_state', 1)
                        ->value('cate_id');

                    if ($goo_goods_encode) {
                        // 查询商品品类id
                        $goo_cate_id = DB::table('goods')
                            ->where('goo_id', $goo_goods_encode->goo_id)
                            ->value('goo_cate_id');
                        if (empty($cate_id)) {
                            $cate_data['cate_cid'] = $user_info->adm_cid;
                            $cate_data['cate_shop_id'] = $user_info->adm_shop_id;
                            $cate_data['cate_superior_shop_id'] = $shop_id;
                            $cate_data['cate_name'] = $goo_add['goo_cate_name'];
                            $cate_data['cate_create_time'] = date('Y-m-d H:i:s');
                            $cate_data['cate_goods_number'] = 1;
                            $cate_id = DB::table('category')->insertGetId($cate_data);
                            $caco_add['caco_shop_id'] = $user_info->adm_shop_id;
                            $caco_add['caco_cate_id'] = $cate_id;
                            $caco_add['caco_goods_number'] = 1;
                            $caco_id = DB::table('category_correlation')->insert($caco_add);
                            if (!$cate_id || !$caco_id) {
                                DB::rollBack();
                                return response()->json(['code' => 500, 'msg' => '品类添加失败', 'data' => '品类添加失败']);
                            }
                            unset($cate_data);
                            unset($caco_add);
                        }
                        if ($goo_cate_id != $cate_id) {
                            if ($goo_goods_encode->goo_class == 1) {
                                $cate_where['caco_shop_id'] = $user_info->adm_shop_id;
                                $cate_where['caco_cate_id'] = $cate_id;
                                $inc_cate_res = DB::table('category_correlation')
                                    ->where('caco_cate_id', $cate_id)
                                    ->where('caco_shop_id', $user_info->adm_shop_id)
                                    ->increment('caco_goods_number', 1);
                                $cate_where['caco_cate_id'] = $goo_cate_id;
                                $dec_cate_res = DB::table('category_correlation')
                                    ->where('caco_cate_id', $goo_cate_id)
                                    ->where('caco_shop_id', $user_info->adm_shop_id)
                                    ->decrement('caco_goods_number', 1);
                                if (!$inc_cate_res || !$dec_cate_res) {
                                    DB::rollBack();
                                    return response()->json(['code' => 500, 'msg' => '上传失败10', 'data' => '上传失败10']);
                                }
                            }
                        } else {
                            $inc_cate_res = true;
                            $dec_cate_res = true;
                        }
                    } else {
                        $inc_cate_res = true;
                        $dec_cate_res = true;
                    }
                    $goo_add['goo_cate_id'] = $cate_id;

                    // 商品品牌
                    $goo_add['goo_bra_name'] = trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue());
                    if (empty($goo_add['goo_bra_name'])) {
                        $goo_add['goo_bra_name'] = ''; //品牌名称
                        $goo_add['goo_bra_id'] = 0; //品牌id
                        $goo_add['goo_brse_id'] = 0; //品牌系列id
                    } else {
                        // 查询商品品牌是否存在
                        $bra_id = DB::table('brand')
                            ->where(function ($query) use ($user_info) {
                                $query->where('bra_cid', $user_info->adm_cid)
                                    ->orWhere('bra_cid', 0);
                            })
                            ->where(function ($query) use ($user_info) {
                                $query->where('bra_shop_id', $user_info->adm_shop_id)
                                    ->orWhere('bra_shop_id', 0);
                            })
                            ->where('bra_name', $goo_add['goo_bra_name'])
                            ->where('bra_delete', 1)
                            ->where('bra_state', 1)
                            ->value('bra_id');
                        if (empty($bra_id)) {
                            $bra_data['bra_cid'] = $user_info->adm_cid;
                            $bra_data['bra_shop_id'] = $user_info->adm_shop_id;
                            $bra_data['bra_superior_shop_id'] = $shop_id;
                            $bra_data['bra_name'] = $goo_add['goo_bra_name'];
                            $bra_data['bra_create_time'] = date('Y-m-d H:i:s');
                            $bra_data['bra_goods_number'] = 1;
                            $bra_id = DB::table('brand')->insertGetId($bra_data);
                            $brco_add['brco_bra_id'] = $bra_id;
                            $brco_add['brco_shop_id'] = $shop_id;
                            $brco_add['brco_goods_number'] = 1;
                            $brco_id = DB::table('brand_correlation')->insertGetId($brco_add);
                            if (!$bra_id || !$brco_id) {
                                DB::rollBack();
                                return response()->json(['code' => 500, 'msg' => '新品牌添加失败', 'data' => '新品牌添加失败']);
                            }
                            unset($bra_data);
                            unset($brco_add);
                        }

                        if ($goo_goods_encode) {
                            // 查询商品品牌id
                            $goo_bra_id = DB::table('goods')
                                ->where('goo_id', $goo_goods_encode->goo_id)
                                ->value('goo_bra_id');

                            if ($goo_bra_id != $bra_id) {
                                if ($goo_goods_encode->goo_class == 1) {
                                    $inc_bra_res = DB::table('brand_correlation')
                                        ->where('brco_bra_id', $bra_id)
                                        ->where('brco_shop_id', $user_info->adm_shop_id)
                                        ->increment('brco_goods_number', 1);
                                    if ($goo_bra_id) {
                                        $dec_bra_res = DB::table('brand_correlation')
                                            ->where('brco_bra_id', $goo_bra_id)
                                            ->where('brco_shop_id', $user_info->adm_shop_id)
                                            ->decrement('brco_goods_number', 1);
                                    }
                                    if (!$inc_bra_res || !$dec_bra_res) {
                                        DB::rollBack();
                                        return response()->json(['code' => 500, 'msg' => '上传失败12', 'data' => '上传失败12']);
                                    }
                                }
                            } else {
                                $inc_bra_res = true;
                                $dec_bra_res = true;
                            }
                        } else {
                            $inc_bra_res = true;
                            $dec_bra_res = true;
                        }
                        $goo_add['goo_bra_id'] = $bra_id;
                        if ($goo_add['goo_bra_id']) {
                            // 品牌系列
                            $brse_name = trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue());
                            if (!empty($brse_name)) {
                                $brse_id = DB::table('brand_serie')
                                    ->where(function ($query) use ($user_info) {
                                        $query->where('brse_cid', $user_info->adm_cid)
                                            ->orWhere('brse_cid', 0);
                                    })
                                    ->where(function ($query) use ($shop_id) {
                                        $query->where('brse_superior_shop_id', $shop_id)
                                            ->orWhere('brse_superior_shop_id', 0);
                                    })
                                    ->where('brse_bra_id', $goo_add['goo_bra_id'])
                                    ->where('brse_name', $brse_name)
                                    ->where('brse_delete', 1)
                                    ->where('brse_state', 1)
                                    ->value('brse_id');

                                if ($goo_goods_encode) {
                                    // 查询商品系列id
                                    $goo_brse_id = DB::table('goods')
                                        ->where('goo_id', $goo_goods_encode->goo_id)
                                        ->value('goo_brse_id');
                                    if (empty($brse_id)) {
                                        $brse_data['brse_cid'] = $user_info->adm_cid;
                                        $brse_data['brse_shop_id'] = $user_info->adm_shop_id;
                                        $brse_data['brse_superior_shop_id'] = $shop_id;
                                        $brse_data['brse_bra_id'] = $goo_add['goo_bra_id'];
                                        $brse_data['brse_cate_id'] = $cate_id;
                                        $brse_data['brse_name'] = $brse_name;
                                        $brse_data['brse_create_time'] = date('Y-m-d H:i:s');
                                        $brse_data['brse_goods_number'] = 1;
                                        $brse_id = DB::table('brand_serie')->insertGetId($brse_data);
                                        $brsc_add['brsc_shop_id'] = $user_info->adm_shop_id;
                                        $brsc_add['brsc_brse_id'] = $brse_id;
                                        $brsc_add['brsc_goods_number'] = 1;
                                        $brsc_id = DB::table('brand_serie_correlation')->insertGetId($brsc_add);
                                        if (!$brse_id || !$brsc_id) {
                                            DB::rollBack();
                                            return response()->json(['code' => 500, 'msg' => '系列添加失败', 'data' => '系列添加失败']);
                                        }
                                    }
                                    if ($goo_brse_id != $brse_id) {
                                        if ($goo_goods_encode->goo_class == 1) {
                                            $inc_brsc_res = DB::table('brand_serie_correlation')
                                                ->where('brsc_brse_id', $brse_id)
                                                ->where('brsc_shop_id', $user_info->adm_shop_id)
                                                ->increment('brsc_goods_number', 1);
                                            if ($goo_brse_id) {
                                                $dec_brsc_res = DB::table('brand_serie_correlation')
                                                    ->where('brsc_brse_id', $goo_brse_id)
                                                    ->where('brsc_shop_id', $user_info->adm_shop_id)
                                                    ->decrement('brsc_goods_number', 1);
                                            }
                                            if (!$inc_brsc_res || !$dec_brsc_res) {
                                                DB::rollBack();
                                                return response()->json(['code' => 500, 'msg' => '上传失败13', 'data' => '上传失败13']);
                                            }
                                        }
                                    } else {
                                        $inc_brsc_res = true;
                                        $dec_brsc_res = true;
                                    }
                                } else {
                                    $inc_brsc_res = true;
                                    $dec_brsc_res = true;
                                }
                                $goo_add['goo_brse_id'] = $brse_id;
                            } else {
                                $goo_add['goo_brse_id'] = 0; //品牌系列id
                            }
                        } else {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '请选择所属品牌', 'data' => '请选择所属品牌']);
                        }
                    }

                    // 零售价
                    $goo_add['goo_price'] = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                    if (empty($goo_add['goo_price'])) {
                        $goo_add['goo_price'] = 0;
                    } else {
                        $goo_add['goo_price'] = trim($goo_add['goo_price']) * 100;
                    }

                    // 批发价
                    $goo_add['goo_wholesale_price'] = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();
                    if (empty($goo_add['goo_wholesale_price'])) {
                        $goo_add['goo_wholesale_price'] = 0;
                    } else {
                        $goo_add['goo_wholesale_price'] = trim($goo_add['goo_wholesale_price']) * 100;
                    }

                    // 采购价
                    $goo_add['goo_purchase_price'] = $objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue();
                    if (empty($goo_add['goo_purchase_price'])) {
                        $goo_add['goo_purchase_price'] = 0;
                    } else {
                        $goo_add['goo_purchase_price'] = trim($goo_add['goo_purchase_price']) * 100;
                    }

                    // 单位
                    $goo_add['goo_unit'] = trim($objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue());
                    $get_goo_add['goo_unit_conversion'] = trim($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue());
                    if (empty($goo_add['goo_unit'])) {
                        return response()->json(['code' => 500, 'msg' => '单位必填', 'data' => '单位必填']);
                    } else {
                        if ($goo_add['goo_unit'] == '卷') {
                            $goo_add['goo_unta_id'] = 1;
                            $goo_add['goo_unit_conversion'] = $get_goo_add['goo_unit_conversion'];
                            if (empty($goo_add['goo_unit_conversion'])) {
                                return response()->json(['code' => 500, 'msg' => '单位长度必填', 'data' => '单位长度必填']);
                            }
                        }
                        if ($goo_add['goo_unit'] == '厘米') {
                            $goo_add['goo_unta_id'] = 2;
                        }
                        if ($goo_add['goo_unit'] == '个') {
                            $goo_add['goo_unta_id'] = 3;
                        }
                        if ($goo_add['goo_unit'] == '米') {
                            $goo_add['goo_unta_id'] = 4;
                        }
                        if ($goo_add['goo_unit'] == '次') {
                            $goo_add['goo_unta_id'] = 5;
                        }
                        if ($goo_add['goo_unit'] == '套') {
                            $goo_add['goo_unta_id'] = 6;
                        }
                        if ($goo_add['goo_unit'] == '张') {
                            $goo_add['goo_unta_id'] = 7;
                        }
                        if ($goo_add['goo_unit'] == '车') {
                            $goo_add['goo_unta_id'] = 8;
                        }
                    }
                    if (strlen($goo_add['goo_unit']) > 60) {
                        return response()->json(['code' => 500, 'msg' => '单位最多20个字', 'data' => '单位最多20个字']);
                    }

                    // 商品属性
                    $supplier = [];
                    $goo_attribute = $objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue();

                    if (!empty($goo_attribute)) {
                        $goo_attribute = explode(',', trim($goo_attribute));
                        foreach ($goo_attribute as $key => $value) {
                            if ($value) {
                                if (strpos($value, '：') === false) {
                                    DB::rollBack();
                                    return response()->json(['code' => 500, 'msg' => '商品属性格式不正确4', 'data' => '商品属性格式不正确4']);
                                }
                                $goo_attributes = explode('：', $value);
                                $supplier[] = ['key' => $goo_attributes[0], 'value' => $goo_attributes[1]];
                                $goo_add['goo_attribute'] = json_encode($supplier);
                                unset($goo_attributes);
                            }
                        }
                    } else {
                        $goo_add['goo_attribute'] = '';
                    }

                    if ($goo_goods_encode) {
                        // 商品数量
                        $num = 1;
                        $goo_add['goo_type'] = 1; //1正常商品2赠品商品3活动商品4旧货商品
                        $goo_add['goo_update_time'] = date('Y-m-d H:i:s');
                        $res = DB::table('goods')
                            ->where('goo_type', 1)
                            ->where('goo_name', $goo_goods_encode->goo_name)
                            ->where('goo_shop_id', $user_info->adm_shop_id)
                            ->update($goo_add);
                        if (!$res) {
                            DB::rollBack();
                            return response()->json(['code' => 500, 'msg' => '上传失败02', 'data' => '上传失败02']);
                        }
                    }
                }
                if (!empty($encode_arr)) {
                    $data['time'] = date('Y-m-d H:i:s');
                    $data['user_info'] = $user_info;
                    $data['goo_name'] = $goo_name_arr;
                    logRecord($data, 'goods_lead_log', 2);
                }
                Common::addLog($user_info, getRealIp($request), '商品列表', '批量编辑导入', '导入商品成功');
                DB::commit();
                return response()->json(['code' => 200, 'msg' => '上传成功', 'data' => '上传成功']);
            } else {
                return response()->json(['code' => 500, 'msg' => '上传有误，请重新上传', 'data' => '上传有误，请重新上传']);
            }
        } else {
            return response()->json(['code' => 500, 'msg' => $res, 'data' => $res]);
        }
    }

    // 批量编辑导入
    public function verifyEditGoods($request)
    {
        ignore_user_abort();
        set_time_limit(0);

        $file = $request->file('file');

        if ($file->isValid()) {
            // 获取表格的大小，限制上传表格的大小5M
            $file_size = $_FILES['file']['size'];
            if ($file_size > 5 * 1024 * 1024) {
                return '文件大小不能超过5M';
            }

            // 限制上传表格类型
            $ext = $file->getClientOriginalExtension(); //文件拓展名
            if ($ext != 'xlsx') {
                return '仅允许上传以xlsx结尾的后缀文件';
            }

            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');
            $filename = $_FILES['file']['tmp_name'];
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            if ($highestRow < 2) {
                return '未获取到商品数据';
            }
            if ($highestRow > 2502) {
                return '一次最多导入1500条数据';
            }

            // 循环读取excel表格，整合成数组,如果是不指定key的二维,就用$data[i][j]表示。
            $hint = '';
            for ($j = 2; $j <= $highestRow; $j++) {
                // 商品名称
                $goo_add['goo_name'] = trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue());
                if (empty($goo_add['goo_name'])) {
                    $hint .= '商品名称必填，';
                }
                if (strlen($goo_add['goo_name']) > 240) {
                    $hint .= '商品名称最多80个字，';
                }
                // 商品品类
                $goo_add['goo_cate_name'] = trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                if (empty($goo_add['goo_cate_name'])) {
                    $hint .= '商品品类必填，';
                }
                // 单位
                $goo_add['goo_unit'] = trim($objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue());
                if (strlen($goo_add['goo_unit']) > 60) {
                    $hint .= '单位最多20个字，';
                }
                // 商品属性
                $goo_attribute = $objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue();
                if (!empty($goo_attribute)) {
                    $goo_attribute = explode(',', trim($goo_attribute));
                    foreach ($goo_attribute as $key => $value) {
                        if ($value) {
                            if (strpos($value, '：') === false) {
                                $hint .= '商品属性格式不正确5，';
                            }
                        }
                    }
                }
            }
            return $hint;
        } else {
            return '上传有误，请重新上传！';
        }
    }

    // 获取单位名称数据
    public function selectUnit(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('unit_table')
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['unta_name'])) { //单位名称
                    $query->where('unta_name', 'like', '%' . $search_data['unta_name'] . '%');
                }
            })
            ->orderBy('unta_id', 'asc')
            ->select('unta_id', 'unta_name')
            ->paginate($this->show_count);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $list_items = $list_data->items();
        $data_info['data'] = $list_items; //返回数据
        return response()->json(['code' => 200, 'msg' => 'success', 'data_info' => $data_info]);
    }

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

        // 获取当前操作账号信息
        $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;

        $list_data = DB::table('bind_good')
            ->where('bigo_shop_id', $user_info->adm_shop_id)
            ->where(function ($query) use ($request) {
                if (!empty($request['bigo_goo_id'])) { //单位名称
                    $query->where('bigo_goo_id', $request['bigo_goo_id']);
                }
            })
            ->orderBy('bigo_id', 'desc')
            ->paginate($this->show_count);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $list_items = $list_data->items();
        $data_info['data'] = $list_items;
        // 获取当前列表下的按钮
        $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' => '暂无数据', 'data' => '暂无数据']);
        }
    }

    /**
     * 绑定上级门店商品
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-02-27
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function bindGoods(Request $request) {
        // 验证数据
        $verify_data = new VerifyGoodsListController;
        $error_message = $verify_data->bindGoodsValidator($request->all());
        if ($error_message) {
            return response()->json(['code' => 500, 'msg' => $error_message, 'data' => '参数错误',]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $find_data = DB::table('bind_good')
            ->where('bigo_shop_id', $user_info->adm_shop_id)
            ->where('bigo_goo_id', $request['goo_id'])
            ->where('bigo_bind_shop_id', $request['shop_id'])
            ->where('bigo_bind_goo_id', $request['bind_goo_id'])
            ->first();
        if ($find_data) {
            return response()->json(['code' => 500, 'msg' => '此商品已绑定', 'data' =>'']);
        }
        $add_data['bigo_shop_id'] = $user_info->adm_shop_id;
        $add_data['bigo_shop_name'] = DB::table('shop')->where('shop_id', $user_info->adm_shop_id)->value('shop_store_name');
        $add_data['bigo_goo_id'] = $request['goo_id'];
        $add_data['bigo_goo_name'] = DB::table('goods')->where('goo_id', $request['goo_id'])->value('goo_name');
        $add_data['bigo_bind_shop_id'] = $request['shop_id'];
        $add_data['bigo_bind_shop_name'] = DB::table('shop')->where('shop_id', $request['shop_id'])->value('shop_store_name');
        $add_data['bigo_bind_goo_id'] = $request['bind_goo_id'];
        $add_data['bigo_bind_goo_name'] = DB::table('goods')->where('goo_id', $request['bind_goo_id'])->value('goo_name');
        $add_data['bigo_create_time'] = date('Y-m-d H:i:s');
        $add_data['bigo_create_id'] = $user_info->adm_id;
        $add_res = DB::table('bind_good')->insertGetId($add_data);
        return response()->json(['code' => 200, 'msg' => '绑定成功', 'data' =>'']);
    }
}
