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

namespace app\admin\controller\bbfxshop\scoreshop;

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\Scoreshop;
    }

    public function list(){
        $params = $this->param();
        
        $this->model->resetStock(UNIACID);
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = ["uniacid"=>UNIACID];
        
        $keyword = trim($params['keyword']);
        $category_id = intval($params['category_id']);
        $status = intval($params['status']);
        if($keyword){
            $where['title'] = ['like','&'.$keyword.'&'];
        }
        
        if($category_id > 0){
            $goods_category = Db::name("bbfx_scoreshop_goods_category")->where(["category_id"=>$category_id])->select();
            $goods_ids = array_column($goods_category,"goods_id");
            if(empty($goods_ids)){
                $goods_ids = [-1];
            }
            $where['id'] = ['in',$goods_ids];
        }
        
        if(!empty($status)){
            if($status != 2) $status = 0;
            $where['status'] = $status;
        }
        
    	$list = Db::name("bbfx_scoreshop_goods")->where($where)->order('id desc')->limit(($pindex - 1) * $psize,$psize)->select();
    	
      	foreach($list as $key => &$val){
      	    $slides = iunserializer($val['slides']);
      	    foreach ($slides as $k => &$v){
      	        $v = cdnurl($v);
      	    }
      	    unset($v);
      	    $val['slides'] =$slides;
        	$val['thumb'] = cdnurl($val['thumb']);
        	$val['share_img'] = cdnurl($val['share_img']);
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
        	
        	$categorys = Db::name("bbfx_scoreshop_goods_category")->alias("a")->join("bbfx_scoreshop_category b","a.category_id=b.id")->where(['a.uniacid'=>UNIACID,'a.goods_id'=>$val['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;
        	
        	$sales_volume = Db::name("bbfx_scoreshop_order_goods")->alias("og")->join("bbfx_scoreshop_order o","o.id=og.order_id")->where(['o.uniacid'=>UNIACID,'og.goods_id'=>$val['id'],'o.status'=>['in',[1,2,3]]])->field([])->count();
        	$sales_volume = intval($sales_volume);
        	
        	$val['sales_volume'] = intval($val['sales_volume'] + $sales_volume);
        	
        }
        unset($val);
        
    	$total = Db::name("bbfx_scoreshop_goods")->where($where)->count();
    	
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function status(){
        $params = $this->param();
        
        $id = intval($params['id']);
        $status = intval($params['status']);
        $res = Db::name("bbfx_scoreshop_goods")->where(["id"=>$id])->update(["status"=>$status]);
        if($res){
            \app\admin\model\AdminLog::record("","",['id'=>$id,"status"=>$status],'bbfx_scoreshop_goods');
            __success("操作成功");
        }
        else{
            __success("操作成功");
        }
    }
    
    public function search(){
        $params = $this->param();
        
        $goodsids = trim($params['goodsids']);
        $goodsids = explode(",",$goodsids);
        $list = Db::name("bbfx_scoreshop_goods")->where(['uniacid'=>UNIACID,'id'=>['in',$goodsids]])->field(['id','title','thumb'])->select();
        $cate = Db::name("bbfx_scoreshop_category")->where(["uniacid"=>UNIACID,"status"=>1])->order('sort desc')->select();
        foreach ($list as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
            if($cate && $cate[$val['category_id']]){
        	    $val['cate_title'] = $cate[$val['category_id']]['title'];
        	}
        	else{
        	    $val['cate_title'] = "";
        	}
        }
        unset($val);
        
        if(empty($list)){
            __error("未查询到数据");
        }
        else{
            __success("操作成功",$list);
        }
    }
    
    public function detail(){
        $params = $this->param();
        
        $id = intval($params['id']);
        $goods = Db::name("bbfx_scoreshop_goods")->where(['id'=>$id])->find();
        
        $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels();
        
        
        $result = ['levels'=>$levels];
        if(!empty($goods)){
             
            $slides = iunserializer($goods['slides']);
            foreach ($slides as $key => &$val){
                $val = cdnurl($val);
            }
            unset($val);
            $videos = iunserializer($goods['videos']);
            foreach ($videos as $key => &$val){
                $val = cdnurl($val);
            }
            unset($val);
            
            $goods['levels'] = iunserializer($goods['levels']);
            foreach ($goods['levels'] as $k => &$v){
                $v = intval($v);
            }
            unset($v);
            $goods['slides'] = $slides;
            $goods['videos'] = $videos;
            $goods['thumb'] = cdnurl($goods['thumb']);
            $goods['share_img'] = cdnurl($goods['share_img']);
            $goods['attr'] = [];
            if($goods['is_recommend'] == 1){
                $goods['attr'][] = 1;
            }
            if($goods['is_new'] == 1){
                $goods['attr'][] = 2;
            }
            if($goods['is_hot'] == 1){
                $goods['attr'][] = 3;
            }
            if($goods['is_nodiscount'] == 1){
                $goods['attr'][] = 4;
            }
            
            $category_ids = [];
            $categorys = Db::name("bbfx_scoreshop_goods_category")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->select();
            $category_ids = array_column($categorys, 'category_id');
            
            $goods['category_ids'] = $category_ids;
            
            $hexiao_store_ids = [];
            $store_goods = Db::name("bbfx_scoreshop_store_goods")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->select();
            if(!empty($store_goods)){
                $hexiao_store_ids = array_column($store_goods, 'store_id');
            }
            $goods['hexiao_store_ids'] = $hexiao_store_ids;
            $plugin = iunserializer($goods['plugin']);
            
        }
        else{
            $plugin = [];
        }

        if(is_null($plugin['fenxiao'])){
            $plugin['fenxiao'] = ['rule'=>0,'commission1'=>['level'=>['money1'=>'','money2'=>''],'grade'=>[],'grade_rate'=>[]]];
        }

        $grade1 = [];
        $grade1_rate = [];
        foreach ($levels as $key => $val){
            $grade1['level'.$val['id']] = round($plugin['fenxiao']['commission1']['grade']['level'.$val['id']],2);
            $grade1_rate['level'.$val['id']] = round($plugin['fenxiao']['commission1']['grade_rate']['level'.$val['id']],2);
        }

        $plugin['fenxiao']['commission1']['grade'] = $grade1;
        $plugin['fenxiao']['commission1']['grade_rate'] = $grade1_rate;

        $result['plugin'] = $plugin;
        if(!empty($goods)){
            $goods['plugin'] = $plugin;
            $result['goods'] = $goods;
        }
        
        __success("操作成功",$result);
    }
    
    public function post(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        $goods = Db::name("bbfx_scoreshop_goods")->where(['id'=>$id])->find();
        
        $msg = "";
      	$sort = intval($params['sort']);
        $score = floatval($params['score']);
      	if(empty($params['title'])){
        	$msg = "请填写商品名称";
        }
      	if(empty($params['thumb'])){
        	$msg = "请上传商品图片";
        }
      	if($score <= 0){
        	$msg = "请填写商品兑换积分";
        }
      
      	if($msg){
        	__error($msg);
        }
        
        $price = floatval($params['price']);
        $o_price = floatval($params['o_price']);
        // $content = htmlspecialchars_decode($params['content']); 
        $content = htmlspecialchars_decode($this->param("content/h")); 
        $type = max(1,intval($params['type']));
        if(!empty($goods)){
            $type = $goods['type'];
        }
    	$data = array(
        	"uniacid"=>UNIACID,
          	"title"=>$params['title'],
          	"thumb"=>$params['thumb'],
          	"score"=>$score,
          	"price"=>$price,
          	"o_price"=>$o_price,
          	"express_fee"=>floatval($params['express_fee']),
          	"minbuy"=>max(1,intval($params['minbuy'])),
          	"maxbuy"=>intval($params['maxbuy']),
          	"daily_buy"=>intval($params['daily_buy']),
          	"monthly_buy"=>intval($params['monthly_buy']),
          	"total_maxbuy"=>intval($params['total_maxbuy']), 
          	"shippingfee_template_id"=>intval($params['shippingfee_template_id']), 
          	"weight"=>round($params['weight'],2), 
          	"volume"=>round($params['volume'],2), 
          	"levels"=>iserializer($params['levels']),
          	"status"=>$params['status'],
          	"fahuo_content"=>$params['fahuo_content'],
          	"content"=>$content,
          	"sort"=>$sort,
          	"is_recommend"=>0,
          	"is_new"=>0,
          	"is_hot"=>0,
          	"stock"=>intval($params['stock']),
          	"is_fenxiao"=>intval($params['is_fenxiao']),
          	"plugin"=>iserializer($params['plugin']),
          	"delivery_method"=>intval($params['delivery_method']),
        );
        
        
        if($type == 2 && ($params['delivery_method'] == 2 || $params['delivery_method'] == 3) || ($type == 4 && intval($params['is_hexiao']) == 1)){
            $data['is_hexiao'] = 1;
            $data['hexiao_num'] = max(1,intval($params['hexiao_num']));
            $data['hexiao_store_type'] = intval($params['hexiao_store_type']);
            if($params['hexiao_store_type'] == 1 && empty($params['hexiao_store_ids'])){
                __error("请选择核销门店");
            }
            
        }
        else{
            $data['is_hexiao'] = 0;
        }
        
        
        $attr = $params['attr'];
        if(in_array(1,$attr)){
            $data['is_recommend'] = 1;
        }
        if(in_array(2,$attr)){
            $data['is_new'] = 1;
        }
        if(in_array(3,$attr)){
            $data['is_hot'] = 1;
        }
        if(in_array(4,$attr)){
            $data['is_nodiscount'] = 1;
        }
        
        
        
        $data['share_title'] = $params['share_title'];
        $data['share_img'] = $params['share_img'];
        
        $slides = $params['slides'];
        
        foreach ($slides as $key => &$val){
            $val = replaceSiteroot($val);
        }
        unset($val);
        
        $videos = $params['videos'];
        foreach ($videos as $key => &$val){
            $val = replaceSiteroot($val);
        }
        unset($val);
        
        $data["slides"] = iserializer($slides);
        $data["videos"] = iserializer($videos);
        $data['share_img'] = replaceSiteroot($data['share_img']);
        $data['thumb'] = replaceSiteroot($data['thumb']);
        
      	if(!empty($goods)){
          	$res = Db::name("bbfx_scoreshop_goods")->where(["id"=>$goods['id']])->update($data);
        }
      	else{
      	    
      	    $data['type'] = $type;
          	$data['createtime'] = time();
          	
        	$id = Db::name("bbfx_scoreshop_goods")->insertGetId($data);
            $res = $id;
        }
        
        if($id){
            $category_ids = $params['category_ids'];
            $categorys = Db::name("bbfx_scoreshop_goods_category")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->select();
            $categorys = array_skey($categorys,'category_id');
            $c_ids = [];
            if(!empty($category_ids)){
                foreach ($category_ids as $key => $val){
                    $c_ids[$val] = true;
                    if(empty($categorys[$val])){
                        Db::name("bbfx_scoreshop_goods_category")->insert(['uniacid'=>UNIACID,'goods_id'=>$id,'category_id'=>$val]);
                    }
                }
            }
            
            foreach ($categorys as $key => $val){
                if(empty($c_ids[$val['category_id']])){
                    Db::name("bbfx_scoreshop_goods_category")->where(['id'=>$val['id']])->delete();
                }
            }
            
            if($data['is_hexiao'] == 1){
                $hexiao_store_ids = $params['hexiao_store_ids'];
                $store_goods = Db::name("bbfx_scoreshop_store_goods")->where(['uniacid'=>UNIACID,'goods_id'=>$goods['id']])->select();
                $store_goods = array_skey($store_goods,'store_id');
                $s_ids = [];
                if(!empty($hexiao_store_ids)){
                    foreach ($hexiao_store_ids as $key => $val){
                        $s_ids[$val] = true;
                        if(empty($store_goods[$val])){
                            Db::name("bbfx_scoreshop_store_goods")->insert(['uniacid'=>UNIACID,'goods_id'=>$id,'store_id'=>$val]);
                        }
                    }
                }
                foreach ($store_goods as $key => $val){
                    if(empty($s_ids[$val['store_id']])){
                        Db::name("bbfx_scoreshop_store_goods")->where(['id'=>$val['id']])->delete();
                    }
                }
                
            }
            
            if($type == 1){
                $goods_stock = Db::name("bbfx_scoreshop_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$id,'status'=>0])->count();
                $goods_stock = intval($goods_stock);
                Db::name("bbfx_scoreshop_goods")->where(['id'=>$id])->update(['stock'=>$goods_stock]);
            }
            
            $data['id'] = $id;
            \app\admin\model\AdminLog::record("","",$data,'bbfx_scoreshop_goods');
        }
      	__success("编辑成功");
        
    }
    
    public function sel_list(){
        $params = $this->param();
        
        
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = ["uniacid"=>UNIACID,'status'=>1];
        $keyword = trim($params['keyword']);
        $category_id = intval($params['category_id']);
        if($keyword){
            $where['title'] = ['like',"%".$keyword."%"];
        }
        
        if($category_id){
            $goods_category = Db::name("bbfx_scoreshop_goods_category")->where("category_id",$category_id)->select();
            $goods_ids = array_column($goods_category,"goods_id");
            $where['id'] = ['in',$goods_ids];
        }
        
        $list = Db::name("bbfx_scoreshop_goods")->where([])->field('id,title,thumb')->order('sort desc')->limit(($pindex - 1) * $psize,$psize)->select();
      	foreach($list as $key => $val){
        	$list[$key]['thumb'] = cdnurl($val['thumb']);
        }
    	$total = Db::name("bbfx_scoreshop_goods")->where($where)->count();
      	
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function serialnumberList(){
        $params = $this->param();
        
        $goods_id = intval($params['goods_id']);
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
    
        $list = Db::name("bbfx_scoreshop_serial_number")->alias("a")->join("bbfx_scoreshop_goods b","a.goods_id=b.id")->where(["b.uniacid"=>UNIACID,"a.goods_id"=>$goods_id])->field('a.*,b.title')->order('a.id desc')->limit(($pindex - 1) * $psize,$psize)->select();
        
        $total = Db::name("bbfx_scoreshop_serial_number")->where(["uniacid"=>UNIACID,"goods_id"=>$goods_id])->count();
        
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function serialnumberPost(){
        $params = $this->param();
        
        $goods_id = intval($params['goods_id']);
        $serial_number = trim($params['serial_number']);
        
        $serial_number = explode(",",$serial_number);
        $data = array("uniacid"=>UNIACID,"goods_id"=>$goods_id);
        foreach ($serial_number as $key => $val){
            if(!empty(trim($val))){
                $data['val'] = $val;
                Db::name("bbfx_scoreshop_serial_number")->insert($data);
            }
        }
        $data = ["goods_id"=>$goods_id,'val'=>implode(",",$serial_number)];
        
        $goods_stock = Db::name("bbfx_scoreshop_serial_number")->where(['uniacid'=>UNIACID,'goods_id'=>$goods_id,'status'=>0])->count();
        $goods_stock = intval($goods_stock);
        Db::name("bbfx_scoreshop_goods")->where(['id'=>$goods_id])->update(['stock'=>$goods_stock]);
        
        
        \app\admin\model\AdminLog::record("商品管理-商品列表-添加卡密","卡密：".$data['val'],$data);
        __success("添加成功");
    }
    
    public function delete(){
        $this->commonDelete("bbfx_scoreshop_goods");
    }
    
    
    public function serialnumberDel(){
        $this->commonDelete("bbfx_scoreshop_serial_number");
    }
}