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

namespace app\api\controller\pintuan;

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

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

    public function index(){

        $pintuan_goods = Db::name("bbfx_pintuan_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id")
            ->where(['a.uniacid'=>UNIACID,'b.stock'=>['>',0],'b.status'=>1,'a.status'=>1])
            ->where(function($query){
                $query->whereOr(function($query){
                    $query->where(['a.is_sync_stock'=>1]);
                });
                $query->whereOr(function($query){
                    $query->where(['a.is_sync_stock'=>0,'a.stock'=>['>',0]]);
                });
            })
            ->field("a.*,b.title,b.subtitle,b.thumb,b.price as o_price,a.virtual_pintian")
            ->order('a.sort desc,a.id desc')->limit(0,3)->select();
        
        foreach ($pintuan_goods as $key => &$val){
            
        	$val['thumb'] = cdnurl($val['thumb']);
            
            $total = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_order b","a.order_id=b.id")->where(['b.uniacid'=>UNIACID,'b.is_pay'=>1,'a.pintuan_goods_id'=>$val['id']])->sum("a.total");
            
            $pintuan_num = Db::name('bbfx_pintuan_order')->where(['uniacid'=>UNIACID,'status'=>0,'pintuan_goods_id'=>$val['id']])->count();
            $pintuan_total = Db::name('bbfx_pintuan_order')->where(['uniacid'=>UNIACID,'status'=>['in',[0,1,2]],'pintuan_goods_id'=>$val['id']])->count();
            $val['pintuan_num_ok'] = intval($pintuan_num);
            $val['pintuan_total'] = intval($pintuan_total);
            $val['sales_volume'] = $val['virtual_pintian'] + intval($total);
        }
        unset($val);

        __success("操作成功",['pintuan_goods'=>$pintuan_goods]);
    }
    
    public function getList(){
        $params = $this->param(['limit/d']);

        $list = Db::name("bbfx_pintuan_goods")
            ->alias("a")->join("bbfx_goods b","a.goods_id=b.id")
            ->where(['a.uniacid'=>UNIACID,'b.stock'=>['>',0],'b.status'=>1,'a.status'=>1])
            ->where(function($query){
                $query->whereOr(function($query){
                    $query->where(['a.is_sync_stock'=>1]);
                });
                $query->whereOr(function($query){
                    $query->where(['a.is_sync_stock'=>0,'a.stock'=>['>',0]]);
                });
            })
            ->field("a.*,b.title,b.subtitle,b.thumb,b.price as o_price,a.virtual_pintian")
            ->order('a.sort desc,a.id desc')->select();
        
        foreach ($list as $key => &$val){
            
        	$val['thumb'] = cdnurl($val['thumb']);
            
            $total = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_order b","a.order_id=b.id")->where(['b.uniacid'=>UNIACID,'b.is_pay'=>1,'a.pintuan_goods_id'=>$val['id']])->sum("a.total");
            
            $pintuan_num = Db::name('bbfx_pintuan_order')->where(['uniacid'=>UNIACID,'status'=>0,'pintuan_goods_id'=>$val['id']])->count();
            $pintuan_total = Db::name('bbfx_pintuan_order')->where(['uniacid'=>UNIACID,'status'=>['in',[0,1,2]],'pintuan_goods_id'=>$val['id']])->count();
            $val['pintuan_num_ok'] = intval($pintuan_num);
            $val['pintuan_total'] = intval($pintuan_total);
            $val['sales_volume'] = $val['virtual_pintian'] + intval($total);
        }
        unset($val);
        
        __success("操作成功",$list);
    }
    
    public function check(){
        $params = $this->param(['id/d','pintuan_order_id/d']);
        $goods = Db::name('bbfx_pintuan_goods')->where(['id'=>$params['id']])->find();
        if(empty($goods)){
            __error("拼团活动已被删除");
        }
        // if($goods['status'] != 1 || ($goods['endtime'] > 0 && $goods['endtime'] < time())){
        if($goods['status'] != 1){
            __error("拼团活动已结束");
        }
        
        if($params['pintuan_order_id'] > 0){
            $pintuan_order = Db::name("bbfx_pintuan_order")->where(['id'=>$params['pintuan_order_id']])->find();
            if(empty($pintuan_order)){
                __error("参团活动存在");
            }
            if($pintuan_order['status'] != 0){
                __error("参团活动已结束");
            }
        }
        
        __success("操作成功");
    }
    
    public function detail(){
        $params = $this->param(['id/d','platform/s']);
        
        $goods = Db::name("bbfx_pintuan_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id")->where(['a.uniacid'=>UNIACID,'b.status'=>1,'a.id'=>$params['id']])->field("a.*,b.title,b.subtitle,b.thumb,b.is_spec,b.is_setmeal,b.is_hexiao,b.price as o_price,b.slides,b.videos,b.content,b.unit")->find();
        
        if(empty($goods)){
            __error("拼团商品不存在或已下架");
        }
        
        $plugin = iunserializer($goods['plugin']);
        if(empty($plugin['rebate_pintuan'])){
            $plugin['rebate_pintuan'] = ['status'=>0,'pintuan_success_num'=>'','pintuan_fail_num'=>'','pintuan_fail_reward'=>''];
            if(!empty($goods)){
                $plugin['rebate_pintuan']['pintuan_success_num'] = $goods['pintuan_num'];
            }
        }
        $goods['plugin'] = $plugin;
        
    	$goods['thumb'] = cdnurl($goods['thumb']);
    	$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['is_spec'] == 1 && $goods['is_setmeal'] == 1){
            $sku_list = Db::name("bbfx_goods_spec_sku")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['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;
        }
        
        $total = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_order b","a.order_id=b.id")->where(['b.uniacid'=>UNIACID,'b.is_pay'=>1,'a.pintuan_goods_id'=>$goods['id']])->sum("a.total");
        $pintuan_total = Db::name('bbfx_pintuan_order')->where(['uniacid'=>UNIACID,'status'=>['in',[0,1,2]],'pintuan_goods_id'=>$goods['id']])->count();
        $pintuan_num = Db::name('bbfx_pintuan_order')->where(['uniacid'=>UNIACID,'status'=>0,'pintuan_goods_id'=>$goods['id']])->count();
        $goods['pintuan_num_ok'] = intval($pintuan_num);
        $goods['pintuan_total'] = intval($pintuan_total);
        $goods['sales_volume'] = $goods['virtual_pintian'] + intval($total);

        $page = "plugin/pintuan/list/list?id={$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_{$goods['uniacid']}_".intval($this->user['id'])."_".$goods['id']);
        }
        else{
            $url = request()->domain()."/mobile/#/".$page;
            $result = \app\common\model\QRcode::create($url, "pintuan_qrcode_{$goods['uniacid']}_".intval($this->user['id'])."_".$goods['id']);
        }
        $goods['pintuan_goods_qrcode'] = '';
        if($result['code'] == 1){
            $goods['pintuan_goods_qrcode'] = cdnurl($result['data']['url'].'?t='.time()); 
        }

        $pintuan_list1 = Db::name("bbfx_pintuan_order")->where(['uniacid'=>UNIACID,'pintuan_goods_id'=>$goods['id'],'status'=>0,'starttime'=>['<',time()],'endtime'=>['>',time()]])->order("id desc")->select();
        $pintuan_list2 = Db::name("bbfx_pintuan_order")->where(['uniacid'=>UNIACID,'pintuan_goods_id'=>$goods['id'],'status'=>0,'starttime'=>['<',time()],'endtime'=>0])->order("id desc")->select();
        $pintuan_list = [];
        if(empty($pintuan_list1)) $pintuan_list1 = [];
        $pintuan_list = array_merge($pintuan_list,$pintuan_list1);

        if(empty($pintuan_list2)) $pintuan_list2 = [];
        $pintuan_list = array_merge($pintuan_list,$pintuan_list2);
        
        foreach ($pintuan_list as $key => &$val){
            $user_list = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where(['a.uniacid'=>UNIACID,'a.is_pay'=>1,'a.pintuan_order_id'=>$val['id']])->field("a.id,a.user_id,b.nickname,b.avatar")->order("a.id asc")->select();
            
            foreach ($user_list as $k => &$v){
                $v['avatar'] = cdnurl($v['avatar']);
            }
            unset($v);
            $user_list[0]['is_tuanzhang'] = 1;
            $val['user_list'] = $user_list;
            $val['pintuan_num_ok'] = count($user_list);
            $val['progress'] = intval(($val['pintuan_num_ok'] / $goods['pintuan_num']) * 100);
            $downtime = 0;
            if($val['endtime'] > 0){
                $downtime = $val['endtime'] - time();
            }
            if($downtime < 0){
                $downtime = 0;
            }
            $val['downtime'] = $downtime;
        }
        unset($val);
        
        $createtimes = array_column($pintuan_list,'pintuan_num_ok');
        array_multisort($createtimes,SORT_DESC,$pintuan_list);
        
        // $pintuan_order = Db::name("bbfx_pintuan_order")->where(['uniacid'=>UNIACID,'pintuan_goods_id'=>$goods['id'],'user_id'=>$this->user['id'],'status'=>0])->order("id desc")->find();
        $pintuan_order = Db::name("bbfx_pintuan_order")->alias("a")->join("bbfx_order b","a.id = b.pintuan_order_id","LEFT")->where(['a.uniacid'=>UNIACID,'a.pintuan_goods_id'=>$goods['id'],'b.user_id'=>$this->user['id'],'a.status'=>0,'b.is_pay'=>1])->field("a.*")->order("a.id desc")->find();
        
        $pintuan_user_list = Db::name("bbfx_order")->alias("a")->join("bbfx_pintuan_order b","a.pintuan_order_id=b.id","LEFT")->join("bbfx_user c","c.id=a.user_id","LEFT")->where(['a.uniacid'=>UNIACID,'b.pintuan_goods_id'=>$goods['id'],'a.status'=>['>',0],'a.refund_status'=>['in',[-1,2]]])->field("a.user_id,c.avatar,c.nickname,b.id,a.createtime")->order("a.id desc")->group("a.user_id")->select();
        
        foreach ($pintuan_user_list as $key => &$val){
            $order_num = Db::name("bbfx_order")->alias("a")->join("bbfx_pintuan_order b","a.pintuan_order_id=b.id","LEFT")->where(['a.uniacid'=>UNIACID,'a.user_id'=>$val['user_id'],'a.status'=>['>',0],'b.pintuan_goods_id'=>$goods['id']])->count();
            $val['createtime'] = date('m-d H:i:s',$val['createtime']);
            $val['share_num'] = 0;
            $val['order_num'] = $order_num;
            $val['avatar'] = cdnurl($val['avatar']);
        }
        unset($val);
        
        $result = ['goods'=>$goods,'pintuan_list'=>$pintuan_list,'pintuan_user_list'=>$pintuan_user_list];
        if(!empty($pintuan_order)){
            $pintuan_order['pintuan_residue'] = $goods['pintuan_num'] - Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'refund_status'=>-1,'pintuan_order_id'=>$pintuan_order['id']])->count();
            $result['pintuan_order'] = $pintuan_order;
        }
        
        __success("操作成功",$result);
    }
    
    
}