<?php

namespace App\Http\Controllers\Mounting\Shop;

use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Traits\ResourceControllerMethod;
use App\Services\Shop\GoodsService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use App\Models\OperationLog;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use \PhpOffice\PhpSpreadsheet\IOFactory;

// 商品管理
class GoodsController extends Controller
{
    public function __construct()
    {
        $this->dataService = $service = new GoodsService();
        $this->bootWithService($service);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->indexValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->searchPage($user_info, $request->all(), $request['show_count']);
        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if (empty($search_data)) {
            return response()->json(['code'=>200, 'msg'=>'未找到数据', 'data'=>$search_data, 'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data, 'list_button'=>$list_button]);
        }
    }

    // 详情
    public function info(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->infoValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->info($user_info, $request->all());
        if (empty($search_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
        }
    }

    // 分类列表
    public function classificationIndex(Request $request)
    {
        // 查询字段
        $field_columns = ['gocl_id', 'gocl_name', 'gocl_sort', 'gocl_remark', 'gocl_state'];
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $search_data = $this->dataService->classificationIndex($user_info, $request->all(), 10, $field_columns);
        return $search_data;
    }

    // 获取分类
    public function getClassification(Request $request)
    {
        $user_info = LoginUserService::getUser();
        $search_data = $this->dataService->getClassification($user_info, $request->all());
        return $search_data;
    }

    // 新增商品
    public function add(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        
        $exist = GoodsService::goodsnameExists($user_info, $request->all(), 0);
        if ($exist) {
            return $this->error('同名内容已经存在', ErrorInc::DATA_EXIST);
        }
        DB::beginTransaction();
        $res = GoodsService::add($user_info, $request->all());
        if ($res['code'] == 200) {
            // 生成操作记录
            $palo_res = paitLog($user_info, $res['data'], '新建商品', '');
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '新增', '新增'.$request['pait_name'].'成功');
            DB::commit();
            return $this->success('新增成功');
        } else {
            DB::rollBack();
            return response()->json($res);
        }
    }

    // 新增分类
    public function addClassification(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->addClassificationValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $exist = GoodsService::nameExists($user_info, $request->all(), 0);
        if ($exist) {
            return $this->error('同名内容已经存在', ErrorInc::DATA_EXIST);
        }
        DB::beginTransaction();
        $res = GoodsService::addClassification($user_info, $request->all());
        if ($res) {
            DB::commit();
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '新增分类', '新增成功');
            return $this->success('新增成功');
        } else {
            DB::rollBack();
            return $this->error('新增失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 编辑分类
    public function editClassification(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->editClassificationValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        $exist = GoodsService::nameExists($user_info, $request->all(), $request['gocl_id']);
        if ($exist) {
            return $this->error('同名内容已经存在', ErrorInc::DATA_EXIST);
        }
        DB::beginTransaction();
        $res = GoodsService::editClassification($user_info, $request->all());
        if ($res) {
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '编辑分类', '编辑成功');
            DB::commit();
            return $this->success('编辑成功');
        } else {
            DB::rollBack();
            return $this->error('编辑失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 会员卡明细
    public function claIndex(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->detailIndexValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }

        // 获取用户信息
        $user_info = LoginUserService::getUser();
        // 查询字段
        $field_columns = ['vcre_id', 'vcre_myvi_id', 'vcre_user_id', 'vcre_ord_num', 'vcre_ord_id', 'vcre_create_time', 'vcre_car_adm_name', 'vcre_car_adm_phone', 'vcre_myvi_num', 'myvi_name', 'vcre_log', 'vcre_num_change', 'orcl_car_num'];
        $res = VipCardService::detailIndex($user_info, $request->all(), 10, $field_columns);
        if (empty($res)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            // 获取当前列表下的按钮
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$res]);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->editShowValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        if ($request['type'] == 1) {
            $return_data = $this->dataService->info($user_info, $request->all());
            return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
        }
        // 验证参数
        $error_message = $this->dataService->mainValidator->editValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        $exist = GoodsService::goodsnameExists($user_info, $request->all(), $request['pait_id']);
        if ($exist) {
            return $this->error('同名内容已经存在', ErrorInc::DATA_EXIST);
        }
        DB::beginTransaction();
        $res = GoodsService::edit($user_info,$request->all());
        if ($res['code'] ==200) {
            // 生成操作记录
            $palo_res = paitLog($user_info, $request['pait_id'], '编辑商品', '');
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '编辑', '编辑成功');
            DB::commit();
            return $this->success('编辑成功');
        } else {
            DB::rollBack();
            return response()->json($res);
        }
    }

    // 开启
    public function claStart(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->claStartValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $res = GoodsService::editState($request['gocl_id'], 1);
        if ($res) {
            // 获取启用的名称
            OperationLog::addLog($user_info, getRealIp($request), '商品分类', '开启', '开启成功');
            DB::commit();
            return $this->success('开启成功');
        } else {
            DB::rollBack();
            return $this->error('开启失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 分类关闭
    public function claStop(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->claStartValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $res = GoodsService::editState($request['gocl_id'], 2);
        if ($res) {
            OperationLog::addLog($user_info, getRealIp($request), '会员卡', '关闭', '关闭成功');
            DB::commit();
            return $this->success('关闭成功');
        } else {
            DB::rollBack();
            return $this->error('关闭失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 上架
    public function start(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->startValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $pait_saleable_quantity = DB::table('package_items')
            ->where('pait_id', $request['pait_id'])
            ->value('pait_saleable_quantity');
        if ($pait_saleable_quantity <= 0) {
            return $this->error('可售数量为0，请补货后上架', ErrorInc::INVALID_PARAM);
        }
        $res = GoodsService::goodseditState($request['pait_id'], 1);
        if ($res) {
            // 生成操作记录
            $palo_res = paitLog($user_info, $res, '上架商品', '');
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '上架', '上架成功');
            DB::commit();
            return $this->success('上架成功');
        } else {
            DB::rollBack();
            return $this->error('上架失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 下架商品
    public function stop(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->startValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $res = GoodsService::goodseditState($request['pait_id'], 2);
        if ($res) {
            // 生成操作记录
            $palo_res = paitLog($user_info, $res, '下架商品', '');
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '下架', '下架成功');
            DB::commit();
            return $this->success('下架成功');
        } else {
            DB::rollBack();
            return $this->error('下架失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 删除分类
    public function claDelete(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->claDeleteValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();
        DB::beginTransaction();
        $find_data = DB::table('package_items')
            ->where('pait_classify_id', $request['gocl_id'])
            ->first();
        if ($find_data) {
           return ['code' => 500, 'msg' => '此分类下含有套餐，不可删除', 'data' => ''];
        }
        $res = GoodsService::claDelete($request['gocl_id']);
        if ($res) {
            OperationLog::addLog($user_info, getRealIp($request), '商品分类', '删除', '删除成功');
            DB::commit();
            return $this->success('删除成功');
        } else {
            DB::rollBack();
            return $this->error('删除失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 补货
    public function replenishment(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->replenishmentValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        DB::beginTransaction();
        $res = GoodsService::replenishment($user_info,$request->all());
        if ($res['code'] == 200) {
            // 生成操作记录
            $palo_res = paitLog($user_info, $request['pait_id'], '补货', '补货数量：'.$request['number'].'');
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '补货', '补货成功');
            DB::commit();
            return $this->success('补货成功');
        } else {
            DB::rollBack();
            return $this->error('补货失败', ErrorInc::MYSQL_FAILED);
        }
    }

    // 商品操作记录
    public function paitLogIndex(Request $request)
    {
        
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $search_data = GoodsService::paitLogIndex($user_info,$request->all(), 10);
        if (empty($search_data)) {
            return $this->error('未找到数据', ErrorInc::DATA_EMPTY);
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$search_data]);
        }
    }

    /**
     * 关联商品列表
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function colist(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->colistValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $search_data = GoodsService::colist($user_info,$request->all(), 10);

        if ($search_data['code'] == 200) {
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '补货', '补货成功');
        }
        return response()->json($search_data);
    }

    /**
     * 关联商品
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function correlation(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->correlationValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $search_data = GoodsService::correlation($user_info,$request->all(), 10);

        if ($search_data['code'] == 200) {
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '关联商品', '关联成功');
        }
        return response()->json($search_data);
    }

    /**
     * 查询商品
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function package(Request $request)
    {
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $search_data = GoodsService::package($user_info,$request->all(), 10);

        return response()->json($search_data);
    }

    /**
     * 删除关联商品
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-10-23
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function delCorrelation(Request $request)
    {
        // 验证参数
        $error_message = $this->dataService->mainValidator->correlationValidator($request->all());
        if (!empty($error_message)) {
            return $this->error($error_message, ErrorInc::INVALID_PARAM);
        }
        // 获取用户信息
        $user_info = LoginUserService::getUser();

        $search_data = GoodsService::delCorrelation($user_info,$request->all(), 10);

        if ($search_data['code'] == 200) {
            OperationLog::addLog($user_info, getRealIp($request), '商品列表', '关联商品', '解除关联');
        }
        return response()->json($search_data);
    }
}