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

namespace app\api\controller\bargain;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\User;


class Goods extends Base
{
    protected $noNeedLogin = ['getList','detail'];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Bargain;
    }

    
    public function bargainGoodsPrice(){
        $id = $this->param('id/d');
        $result = $this->model->bargainGoodsPrice($id,$this->user['id']);
        __result($result);
    }

    public function getList(){
        $params = $this->param(['category_id/d','sort/d','keyword/s','page/d','platform/s']);
        $page = max(1, intval($params["page"]));
        $limit = 10;
        $where = ['a.uniacid'=>UNIACID,'a.status'=>1,'b.status'=>1];
        if($params['category_id'] > 0){
            // $goods_category = Db::name("bbfx_goods_category")->where(['uniacid'=>UNIACID,'category_id'=>$params['category_id']])->select();
            // if(empty($goods_category)) $goods_category = [];
            // $gids = array_column($goods_category,'goods_id');
            // if(empty($gids)) $gids = [];
            // $where['a.goods_id'] = ['in',$gids];
            $where['a.category_id'] = $params['category_id'];
        }

        $orderby = "a.zhiding desc,a.id desc";
        if($params['sort'] == 1){
            $orderby = "a.zhiding desc,b.sales_volume desc";
        }
        else if($params['sort'] == 2){
            $orderby = "a.zhiding desc,a.price desc";
        }
        if(!empty($params['keyword'])){
            $where['b.title'] = ['like','%'.$params['keyword'].'%'];
        }
        
        $list = Db::name("bbfx_bargain_goods")
            ->alias("a")->join("bbfx_goods b","a.goods_id = b.id","LEFT")
            ->where($where)->order($orderby)
            ->field("a.*,b.title,b.thumb,b.price as o_price,b.sales_volume")
            ->limit(($page - 1) * $limit,$limit)
            ->select();

        foreach($list as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
            $val['bargain_price'] = round($val['s_price'] - $val['price'],2);
            $val['bargain_count'] = Db::name("bbfx_bargain_goods_log")->where(['uniacid'=>UNIACID,'bargain_goods_id'=>$val['id'],'createtime'=>['>',$val['stime']]])->count();
            $val['is_bargain'] = 0;
            $log = Db::name("bbfx_bargain_goods_log")->where(['uniacid'=>UNIACID,'bargain_goods_id'=>$val['id'],'user_id'=>intval($this->user['id']),'createtime'=>['>',$val['stime']]])->where(['createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->count();
            if(!empty($log)){
                $val['is_bargain'] = 1;
            }
            $val['check_num'] = $val['virtual_check_num'] + $val['check_num'];

            $page = "plugin/bargain/detail?bargain_id=".$val['id'];
            $filename = "bargain_goods_".$val['id'];
            if(!empty($this->user)){
                $page .= "&sup_uid=".$this->user['id'];
                $filename = $params['platform']."_bargain_goods_".$val['id']."_".$this->user['id'];
            }
            $val['bargain_goods_qrcode'] = ""; 
            if($params['platform'] == 'wxapp' || $params['platform'] == 'WXAPP'){
                $result = \app\common\model\bbfxshop\Weixin::getUnlimitedQRCode($page,$filename,1);
            }
            else{
                $result = \app\common\model\QRcode::create(request()->domain()."/mobile/#/".$page,$filename,1);
            }
            
            if($result['code'] == 1){
                $val['bargain_goods_qrcode'] = cdnurl($result['data']['url'])."?t=".time();
            }
        }
        unset($val);

        __success("操作成功",['list'=>$list]);
    }
    
    public function detail(){
        $params = $this->param();
        $id = $this->param('id/d');
        $bargain_goods = Db::name("bbfx_bargain_goods")->where(['uniacid'=>UNIACID,'id'=>$id,'status'=>1])->find();
        if(empty($bargain_goods)){
            __error("商品不存在");
        }
        $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$bargain_goods['goods_id'],'status'=>1])->find();
        if(empty($goods)){
            __error("商品不存在");
        }
        $bargain_goods['check_num'] = $bargain_goods['virtual_check_num'] + $bargain_goods['check_num'];
        $bargain_goods['use_desc'] = iunserializer($bargain_goods['use_desc']);
        $bargain_goods['bargain_price'] = round($bargain_goods['s_price'] - $bargain_goods['price'],2);
        $bargain_goods['bargain_count'] = Db::name("bbfx_bargain_goods_log")->where(['uniacid'=>UNIACID,'bargain_goods_id'=>$bargain_goods['id'],'createtime'=>['>',$bargain_goods['stime']]])->count();
        $bargain_goods['is_bargain'] = 0;
        $log = Db::name("bbfx_bargain_goods_log")->where(['uniacid'=>UNIACID,'bargain_goods_id'=>$bargain_goods['id'],'user_id'=>intval($this->user['id']),'createtime'=>['>',$bargain_goods['stime']]])->where(['createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))]])->count();
        if(!empty($log)){
            $bargain_goods['is_bargain'] = 1;
        }

        $downtime = $bargain_goods['stime'] + $bargain_goods['effective_day'] * 24 * 60 * 60 - time();
        
        $bargain_goods['downtime'] = max(0,$downtime);

        $goods_id = $goods['id'];
        $utk = $this->param("utk/s");

        \app\common\model\bbfxshop\Goods::browse($goods['id'],intval($this->user['id']),$utk);
        $result = \app\common\model\bbfxshop\Goods::visitor($goods['id'],intval($this->user['id']),$utk);
        if($result['code'] == 1){
            Db::name("bbfx_bargain_goods")->where(['uniacid'=>UNIACID,'id'=>$bargain_goods['id']])->setInc("check_num",1);
        }
        
        $goods['parameter'] = iunserializer($goods['parameter']);
        
        
        $goods['o_price'] = $goods['price'];
        $goods['price'] = $bargain_goods['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;
        }

        $page = "plugin/bargain/detail?bargain_id=".$bargain_goods['id'];
        $filename = "bargain_goods_".$bargain_goods['id'];
        if(!empty($this->user)){
            $page .= "&sup_uid=".$this->user['id'];
            $filename = $params['platform']."_bargain_goods_".$bargain_goods['id']."_".$this->user['id'];
        }
        $bargain_goods['bargain_goods_qrcode'] = ""; 
        if($params['platform'] == 'wxapp' || $params['platform'] == 'WXAPP'){
            $result = \app\common\model\bbfxshop\Weixin::getUnlimitedQRCode($page,$filename,1);
        }
        else{
            $result = \app\common\model\QRcode::create(request()->domain()."/mobile/#/".$page,$filename,1);
        }
        
        if($result['code'] == 1){
            $bargain_goods['bargain_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,'bargain_goods'=>$bargain_goods);
        
        __success("操作成功",$result);
    }
}