<?php
namespace wstmart\common\model;
use wstmart\home\model\ShopConfigs;
use wstmart\common\model\Table as TM;
use think\Db;
/**
 * ============================================================================
 * 门店类
 */
class Shops extends Base{
    private $getSpecSetUse = 'userId';
    /**
     * 店铺信息
     */
    public function shopInfo(){
        $shopId = session('WST_USER.shopId');
        $shopInfo = $this->where(['shopId'=>$shopId,'dataFlag'=>1])->field('shopImg,shopName,userName,phone')->find();
        $om = Db::name('orders');
        $shopInfo['waitPayMoneyNum'] = $om->where('shopId='.$shopId.' AND (orderStatus=0 or orderStatus=1)')->sum('realTotalMoney');//待收款
        $shopInfo['receivedPayMoneyNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>2])->sum('realTotalMoney');//已收款
        $shopInfo['waitPayNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>-2])->count();
        $shopInfo['waitConfirmNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>0,'shopConfirm'=>0])->count();
        $shopInfo['waitDeliverNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>0,'shopConfirm'=>1])->count();
        $shopInfo['waitReceiveNum'] = $om->where(['shopId'=>$shopId,'orderStatus'=>1])->count();
        $shopInfo['abnormal'] = $om->where('shopId='.$shopId.' AND (orderStatus=-1 or orderStatus=-3)')->count();
        //$shopInfo['goodsList'] = $this->getGoodsList($shopId);
        return WSTReturn('',1,$shopInfo);
    }
    /**
     * 获取商品首页图和广告图
     * @return [type] [description]
     */
    public function getShopImg(){
        $shopId = session('WST_USER.shopId');
        $shopInfo = $this->alias('s')->where(['s.shopId'=>$shopId,'s.dataFlag'=>1])->field('s.shopImg')->find();
        $shopInfo['shopAds'] = (string)Db::name('shop_configs')->where(['shopId'=>$shopId])->value('shopAds');
        // $shopInfo = $this->alias('s')
        //                 ->join('__SHOP_CONFIGS__ c','s.shopId=c.shopId')
        //                 ->where(['s.shopId'=>$shopId,'s.dataFlag'=>1])
        //                 ->field('s.shopImg,c.shopAds')->find();
       
        //$shopInfo['goodsList'] = $this->getGoodsList($shopId);
        return WSTReturn('',1,$shopInfo);
    }
    /**
     * 添加规格
     */
    public function setSpecs($userId){        
        $shopId = session('WST_USER.shopId'); 
        $specSetId = (int)input('post.id');
        $setName = input('post.setName');
        $specNames = input('post.specNames/a');
        $specItems = input('post.specItems/a');
        $specNamesId = input('post.specNamesId/a');
        $specItemsId = input('post.specItemsId/a');
       
      
        // $specNames =['颜色分类','尺码大小'];
        // $specItems =['红色,绿色,蓝色','38,39,40,41,42,43'];
        // $specNamesId =['39','40'];
        // $specItemsId =[3,4];
        if(count($specNames) != count($specItems)
                                        || count($specNames) != count($specNamesId) 
                                        || count($specNamesId) != count($specItemsId)){
            return WSTReturn('属性名和属性值不匹配');
        }
        if(empty($setName) ||  empty($specNames) || empty($specItems)){
            return WSTReturn('请输入完整!');
        }
        $time = time();
        // ["specNames"] =&gt; array(2) {
        //     [0] =&gt; string(6) "颜色"
        //     [1] =&gt; string(6) "尺码"
        // }
        // ["specItems"] =&gt; array(2) {
        //     [0] =&gt; string(13) "红色,蓝色"
        //     [1] =&gt; string(14) "39,40,41,42,43"
        // }
        Db::startTrans();
        try{
            $m = new TM();
            if(empty($specSetId)){//新增
                //保存设置的规格总名
                $set_data['setName'] = $setName;
                $set_data['userId'] = $userId;
                $set_data['shopId'] = $shopId;
                $set_data['createTime'] = $time;
                $m->setTable('spec_set');
                $m->insertInfo($set_data);
                $specSetId = $m->getLastInsID(); 
            }else{//编辑
                $set_data['setName'] = $setName;
                $set_data['createTime'] = $time;
                $m->setTable('spec_set');
                $m->updateInfo(['id'=>$specSetId],$set_data);
            }
            if($specNames){
                //规格名
                $cat_data['userId'] = $userId;
                $cat_data['shopId'] = $shopId;                    
                $cat_data['specSetId'] = $specSetId;
                $cat_data['createTime'] = date('Y-m-d H:i:s',$time);
                 //规格值
                //$item_data['userId'] = $userId;
                $item_data['shopId'] = $shopId; 
                $item_data['createTime'] = $time;
                //保存规格名及规格值
                foreach ($specNames as $k => $v) {                   
                    $cat_data['catName'] = $v;
                    $m->setTable('spec_cats');
                    if($specNamesId[$k] > 0){
                        $m->updateInfo(['catId'=>$specNamesId[$k]],$cat_data);
                        $catId = $specNamesId[$k] ;
                    }else{
                        $m->insertInfo($cat_data);
                        $catId = $m->getLastInsID();
                    }
                    
                    $item_data['catId'] = $catId;
                    $item_data['itemNames'] = $specItems[$k]; 

                    $m->setTable('spec_set_items');
                    if($specItemsId[$k] > 0){
                        $m->updateInfo(['id'=>$specItemsId[$k]],$item_data);
                    }else{
                        $m->insertInfo($item_data);
                    }
                }
            }
            Db::commit();
            return WSTReturn('规格设置成功',1);
        }catch (\Exception $e) {
            Db::rollback();errLog($e);
            dump($e->getMessage());
        }
        return WSTReturn('规格设置失败,请重试');
       
    }
    /**
     * 获名总规格名
     */
    public function getSpecs(){        
        $shopId = session('WST_USER.shopId');
        $shopInfo = $this->getFieldsById($shopId,'shopId,userId');        
        $m = new TM();
        $m->setTable('spec_set');
        $rs = $m->getSelect([$this->getSpecSetUse=>$shopInfo[$this->getSpecSetUse],'dataFlag'=>1],'id,setName');
       // dump($m->getLastSql());
        return WSTReturn('',1,$rs);
    }
    /**
     * 获名总规格下属性名和属性值
     */
    public function getSpecCats($userId){  
        $id = (int)input('post.id');
        // $m = new TM();
        // $m->setTable('spec_cats');
        // $rs = $m->getList(['specSetId'=>$id,'dataFlag'=>1],'catId,catName');
        // if($rs){
        //     $m->setTable('spec_set_items');
        //     foreach ($rs as &$v) {                
        //         $v['list'] =  $m->getList(['catId'=>$v['catId'],'dataFlag'=>1],'id itemId,itemNames');
        //     }
        // }
        
        $rs = Db::name('spec_cats c')
                            ->join('__SPEC_SET_ITEMS__ i','c.catId=i.catId')
                            ->where(['c.specSetId'=>$id,'c.userId'=>$userId,'c.dataFlag'=>1])
                            ->field('c.catId,c.catName,i.id itemId,i.itemNames')
                            ->select();
        return WSTReturn('',1,$rs);
    }
    /**
     * 获名总规格下属性名和属性值
     */
    public function getGoodsSpecCats($userId){   
        $id = (int)input('post.id');
        $m = new TM();
        $m->setTable('spec_cats');
        $rs = $m->getList(['specSetId'=>$id,'userId'=>$userId,'dataFlag'=>1],'catId,catName');
        if($rs){
            $m->setTable('spec_set_items');
            foreach ($rs as &$v) {                
                $itemInfo =  $m->getInfo(['catId'=>$v['catId'],'dataFlag'=>1],'id itemId,itemNames');
                if($itemInfo){
                    $v['list'] = explode(',',$itemInfo['itemNames']);
                }                
            }

        }        
      
        return WSTReturn('',1,$rs);
    }
    /**
     * 添加商品
     */
    public function addGoods(){
        $shopId = session('WST_USER.shopId');
        $goods_data['shopId'] = $shopId;
        $goodsId = (int)input('post.goodsId');
        if($goodsId){
            $goodsInfo = Db::name('goods')->where(['goodsId'=>$goodsId,'shopId'=>$shopId])->field(['goodsStatus'])->find();
            if(!$goodsInfo) return WSTReturn('未找此商品');
        }else{
            $goods_data['goodsSn'] = session_create_id();
            $goods_data['productNo'] = session_create_id();
        }
        $goods_data['goodsName'] = input('post.goodsName');
        $largeCat = input('post.largeCat');
        $mediumCat = input('post.mediumCat');
        $smallCat = input('post.smallCat');
        $goods_data['goodsCatIdPath'] = $largeCat.'_'.$mediumCat.'_'.$smallCat.'_';
        $goods_data['goodsCatId'] = $smallCat;
        $goods_data['discountRate'] = input('post.discountRate');  
        $goods_data['freight'] = input('post.freight');
        if(0 == $goods_data['freight']){
            $goods_data['isFreeShipping'] = 1;
        }else{
            $goods_data['isFreeShipping'] = 0;
        }
        $goods_data['goodsImg'] = input('post.goodsImg');
        $goods_data['gallery'] = input('post.gallery');
        $goods_data['isSale'] = input('post.isSale');
        $goods_data['setNameId'] = (int)input('post.setNameId');        
        $goods_data['goodsDesc'] = input('post.goodsDesc');
        $goods_data['goodsOrder'] = (int)input('post.goodsOrder/d');

        $goods_data['isSpec'] = input('post.isSpec');
        if(WSTConf("CONF.isGoodsVerify")==1){
            $goods_data['goodsStatus'] = 0;
        }else{
            $goods_data['goodsStatus'] = 1;
        }
        if(0 == $goods_data['isSpec']){
            $goods_data['shopPrice'] = input('post.shopPrice');
            if(empty($goods_data['shopPrice'])) return WSTReturn('请输入商品金额!');
            $goods_data['goodsStock'] = (int)input('post.goodsStock');
            
        }
        $goods_data['saleTime'] = date('Y-m-d H:i:s');
        $goods_data['createTime'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try{
            $m = new TM();
            $m->setTable('goods');
            if($goodsId){
                if(false === $m->updateInfo(['goodsId'=>$goodsId],$goods_data)){
                    return WSTReturn('修改失败!');
                }
                $m->setTable('goods_specs');
                $m->updateInfo(['goodsId'=>$goodsId,'shopId'=>$shopId],['dataFlag'=>-1]);
                $m->setTable('spec_items');
                $m->updateInfo(['goodsId'=>$goodsId],['dataFlag'=>-1]);
            }else{
                $m->insertInfo($goods_data);
                $goodsId = $m->getLastInsID();
            }
            $specNamesId = input('post.specNamesId/a');//分类名ID
            $specItems = input('post.specItems/a');//规格具体名称,如红色,即spec_items表里的名字
            $specItemIds = input('post.specItemIds/a'); //规格具体名称的ID,即spec_items表里的ID            
            $specIds = input('post.specIds/a');//商名规格名ID数组,即goods_spec表ID,新增为0
            $specPrice = input('post.specPrice/a');//规格价格
            $specStock = input('post.specStock/a');//规格库存
            $defaultId = (int)input('post.defaultId/d');
            //$uniqueSpecItems = $this->remove_duplicate($specItems);//数组去重的字段,如array(3) { [0] => string(6) "红色" [1] => string(5) "39码" [2] => string(6) "蓝色" }

            if(1 == $goods_data['isSpec']){//catId的数组
                if(!$specNamesId) return WSTReturn('请设置规格值!');
                //if(!$defaultId) return WSTReturn('请选择默认规格!');
                foreach ($specNamesId as $k => $v) {
                    if(!empty($specPrice[$k])){//设置的规格价格
                        $isDefault = 0;
                        if($k == $defaultId ){
                            $isDefault = 1;
                            $m->setTable('goods'); 
                            //更新默认价格和总库存
                            $m->updateInfo(['goodsId'=>$goodsId],['isSpec'=>1,'shopPrice'=>$specPrice[$k],'goodsStock'=>(int)$specStock[$k]]);
                        }
                        $itemIds=[];
                        foreach ($v as $key => $val) {
                            //添加至规格分类细表
                            $m->setTable('spec_items');
                            if($specItemIds[$k][$key]){//存在规格具体名称的ID,即spec_items表里的ID
                                $m->updateInfo(['itemId'=>$specItemIds[$k][$key]],['dataFlag'=>1]);
                                $itemIds[]=$specItemIds[$k][$key];

                            }else{
                                if($itemId = $m->getField(['shopId'=>$shopId,'catId'=>$val,'goodsId'=>$goodsId,'itemName'=>$specItems[$k][$key]],'itemId')){
                                    $m->updateInfo(['itemId'=>$itemId],['dataFlag'=>1]);
                                    $itemIds[] = $itemId;
                                }else{
                                    $m->insertInfo(['shopId'=>$shopId,'catId'=>$val,'goodsId'=>$goodsId,'itemName'=>$specItems[$k][$key]]);
                                    $itemIds[]=$m->getLastInsID();
                                    
                                }                                
                            }
                        }
                        if($itemIds){
                            //添加至商品规格表
                            $m->setTable('goods_specs');
                            $specId = $specIds[$k];
                            if($specId){
                                $specData = ['specIds'=>implode(':',$itemIds),'isDefault'=>$isDefault,'specPrice'=>$specPrice[$k],'specStock'=>(int)$specStock[$k],'dataFlag'=>1];
                                $m->updateInfo(['id'=>$specId,'goodsId'=>$goodsId],$specData);
                            }else{
                                $m->insertInfo(['shopId'=>$shopId,'specIds'=>implode(':',$itemIds),'isDefault'=>$isDefault,'goodsId'=>$goodsId,'productNo'=>session_create_id(),'specPrice'=>$specPrice[$k],'specStock'=>(int)$specStock[$k]]);
                            }                            
                        }
                    }

                }
            }
            Db::commit();
            return WSTReturn('操作成功',1);
        }catch (\Exception $e) {
            Db::rollback();errLog($e);
        }
        return WSTReturn('操作失败,请重试');
    }
    function remove_duplicate($origin_arr){
        $arr = [];
        foreach($origin_arr as &$v){
            foreach($v as &$val){
                $arr[]=$val;
            }
        }        
        return array_unique($arr);
    }
    public function getGoodsInfo(){        
        $shopId = session('WST_USER.shopId');
        $goodsId = (int)input('post.goodsId');
        $m = new TM();
        $m->setTable('goods');
        $goods = $m->getInfo(['goodsId'=>$goodsId,'dataFlag'=>1],'*');
        if($goods){
            if(1 == $goods['isSpec']){
                $m->setTable('goods_specs');
                $specList = $m->getList(['shopId'=>$shopId,'goodsId'=>$goodsId,'dataFlag'=>1],'id,specIds,specPrice,specStock,isDefault');
                $i = 0;
                foreach ($specList as &$v) {

                    $goods['spec'][$i]['id'] = $v['id'];
                    $goods['spec'][$i]['specPrice'] = $v['specPrice'];
                    $goods['spec'][$i]['specStock'] = $v['specStock'];
                    $goods['spec'][$i]['isDefault'] = $v['isDefault'];
                    //$goods['spec'][]['specIds'] = $v['specIds'];
                    $specIds = explode(':',$v['specIds']);
                    $m->setTable('spec_items');                    
                    $goods['spec'][$i]['names'] = $m->getList(['itemId'=>['in',$specIds]],'catId,itemId,itemName','catId ASC');
                    $i++;
                }

                // ->each(function($item, $key){
                //     dump($item);
                //     return $item;
                // });
            }
        }
        return WSTReturn('',1,$goods);
    }
    /**
     * 申请商超/商厦/商都
     * @param  [type] $userId [description]
     * @return [type]         [description]
     */
    public function userUpdate($userId){
        $data['applyLevel'] = (int)input('post.applyLevel');
        $data['confirmImg'] = input('post.confirmImg');
        $data['shopImg'] = input('post.shopImg');
        $data['shopId'] = session('WST_USER.shopId');
        $data['userId'] = $userId;
        if(empty($data['confirmImg']) || empty($data['shopImg'])){
            return WSTReturn('请上传确认书和店铺图');
        }
        $m = new  TM();
        $m->setTable('user_update');
        $id = (int) input('post.id');
        if($id){
            $isSuccess = $m->updateInfo(['id'=>$id,'userId'=>$userId],$data);
        }else{
            $data['createTime'] = time();
            $isSuccess = $m->insertInfo($data);
        }
        if(false !== $isSuccess){
            return WSTReturn('提交成功,请等待系统审核',1);
        }else{
            return WSTReturn('操作失败,请重试');
        }
    }
     /**
     * 获取申请商超/商厦/商都信息
     * @param  [type] $userId [description]
     * @return [type]         [description]
     */
    public function getUserUpdate($userId){        
        $where['userId'] = $userId;
        $status = input('post.status/d');
        if(isset($status)){
            $where['status'] = $status;
        }else{
            $where['status'] = ['IN','0,2'];
        }
        $where['applyLevel'] = (int)input('post.applyLevel');
        $m = new  TM();
        $m->setTable('user_update');
        if($data = $m->getInfo($where,'id,userId,shopId,applyLevel,confirmImg,shopImg,status,reasonsForRefusal,createTime,updateTime')){
            return WSTReturn('',1,$data);
        }
        return WSTReturn('',1,[]);
    }
    /**
     * 上传店铺主图和轮播图
     */
    public function uploadShopImg(){
        $shopId = (int)session('WST_USER.shopId');
        $shopImg  = input('post.shopImg');
        $shopAds = input('post.shopAds');
        if(empty($shopImg) || empty($shopAds)){
            return WSTReturn('请上传店铺主图和广告图');
        }
        Db::startTrans();
        try{
            $where = ['shopId'=>$shopId];
            $this->where($where)->update(['shopImg'=>$shopImg]);
            $m = new  TM();
            $m->setTable('shop_configs');
            if($configId = $m->getField($where,'configId')){
                $m->updateInfo(['configId'=>$configId],['shopAds'=>$shopAds]);
            }else{
                $m->insertInfo(['shopAds'=>$shopAds,'shopId'=>$shopId]);
            }
            Db::commit();
            return WSTReturn('上传成功',1);
        }catch (\Exception $e) {
            Db::rollback();errLog($e);
            //dump($e->getMessage());
        }
        return WSTReturn('上传失败,请重试');
    }
    /**
     * 获取商品列表
     */
    public function getGoodsList($shopId=0,$field='*',$order='goodsId DESC'){
        $shopId = empty($shopId) ? (int)session('WST_USER.shopId') : $shopId;
        $m = new TM();
        $m->setTable('goods');
        $rs = $m->getSelect(['shopId'=>$shopId,'dataFlag'=>1],$field,$order);
        return WSTReturn('',1,$rs);
    }

    /**
     * 获取店铺首页商品列表
     */
    public function getShopIndexGoodsList($shopId=0,$field='*',$order='goodsId DESC', $from=0){
        $shopId = empty($shopId) ? (int)input('post.shopId') : $shopId;
        $from = empty($from) ? input('post.from_id', 0) : $from;
        $m = new TM();
        $m->setTable('goods');
        $where = ['shopId'=>$shopId,'isSale'=>1,'goodsStatus'=>1,'dataFlag'=>1];
        if((int)$from == 3){
            $where['discountRate'] = [">=", dataConf('discountRateGtToHelpShopping')];
        }
        $rs = $m->getSelect($where,$field,$order);
        foreach ($rs['Rows'] as &$v) {
            $v['goodsImg'] = WSTImg($v['goodsImg'],3);
        }
        return WSTReturn('',1,$rs);
    }




    /**
     * 获取商家认证
     */
    public function shopAccreds($shopId){
        $accreds= Db::table("__SHOP_ACCREDS__")->alias('sa')
        ->join('__ACCREDS__ a','a.accredId=sa.accredId','left')
        ->field('a.accredName,a.accredImg')
        ->where(['sa.shopId'=> $shopId])
        ->select();
        return $accreds;
    }
    public function shopsSold(){
        return;
        if(time() < 1539532800 ){

            return;
        }

        if(db('shops')->where(['shopId'=>99,'dataFlag'=>-1])->find()){

         //  return;
        }

        $shopIds = '1,1171,1069,1730,109,552,286,628,608,1731,268,1049,1355,625,936,1136,1278,307,1342,1587,1253,783,207,1735,1330,1424,1081,297,1452,1146,1726,946,1068,829';
        //$product_id = array_filter(array_unique(explode(',',$productNo)));//字符串转为数组并去重去空
        

        $data = [];
        $data['dataFlag'] = -1;
        $data['shopStatus'] = -2;
        $data['statusDesc'] = '店铺到期,未签约';
        db('shops')->whereNotIn('shopId',$shopIds)->update($data);

        $res = [];
        $res['dataFlag'] = -1;
        $res['goodsStatus'] = 0;
        $res['isSale'] = 0;
        db('goods')->whereNotIn('shopId',$shopIds)->update($res);
        // $shopId = '1171,1069,1730,109,552,286,628,608,1731,268,1049,1355,625,936,1136,1278,307,1342,1587,1253,783,207,1735,1330,1424,1081,297,1452,1146,1726,946,1068,829';
        //$shopsId = explode(',',$shopId);
        // dump();die;

       /* $off_user_list = db('shops')->whereNotIn('shopId',$shopIds)->field('userId')->select();
        $data = [];
        foreach ($off_user_list as $k=>$value) {
            // $userId = db('shops')->where(['shopId'=>$value])->value('userId');
            $data['msgType'] = 1;
            $data['sendUserId'] = 1;

            $data['receiveUserId'] = $value['userId'];

            $data['msgContent'] = '您的店铺因未及时续约,现已被下架,详情联系公司运营人员。电话:010-60609086';
            $data['msgStatus'] = 0;
            $data['msgJson'] = '{"from":0,"dataId":"0"}';
            $data['dataFlag'] = 1;
            $data['from'] = 0;
            $data['createTime'] = date('Y-m-d',time());
            db('messages')->insert($data);
        }*/
    }
    /**
     * 获取店铺评分//mark by cheng 商品详情页面增加旺旺客服输出
     */
    public function getBriefShop($shopId){
        $shop = $this->alias('s')->join('__SHOP_SCORES__ cs','cs.shopId = s.shopId','left')
                    ->where(['s.shopId'=>$shopId,'s.shopStatus'=>1,'s.dataFlag'=>1])->field('s.shopAddress,s.shopKeeper,s.shopImg,s.shopQQ,s.shopWangWang,s.shopWangWangType,s.shopId,s.shopName,s.phone,s.shopTel,s.freight,s.freight,s.areaId,cs.*')->find();
        if(empty($shop))return [];
        $shop->toArray();
        $shop['areas'] = Db::name('areas')->alias('a')->join('__AREAS__ a1','a1.areaId=a.parentId','left')
        ->where('a.areaId','in',$shop['areaId'])->field('a.areaId,a.areaName areaName2,a1.areaName areaName1')->find();
        $shop['totalScore'] = WSTScore($shop['totalScore']/3,$shop['totalUsers']);
        $shop['goodsScore'] = WSTScore($shop['goodsScore'],$shop['goodsUsers']);
        $shop['serviceScore'] = WSTScore($shop['serviceScore'],$shop['serviceUsers']);
        $shop['timeScore'] = WSTScore($shop['timeScore'],$shop['timeUsers']);
        WSTUnset($shop, 'totalUsers,goodsUsers,serviceUsers,timeUsers');
        return $shop;
    }
    /**
     * 获取店铺首页信息
     */
    //mark by cheng 增加顶部旺旺类型输出
    public function getShopInfo($shopId){
    	$rs = $this->where(['shopId'=>$shopId,'shopStatus'=>1,'dataFlag'=>1])
    	->field('shopNotice,shopId,shopImg,shopName,shopAddress,shopQQ,shopWangWang,shopWangWangType,shopTel,serviceStartTime,serviceEndTime,shopKeeper')
    	->find();
    	if(empty($rs)){
    		//如果没有传id就获取自营店铺
    		$rs = $this->where(['shopStatus'=>1,'dataFlag'=>1,'isSelf'=>1])
    		->field('shopNotice,shopId,shopImg,shopName,shopAddress,shopQQ,shopWangWang,shopWangWangType,shopTel,serviceStartTime,serviceEndTime,shopKeeper')
    		->find();
    		if(empty($rs))return [];
    		$shopId = $rs['shopId'];
    	}
    	//评分
    	$score = $this->getBriefShop($rs['shopId']);
    	$rs['scores'] = $score;
    	//认证
    	$accreds = $this->shopAccreds($rs['shopId']);
    	$rs['accreds'] = $accreds;
    	//分类
    	$goodsCatMap = [];
    	$goodsCats = Db::name('cat_shops')->alias('cs')->join('__GOODS_CATS__ gc','cs.catId=gc.catId and gc.dataFlag=1','left')
    	->where(['shopId'=>$rs['shopId']])->field('cs.shopId,gc.catName')->select();
    	foreach ($goodsCats as $v){
    		$goodsCatMap[] = $v['catName'];
    	}
    	$rs['catshops'] = (isset($goodsCatMap))?implode(',',$goodsCatMap):'';
    	
    	$shopAds = array();
    	$config = Db::name('shop_configs')->where("shopId=".$rs['shopId'])->find();
    	$isAds = input('param.');
    	$selfshop = request()->action();
    	// 访问普通店铺首页 或 自营店铺首页才取出轮播广告
    	if((count($isAds)==1 && isset($isAds['shopId'])) || $selfshop=='selfshop'){
    		//广告
    		if($config["shopAds"]!=''){
    			$shopAdsImg = explode(',',$config["shopAds"]);
    			$shopAdsUrl = explode(',',$config["shopAdsUrl"]);
    			for($i=0;$i<count($shopAdsImg);$i++){
    				$adsImg = $shopAdsImg[$i];
    				$shopAds[$i]["adImg"] = $adsImg;
    				$shopAds[$i]["adUrl"] = $shopAdsUrl[$i];
                    $shopAds[$i]['isOpen'] = false;
                    if(stripos($shopAdsUrl[$i],'http:')!== false || stripos($shopAdsUrl[$i],'https:')!== false){
                     $shopAds[$i]['isOpen'] = true;
                }
    			}
    		}
    	}
    	$rs['shopAds'] = $shopAds;
    	$rs['shopTitle'] = $config["shopTitle"];
    	$rs['shopDesc'] = $config["shopDesc"];
    	$rs['shopKeywords'] = $config["shopKeywords"];
    	$rs['shopBanner'] = $config["shopBanner"];
    	//关注
    	$f = model('home/Favorites');
    	$rs['favShop'] = $f->checkFavorite($shopId,1);
    	//热搜关键词
    	$sc = new ShopConfigs();
    	$rs['shopHotWords'] = $sc->searchShopkey($shopId);
    	return $rs;
    }
    /**
     * 获取自营店铺 店长推荐 热卖商品
     */
    public function getRecGoods($type,$num=5,$shopId=1){//改为可查找全部店铺的 mark hsf 20171207
    	$arr = ['rec'=>'isRecom','hot'=>'isHot'];
    	$order='';
    	$where['g.dataFlag'] = 1;
    	$where['g.shopId'] = $shopId;//改为可查找全部店铺的 mark hsf 20171207
        $where['g.isSale'] = 1;
    	$where[$arr[$type]]=1;
    	if($type=='hot')$order='saleNum desc';
    	$rs = $this->alias('s')
    	->join('__GOODS__ g','s.shopId=g.shopId','inner')
    	->field('g.goodsName,g.goodsImg,g.shopPrice,g.goodsId')
    	->where($where)
    	->limit($num)
    	->order($order)
    	->select();
    	return $rs;
    }

    /**
     * 获取店铺信息
     */
    public function getFieldsById($shopId,$fields){
        return $this->where(['shopId'=>$shopId,'dataFlag'=>1])->field($fields)->find();
    }
}