<?php

namespace App\Http\Controllers\Api\ProductManage;

use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\ProductManage\VerifyBrandSerieController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Services\PublicSearch;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyBrandSerieController;
        $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;

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

        $post['string'] = 'brse_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);

        $search_data = $request->all();
        $list_data = DB::table('brand_serie as bs')
            ->leftjoin('brand as br', 'br.bra_id', '=', 'bs.brse_bra_id')
            ->where('brse_delete', 1)
            ->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, $where_data) {
                $query->whereIn($where_data['string'], $where_data['shop_id']);
            })
            ->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['brse_state'])) {
                    $query->where('brse_state', $search_data['brse_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['brse_class'])) {
                    $query->where('brse_class', $search_data['brse_class']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bra_id'])) {
                    $query->where('bra_id', $search_data['bra_id']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['brse_cate_id'])) {
                    $query->where('brse_cate_id', $search_data['brse_cate_id']);
                }
            })
            ->select('brse_id', 'brse_name', 'bra_id', 'bra_name', 'brse_state', 'brse_class', 'brse_cate_id', 'brse_second_cate_id', 'brse_shop_id')
            ->orderBy('brse_class', 'desc')
            ->orderBy('brse_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();
        $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) {
                $cate_second_data = DB::table('category')
                    ->whereIn('cate_id', $brse_second_cate_id)
                    ->select('cate_id', 'cate_name', 'cate_parent_id')
                    ->get();
            }
            $brsc_brse_id = array_filter(array_unique(array_column($list_items, 'brse_id')));
            if ($brsc_brse_id) {
                // 查询品牌系列的关联表数据
                $find_brco_data = DB::table('brand_serie_correlation')
                    ->where('brsc_shop_id', $user_info->adm_shop_id)
                    ->whereIn('brsc_brse_id', $brsc_brse_id)
                    ->pluck('brsc_goods_number', 'brsc_brse_id')
                    ->toArray();
                foreach ($list_items as $key => $value) {
                    if (isset($find_brco_data[$value->brse_id])) {
                        $list_items[$key]->brse_goods_number = $find_brco_data[$value->brse_id];
                    }
                }
            }
        }
        $data_info['data'] = $list_items; //返回数据
        $data_info['cate_data'] = $cate_data;
        $data_info['cate_second_data'] = $cate_second_data;

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_items) {
            if ($list_button) {
                foreach ($list_items as $key => $value) {
                    foreach ($list_button as $key_b => $value_b) {
                        if ($user_info->adm_shop_id == $value->brse_shop_id) {
                            if ($value_b['pri_operate_method'] == 'edit') {//编辑
                                $list_items[$key]->list_button_one[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'stop' && $value->brse_state == 1) {//停用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'start' && $value->brse_state == 2) {//启用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            $list_items[$key]->edit = 1;
                        }
                    }
                    if ($user_info->adm_shop_id != $value->brse_shop_id)  {
                        $list_items[$key]->list_button_one[] = [];
                        $list_items[$key]->list_button_two[] = [];
                        $list_items[$key]->edit = 2;
                    }
                }
            }
            $data_info['data'] = $list_items; //返回数据
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'暂无数据', 'data'=>'暂无数据']);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyBrandSerieController;
        $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]);
        }

        // 获取当前操作账号信息
        $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_sepr = DB::table('brand_serie')
            ->where('brse_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('brse_shop_id', 0)
                    ->orwhere('brse_shop_id', $user_info->adm_shop_id);
            })
            ->where('brse_bra_id', $request['bra_id'])
            ->where('brse_name', $request['brse_name'])
            ->select('brse_id')
            ->first();
        if ($find_sepr) {
            return response()->json(['code'=>500, 'msg'=>'当前品牌下的系列名称已存在', 'data'=>'当前品牌下的系列名称已存在']);
        }

        $find_bra = DB::table('brand_serie')
            ->where('brse_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('brse_shop_id', 0)
                    ->orwhere('brse_shop_id', $user_info->adm_shop_id);
            })
            ->where('brse_sequence', '<>', 0)
            ->where('brse_sequence', $request['brse_sequence'])
            ->select('brse_id')
            ->first();
        if ($find_bra) {
            return response()->json(['code'=>500, 'msg'=>'品牌系列序号已存在', 'data'=>'品牌系列序号已存在']);
        }

        // 2 新增一个品牌系列数据
        $brse_add_data = [
            'brse_cid' => $user_info->adm_cid,
            'brse_shop_id' => $user_info->adm_shop_id,
            'brse_superior_shop_id' => $shop_id,
            'brse_bra_id' => $request['bra_id'],
            'brse_name' => $request['brse_name'],
            'brse_cate_id' => $request['cate_id'], //一级品类id
            'brse_second_cate_id' => $request['cate_two_id'] ? $request['cate_two_id'] : '0', //二级品类id
        ];

        // 新增品牌系列
        $brse_res =  DB::table('brand_serie')->insertGetid($brse_add_data);
        $data['brse_id'] = $brse_res;
        $brsc['brsc_sequence'] = $request['brsc_sequence'] ?? '';
        $brsc['brsc_update_time'] = date('Y-m-d H:i:s');
        $brsc['brsc_shop_id'] = $user_info->adm_shop_id;
        $brsc['brsc_brse_id'] = $brse_res;

        $brsc_res = DB::table('brand_serie_correlation')->insert($brsc);
        if ($brse_res && $brsc_res) {
            Common::addLog($user_info, getRealIp($request), '品牌系列', '新增', '新增品牌系列：' . $request['brse_name'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'新增品牌系列：成功', 'data'=>$data]);
        } else {
            return response()->json(['code'=>500, 'msg'=>'新增品牌系列：失败', 'data'=>'']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyBrandSerieController;
        $error_message = $verify_data->editValidator($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;

        // 1. 判断品牌系列名称是否存在
        $find_sepr = DB::table('brand_serie')
            ->where('brse_id', '<>', $request['brse_id'])
            ->where('brse_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('brse_shop_id', 0)
                    ->orwhere('brse_shop_id', $user_info->adm_shop_id);
            })
            ->where('brse_bra_id', $request['bra_id'])
            ->where('brse_name', $request['brse_name'])
            ->select('brse_id')
            ->first();
        if ($find_sepr) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前品牌下的系列名称已存在']);
        }

        $find_bra = DB::table('brand_serie')
            ->where('brse_id', '<>', $request['brse_id'])
            ->where('brse_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('brse_shop_id', 0)
                    ->orwhere('brse_shop_id', $user_info->adm_shop_id);
            })
            ->where('brse_sequence', '<>', 0)
            ->where('brse_sequence', $request['brse_sequence'])
            ->select('brse_id')
            ->first();
        if ($find_bra) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'品牌系列序号已存在']);
        }

        // 2 编辑品牌系列数据
        $brse_edit_data = [
            'brse_cid' => $user_info->adm_cid,
            'brse_shop_id' => $user_info->adm_shop_id,
            'brse_superior_shop_id' => $shop_id,
            'brse_bra_id' => $request['bra_id'],
            'brse_name' => $request['brse_name'],
            'brse_sequence' => $request['brse_sequence'],
            'brse_cate_id' => $request['cate_id'], //一级品类id
            'brse_second_cate_id' => $request['cate_two_id'] ? $request['cate_two_id'] : '0', //二级品类id
            'brse_update_time' => date('Y-m-d H:i:s'),
        ];

        DB::beginTransaction();
        // 编辑品牌系列
        $brse_res =  DB::table('brand_serie')
            ->where('brse_id', $request['brse_id'])
            ->update($brse_edit_data);

        // 3 编辑品牌系列下所属商品的品牌系列名称
        // 3.1 查询当前品牌系列下的绑定的商品数量
        $find_bra =  DB::table('brand_serie')
            ->where('brse_id', $request['brse_id'])
            ->select('brse_goods_number')
            ->first();

        if ($find_bra->brse_goods_number) {
            // 3.2 当前品牌系列下绑定的有商品，更改商品中的品类名称
            $edit_goods['goo_brse_id'] = $request['brse_id'];
            $edit_goods['goo_update_time'] = date('Y-m-d H:i:s');
            $goods_res =  DB::table('goods')
                ->where('goo_brse_id', $request['brse_id'])
                ->where('goo_delete', 1)
                ->update($edit_goods);
        } else {
            $goods_res = true;
        }

        if ($brse_res && $goods_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '品牌系列', '编辑', '编辑品牌系列：' . $request['brse_name'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'编辑品牌系列：成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'编辑品牌系列：失败']);
        }
    }

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

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

        // 查询信息
        $find_bra = DB::table('brand_serie')
            ->whereIn('brse_id', $request['brse_id'])
            ->select('brse_name')
            ->get();
        foreach ($find_bra as $key => $value) {
            $brse_name[] = $value->brse_name;
        }

        // 启用
        $update_data['brse_state'] = 1; //状态1启用2停用
        $update_data['brse_update_time'] = date('Y-m-d H:i:s');
        $brse_res = DB::table('brand_serie')
            ->whereIn('brse_id', $request['brse_id'])
            ->update($update_data);

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

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

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

        // 查询信息
        $find_bra = DB::table('brand_serie')
            ->whereIn('brse_id', $request['brse_id'])
            ->select('brse_name')
            ->get();
        foreach ($find_bra as $key => $value) {
            $brse_name[] = $value->brse_name;
        }

        // 启用
        $update_data['brse_state'] = 2; //状态1启用2停用
        $update_data['brse_update_time'] = date('Y-m-d H:i:s');
        $brse_res = DB::table('brand_serie')
            ->whereIn('brse_id', $request['brse_id'])
            ->update($update_data);

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

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

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

        // 品牌系列下有商品不得删除
        $goods = DB::table('goods')
            ->whereIn('goo_brse_id', $request['brse_id'])
            ->where('goo_delete', 1)
            ->first();
        if ($goods) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'品牌系列下有商品不得删除']);
        }

        // 查询信息
        $find_bra = DB::table('brand_serie')
            ->whereIn('brse_id', $request['brse_id'])
            ->select('brse_name')
            ->get();
        foreach ($find_bra as $key => $value) {
            $brse_name[] = $value->brse_name;
        }

        // 删除
        $update_data['brse_delete'] = 2; //是否删除：1正常2已删除
        $update_data['brse_update_time'] = date('Y-m-d H:i:s');
        $brse_res = DB::table('brand_serie')
            ->whereIn('brse_id', $request['brse_id'])
            ->update($update_data);

        if ($brse_res) {
            Common::addLog($user_info, getRealIp($request), '品牌系列', '删除', '品牌系列：（' . implode(',', $brse_name) . '）删除成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'删除成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'删除失败']);
        }
    }

    // 获取品牌系列数据
    public function getBrandSerie(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $select_field = "brse_id, brse_name";

        $public_search = new PublicSearch;
        $list_data = $public_search->searchBrandSerie($user_info, $request->all(), $select_field);
        return response()->json(['code'=>200, 'msg'=>'success', 'data_info'=>$list_data['data_info']]);
    }

    // 搜索品类
    public function getCategory(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;
        }

        if (empty($request['cate_id'])) {
            // 查询品类信息
            $find_cate = DB::table('category')
                ->where(function ($query) use ($user_info, $shop_state) {
                    if ($shop_state) {
                        $query->where('cate_cid', 0)
                            ->orwhere('cate_cid', $user_info->adm_cid);
                    } else {
                        $query->where('cate_cid', $user_info->adm_cid);
                    }
                })
                ->where(function ($query) use ($user_info, $shop_state) {
                    if ($shop_state) {
                        $query->where('cate_shop_id', 0)
                            ->orwhere('cate_shop_id', $user_info->adm_shop_id);
                    } else {
                        $query->where('cate_shop_id', $user_info->adm_shop_id);
                    }
                })
                ->where('cate_delete', 1)
                ->where('cate_state', 1)
                ->where('cate_parent_id', 0)
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['cate_name'])) {
                        $query->where('cate_name', 'like', '%' . $search_data['cate_name'] . '%');
                    }
                })
                ->select('cate_id', 'cate_name')
                ->get();
        } else {
            $find_cate = DB::table('category')
                ->where(function ($query) use ($user_info, $shop_state) {
                    if ($shop_state) {
                        $query->where('cate_cid', 0)
                            ->orwhere('cate_cid', $user_info->adm_cid);
                    } else {
                        $query->where('cate_cid', $user_info->adm_cid);
                    }
                })
                ->where(function ($query) use ($user_info, $shop_state) {
                    if ($shop_state) {
                        $query->where('cate_shop_id', 0)
                            ->orwhere('cate_shop_id', $user_info->adm_shop_id);
                    } else {
                        $query->where('cate_shop_id', $user_info->adm_shop_id);
                    }
                })
                ->where('cate_delete', 1)
                ->where('cate_state', 1)
                ->where('cate_parent_id', $request['cate_id'])
                ->where(function ($query) use ($search_data) {
                    if (!empty($search_data['cate_name'])) {
                        $query->where('cate_name', 'like', '%' . $search_data['cate_name'] . '%');
                    }
                })
                ->select('cate_id as cate_two_id', 'cate_name as cate_two_name')
                ->get();
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data_info'=>$find_cate]);
    }
}
