<?php

namespace App\Http\Controllers\Common;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Validator;
use App\Models\GoodsSeries;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\BmmcService;
use Illuminate\Support\Facades\Redis;
use App\Services\RedisService;
use App\Services\CategoryService;
class GoodsSeriesController extends BaseController
{
  	/**
	 * 列表
	 * @param Request $request
	 * @author du 2021年7月20日下午1:44:03
	 */
	public function index (Request $request)
	{
		$page_size = $request->input('page_size',10);
		$page = $request->input('page',1);
		if($page<1){
			$page = 1;
		}
		$Db = new GoodsSeries;
		
		if($request->filled('pg_series')){
			$pg_series = $request->input('pg_series');
			$Db = $Db->where('gs_series','like','%'.$pg_series.'%');
		}
		if($request->filled('cd_id')){
			$cd_id = $request->input('cd_id');
			$Db = $Db->where('cd_id',$cd_id);
		}
		if($request->filled('gs_bid')){
			$gs_bid = $request->input('gs_bid');
			$Db = $Db->where('gs_bid',$gs_bid);
		}
		
		$paginate = $Db->paginate($page_size);
		$list = self::dataToArray($paginate->items());
	
		$all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
		$export = BmmcService::getTopButton('addGoodsSeries','', $all_button);
		$data['button_top'] = $export['button_top']??[];//顶部按钮
		$data['button_search'] = $export['button_search']??[];//搜索栏按钮
		
		
		if ($list){		
			$cpname = CategoryService::getall([],'cd_id');	
			foreach ($list as $k=>$v){
				$list[$k]['cd_name'] = $cpname[$v['cd_id']]['cd_pname']??'';				
				$button = [];
				if ($v['gs_state'] == 1){
					$button[] = 'editaddGoodsSeriesDel';
				}elseif($v['gs_state'] == 2){
					$button[] = 'editaddGoodsSeriesDelQ';
				}
				$button[] = 'editGoodsSeries';
				$button = BmmcService::getListButton($button,$all_button);
				$list[$k]['button_one'] = $button['button_one']??[];
				$list[$k]['button_two'] = $button['button_two']??[];
				$list[$k]['button_three'] = $button['button_three']??[];
			}
			//返回数据
			$data['list'] = $list;
			$data['page'] = [
				'count' => $paginate->total(),
                'page'=> $paginate->currentPage(),
                'page_size' => $page_size,
                'allPage' => $paginate->lastPage()
			];
			return $this->success('获取成功', $data);
		}else{
			return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $data);
		}
	}	

	/**
	 * @name  添加系列
     * @param cd_id 品类ID
     * @param gs_bid 品牌ID
     * @param gs_series  系列
     * @param brand_name 品牌名称
	 * @param Request $request
	 * @author du 2021年7月20日下午1:51:57
	 */
    public function addGoodsSeries (Request $request)
    {
        $input = $request->only('brand_name','gs_series','gs_bid','cd_id');        
        $rules = [
        		'gs_series' => 'required|string',
        		'gs_bid' => 'required|int',
        		'cd_id' => 'required|int',
        		'brand_name' => 'required|string',
        ];
        $message = [
        		'gs_series.required' => "系列名称不能为空",
        		'gs_bid.required' => "品牌ID不能为空",
        		'cd_id.required' => "品类ID不能为空",
        		'brand_name.required' => "品牌名称不能为空",
        ];
        $Validator = Validator::make ( $input, $rules, $message );
        if ($Validator->fails ()) {
        	return $this->error ( $Validator->errors ()->first (), ErrorInc::INVALID_PARAM,[]);
        	exit();
        }
        $exit = GoodsSeries::where('gs_series', $input['gs_series'])->where('cd_id', $input['cd_id'])->where('gs_bid', $input['gs_bid'])->value('gs_id');
        if ($exit) {
           return $this->error('该系列名已存在', ErrorInc::REPEAT_SUBMIT, []);exit;   
        }
     
        $res = GoodsSeries::insert([
            'gs_bid'       => $input['gs_bid'],
        	'cd_id'       => $input['cd_id'],
            'gs_series'    => $input['gs_series'],
            'gs_brandname' => $input['brand_name'],
            'gs_creactime' => date("Y-m-d H:i:s"),
            'gs_sort'      => 0
        ]);

        if ($res) {
        //更新redis内容
        	if(RedisService::redisGet('gseriesList'.$input['gs_bid'].$input['cd_id'])){
        		$gs_bid = $input['gs_bid'];
        		$cd_id = $input['cd_id'];        		        
	        	$gseriesLists = $this->gseriesList($gs_bid,$cd_id);
	    		$gseriesList = json_encode($gseriesLists);
	    		RedisService::redisSet('gseriesList'.$gs_bid.$cd_id,$gseriesList);
        	}
            $content = '系列名称：'.$input['gs_series'];
            $this->insertingLog('添加，','',$content,'系列管理',$request->ip(),$request->get('session_token')['admin_acc']);//备注
            return $this->success('添加成功', []);exit;
        }else{
        	return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);exit;
        }
    }

    /**
     * @name  编辑
     * @param type 1:信息展示　2：修改
     * @param gs_id      数据id
     * @param gs_series  系列
     * @param brand_name 品牌名称 
     * @param Request $request
     * @author du 2021年7月20日下午2:27:00
     */
    public function editGoodsSeries (Request $request)
    {
        if (!$request->filled('gs_id')||!$request->filled('type')){
        	return $this->error(' 参数错误', ErrorInc::INVALID_PARAM, []);exit;
        }
       
        $input = $request->only('brand_name','gs_series','gs_bid','cd_id','gs_id','type'); 
        
        $type = $input['type'];

        if($type==1){
        	$info = GoodsSeries::where('gs_series', $input['gs_series'])->first();
        	if($info){
        		return $this->success('获取成功', $info);exit;
        	}else{
        		return $this->error('暂无数据',ErrorInc::DATA_EMPTY, []);exit;
        	}
        	
        }elseif($type==2){
        	$rules = [
        			'gs_series' => 'required|string',
        			'gs_bid' => 'required|int',
        			'cd_id' => 'required|int',
        			'brand_name' => 'required|string',
        	];
        	$message = [
        			'gs_series.required' => "系统名称不能为空",
        			'gs_bid.required' => "品牌不能为空",
        			'cd_id.required' => "品类不能为空",
        			'brand_name.required' => "品牌名称不能为空",
        	];
        	$Validator = Validator::make ( $input, $rules, $message );
        	if ($Validator->fails ()) {
        		return $this->error ( $Validator->errors ()->first (), ErrorInc::INVALID_PARAM,[]);
        		exit();
        	}
        	$exit = GoodsSeries::where('gs_series', $input['gs_series'])->where('cd_id', $input['cd_id'])->where('gs_bid', $input['gs_bid'])->where('gs_id','!=',$input['gs_id'])->value('gs_id');
        	if ($exit) {
        		return $this->error('该系列名已存在', ErrorInc::REPEAT_SUBMIT, []);exit;
        	}
        	
        	$res = DB::table('goods_series')->where('gs_id', $input['gs_id'])->update([
        			'gs_series'    => $input['gs_series'],
        			'gs_brandname' => $input['brand_name'],
        			'gs_bid'       => $input['gs_bid'],
        			'cd_id'       => $input['cd_id'],
        	]);
        	
        	if ($res) {
        		//更新redis内容
        		if(RedisService::redisGet('gseriesList'.$input['gs_bid'].$input['cd_id'])){
        			$gs_bid = $input['gs_bid'];
        			$cd_id = $input['cd_id'];
        			$gseriesLists = $this->gseriesList($gs_bid,$cd_id);
        			$gseriesList = json_encode($gseriesLists);
        			RedisService::redisSet('gseriesList'.$gs_bid.$cd_id,$gseriesList);
        		}
        		 
        		$content = $input['gs_series'].'-'.$input['brand_name'].'-'.$input['gs_bid'].'-'.$input['cd_id'];
        		$this->insertingLog('编辑，','',$content,'系列管理',$request->ip(),$request->get('session_token')['admin_acc']);
        		return $this->success('编辑成功', []);exit;
        	}else{
        	
        		return $this->error('编辑失败', ErrorInc::MYSQL_FAILED, []);exit;
        	}
        	
        }else{
        	return $this->error(' 参数错误', ErrorInc::INVALID_PARAM, []);exit;
        }
        
      }

    /**
     * @name  编辑停用启用
     * @param gs_id      数据id
     * @param Request $request
     * @author du 2021年7月20日下午2:08:14
     */
    public function editaddGoodsSeriesDel (Request $request)
    {
    	if(!$request->filled('gs_id')){
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$id = intval($request->input('gs_id'));
    	 
    	$del_flag = GoodsSeries::where('gs_id',$id)->value('gs_state');
    	 
    	if ($del_flag == 1){
    		$poss['gs_state'] = 2;
    	}elseif ($del_flag == 2){
    		$poss['gs_state'] = 1;
    	}
    	$res = GoodsSeries::where('gs_id',$id)->update($poss);
    	if($res){
    		$this->insertingLog('编辑系列开关','',$id,'系列管理',$request->ip(),$request->get('session_token')['admin_acc']);
    		return $this->success('操作成功', []);
    	}else{
    		return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
    	}    
        
        	
    }

    /**
     * 获取系列列表
     * @param $gs_bid 品牌ID
     * @param $cd_id 品类ID
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月20日下午3:28:11
     */
    public function gseriesListSearch(Request $request){
    	if(!$request->filled('gs_bid')||!$request->filled('cd_id')){
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$gs_bid = $request->input('gs_bid');
    	$cd_id = $request->input('cd_id');    	
    	if(RedisService::redisGet('gseriesList'.$gs_bid.$cd_id)){
    		//echo 1;
    		$gseriesList = RedisService::redisGet('gseriesList'.$gs_bid.$cd_id);
    		return $this->success('获取成功', $gseriesList);
    		//return $cdList;
    	}else{
    		//echo 2;    		
    		$gseriesLists = $this->gseriesList($gs_bid,$cd_id);    		
    		$gseriesList = json_encode($gseriesLists);    		
    		RedisService::redisSet('gseriesList'.$gs_bid.$cd_id,$gseriesList);    		
    		return $this->success('获取成功',$gseriesLists);
    	}
    }
     
    /**
     * 所有品牌系列数据
     * @param $gs_bid 品牌ID
     * @param $cd_id 品类ID
     * @return array
     * @author du 2021年7月20日下午3:16:43
     */
    public function gseriesList($gs_bid,$cd_id){
    	$data = GoodsSeries::where('gs_state',1)->where('gs_bid',$gs_bid)->where('cd_id',$cd_id)->select('gs_id','gs_series','gs_brandname')->orderBy('gs_id','DESC')->get();
    	return $data;
    }
    

    /**
     * 根据某一品类获取系列列表数据 
     * @param Request $request
     * @param cd_id 品类ＩＤ
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月23日下午3:07:35
     */
    public function getGoodsSerieByCdId(Request $request)
    {
    	if(!$request->filled('cd_id')){
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$cd_id = intval($request->input('cd_id'));
    	$series = GoodsSeries::where('cd_id',$cd_id)->select('gs_id','gs_series')->get()->toarray();    	
    	if($series){
    		return $this->success('获取成功',$series);exit;    	
    	}else{
    		return $this->error('暂无数据',ErrorInc::DATA_EMPTY, []);exit;
    	}
    }

    
}
