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

namespace app\admin\controller\bbfxshop\pintuan;

use app\admin\controller\bbfxshop\Base;
use think\Db;


class Goods extends Base
{

    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Pintuan;
    }
    
    public function getList(){
        $params = $this->param();
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = ["a.uniacid"=>UNIACID];
        
        $keyword = trim($params['keyword']);
        $type = intval($params['type']);
        
        
    	$list = Db::name("bbfx_pintuan_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id")->where($where)->where(function($query) use($keyword){
    	    if(!empty($keyword)){
    	        $whereOr = [];
    	        $whereOr['b.title'] = ['like',"%".$keyword."%"];
    	        
    	        $query->whereOr($whereOr);
    	    }
    	})->field("a.*,b.title,b.thumb,b.stock as goods_stock")->order('a.sort desc,a.id desc')->limit(($pindex - 1) * $psize,$psize)->select();
      	foreach($list as $key => &$val){
      	    
        	$val['thumb'] = cdnurl($val['thumb']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
        	
            $categorys = Db::name("bbfx_goods_category")->alias("a")->join("bbfx_category b","a.category_id=b.id")->where(['a.uniacid'=>UNIACID,'a.goods_id'=>$val['goods_id']])->field('b.id,b.title')->order('b.sort desc')->select();
        	
        	$val['categorys'] = $categorys;
        	
        	$typeText = "";
        	if($val['type'] == 1){
        	    $typeText = "卡密商品";
        	}
        	else if($val['type'] == 2){
        	    $typeText = "实体商品";
        	}
        	else if($val['type'] == 3){
        	    $typeText = "核销商品";
        	}
        	else if($val['type'] == 4){
        	    $typeText = "虚拟商品";
        	}
        	
        	$val['typeText'] = $typeText;

            $val['merchant_name'] = Db::name("bbfx_merchant")->where(['uniacid'=>UNIACID,'id'=>$val['mid']])->value("name");
            if(empty($val['merchant_name'])) $val['merchant_name'] = '';
            
        }
        unset($val);
    	$total = Db::name("bbfx_pintuan_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id")->where($where)->where(function($query) use($keyword){
    	    if(!empty($keyword)){
    	        $whereOr = [];
    	        $whereOr['b.title'] = ['like',"%".$keyword."%"];
    	        
    	        $query->whereOr($whereOr);
    	    }
    	})->count();
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function detail(){
        $params = $this->param();
        
        $id = intval($params['id']);
        $goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$id])->find();
        $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'];
                $plugin['rebate_pintuan']['pintuan_fail_num'] = 0;
            }
        }
        if(empty($plugin['pintuan_miandan'])){
            $plugin['pintuan_miandan'] = ['status'=>0,'pintuan_success_num'=>'','pintuan_fail_num'=>''];
            if(!empty($goods)){
                $plugin['pintuan_miandan']['pintuan_success_num'] = 0;
                $plugin['pintuan_miandan']['pintuan_fail_num'] = $goods['pintuan_num'];
            }
        }
        $plugin['rebate_pintuan']['status'] = intval($plugin['rebate_pintuan']['status']);
        $plugin['pintuan_miandan']['status'] = intval($plugin['pintuan_miandan']['status']);
        if(!empty($goods)){
            $goods['goods_id'] = (string)$goods['goods_id'];
            $goods['plugin'] = $plugin;
            
            __success("操作成功",$goods);
        }
        else{
            __error("拼团商品不存在",['plugin'=>$plugin]);
        }
    }
    
    public function post(){
        $params = $this->param();
        
        $id = intval($params['id']);
        $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$id])->find();
        $price = round($params['price'],2);
        $kaituan_price = round($params['kaituan_price'],2);
        $pintuan_num = intval($params['pintuan_num']);
      	if(empty($params['goods_id'])){
        	__error("请选择商品");
        }
        
        $goods = Db::name("bbfx_goods")->where(['id'=>$params['goods_id']])->find();
        
        if(empty($goods)){
            __error("绑定商品信息错误");
        }
        
        if($price <= 0){
        	__error("请输入拼团价格");
        }
        if($pintuan_num <= 1){
        	__error("请输入成团人数");
        }
        
        if(intval($params['is_limitedtime']) == 1 && intval($params['yx_day']) <= 0){
            __error("请输入有效天数");
        }
        if($price <= 0){
            __error("拼团价格必须大于0");
        }
        if($price > $goods['price']){
            __error("拼团价格不能大于商品售价");
        }
        if($params['is_tuanzhangyh'] == 1 && $kaituan_price <= 0){
            __error("开团价格必须大于0");
        }
        if($params['is_tuanzhangyh'] == 1 && $kaituan_price > $price){
            // __error("开团价格必须小于等于拼团价格");
        }
        
        

        $plugin = $params['plugin'];
        $rebate_pintuan = $plugin['rebate_pintuan'];
        $pintuan_miandan = $plugin['pintuan_miandan'];
        $base = \app\common\model\bbfxshop\Common::getConfig(true);
        // 返利拼团
        if($base['rebate_pintuan']['status'] == 1 && $rebate_pintuan['status'] == 1){
            $pintuan_success_num = intval($rebate_pintuan['pintuan_success_num']);
            $pintuan_fail_num = intval($rebate_pintuan['pintuan_fail_num']);
            if($pintuan_success_num <= 0 && $pintuan_fail_num <= 0){
                $pintuan_success_num = $pintuan_num;
                $pintuan_fail_num = 0;
            }
            else{
                $pintuan_fail_num = $pintuan_num - $pintuan_success_num;
            }
            if($pintuan_success_num > $pintuan_num){
                __error("返利拼团拼中人数不得大于成团人数");
            }
            $plugin['rebate_pintuan']['pintuan_success_num'] = $pintuan_success_num;
            $plugin['rebate_pintuan']['pintuan_fail_num'] = $pintuan_fail_num;
        }

        // 拼团免单
        if($base['pintuan_miandan']['status'] == 1 && $pintuan_miandan['status'] == 1){
            $pintuan_success_num = intval($pintuan_miandan['pintuan_success_num']);
            $pintuan_fail_num = intval($pintuan_miandan['pintuan_fail_num']);
            if($pintuan_success_num <= 0 && $pintuan_fail_num <= 0){
                $pintuan_success_num = 0;
                $pintuan_fail_num = $pintuan_num;
            }
            else{
                $pintuan_fail_num = $pintuan_num - $pintuan_success_num;
            }
            if($pintuan_success_num > $pintuan_num){
                __error("拼团免单拼中人数不得大于成团人数");
            }
            $plugin['pintuan_miandan']['pintuan_success_num'] = $pintuan_success_num;
            $plugin['pintuan_miandan']['pintuan_fail_num'] = $pintuan_fail_num;
        }

        if($base['rebate_pintuan']['status'] == 1 && $rebate_pintuan['status'] == 1 && $base['pintuan_miandan']['status'] == 1 && $pintuan_miandan['status'] == 1){
            __error("拼团免单与返利拼团逻辑冲突不能同时开启");
        }
        
    	$data = array(
        	"uniacid"=>UNIACID,
          	"price"=>$price,
          	"pintuan_num"=>$pintuan_num,
          	"auto_pintuan_success"=>intval($params['auto_pintuan_success']),
          	"buy"=>intval($params['buy']),
          	"stock"=>intval($params['stock']),
          	"is_sync_stock"=>intval($params['is_sync_stock']),
          	"is_limitedtime"=>intval($params['is_limitedtime']),
          	"yx_day"=>intval($params['yx_day']),
          	"is_tuanzhangyh"=>intval($params['is_tuanzhangyh']),
          	"kaituan_price"=>$kaituan_price,
          	"virtual_pintian"=>intval($params['virtual_pintian']),
          	"plugin"=>iserializer($params['plugin']),
          	"sort"=>intval($params['sort']),
        );
        
        
        
        $sku_list = $params['sku_list'];
        if($goods['is_spec'] == 1){
            if(empty($sku_list)){
                __error("商品规格数据错误");
            }
            foreach($sku_list as $key => $val){
                $pintuan_price = round($val['pintuan_price'],2);
                $kaituan_price = round($val['kaituan_price'],2);
                if($pintuan_price <= 0){
                    __error("规格拼团价格必须大于0");
                }
                if($pintuan_price > $val['price']){
                    __error("规格拼团价格不能大于商品规格售价");
                }
                if($data['is_tuanzhangyh'] == 1 && $kaituan_price <= 0){
                    __error("规格开团价格必须大于0");
                }
                if($data['is_tuanzhangyh'] == 1 && $kaituan_price > $pintuan_price){
                    __error("规格开团价格必须小于等于规格拼团价格");
                }
            }
        }
        
        
        
        if($data['is_sync_stock'] != 1){
            if($goods['stock'] <= 0){
                __error("该商品无库存，请重新选择商品");
            }
            if($data['stock'] > $goods['stock']){
                __error("活动库存不得大于商品库存");
            }
        }
        
      	if(!empty($pintuan_goods)){
      	    
      	    if($pintuan_goods['goods_id'] != $params['goods_id']){
      	        __error("不可重新绑定商城商品");
      	    }
      	    
      	    if($params['is_limitedtime'] == 1 && $pintuan_goods['yx_day'] != intval($params['yx_day'])){
                // $data['endtime'] = time() + intval($params['yx_day']) * 24 * 60 * 60;
            }
            $res = Db::name("bbfx_pintuan_goods")->where(["id"=>$pintuan_goods['id']])->update($data);
            $id = $pintuan_goods['id'];
        }
      	else{
            $data['mid'] = $goods['mid'];
      	    $data['goods_id'] = $params['goods_id'];
          	$data['createtime'] = time();
          	if($params['is_limitedtime'] == 1){
                // $data['endtime'] = time() + intval($params['yx_day']) * 24 * 60 * 60;
            }
            $res = Db::name("bbfx_pintuan_goods")->insertGetId($data);
            $id = $res;
        }
        
        if($id > 0){
            if($goods['is_spec'] == 1){
                foreach($sku_list as $key => $val){
                    Db::name("bbfx_goods_spec_sku")->where(['id'=>$val['id']])->update(['pintuan_price'=>$val['pintuan_price'],'kaituan_price'=>$val['kaituan_price']]);
                }
            }
            
        }
        
        if($res){
            $data['id'] = $id;
            \app\admin\model\AdminLog::record("","",$data,"bbfx_pintuan_goods");
            __success("编辑成功");
        }
        else{
            __success("操作成功");
        }
        
    }
    
    public function status(){
        $id = $this->param("id/d");
        $status = $this->param("status/d");
        if($status != 1){
            $status = 0;    
        }
        
        $res = Db::name("bbfx_pintuan_goods")->where(['id'=>$id])->update(['status'=>$status]);
        if($res){
            $data = ['id'=>$id,'status'=>$status];
            \app\admin\model\AdminLog::record("","",$data,"bbfx_pintuan_goods");
            __success("操作成功");
        }
        else{
            __error("操作失败");
        }
    }
    
    public function delete(){
        $this->commonDelete("bbfx_pintuan_goods");
    }
}