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

namespace app\admin\controller\bbfxshop\goods;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use app\common\model\bbfxshop\FenxiaoLevel;
use app\common\model\bbfxshop\Goods as GoodsModel;
use app\common\model\QRcode;
use app\common\model\bbfxshop\Weixin;

class Goods extends Base
{
    protected $goods_type = 0;

    public function _initialize(){
        parent::_initialize();
    }

    public function copy(){
        $id = $this->param("id/d");
        $result = GoodsModel::copy($id);
        __result($result);
    }
    
    public function getStockLog(){
        $params = $this->param();
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        $goods_id = $this->param("goods_id/d");
        $export = intval($params['export']);
        $where = ['uniacid'=>UNIACID,'goods_id'=>$goods_id];
        if($export == 1){
            $psize = 999999;
        }
        $list = Db::name("bbfx_goods_stock_log")->where($where)->order("createtime desc")->limit(($pindex-1)*$psize,$psize)->select();
        
        foreach ($list as $key => &$val){
            $info = iunserializer($val['info']);
            $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            if(!empty($info['remarks'])){
                $val['remarks'] .= "-".$info['remarks'];
            }
            
            if($export == 1){
    	        $export_list[] = array(
    	            $val['id'],
    	            $val['title'],
    	            $val['stock'],
    	            $val['before'],
    	            $val['after'],
    	            $val['remarks'],
    	            $val['createtime']
    	        );
    	    }
        }
        unset($val);
        
        if($export == 1){
    	    $headArr = ["ID","商品名称","变动库存","变动前","变动后","备注","操作时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("stock-".date("Y-m-d"),$headArr,$export_list);
    	}
        
        $total = Db::name("bbfx_goods_stock_log")->where($where)->count();
        
        __success("操作成功",['list'=>$list,'total'=>$total]);
    }
    
    public function setStock(){
        $goods_id = $this->param("goods_id/d");
        $sku_id = $this->param("sku_id/d");
        $type = $this->param("type/d");
        $remarks = $this->param("remarks/s");
        $stock = max(0,$this->param("stock/d"));
        
        if($stock <= 0){
            __error("请输入变动库存");
        }
        if($type != 1){
            $stock = 0 - $stock;
        }
        
        $result = GoodsModel::setStock($goods_id,$sku_id,$stock,$this->auth->id,0,0,"管理员操作",['remarks'=>$remarks]);
        if($result['code'] == 1){
            $data = ['id'=>$goods_id,'stock'=>$result['data']['after']];
            \app\admin\model\AdminLog::record("","",$data,"bbfx_goods");
        }
        
        __result($result);
    }
    
    public function getSkuList(){
        $goods_id = $this->param("goods_id/d");
        
        $list = Db::name("bbfx_goods_spec_sku")->where(['goods_id'=>$goods_id])->select();
        
        __success("操作成功",['list'=>$list]);
    }
    
    public function list(){
        
        $params = $this->param();
        $params['goods_type'] = $this->goods_type;
        $result = GoodsModel::getList($params);
        
        __result($result);
    }

    public function getList(){
        
        $params = $this->param();
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = ["uniacid"=>UNIACID,'status'=>1,'sh_status'=>1];
        $export = intval($params['export']);
        $keyword = trim($params['keyword']);
        $category_id = intval($params['category_id']);
        $status = intval($params['status']);
        $goods_type = intval($params['goods_type']);
        if($keyword){
            $where['title'] = ['like','%'.$keyword.'%'];
        }
        if($goods_type > 0){
            $where['type'] = $goods_type;
        }
        
        if($category_id > 0){
            $cids = [$category_id];
            $category_list = Db::name("bbfx_category")->where(["uniacid"=>UNIACID,'pid'=>$category_id])->select();
            foreach ($category_list as $k => $v){
                $cids[] = $v['id'];
                $child1 = Db::name("bbfx_category")->where(["uniacid"=>UNIACID,'pid'=>$v['id']])->select();
                if(!empty($child1)){
                    $cids = array_merge($cids,array_column($child1,"id"));
                }
            }
            
            $goods_category = Db::name("bbfx_goods_category")->where(['category_id'=>['in',$cids]])->select();
            $goods_ids = array_column($goods_category,"goods_id");
            $where['id'] = ['in',$goods_ids];
        }
        
        
        if($export == 1){
            $pindex = 1;
            $psize = 999999;
        }
    	$list = Db::name("bbfx_goods")->where($where)->order('sort desc,id desc')->limit(($pindex - 1) * $psize,$psize)->select();
    	$export_list = [];
      	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_goods_category")->alias("a")->join("bbfx_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;

            $val['merchant_name'] = Db::name("bbfx_merchant")->where(['uniacid'=>UNIACID,'id'=>$val['mid']])->value("name");
            if(empty($val['merchant_name'])) $val['merchant_name'] = '';
        	
        	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']]);
        	    }
        	}
        	
        	if($export == 1){
        	    $category_name = "";
        	    if(!empty($categorys)){
        	        $category_name = implode(",",array_column($categorys,"title"));
        	    }
        	    $export_list[] = [
        	        $val['id'],
        	        $val['title'],
                    $val['product_code'],
        	        $typeText,
        	        $category_name,
        	        $val['price'],
        	        $val['stock'],
        	        $val['sales_volume'],
        	        $val['createtime']
        	    ];
        	}
        	else{
        	    
        	    $page = "pages/goods/detail?id=".$val['id'];
        	    
                $val['wxapp_url'] = $page;
                $val['h5_qrcode'] = "";
                $val['wxapp_qrcode'] = "";
                $result = Weixin::getUnlimitedQRCode($page,"goods_".$val['id'],1);
                if($result['code'] == 1){
                    $val['wxapp_qrcode'] = cdnurl($result['data']['url'])."?t=".time();
                }
                
                if(strstr($page, '?')){
                    $page .= "&i=".UNIACID;
                }
                else{
                    $page .= "?i=".UNIACID;
                }
                $h5_url = request()->domain()."/mobile/#/".$page;
                $val['h5_url'] = $h5_url;
                $result = QRcode::create($h5_url,"goods_h5_".$val['id']);
                if($result['code'] == 1){
                    $val['h5_qrcode'] = cdnurl($result['data']['url'])."?t=".time();
                }
        	}
        }
        unset($al);
        
        if($export == 1){
    	    $headArr = ["ID","商品名称","商品编码","商品类型","商品分类","商品价格","商品库存","商品销量","创建时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("goods-".date("Y-m-d"),$headArr,$export_list);
    	}
        
    	$total = Db::name("bbfx_goods")->where($where)->count();
        
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function status(){
        $params = $this->param();
        
        $ids = trim($params['id']);
        $status = intval($params['status']);
        
        if($status != 1){
            $status = 0;
        }
        
        if(empty($ids)){
            __error("请选择需要操作的商品");
        }
        
        $ids = explode(",",$ids);
        foreach ($ids as $k => &$v){
            $v = intval($v);
        }
        unset($v);
        
        $res = Db::name("bbfx_goods")->where(["id"=>['in',$ids]])->update(["status"=>$status]);
        if($res){
            
            $data = ['id'=>implode(",",$ids),'status'=>$status];
            \app\admin\model\AdminLog::record("","",$data,"bbfx_goods");
            
            __success("操作成功");
        }
        else{
            __success("操作成功");
        }
    }
    
    public function search(){
        $params = $this->param();
        
        $goodsids = trim($params['goodsids']);
        $goodsids = explode(",",$goodsids);
        
        
        $where = ['uniacid'=>UNIACID,'id'=>['in',$goodsids]];
        $keyword = $params['keyword'];
        if(!empty($keyword)){
            $where['title'] = ['like','%'.$keyword.'%'];
            $where['mid'] = 0;
        }
        
        $list = Db::name("bbfx_goods")->where($where)->field(['id','mid','title','thumb','price','stock','is_spec'])->select();
        
        foreach ($list as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
            
            $cate_title = Db::name("bbfx_goods_category")->alias("a")->join("bbfx_category b","a.category_id=b.id")->where(['a.uniacid'=>UNIACID,'a.goods_id'=>$val['id']])->field('b.id,b.title')->value("title");
            
            if(!empty($cate_title)){
        	    $val['cate_title'] = $cate_title;
        	}
        	else{
        	    $val['cate_title'] = "";
        	}
        	
        	if($val['is_spec'] == 1){
        	    $sku_list = Db::name("bbfx_goods_spec_sku")->where(['uniacid'=>UNIACID,'goods_id'=>$val['id']])->select();
        	    foreach ($sku_list as $k => &$v){
        	        $v['thumb'] = cdnurl($v['thumb']);
        	    }
        	    unset($v);
        	    $val['sku_list'] = $sku_list;
        	}
        }
        unset($val);
        
        if(empty($list)){
            __error("未查询到数据");
        }
        else{
            __success("操作成功",$list);
        }
    }
    
    public function detail(){
        $params = $this->param();
        $result = GoodsModel::detail($params);
        __result($result);
    }
    
    public function post(){
        $params = $this->param();
        
        $params['content'] = htmlspecialchars_decode($this->param("content/h"));
        if($this->goods_type > 0){
            $params['type'] = $this->goods_type;
        }
    	$result = GoodsModel::saveGoods($params,$this->auth->id);
        
        if($result['code'] == 1){
            $changed = $this->getChangedData($result['data']['goods'],$result['data']['new_data']);
            \app\admin\model\AdminLog::record("","",$changed,"bbfx_goods");
        }
        
      	__result($result);
        
    }

    public function setSort(){
        $id = $this->param("id/d");
        $s_id = $this->param("s_id/d");
        $e_id = $this->param("e_id/d");
        $goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$id])->field("id,sort")->find();
        if(empty($goods)){
            __error("商品不存在");
        }
        $s_goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$s_id])->field("id,sort")->find();
        $e_goods = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$e_id])->field("id,sort")->find();
        if(!empty($s_goods)){
            
            if($goods['sort'] > $s_goods['sort']){
                $max = $goods['sort'];
                $min = $s_goods['sort'];
                $sort = $max;
                $sort1 = $min;
            }
            else{
                $max = $s_goods['sort'];
                $min = $goods['sort'];
                $sort = $max - 2;
                $sort1 = $max - 1;
            }
            
            $list = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'sort'=>['>=',$min]])->where(['sort'=>['<=',$max]])->field("id,sort")->order("sort desc,id desc")->select();
            Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$id])->update(['sort'=>$sort1]);
            
            foreach ($list as $key => $val){
                if($val['id'] != $id){
                    Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$val['id']])->update(['sort'=>$sort]);
                    $sort--;
                }
            }
        }
        else{
            if(empty($e_goods)){
                __error("商品信息错误");
            }
            
            $max = $e_goods['sort'];
            $min = $goods['sort'];
            
            $list = Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'sort'=>['>=',$min]])->where(['sort'=>['<=',$max]])->field("id,sort")->order("sort desc,id desc")->select();
            Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$id])->update(['sort'=>$e_goods['sort']]);
            $sort = $max - 1;
            foreach ($list as $key => $val){
                if($val['id'] != $id){
                    Db::name("bbfx_goods")->where(['uniacid'=>UNIACID,'id'=>$val['id']])->update(['sort'=>$sort]);
                    $sort--;
                }
            }
        }
        
        __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,'mid'=>0];
        $keyword = trim($params['keyword']);
        $category_id = intval($params['category_id']);
        if($keyword){
            $where['title'] = ['like',"%".$keyword."%"];
        }
        
        if($category_id){
            $goods_category = Db::name("bbfx_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_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_goods")->where($where)->count();
      	
        __success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function delete(){
        $this->commonDelete("bbfx_goods");
    }
}