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

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

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCategoryListController;
        $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'] = 'a.'.'cate_';
        $post['user_info'] = $user_info;
        $type = 3;
        $where_data = whereFunction($post,$type);
        $search_data = $request->all();
        $list_data = DB::table('category as a')
            ->leftJoin('category as b', 'a.cate_parent_id', '=', 'b.cate_id')
            ->where('a.cate_delete', 1)
            ->where(function ($query) use ($user_info, $shop_state) {
                if ($shop_state) {
                    $query->where('a.cate_cid', 0)
                        ->orwhere('a.cate_cid', $user_info->adm_cid);
                } else {
                    $query->where('a.cate_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['cate_name'])) {
                    $query->where('a.cate_name', 'like', '%' . $search_data['cate_name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['cate_state'])) {
                    $query->where('a.cate_state', $search_data['cate_state']);
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['cate_class'])) {
                    $query->where('a.cate_class', $search_data['cate_class']);
                }
            }) //类型1自营品类2搜索品类
            ->select('a.cate_id', 'a.cate_name', 'a.cate_state', 'a.cate_parent_id', 'b.cate_name as cate_parent_name', 'a.cate_class', 'a.cate_shop_id')
            ->orderBy('a.cate_class', 'desc')
            ->orderBy('a.cate_id', 'desc')
            ->paginate($this->show_count);
        $list_items = $list_data->items();
        if ($list_items) {
            $caco_cate_id = array_filter(array_unique(array_column($list_items, 'cate_id')));
            if ($caco_cate_id) {
                // 查询品类关联表数据
                $find_caco_data = DB::table('category_correlation')
                    ->where('caco_shop_id', $user_info->adm_shop_id)
                    ->whereIn('caco_cate_id', $caco_cate_id)
                    ->pluck('caco_goods_number', 'caco_cate_id')->toArray();

                foreach ($list_items as $key => $value) {
                    if (isset($find_caco_data[$value->cate_id])) {
                        $list_items[$key]->cate_goods_number = $find_caco_data[$value->cate_id];
                    }
                }
            }
        }
        $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) {
            if ($list_button) {
                foreach ($list_items as $key => $value) {
                    foreach ($list_button as $key_b => $value_b) {
                        if ($user_info->adm_shop_id == $value->cate_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->cate_state == 1) {//停用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            if ($value_b['pri_operate_method'] == 'start' && $value->cate_state == 2) {//启用
                                $list_items[$key]->list_button_two[] = $value_b;
                            }
                            $list_items[$key]->edit = 1;
                        }
                    }
                    if ($user_info->adm_shop_id != $value->cate_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'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyCategoryListController;
        $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('category')
            ->where('cate_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('cate_shop_id', 0)
                    ->orwhere('cate_shop_id', $user_info->adm_shop_id);
            })
            ->where('cate_name', $request['cate_name'])
            ->select('cate_id')
            ->first();
        if ($find_sepr) {
            return response()->json(["code"=>500, 'msg'=>'品类已存在', 'data'=>'品类已存在']);
        }

        // 2 新增一个品类数据
        $cate_add_data['cate_cid'] = $user_info->adm_cid;
        $cate_add_data['cate_shop_id'] = $user_info->adm_shop_id;
        $cate_add_data['cate_superior_shop_id'] = $shop_id;
        $cate_add_data['cate_name'] = $request['cate_name'];
        $cate_add_data['cate_parent_id'] = $request['cate_parent_id'];

        // 判断隶属上级
        if ($request['cate_parent_id']) {
            // 查找隶属品类是第几级
            $cate_rank = DB::table('category')
                ->where('cate_id', $request['cate_parent_id'])
                ->select('cate_rank')
                ->first();

            if ($cate_rank->cate_rank >= 3) {
                return response()->json(["code"=>500, 'msg'=>'所属品类已超过三级', 'data'=>'所属品类已超过三级']);
            }
            $cate_add_data['cate_rank'] = $cate_rank->cate_rank + 1;
        } else {
            $cate_add_data['cate_rank'] = 1;
        }

        // 新增品类
        $cate_res =  DB::table('category')->insertGetid($cate_add_data);
        $data['cate_id'] = $cate_res;
        $caco['caco_shop_id'] = $user_info->adm_shop_id;
        $caco['caco_cate_id'] = $cate_res;
        $caco_res = DB::table('category_correlation')->insert($caco);

        if ($cate_res && $caco_res) {
            Common::addLog($user_info, getRealIp($request), '品类', '新增', '新增品类：' . $request['cate_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 VerifyCategoryListController;
        $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('category')
            ->where('cate_id', '<>', $request['cate_id'])
            ->where('cate_delete', 1)
            ->where(function ($query) use ($user_info) {
                $query->where('cate_shop_id', 0)
                    ->orwhere('cate_shop_id', $user_info->adm_shop_id);
            })
            ->where('cate_name', $request['cate_name'])
            ->select('cate_id')
            ->first();
        if ($find_sepr) {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'品类已存在']);
        }

        // 2 编辑品类数据
        $cate_edit_data['cate_cid'] = $user_info->adm_cid;
        $cate_edit_data['cate_shop_id'] = $user_info->adm_shop_id;
        $cate_edit_data['cate_superior_shop_id'] = $shop_id;
        $cate_edit_data['cate_name'] = $request['cate_name'];
        $cate_edit_data['cate_parent_id'] = $request['cate_parent_id'];
        $cate_edit_data['cate_update_time'] = date('Y-m-d H:i:s');

        // 2.1 判断隶属上级是否为0
        if ($request['cate_parent_id']) {
            // 2.2 查找隶属品类是第几级
            $cate_rank = DB::table('category')
                ->where('cate_id', $request['cate_parent_id'])
                ->select('cate_rank')
                ->first();
            if ($cate_rank->cate_rank >= 3) {
                return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'所属品类已超过三级']);
            }
            $cate_edit_data['cate_rank'] = $cate_rank->cate_rank + 1;
        } else {
            $cate_edit_data['cate_rank'] = 1;
        }

        DB::beginTransaction();
        // 编辑品类
        $cate_res =  DB::table('category')
            ->where('cate_id', $request['cate_id'])
            ->update($cate_edit_data);

        // 3. 编辑品类下所属商品的品类名称
        // 3.1 查询当前品类下的商品数量
        $find_cate =  DB::table('category')
            ->where('cate_id', $request['cate_id'])
            ->select('cate_goods_number', 'cate_class')
            ->first();
        if ($find_cate->cate_class == 2) {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'所属品类已超过三级']);
        }
        if ($find_cate->cate_goods_number) {
            // 3.2 当前品类下绑定的有商品，更改商品中的品类名称
            $edit_goods['goo_update_time'] = date('Y-m-d H:i:s');
            $edit_goods['goo_cate_name'] = $request['cate_name'];
            $goods_res =  DB::table('goods')
                ->where('goo_cate_id', $request['cate_id'])
                ->where('goo_delete', 1)
                ->update($edit_goods);
        } else {
            $goods_res = true;
        }
        if ($cate_res && $goods_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '品类', '编辑', '编辑品类：' . $request['cate_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 VerifyCategoryListController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

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

        // 启用
        $update_data['cate_state'] = 1; //状态1启用2停用
        $update_data['cate_update_time'] = date('Y-m-d H:i:s');
        $cate_res = DB::table('category')
            ->whereIn('cate_id', $request['cate_id'])
            ->update($update_data);

        if ($cate_res) {
            Common::addLog($user_info, getRealIp($request), '品类', '启用', '品类：（' . implode(',', $cate_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 VerifyCategoryListController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

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

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

        // 停用
        $update_data['cate_state'] = 2; //状态1启用2停用
        $update_data['cate_update_time'] = date('Y-m-d H:i:s');
        $cate_res = DB::table('category')
            ->whereIn('cate_id', $request['cate_id'])
            ->update($update_data);

        if ($cate_res) {
            Common::addLog($user_info, getRealIp($request), '品类', '停用', '品类：（' . implode(',', $cate_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 VerifyCategoryListController;
        $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_cate_id', $request['cate_id'])
            ->where('goo_delete', 1)
            ->first();
        if ($goods) {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'品类下有商品不得删除']);
        }
        // 品类下有子品类不得删除
        $son_category = DB::table('category')
            ->whereIn('cate_parent_id', $request['cate_id'])
            ->where('cate_delete', 1)
            ->first();
        if ($son_category) {
            return response()->json(["code"=>500, 'msg'=>'error', 'data'=>'品类下有子品类不得删除']);
        }

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

        // 删除
        $update_data['cate_delete'] = 2; //是否删除：1正常2已删除
        $update_data['cate_update_time'] = date('Y-m-d H:i:s');
        $cate_res = DB::table('category')
            ->whereIn('cate_id', $request['cate_id'])
            ->update($update_data);

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

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

        $select_field = "cate_id, cate_name";

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