<?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\VerifyBrandListController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use App\Http\Models\Services\PublicSearch;

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyBrandListController;
        $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'] = 'bra_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        $list_data = DB::table('brand')
            ->where('bra_delete', 1)
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('bra_cid', 0)
                        ->orwhere('bra_cid', $user_info->adm_cid);
                } else {
                    $query->where('bra_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['bra_name'])) {
                    $query->where('bra_name', 'like', '%' . $search_data['bra_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bra_state'])) {
                    $query->where('bra_state', $search_data['bra_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['bra_class'])) {
                    $query->where('bra_class', $search_data['bra_class']);
                }
            }) //类型1自营商品2系统商品
            ->select('bra_id', 'bra_name', 'bra_state', 'bra_class', 'bra_sequence', 'bra_goods_number', 'bra_shop_id')
            ->orderBy('bra_class', 'desc')
            ->orderBy('bra_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $brco_bra_id = array_unique(array_column($list_items, 'bra_id'));
            // 查询品牌关联表数据
            $find_brco_data = DB::table('brand_correlation')
                ->where('brco_shop_id', $user_info->adm_shop_id)
                ->whereIn('brco_bra_id', $brco_bra_id)
                ->select('brco_bra_id', 'brco_goods_number', 'brco_sequence')
                ->get()->toArray();
            $find_brco_data = array_column($find_brco_data, null, 'brco_bra_id');
            foreach ($list_items as $key => $value) {
                if (isset($find_brco_data[$value->bra_id])) {
                    $list_items[$key]->bra_goods_number = $find_brco_data[$value->bra_id]->brco_goods_number;
                    $list_items[$key]->bra_sequence = $find_brco_data[$value->bra_id]->brco_sequence;
                }
            }
        }
        $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_items;                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        //获取top按钮
        $sea_button_data = 'add,start,stop';
        $sea_button_data = CommonService::getTopButton('',$sea_button_data,$list_button);
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                if ($list_button) {
                    if ($user_info->adm_shop_id == $value->bra_shop_id) {
                        foreach ($list_button as $k=> $value_b) {
                            if ($value_b['pri_operate_method'] == 'edit') {//编辑
                                $list_items[$key]->list_button_one[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'start' && $value->bra_state == 2) {//开启
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'stop' && $value->bra_state == 1) {//停用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                        }
                        $list_items[$key]->edit = 1;
                    } else {
                        $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'=>200, 'msg'=>'暂无数据', 'data'=>[]]);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyBrandListController;
        $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')
            ->where('bra_delete', 1)
            ->where('bra_cid', $user_info->adm_cid)
            ->where('bra_superior_shop_id', $shop_id)
            ->where('bra_name', $request['bra_name'])
            ->select('bra_id')
            ->first();
        if ($find_sepr) {
            return response()->json(['code'=>500, 'msg'=>'品牌已存在', 'data'=>'品牌已存在']);
        }

        // 2、判断品牌序号是否存在
        $find_bra = DB::table('brand as bra')
            ->leftjoin('brand_correlation as brco', 'brco.brco_bra_id', '=', 'bra.bra_id')
            ->where(function ($query) use ($user_info) {
                $query->where('bra_shop_id', 0)
                    ->orwhere('bra_shop_id', $user_info->adm_shop_id);
            })
            ->where('bra_sequence', '<>', 0)
            ->where('bra_sequence', $request['bra_sequence'])
            ->where('bra_delete', 1)
            ->select('bra_id')
            ->first();
        if ($find_bra) {
            return response()->json(['code'=>500, 'msg'=>'品牌序号已存在', 'data'=>'品牌序号已存在']);
        }

        // 2 新增一个品牌数据
        $bra_add_data['bra_cid'] = $user_info->adm_cid;
        $bra_add_data['bra_shop_id'] = $user_info->adm_shop_id;
        $bra_add_data['bra_superior_shop_id'] = $shop_id;
        $bra_add_data['bra_name'] = $request['bra_name'];
        $bra_add_data['bra_sequence'] = $request['bra_sequence'];

        DB::beginTransaction();

        // 新增品牌
        $bra_res =  DB::table('brand')->insertGetId($bra_add_data);
        $data['bra_id'] = $bra_res;
        $brco['brco_shop_id'] = $user_info->adm_shop_id;
        $brco['brco_bra_id'] = $bra_res;
        $brco['brco_sequence'] = $request['bra_sequence'];
        $brco_res = DB::table('brand_correlation')->insert($brco);

        if ($bra_res && $brco_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '品牌', '新增', '新增品牌：' . $request['bra_name'] . '成功');
            return response()->json(['code'=>200, 'msg'=>'新增品牌：成功', 'data'=>$data]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'新增品牌：失败', 'data'=>'']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyBrandListController;
        $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')
            ->where('bra_id', '<>', $request['bra_id'])
            ->where('bra_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('bra_shop_id', 0)
                    ->orwhere('bra_shop_id', $user_info->adm_shop_id);
            })
            ->where('bra_name', $request['bra_name'])
            ->select('bra_id')
            ->first();
        if ($find_sepr) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'品牌已存在']);
        }

        $find_bra = DB::table('brand as bra')
            ->leftjoin('brand_correlation as brco', 'brco.brco_bra_id', '=', 'bra.bra_id')
            ->where('bra_id', '<>', $request['bra_id'])
            ->where('bra_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('bra_shop_id', 0)
                    ->orwhere('bra_shop_id', $user_info->adm_shop_id);
            })
            ->where('bra_sequence', '<>', 0)
            ->where('bra_sequence', $request['bra_sequence'])
            ->select('bra_id')
            ->first();
        if ($find_bra) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'品牌序号已存在']);
        }

        // 2 编辑品牌数据
        $bra_edit_data['bra_cid'] = $user_info->adm_cid;
        $bra_edit_data['bra_shop_id'] = $user_info->adm_shop_id;
        $bra_edit_data['bra_superior_shop_id'] = $shop_id;
        $bra_edit_data['bra_name'] = $request['bra_name'];
        $bra_edit_data['bra_sequence'] = $request['bra_sequence'];
        $bra_edit_data['bra_update_time'] = date('Y-m-d H:i:s');

        DB::beginTransaction();

        // 编辑品牌
        $bra_res =  DB::table('brand')
            ->where('bra_id', $request['bra_id'])
            ->update($bra_edit_data);

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

        $brco['brco_update_time'] = date('Y-m-d H:i:s');
        $brco['brco_sequence'] = $request['bra_sequence'];
        $brco_res = DB::table('brand_correlation')
            ->where('brco_bra_id', $request['bra_id'])
            ->where('brco_shop_id', $user_info->adm_shop_id)
            ->update($brco);

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

        if ($bra_res && $goods_res && $brco_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '品牌', '编辑', '编辑品牌：' . $request['bra_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 VerifyBrandListController;
        $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')
            ->whereIn('bra_id', $request['bra_id'])
            ->select('bra_name', 'bra_id')
            ->get();
        foreach ($find_bra as $key => $value) {
            $bra_name[] = $value->bra_name;
        }

        // 启用
        $update_data['bra_state'] = 1; //状态1启用2停用
        $update_data['bra_update_time'] = date('Y-m-d H:i:s');
        $bra_res = DB::table('brand')
            ->whereIn('bra_id', $request['bra_id'])
            ->update($update_data);

        if ($bra_res) {
            Common::addLog($user_info, getRealIp($request), '品牌', '启用', '品牌：（' . implode(',', $bra_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 VerifyBrandListController;
        $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')
            ->whereIn('bra_id', $request['bra_id'])
            ->select('bra_name', 'bra_id')
            ->get();
        foreach ($find_bra as $key => $value) {
            $bra_name[] = $value->bra_name;
        }

        // 启用
        $update_data['bra_state'] = 2; //状态1启用2停用
        $update_data['bra_update_time'] = date('Y-m-d H:i:s');
        $bra_res = DB::table('brand')
            ->whereIn('bra_id', $request['bra_id'])
            ->update($update_data);

        if ($bra_res) {
            Common::addLog($user_info, getRealIp($request), '品牌', '停用', '品牌：（' . implode(',', $bra_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 VerifyBrandListController;
        $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_bra_id', $request['bra_id'])
            ->where('goo_delete', 1)
            ->first();
        if ($goods) {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'品牌下有商品不得删除']);
        }

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

        // 删除
        $update_data['bra_delete'] = 2; //是否删除：1正常2已删除
        $update_data['bra_update_time'] = date('Y-m-d H:i:s');
        $bra_res = DB::table('brand')
            ->whereIn('bra_id', $request['bra_id'])
            ->update($update_data);

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

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

        $select_field = "bra_id, bra_name";

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