<?php

namespace App\Http\Controllers\Common;
use App\Http\Controllers\BaseController;
use App\Models\GoodsBrand;
use App\Services\ExceloutService;
use Complex\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Validator;
use App\Models\PjGoods;
use App\Models\GhPrice;
use App\Models\GoodCode;
use App\Models\GoodsAttribute;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\BmmcService;
/**
 * @name 商品管理
 * Class SKUController
 * @package App\Http\Controllers\Common
 */
class GoodsController extends BaseController
{
	/**
	 * 列表
	 * @param Request $request
	 * @return \BlueCity\Core\Controllers\mixed
	 * @author du 2021年7月21日下午4:09:26
	 */
	public function index (Request $request)
    {
        $session = Request()->get('session_token');//用户信息
        $Db = new PjGoods();
        if($request->filled('version')){ //商品型号
            $version = $request->input('version');
            $Db = $Db->whereRaw("(version like '%".$version."%' or brand_name like '%".$version."%'or general_version like '%".$version."%' or national_version like '%".$version."%')");
        }
        if($request->filled('brand_name')){ //商品品牌
            $brand_name = $request->input('brand_name');
            $Db = $Db->where('brand_name','like','%'.$brand_name.'%');
        }

        if($request->filled('pg_series')){
            $pg_series = $request->input('pg_series');
            $Db = $Db->where('pg_series','like','%'.$pg_series.'%');
        }
        $page_size = $request->input('page_size',10);
		$page = $request->input('page',1);
        if(!in_array($request->get('session_token')['admin_groupnew'],[7,8])) {
            $Db = $Db->where('company_id', $session['company_id']);
        }
		if($page<1){
			$page = 1;
		}
        if ($request->input('is_excel') == 1) {
            DB::connection()->enableQueryLog();#开启执行日志
        }
       // ->select('pg_id','is_delect','brand_name','pg_series','version','general_version','gs_bid','cd_id','gs_id','goods_pic_path','pieces','sort_directory','pg_assurance')
		$paginate = $Db->orderBy('pg_id','ASC')->paginate($page_size);
		$list = self::dataToArray($paginate->items());
		//dump($list);exit;
		//print_r(DB::getQueryLog());
        $ghPriceArr = GhPrice::pluck('supply_price','goods_id')->toArray();

        //导出 start
        if ($request->input('is_excel') == 1) {
            $session = $request->get('session_token');
            $sqls = DB::getQueryLog()[1];//sql数组
            $excel = new CommonController();
            return $excel->getExcelOut($request->input('Pri_id'), $sqls, $session);
        }
        //导出 end

        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        $export = BmmcService::getTopButton('addGoods,export','', $all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮

        if($list){
            foreach ($list as $k =>$v){
                $button = [];
                if ($v['is_delect'] == 1){
                	$button[] = 'editGoodsDel';
                }elseif($v['is_delect'] == 2){
                	$button[] = 'editGoodsDelQ';
                }
                $button[] = 'editGoods';
                $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']??[];

                if ($v['is_delect'] == 1){
                    $list[$k]['is_delete_name'] = "启用";
                }elseif($v['is_delect'] == 2){
                    $list[$k]['is_delete_name'] = "停用";
                }
                if ($v['pg_series'] == ''){
                    $list[$k]['goods_number'] = $v['brand_name'].'-'.$v['version'];
                }else{
                    $list[$k]['goods_number'] = $v['brand_name'].'-'.$v['pg_series'].'-'.$v['version'];
                }

                if ($v['goods_pic_path']){
                    $list[$k]['goods_pic_path'] = $v['goods_pic_path'];

                }

                if (isset($ghPriceArr[$v['pg_id']])) {
                    $list[$k]['supply_price'] = $ghPriceArr[$v['pg_id']];
                } else {
                    $list[$k]['supply_price'] = 0;
                }

                //获取产品属性
                $list[$k]['attrInfo'] = GoodsAttribute::where('ga_goods_id',$v['pg_id'])->select('ga_name','ga_number','ga_piece')->get();

                if ($v['dp_length'] !='' && $v['dp_width'] != '' && $v['dp_height'] != ''){
                    $list[$k]['dp_lwh'] = $v['dp_length'].'(长度)'.$v['dp_width'].'(宽度)'.$v['dp_height'].'(高度)';
                }else{
                    $list[$k]['dp_lwh'] = "暂无";
                }

            }

           $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 brand_name 品牌(必填)
     * @param version 名称(必填)
     * @param pg_series 系列
     * @param general_version 通用名称
     * @param goods_pic_path 图片
     * @param pg_assurance 质保时间
     * @param goodcode 统一编码
     * @param supply_price 价格
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月21日下午1:50:28
     */
    public function addGoods (Request $request)
    {
        $input = $request->only('supply_price','dataList','goodcode','brand_name','pg_series','version','general_version','gs_bid','cd_id','gs_id','goods_pic_path','pieces','sort_directory','pg_assurance','pg_parentid');
        $rules = [
        		'sort_directory' => 'required|string',
        		'gs_bid' => 'required|int',
        		'cd_id' => 'required|int',
        		//'gs_id' => 'required|int',
//        		'brand_name' => 'required|string',
        		'version' => 'required|string',
        		'pg_assurance' => 'required|',
        		'dataList' => 'required|',
        		'supply_price' => 'required|',
        ];
        $message = [
        		'sort_directory.required' => "品类不能为空",
        		'gs_bid.required' => "品牌ID不能为空",
        		'cd_id.required' => "品类ID不能为空",
        		//'gs_id.required' => "系列ID不能为空",
//        		'brand_name.required' => "品牌名称不能为空",
        		'version.required' => "名称不能为空",
        		'pg_assurance.required' => "质保时间不能为空",
        		'dataList.required' => "商品属性不能为空",
        		'supply_price.required' => "供货价格不能为空",
        ];
        $Validator = Validator::make ($input,$rules,$message );
        if ($Validator->fails ()) {
        	return $this->error ( $Validator->errors ()->first (), ErrorInc::INVALID_PARAM,[]);
        	exit();
        }
        if($request->filled('pg_series')){
        	$pg_series = $input['pg_series'];
        }else{
        	$pg_series = '';
        }
        $input['brand_name'] = GoodsBrand::where("id",$input['gs_bid'])->value("brand_name");
        $exit = PjGoods::where('version',$input['version'])->where('brand_name',$input['brand_name'])->where('pg_series',$pg_series)->where('company_id',Request()->get('session_token')['company_id'])->value('pg_id');
        if ($exit) {
        	return $this->error('该名已存在', ErrorInc::REPEAT_SUBMIT, []);exit;
        }

        $admin_id = $request->get('session_token')['admin_acc'];
        $nowDate = date('Y-m-d H:i:s');
        $arr['general_version'] = $input['general_version']??'';//别名
        $arr['pieces'] = $input['pieces'];//单位
        $arr['cd_id'] = $input['cd_id'];//品类ＩＤ
        $arr['sort_directory'] = $input['sort_directory']??'';//品类名
        $arr['gs_id'] = $input['gs_id']??'0';//系列ＩＤ
        $arr['pg_series'] = $pg_series??'';//系列名

        $arr['gs_bid'] = $input['gs_bid'];//品牌IＤ
        $arr['brand_name'] = $input['brand_name'];//品牌名
        $arr['pg_assurance'] = $input['pg_assurance'];//质保时间
        $arr['version'] = $input['version'];//商品名
        $arr['goods_pic_path'] = $input['goods_pic_path']??'';
        $arr['oper_peo'] = $admin_id;
        $arr['oper_time'] = $nowDate;
        $arr['company_id'] = Request()->get('session_token')['company_id'];
        $arr['pg_parentid'] = $input['pg_parentid']??0;
        if($arr['pg_series']!=''){
            $pg_seriess = "-".$arr['pg_series'];
        }else{
            $pg_seriess = '';
        }
        $arr['pg_goodsname'] = $arr['brand_name'].$pg_seriess.'-'.$arr['version'];
        DB::beginTransaction();
        $res = PjGoods::insertGetId($arr);

        //添加供货价格
        if($res){
            GhPrice::insert([
                'gh_price_name' => $admin_id,
                'goods_id'      => $res,
                'ser_id'        => 0,
                'create_time'   => $nowDate,
                'remarks'       => '1',
                'supply_price'  => $input['supply_price'],
                'company_id'  => Request()->get('session_token')['company_id'],
            ]);
            //添加统一编码表
            if($request->filled('goodcode')){
            	GoodCode::insert([
            	'pgc_code' 		=> $input['goodcode'],
            	'pgc_pgid'      => $res,
            	'pgc_type'      => 1,
            	'pgc_time'   	=> $nowDate,
            	'new'   		=> 'X'.$input['goodcode'],
            	]
            	);
            }

            //添加商品属性  前端先调用获取属性接口如果有展示再添加，如果没有直接添加
            $ret = $this->addGoodsAttribute($input['cd_id'], $res, $request->get('session_token')['id'], $input['dataList']);
           if(!$ret){
            	DB::rollback();
            	return $this->error('添加失败1', ErrorInc::MYSQL_FAILED, []);exit;
            }

            DB::commit();
            $this->insertingLog('添加，','',$input['version'],'商品管理',$request->ip(),$request->get('session_token')['admin_acc']);
            return $this->success('添加成功', []);exit;
        }else{
        	DB::rollback();
        	return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);exit;
        }

    }

    /**
     * @name 商品修改
     * @param type 类型 1:展示修改数据; 2:修改动作;
     * @param id 商品id
     * @param brand_name 品牌(必填)
     * @param version 名称(必填)
     * @param pg_series 系列
     * @param general_version 通用名称
     * @param goods_pic_path 图片
     * @param pg_assurance 质保时间
     * @param goodcode 统一编码
     * @param supply_price 价格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\BlueCity\Core\Controllers\mixed
     * @author du 2021年7月21日下午2:54:23
     */
    public function editGoods (Request $request)
    {
        if(!$request->filled('type')&&!$request->filled('id')){
            return $this->error(' 参数错误', ErrorInc::INVALID_PARAM, []);exit;
        }
        $id = intval($request->input('id'));

        if($request->input('type') == 1){
            $result = PjGoods::where('pg_id',$id)->select('pg_id','brand_name','pg_series','version','general_version','gs_bid','cd_id','gs_id','goods_pic_path','pieces','sort_directory','pg_assurance','pg_parentid')->first();
            $resAttr = GoodsAttribute::where('ga_goods_id',$id)->select('ga_name','ga_number','ga_piece')->get();

            $result['supply_price'] = GhPrice::where('goods_id',$id)->orderBy('id','DESC')->value('supply_price');

            $result['goodcode'] = GoodCode::where('pgc_pgid',$id)->value('pgc_code');
            if($result){
                 $data = $result;
                $data['resAttr'] = $resAttr;
              return $this->success('获取成功', $data);exit;
            }else{
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
            }
        }elseif($request->input('type') == 2){
        	if(!$id){
        		return $this->error(' 参数错误', ErrorInc::INVALID_PARAM, []);exit;
        	}
            $input = $request->only('id','supply_price','dataList','goodcode','brand_name','pg_series','version','general_version','gs_bid','cd_id','gs_id','goods_pic_path','pieces','sort_directory','pg_assurance','pg_parentid');
            $rules = [
            		//'pg_series' => 'required|string',
            		//'gs_bid' => 'required|int',
            		'cd_id' => 'required|int',
            		//'gs_id' => 'required|int',
            		'brand_name' => 'required|string',
            		'version' => 'required|string',
            		'pg_assurance' => 'required|',
            		'dataList' => 'required|',
            		'supply_price' => 'required|',
            ];
            $message = [
            		//'pg_series.required' => "系列名称不能为空",
            		'gs_bid.required' => "品牌ID不能为空",
            		'cd_id.required' => "品类ID不能为空",
            		//'gs_id.required' => "系列ID不能为空",
            		'brand_name.required' => "品牌名称不能为空",
            		'version.required' => "名称不能为空",
            		'pg_assurance.required' => "质保时间不能为空",
            		'dataList.required' => "商品属性不能为空",
            		'supply_price.required' => "供货价格不能为空",
            ];
            $Validator = Validator::make ($input,$rules,$message );
            if ($Validator->fails ()) {
            	return $this->error ( $Validator->errors ()->first (), ErrorInc::INVALID_PARAM,[]);
            	exit();
            }
            if($request->filled('pg_series')){
            	$pg_series = $input['pg_series'];
            }else{
            	$pg_series = '';
            }
            $exit = PjGoods::where('version',$input['version'])->where('brand_name',$input['brand_name'])->where('pg_series',$pg_series)->where('pg_id','!=',$id)->where('company_id',Request()->get('session_token')['company_id'])->value('pg_id');
            if ($exit) {
            	return $this->error('该名已存在', ErrorInc::REPEAT_SUBMIT, []);exit;
            }
            $admin_id = $request->get('session_token')['admin_acc'];
            $arr['general_version'] = $input['general_version']??'';//别名
            $arr['pieces'] = $input['pieces'];//单位
            $arr['cd_id'] = $input['cd_id'];//品类ＩＤ
            $arr['sort_directory'] = $input['sort_directory'];//品类名
            $arr['gs_id'] = $input['gs_id'];//系列ＩＤ
            $arr['pg_series'] = $pg_series;//系列名
            $arr['gs_bid'] = $input['gs_bid'];//品牌IＤ
            $arr['brand_name'] = $input['brand_name'];//品牌名
            $arr['pg_assurance'] = $input['pg_assurance'];//质保时间
            $arr['version'] = $input['version'];//商品名
            $arr['goods_pic_path'] = $input['goods_pic_path']??'';
            $arr['oper_peo'] = $admin_id;
            if($arr['pg_series']!=''){
                $pg_seriess = "-".$arr['pg_series'];
            }else{
                $pg_seriess = '';
            }
            $arr['pg_goodsname'] = $arr['brand_name'].$pg_seriess.'-'.$arr['version'];
            if($request->filled('pg_parentid')){
                $arr['pg_parentid'] = $input['pg_parentid'];
            }

            DB::beginTransaction();
            //DB::connection()->enableQueryLog();
            $res = PjGoods::where('pg_id',$id)->update($arr);
            //dump($res);
           // print_r(DB::getQueryLog());

            GhPrice::where('goods_id',$id)->update(['gh_price_name' => $admin_id, 'supply_price'  => $input['supply_price']]);
            //添加统一编码表
            if($request->filled('goodcode')){
                GoodCode::where('pgc_pgid',$id)->where('pgc_type',1)->update(['pgc_code'=> $input['goodcode'],'new'=> 'X'.$input['goodcode']]);
            }
            //添加商品属性  前端先调用获取属性接口如果有展示再添加，如果没有直接添加
            $ret = $this->addGoodsAttribute($input['cd_id'],$id, $request->get('session_token')['id'], $input['dataList']);
            if(!$ret){
                DB::rollback();
                return $this->error('修改失败1', ErrorInc::MYSQL_FAILED, []);exit;
            }

            if($res || $ret){

            	DB::commit();//成功则提交
            	$this->insertingLog('编辑，','',$input['version'],'商品管理',$request->ip(),$admin_id);
            	return $this->success('编辑成功', []);exit;

            }else{
            	DB::rollback();//不成功，则回滚
            	return $this->error('编辑失败', ErrorInc::MYSQL_FAILED, []);exit;
            }

        }else{
        	return $this->error(' 参数错误', ErrorInc::INVALID_PARAM, []);exit;
        }
    }

    /**
     * @name 编辑停用、启用
     * @param id 商品id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月21日下午3:18:13
     */
    public function editGoodsDel (Request $request)
    {
        if(!$request->filled('id')){
        	return $this->error(' 参数错误', ErrorInc::INVALID_PARAM, []);exit;
        }
            $id = intval($request->input('id'));

            $info = PjGoods::where('pg_id',$id)->select('is_delect','brand_name','pg_series','version')->first();
            if ($info['is_delect'] == 1){
                $poss['is_delect'] = 2;
            }elseif ($info['is_delect'] == 2){
                $poss['is_delect'] = 1;
            }
            $res = PjGoods::where('pg_id',$id)->update($poss);

            if ($info['pg_series'] != ''){
                $content = $info['brand_name']."-".$info['pg_series']."-".$info['version'];
            }else{
                $content = $info['brand_name']."-".$info['version'];
            }
            if($res){
            	$this->insertingLog('编辑停用启用，','',$content,'商品管理',$request->ip(),$request->get('session_token')['admin_acc']);
                return $this->success('操作成功', []);exit;
            }else{
                return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);exit;
            }
    }


    /**
     *
     * @param int $cd_id
     * @param int $goodsID
     * @param int $admin_id
     * @param array $data
     * @return boolean
     * @author du 2021年7月21日上午10:24:46
     */
    public function addGoodsAttribute($cd_id,$goodsId,$admin_id,$data){
    	$res = GoodsAttribute::where('ga_goods_id',$goodsId)->value('ga_id');
    	if($res){
    		GoodsAttribute::where('ga_goods_id',$goodsId)->delete();
    	}
    	foreach ($data as $k=>$v){
    		DB::connection()->enableQueryLog();
    		$res = GoodsAttribute::insert([
    			'cd_id' 			=> $cd_id,
    			'ga_goods_id' 		=> $goodsId,
    			'ga_admin_id' 		=> $admin_id,
    			'ga_name'    		=> $data[$k]['ga_name'],
    			'ga_number'   		=> $data[$k]['ga_number'],
    			'ga_piece'        	=> $data[$k]['ga_piece'],
    			'ga_creat_time'   	=> date("Y-m-d H:i:s"),

    		]);
    		if(!$res){
    			return false;break;
    		}
    	}
    	return true;
    }


    /**
     * 获取最后一条商品属性
     * @param int $cd_id
     * @return array
     * @author du 2021年7月21日上午10:19:36
     */
    public function getGoodsAttributeLast(Request $request){
    	if(!$request->filled('cd_id')){
    		return $this->error(' 参数错误', ErrorInc::INVALID_PARAM, []);exit;
    	}
    	$cd_id = $request->input('cd_id');
    	$goodsId = PjGoods::where('cd_id',$cd_id)->orderBy('pg_id','Desc')->value('pg_id');
    	if($goodsId){
    		$res = GoodsAttribute::where('ga_goods_id',$goodsId)->select('ga_name','ga_number','ga_piece')->get();
    		if($res){
    			return $this->success('获取成功', $res);
    		}else{
    			return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
    		}
    	}else{
    		return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);
    	}
    }


}
