<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\api\controller\goods;

use app\api\controller\Base;
use think\Db;

class Goods extends Base
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function spec(){
        $params = $this->param();
        
        $id = intval($params['id']); 
        $type = intval($params['type']); 
        $pintuan_goods_id = intval($params['pintuan_goods_id']); 
        
        $goods = Db::name("bbfx_goods")->where(['id'=>$id,'status'=>1])->find();
        if(empty($goods)){
            __error("商品不存在");
        }
        $spec_list = [];
        $sku_data = [];
        $price = $goods['price'];
        $stock = $goods['stock'];
        
        $seckill_goods = [];
        $pintuan_goods = [];
        if($type == 4){
            $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$pintuan_goods_id,'goods_id'=>$goods['id']])->find();
            if(empty($pintuan_goods)){
                __error("拼团商品错误".$pintuan_goods_id);
            }
            $goods['price'] = $pintuan_goods['price'];
            $price = $pintuan_goods['price'];
            $stock = $pintuan_goods['stock'];
        }
        else if($type == 5){
            $bargain_goods_id = intval($params['bargain_goods_id']);
            $bargain_goods = Db::name("bbfx_bargain_goods")->where(['uniacid'=>UNIACID,'id'=>$bargain_goods_id,'status'=>1])->find();
            if(empty($bargain_goods)){
                __error("砍价商品错误".$bargain_goods_id);
            }
            $price = $bargain_goods['price'];
            $stock = $bargain_goods['stock'];
        }
        else if($type == 6){

        }
        else{
            $seckill_activity = Db::name("bbfx_seckill_activity")->where(['status'=>1,'starttime'=>['<',time()]])->where(['endtime'=>['>',time()]])->select();
            if(!empty($seckill_activity)){
                
                foreach ($seckill_activity as $key => $val){
                    $seckill_goods_ids = explode(",",$val['seckill_goods_ids']);
                        
                    $where = ["a.uniacid"=>UNIACID,"a.status"=>1,"a.id"=>['in',$seckill_goods_ids],'a.goods_id'=>$goods['id'],'b.status'=>1];
                    $seckill_goods = Db::name("bbfx_seckill_goods")->alias("a")->join("bbfx_goods b","a.goods_id = b.id")->where($where)->field("a.*,b.title,b.thumb,b.price as o_price")->order(['b.sort desc','b.id desc'])->find();
                    if(!empty($seckill_goods)){
                        $seckill_activity = $val;
                    }
                }
            }
        }
        
        if($goods['is_spec'] == 1){
            
            $spec_list = Db::name("bbfx_goods_spec")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->order('id asc')->select();
            if(!empty($spec_list)){
                foreach ($spec_list as $key => &$val){
                    $spec_items = Db::name("bbfx_goods_spec_item")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id'],'pid'=>$val['id']])->order('id asc')->select();
                    $val['list'] = $spec_items;
                }
                unset($val);
                
                $sku_data = Db::name("bbfx_goods_spec_sku")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->select();
                $sku_data = array_skey($sku_data,"sku");
                
                $goods['stock'] = 0;
                $min_price = 0;
                $max_price = 0;
                
                
                
                foreach ($sku_data as $key => &$val){ 
                    
              	    $price = floatval($val['price']);
              	    if($type == 4){
              	        $price = floatval($val['pintuan_price']);
              	        $val['o_price'] = $val['price'];
              	        $val['price'] = $val['pintuan_price'];
              	    }
                    else if($type == 5){
                        $price = floatval($bargain_goods['price']);
              	        $val['o_price'] = $val['price'];
              	        $val['price'] = $bargain_goods['price'];
                    }
              	    else{
              	        if(!empty($seckill_goods)){
                  	        if($seckill_goods['type'] == 2){
                                $price = $price * (floatval($seckill_goods['discount']) / 10);
                            }
                            else{
                                $price = $seckill_goods['price'];
                            }
                  	    }
              	    }
              	    
              	    $price = round($price,2);
              	    
              	    if($price != $val['price']){
                        $val['o_price'] = $val['price'];
                        $val['price'] = $price;
                    }
                    
                    $val['stock'] = intval($val['stock']);
                    if($goods['stock'] == 0){
                        $stock = $val['stock'];
                    }
                    $val['thumb'] = cdnurl($val['thumb']);
                    if($min_price == 0 || $min_price > $val['price']){
                        $min_price = $val['price'];
                    }
                    if($max_price < $val['price']){
                        $max_price = $val['price'];
                    }
                }
                unset($val);
                
                if($min_price == $max_price){
                    $price = $min_price;
                }
                else{
                    $price = $min_price."~".$max_price;
                }
            }
            else{
                $goods['is_spec'] = 0;
            }
            $price = round($price,2);
        }
        else{
            if($goods['type'] == 1){
                $goods['stock'] = Db::name("bbfx_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id'],'status'=>0])->count();
                $stock = $goods['stock'];
            }
            
            if($type == 4){
                
            }
            else if($type == 5){
                
            }
            else{
                if(!empty($seckill_goods)){
          	        if($seckill_goods['type'] == 2){
                        $price = $goods['price'] * (floatval($seckill_goods['discount']) / 10);
                    }
                    else{
                        $price = $seckill_goods['price'];
                    }
          	    }
          	    else{
          	        $price = \app\common\model\bbfxshop\Order::calculateVipGoodsPrice($this->user,$goods);
          	    }
            }
      	    $price = round($price,2);
      	    if($price != $goods['price']){
                $goods['o_price'] = $goods['price'];
                $goods['price'] = $price;
            }
        }
        
        $goods['thumb'] = cdnurl($goods['thumb']);
        
        $sales_volume = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.status'=>['>',0],'o.order_source'=>['<>',6],'o.refund_status'=>-1,'og.goods_id'=>$goods['id']])->sum("og.total");
        $goods['sales_volume'] = intval($sales_volume + $goods['sales_volume']);
        unset($goods['plugin']);
        __success("操作成功",['goods'=>$goods,'spec_list'=>$spec_list,'sku_data'=>$sku_data,'price'=>$price,'stock'=>$stock]);
    }
    
    public function list(){
        $params = $this->param();
        
        \app\common\model\bbfxshop\Goods::resetStock(UNIACID);
        
        $pindex = max(1, intval($params["page"]));
        $psize = 12;
        $category_id = intval($params['category_id']);
        $attr = intval($params['attr']);
        
        if($category_id){
            $category_ids = [$category_id];
            $child = Db::name("bbfx_category")->where(['pid'=>$category_id,'mid'=>0])->find();
            if(!empty($child)){
                $category_ids[] = $child['id'];
                $three_child = Db::name("bbfx_category")->where(['pid'=>$child['id'],'mid'=>0])->find();
                if(!empty($three_child)){
                    $category_ids[] = $three_child['id'];
                }
            }
            
            $where = ["a.uniacid"=>UNIACID,'a.status'=>1,'a.mid'=>0,'b.category_id'=>['in',$category_ids]];
            if($attr == 1){
                $where['a.is_recommend'] = 1;
            }
            else if($attr == 2){
                $where['a.is_new'] = 1;
            }
            else if($attr == 3){
                $where['a.is_hot'] = 1;
            }
            else if($attr == 4){
                $where['a.is_nodiscount'] = 1;
            }
            $list = Db::name("bbfx_goods")->alias("a")->join("bbfx_goods_category b","a.id=b.goods_id")->where($where)->field("a.id,a.score,a.title,a.subtitle,a.thumb,a.price,a.stock,a.type,a.o_price,a.minbuy,a.maxbuy,a.total_maxbuy,a.unit,a.sales_volume,a.virtual_sale,a.is_nodiscount,a.is_leveldiscount_rule,a.level_discount")->order('is_recommend asc,sort desc')->limit(($pindex - 1) * $psize,$psize)->select();
        }
        else{
            $where = ["uniacid"=>UNIACID,'status'=>1,'mid'=>0];
            if($attr == 1){
                $where['is_recommend'] = 1;
            }
            else if($attr == 2){
                $where['is_new'] = 1;
            }
            else if($attr == 3){
                $where['is_hot'] = 1;
            }
            else if($attr == 4){
                $where['is_nodiscount'] = 1;
            }
            $list = Db::name("bbfx_goods")->where($where)->field("id,score,title,subtitle,thumb,price,stock,type,o_price,minbuy,maxbuy,total_maxbuy,unit,sales_volume,virtual_sale,is_nodiscount,is_leveldiscount_rule,level_discount")->order('is_recommend asc,sort desc')->limit(($pindex - 1) * $psize,$psize)->select();
        }
        
        if(!empty($list)){
            foreach($list as $key=>&$val){
                
            	$val['thumb'] = cdnurl($val['thumb']);
            	
            	if($val['sales_volume'] == 0){
            	    $sales_volume = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.order_source'=>['<>',6],'o.status'=>['>',0],'og.goods_id'=>$val['id']])->sum("og.total");
            	    $val['sales_volume'] = intval($sales_volume);
            	    
            	    if($val['sales_volume'] > 0){
            	        Db::name("bbfx_goods")->where(['id'=>$val['id']])->update(['sales_volume'=>$val['sales_volume']]);
            	    }
            	}
                $val['sales_volume'] = intval($val['sales_volume'] + $val['virtual_sale']);
                
                if($val['type'] == 1){
                    $stock = Db::name("bbfx_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$val['id'],'status'=>0])->count();
                    $val['stock'] = $stock;
                }

            }
            unset($val);
            __success("操作成功",$list);
        }
        else{
            __error($pindex==1?"暂无商品数据~~":"没有数据了"); 
        }
    }
    
    public function getRecommendGoods(){
        $params = $this->param();
        
        $list = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'is_recommend'=>1,'status'=>1,'mid'=>0])->field("id,title,thumb,price,stock,type,o_price,minbuy,maxbuy,total_maxbuy,unit,sales_volume,virtual_sale,is_nodiscount,is_leveldiscount_rule,level_discount")->select();
        if(empty($list)){
            __error("暂无推荐商品"); 
        }
        
        foreach ($list as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
            if($val['sales_volume'] == 0){
        	    $sales_volume = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.order_source'=>['<>',6],'o.status'=>['>',0],'og.goods_id'=>$val['id']])->sum("og.total");
        	    $val['sales_volume'] = intval($sales_volume);
        	    
        	    if($val['sales_volume'] > 0){
        	        Db::name("bbfx_goods")->where(['id'=>$val['id']])->update(['sales_volume'=>$val['sales_volume']]);
        	    }
        	}
            $val['sales_volume'] = intval($val['sales_volume'] + $val['virtual_sale']);
        }
        unset($val);
        
        __success("操作成功",$list);
    }
    
    public function detail(){
        $params = $this->param();
        
        $goods_id = intval($params['id']);
        
        $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'status'=>1,'id'=>$goods_id])->find();
  
      	if(!empty($goods)){

            \app\common\model\bbfxshop\Goods::browse($goods['id'],intval($this->user['id']),$params['utk']);
            \app\common\model\bbfxshop\Goods::visitor($goods['id'],intval($this->user['id']),$params['utk']);
      	    
            $goods['parameter'] = iunserializer($goods['parameter']);
      	    
      	    $seckill_activitys = Db::name("bbfx_seckill_activity")->where(['status'=>1,'starttime'=>['<',time()]])->where(['endtime'=>['>',time()]])->select();
      	    $seckill_goods = [];
            if(!empty($seckill_activitys)){
                
                foreach ($seckill_activitys as $key => $val){
                    $seckill_goods_ids = explode(",",$val['seckill_goods_ids']);
                        
                    $where = ["a.uniacid"=>UNIACID,"a.status"=>1,"a.id"=>['in',$seckill_goods_ids],'a.goods_id'=>$goods['id'],'b.status'=>1];
                    $seckill_goods = Db::name("bbfx_seckill_goods")->alias("a")->join("bbfx_goods b","a.goods_id = b.id")->where($where)->field("a.*,b.title,b.thumb,b.price as o_price")->order(['b.sort desc','b.id desc'])->find();
                    if(!empty($seckill_goods)){
                        $seckill_activity = $val;
                    }
                }
            }
      	    
      	    
      	    if(!empty($seckill_goods)){
      	        if($seckill_goods['type'] == 2){
                    $price = $goods['price'] * (floatval($seckill_goods['discount']) / 10);
                    $goods['seckill_discount'] = $seckill_goods['discount'];
                }
                else{
                    $price = $seckill_goods['price'];
                    $goods['seckill_discount'] = round(($price / $goods['price']) * 10,2);
                }
                $goods['seckill_discount_text'] = "秒杀".$goods['seckill_discount']."折";
                $goods['seckill_activity'] = $seckill_activity;
                $goods['seckill_goods'] = $seckill_goods;
                $goods['seckill_downtime'] = intval($seckill_activity['endtime'] - time());
      	    }
      	    else{
      	        $price = \app\common\model\bbfxshop\Order::calculateVipGoodsPrice($this->user,$goods);
      	    }
      	    
  	        $goods['o_price1'] = $goods['price'];
      	    $price = round($price,2);
      	    if($price != $goods['price']){
  	            $goods['o_price'] = $goods['price'];
  	            $goods['price'] = $price;
  	        }
      	    
      	    $goods['thumb'] = cdnurl($goods['thumb']);
      	    $goods['share_img'] = cdnurl($goods['share_img']);
      	    $goods['authentic_icon'] = cdnurl($goods['authentic_icon']);
      	    
      	    if($goods['fastest_delivery'] > 0){
      	        $fastest_delivery = date("m月d日",strtotime("+{$goods['fastest_delivery']} day"));
      	    }
      	    else{
      	        if(date("H") >= 17){
      	            $fastest_delivery = date("m月d日",strtotime("+1 day"));
      	        }
      	        else{
      	            $fastest_delivery = date("m月d日");
      	        }
      	    }
      	    $delivery = "现在付款，最快{$fastest_delivery}发货";
      	    if($goods['arrive_day'] > 0){
                $arrive_day = $goods['arrive_day'] + $goods['fastest_delivery'];
                
      	        $arrive_day_text = date("m月d日",strtotime("+{$arrive_day} day"));
      	        $delivery .= "，{$arrive_day_text}送达";
      	    }
      	    $goods['delivery'] = $delivery;
      	    
      	    $goods['guarantee'] = iunserializer($goods['guarantee']);
      	    
      	    $slides = [];
      	    $videos_list = cdnurls(iunserializer($goods['videos']));
      	    if(!empty($videos_list)){
      	        foreach ($videos_list as $key => &$val){
  	                $slides[] = ['type'=>'video','url'=>$val];
  	            }
  	            unset($val);
      	    }
      	    $slides_list = cdnurls(iunserializer($goods['slides']));
      	    if(!empty($slides_list)){
  	            foreach ($slides_list as $key => &$val){
  	                $slides[] = ['type'=>'image','url'=>$val];
  	            }
  	            unset($val);
  	        }
      	    $goods['slides'] = $slides;
      	    $goods['images'] = $slides_list;
      	    $goods['videos'] = $videos_list;
      	    
      	    if($goods['type'] == 1){
                $stock = Db::name("bbfx_serial_number")->where(["uniacid"=>UNIACID,"goods_id"=>$goods_id,'status'=>0])->count();
      	        $goods['stock'] = intval($stock);
      	    }
            
            if($goods['sales_volume'] == 0){
        	    $sales_volume = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.order_source'=>['<>',6],'o.status'=>['>',0],'og.goods_id'=>$goods['id']])->sum("og.total");
        	    $goods['sales_volume'] = intval($sales_volume);
        	    
        	    if($goods['sales_volume'] > 0){
        	        Db::name("bbfx_goods")->where(['id'=>$goods['id']])->update(['sales_volume'=>$goods['sales_volume']]);
        	    }
        	}
            $goods['sales_volume'] = intval($goods['sales_volume'] + $goods['virtual_sale']);
            
            $comment_list = Db::name("bbfx_goods_comment")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where(['a.uniacid'=>UNIACID,'a.sh_status'=>1,'a.goods_id'=>$goods['id']])->order("a.createtime desc")->field("a.*,b.avatar,b.nickname")->limit(0,1)->select();
            if(!empty($comment_list)){
                foreach ($comment_list as $key => &$val){
                    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
                    $val['images'] = cdnurls(iunserializer($val['images']));
                    $val['avatar'] = cdnurl($val['avatar']);
                }
                unset($val); 
            }
            else{
                $comment_list = [];
            }
            $comment_total = Db::name("bbfx_goods_comment")->where(['uniacid'=>UNIACID,'sh_status'=>1,'goods_id'=>$goods['id']])->count();
            $goods['comment_list'] = $comment_list;
            $goods['comment_total'] = intval($comment_total);

            $collection = Db::name("bbfx_goods_collection")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id'],'goods_id'=>$goods['id']])->find();
            if(!empty($collection)){
                $goods['is_collection'] = 1;
            }
            else{
                $goods['is_collection'] = 0;
            }
            $page = "pages/goods/detail?id=".$goods['id'];
      	    $filename = $params['platform']."_goods_".$goods['id'];
      	    if(!empty($this->user)){
      	        $page .= "&sup_uid=".$this->user['id'];
      	        $filename = $params['platform']."_goods_".$goods['id']."_".$this->user['id'];
      	    }
      	    $goods['qrcode'] = "";
      	    if($params['platform'] == 'wxapp'){
                $result = \app\common\model\bbfxshop\Weixin::getUnlimitedQRCode($page,$filename,1);
                if($result['code'] == 1){
                    $goods['qrcode'] = cdnurl($result['data']['url'])."?t=".time();
                }
            }
            else{
                
                $result = \app\common\model\QRcode::create(request()->domain()."/mobile/#/".$page,$filename,1);
                if($result['code'] == 1){
                    $goods['qrcode'] = cdnurl($result['data']['url'])."?t=".time();
                }
            }
            $order_user = [];
            if($goods['order_user_scroll'] == 1){
                $order_user = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->join("bbfx_user u","o.user_id=u.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.is_pay'=>1,'og.goods_id'=>$goods['id']])->field("u.id,u.nickname,u.avatar")->group("u.id")->select();
                foreach($order_user as $key => &$val){
                    $val['avatar'] = cdnurl($val['avatar']);
                }
                unset($val);
            }
            

            if($goods['is_spec'] == 1 && $goods['is_setmeal'] == 1){
      	        $sku_list = Db::name("bbfx_goods_spec_sku")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->select();
      	        foreach ($sku_list as $key => &$val){
      	            $val['thumb'] = cdnurl($val['thumb']);
      	            $val['dish'] = iunserializer($val['dish']);
      	        }
      	        unset($val);
      	        $goods['sku_list'] = $sku_list;
      	    }

            $goods['pintuan_goods_qrcode'] = '';
            $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['uniacid'=>UNIACID,'status'=>1,'goods_id'=>$goods['id']])->find();
            if(!empty($pintuan_goods)){
                $page = "plugin/pintuan/list/list?id={$pintuan_goods['id']}";
                if(!empty($this->user)){
                    $page .= "&sup_uid=".$this->user['id'];
                }

                if($params['platform'] == 'wxapp' || $params['platform'] == 'WXAPP'){
                    $result = \app\common\model\bbfxshop\Weixin::getUnlimitedQRCode($page, "pintuan_wxacode_{$pintuan_goods['uniacid']}_".intval($this->user['id'])."_".$pintuan_goods['id']);
                }
                else{
                    $url = request()->domain()."/mobile/#/".$page;
                    $result = \app\common\model\QRcode::create($url, "pintuan_qrcode_{$pintuan_goods['uniacid']}_".intval($this->user['id'])."_".$pintuan_goods['id']);
                }
                if($result['code'] == 1){
                    $goods['pintuan_goods_qrcode'] = cdnurl($result['data']['url'].'?t='.time()); 
                }
            }

            $res = \app\common\model\bbfxshop\CumulativeFanhuan::jisuan(1,$goods,$this->user);
      	    $goods['fanhuan_score'] = $res['fanhuan_score'];
      	    $goods['fanhuan_balance'] = $res['fanhuan_balance'];
            
      	    unset($goods['plugin']);
      	    $result = array("goods"=>$goods,'order_user'=>$order_user,'share_status'=>0);
      	    
      	    $user = $this->user;
      	    
          	__success("操作成功",$result);
        }
      	else{
        	__error("未查询到数据或已被删除");
        }
    }
    
    public function getCategory(){
        $params = $this->param();
        
        $list = \app\common\model\bbfxshop\Goods::getCategoryList();
        if(!empty($list)){
            __success("操作成功",$list);
        }
        else{
            __error("未查询到分类");
        }
    }
    
    public function getCategoryInfo(){
        $category_id = $this->param('category_id/d');
        $cate = Db::name("bbfx_category")->where(['id'=>$category_id,'mid'=>0])->find();
        if($cate){
            __success("操作成功",$cate);
        }
        else{
            __error("未查询到分类");
        }
    }
}
