<?php
/**
 * 微信小程序支付模块
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */

namespace Wxsmall\Model;
use Think\Model;
class TakeoutModel extends Model{
    protected $tableName = 'Goods';
    /**
     * 获取商品列表页面
     * @param array $param 筛选参数
     * @return array 返回信息
     * @rank 会员等级
     */
    public function index($param,$rank=''){
        $return = array('status'=>2,'msg'=>'已加载全部数据');
        if(empty($param['catid'])){
            $cateid=0;
            $temp=C("LIST_TPL_WX");
            /* if($temp=="shops_index_green") {$cateid=0;}
             else{
                 GLOBAL $PurchaseCategory;
                 if(empty($PurchaseCategory))$PurchaseCategory=getcache('PurchaseCategory');
                 foreach($PurchaseCategory as $k=>$v){
                     if($v['pid']==0){
                         $cateid=$v['id'];break;
                     }
                 }
             }*/
        }
        if(isset($param['catid'])&&$param['catid']>0){$cateid=$param['catid'];unset($param['keyword']);}
        if(empty($param['catid'])){
            $param['catid']=$cateid;
            $param['childcatid']=0;
        }
        if($param['catid']>0 && $param['keyword']){unset($param['catid']);}
        $data = D('Common/Takeout')->get_goods_list($param,0);
        $return['data']['init_list'] = $this->get_cart($param);//默认购物车中已加入的商品
        $return['data']['brand_list'] = brand_list(0);//默认购物车中已加入的商品
        if($cateid) {
            if($param['catid'] && $param['childcatid']){
                $return['data']['catid'] = $cateid;//默认分类
                $return['data']['child_id'] = $param['childcatid'];//默认分类
            }else {
                $map = array();
                $map['id'] = $cateid;
                $catpid = M('PurchaseCategory')->where($map)->getField('pid');
                if ($catpid == 0) {
                    $return['data']['catid'] = $cateid;//默认分类
                    $return['data']['child_id'] = 0;//默认分类
                } else {
                    $map = array();
                    $map['id'] = $catpid;
                    $map['pid'] = 0;
                    $cate_pid = M('PurchaseCategory')->where($map)->getField('id');
                    $return['data']['catid'] = $cate_pid;//默认分类
                    $return['data']['child_id'] = $cateid;//默认分类
                }
            }
        }
        if($return['data']['child_id']){$cate_id=$return['data']['child_id'];}elseif($return['data']['catid']){
            $cate_id=$return['data']['catid'];
        }
        if($cate_id){
            $catename=idtoname($cate_id,'PurchaseCategory','name');
        }else{
            $catename='店铺推荐';
            $temp = C("LIST_TPL_WX");
            if ($temp != "shops_index_blue") {
                $catename='分类';
            }
        }
        $return['data']['catename']=$catename;
        //$return['data']['catid'] = $cateid;//默认分类
        // $return['data']['sql'] = $data['sql'];//默认分类
        if(!empty($data['goods_list']['list'])) {
            $return['data']['goods_list'] = array();
            $return['data']['goods_list'] = $this->format_data($data['goods_list']['list'], 2, $cateid, $param,$rank);
            $return['data']['totalpage'] = $data['goods_list']['totalPages'];//商品总页数
            $return['data']['goods_count'] =count($data['goods_list']['list']);//商品总页数

            $return['status'] = 1;
        }
        return $return;
    }


    /**
     * @desc arraySort php二维数组排序 按照指定的key 对数组进行排序
     * @param array $arr 将要排序的数组
     * @param string $keys 指定排序的key
     * @param string $type 排序类型 asc | desc
     * @return array
     */
    public function arraySort($arr, $keys, $type = 'asc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v){
            $keysvalue[$k] = $v[$keys];
        }
        $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
        reset($keysvalue);
        foreach ($keysvalue as $ke => $ve) {
           $new_array[$ke] = $arr[$ke];
        }
        return $new_array;
    }
    public function format_data($list = array(),$type,$cateid=0,$param=array(),$rank=''){
        $result = $list;
        $is_first=$param['is_first'];
        if($list){
            foreach($list as $k=>$v){
                if($type==1){
                    $result[$k]['id'] = $v['id'];
                    $result[$k]['name'] = $v['name'];
                }elseif($type==2){

                    if($is_first>1){
                        $price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$v['id']);
                        $result[$k]['shop_price'] = $price_info['goods_price'];
                        $result[$k]['sprice'] = format_price($price_info['goods_price']);
                    }else{
                        $result[$k]['shop_price'] = $v['shop_price'];
                        $result[$k]['sprice'] = format_price($v['shop_price']);
                    }
                    $price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$v['id']);
                    //322新加
                    $result[$k]['promote_type']=0;
                    if($v['is_promote']){

                        $result[$k]['promote_type']=1;
                        $result[$k]['is_promote'] =$v['is_promote'];
                        $result[$k]['promote_price'] = $v['promote_price'];
                        
                        // $result[$k]['promote_number'] = intval($v['sell_count']); //已抢
                        // if($v['goods_number']>0) $result[$k]['pover_number'] = intval($v['goods_number'])-intval($v['sell_count']); //仅剩
                        // if($v['goods_number']==-1) $result[$k]['pover_number'] = 99999; //仅剩
                        $result[$k]['promote_number'] = intval($v['goods_max_number'])-intval($v['goods_number']); //已抢
                        if($v['goods_number']>0) $result[$k]['pover_number'] = intval($v['goods_number']); //仅剩
                        if($v['goods_number']==0) $result[$k]['pover_number'] = 0;
                        if($v['goods_number']==-1) $result[$k]['pover_number'] = 99999; //仅剩
                        /*
                        * 6-29 $promote_info
                        */
                        $promote_info = M('PromotAct')->where('id='.$v['promote_id'])->field(true)->find();
                        if($v['promote_end_time']<NOW_TIME || ($rank < $promote_info['user_rank'])){
                            $result[$k]['is_overdue'] = 1; //活动结束
                            $result[$k]['type_show']=1;
                            $result[$k]['is_promote']=0;
                        }else if($v['promote_start_time']<=NOW_TIME && $v['promote_end_time']>NOW_TIME){
                            $result[$k]['is_overdue'] = 0;
                            $result[$k]['shop_price'] = $price_info['goods_price'];
                            $result[$k]['type_show']=0;

                            $result[$k]['shop_price']=$v['promote_price'];
                            $discount=format_decimal($price_info['goods_price']/$v['shop_price']*10,1);
                            $result[$k]['discount_mark']='限时'.$discount.'折';
                            $result[$k]['deil_name'] ='限时'.$discount.'折';
                        } 


                    }else if($v['pt_id']){
                        $result[$k]['promote_type']=2;
                        $ptid = M('PromotAct')->where('id='.$v['pt_id'])->field('id,buy_limit,start_time,end_time,user_rank,group_number')->find();
                        $pt_arr=array();
                        $pt_arr['act_id'] = $ptid['id'];
                        $pt_arr['style_ext_id'] = $v['id'];
                        $pt_arr['style'] = 4;
                        $pt_money = M('PromotExt')->where($pt_arr)->getField('remarks');
                        $pt_money = unserialize($pt_money);
                        if($pt_money>0) {$result[$k]['pt_price'] = format_decimal($pt_money,2);}
                        $result[$k]['pt_id'] = $v['pt_id'];
                        // $result[$k]['goods_number'] = $v['goods_number']; //累计售出
                        if($v['goods_number']>0) $result[$k]['goods_number'] = intval($v['goods_number']); //仅剩
                        if($v['goods_number']==-1) $result[$k]['goods_number'] = 99999; //仅剩

                        if($ptid['end_time']<NOW_TIME || ($rank < $ptid['user_rank'])){
                            // $result[$k]['is_overdue'] = 1; //拼团已过期
                            $result[$k]['is_ptdue'] = 1; //拼团已过期
                            $result[$k]['type_show']=1;
                            $result[$k]['pt_id']=0;

                        }else if($ptid['start_time']<=NOW_TIME && $ptid['end_time']>NOW_TIME){
                            $result[$k]['shop_price']=$result[$k]['pt_price'];
                            // $result[$k]['is_overdue'] = 0;                        
                            $result[$k]['is_ptdue'] = 0; 
                            $result[$k]['type_show']=0;
                            $result[$k]['pin_mark']=$ptid['group_number'].'人团';
                        }
                            
                        //已拼
                        $oarrs=array();
                        $oarrs['pt_id'] = $v['pt_id'];
                        $oarrs['pay_status'] = 3;
                        $oarrs['status'] = array('neq',4);
                        $oarrs['is_delete'] = 0;
                        $oi_ids = M('OrderInfo')->where($oarrs)->getField('id',true);
                        if($oi_ids){
                            $maph = array();
                            $maph['order_id'] = array('in',$oi_ids);
                            $maph['goods_id'] = $v['id'];
                            $og_count = M('OrderGoods')->where($maph)->sum('goods_number');
                        }else{
                            $og_count = 0;
                        }
                        $result[$k]['yp_number'] = intval($og_count);
                    }


                   // if($cateid>0&&$cateid!=$v['cat_id'])continue;
                    $result[$k]['id'] = $v['id'];
                    $result[$k]['cat_id'] = $v['cat_id'];
                    $result[$k]['name'] = $v['goods_name'];
                    $result[$k]['market_price'] = $v['market_price'];

                    //408
                    $result[$k]['addname'] = '/images/nocheck_duig.png';

                    //end
                    

                     // echo '6**---'; echo "<pre>"; var_dump($result); die;


                    // $result[$k]['shop_price'] = $price_info['goods_price'];
                    $result[$k]['mprice'] = format_price($v['market_price']);

                    // $result[$k]['balance_price'] =  D("LiveDivided")->get_goods_balancemoney($v['id'],1,$price_info['goods_price']);
                     // 7-5 修改   get_goods_balancemoney
                      $result[$k]['balance_price'] =  $this->get_goods_balancemoney($v['id'],1,$price_info['goods_price']);

                    $result[$k]['sprice'] = format_price($price_info['goods_price']);

                    $result[$k]['img'] = thumb($v['img']);
                    $result[$k]['format_spec'] = D("Common/GoodsAttr")->get_shop_attr($v['id']);
                    $v['format_spec']=$result[$k]['format_spec'];
                    //$result[$k]['format_spec'] = $v['format_spec'];
                    $result[$k]['stock'] = $this->format_stock($param['shop_id'],$v);//根据当前定位的门店信息取出对门店商品库存

                }
            }
        }
        return $result;
    }
      /**获取某商品主播应得的佣金   7-5  
     * @param $goods_id
     */
    public function get_goods_balancemoney($goods_id,$goods_number,$goods_price){
        if(empty($goods_id) || empty($goods_number) || empty($goods_price))return false;
        $map=array();
        $balance_rate=0;
        $map['id']=$goods_id;
        $goods_cate = M("Goods")->where($map)->getField('cat_id');
        if ($goods_cate > 0) {
            //找出某商品一级分类的佣金比
            $balance_rate = D("Common/GoodsCategory")->get_parent_pid($goods_cate);
        }
        //商品总原价
        $goods_total_price=$goods_price*$goods_number;
        //获取主播佣金比
        $a_map=array();
        $a_map['name']='live_balance_rate';
       $anchor_rate=M("LiveSet")->where($a_map)->getField('value');
        //主播应得佣金
        $anchor_balance_price=format_decimal($goods_total_price*(1-$balance_rate/100)*$anchor_rate/100);
        return $anchor_balance_price;
    }

    public function format_stock($shop_id=0,$data=array()){
        $return = array();
        $map = array();
        $map['goods_id'] = $data['id'];
        $map['shop_id'] = $shop_id;
        $map['status'] = 1;
        if($data['format_spec']['newarr']){//此商品有规格属性
            if(!empty($shop_id)){
                $specarr = json_decode($data['format_spec']['combination']);
                $specstrarr = array();
                foreach($specarr as $v){
                    if(empty($v))continue;
                    sort($v);$specstrarr[] = implode('_',$v);
                }
                if($specstrarr){
                    $format = array();
                    foreach($specstrarr as $v){
                        $format[$v] = 0;//初始化商品规格库存
                    }
                    $map['goods_stock'] = array('IN',$specstrarr);
                    $result = M('ShopsGoodsStock')->where($map)->field('goods_stock,goods_number')->select();
                    if($result){
                        foreach($result as $k=>$v){
                            $goods_number= floatval($v['goods_number']);
                            $format[$v['goods_stock']] = $goods_number;
                        }
                    }
                    $return['goods_stock_number'] = $format;
                }
            }else{
                $return['goods_stock_number'] = 0;
            }
        }else{
            if($data['sale_type']==1){//组合商品
                $goods_number = $this->get_group_goods_stock($data['id'],$shop_id);
                $format= floatval($goods_number);
                $return['goods_number'] = $goods_number?$goods_number:0;
            }else{
                $format = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                $format= floatval($format);
                $return['goods_number'] = $format?$format:0;
            }
        }
        return $return;
    }
    //获取组合商品的库存
    public function get_group_goods_stock($goodsid,$shop_id){
        $map=array();
        $map['goodsid']=$goodsid;
        $list = M('GroupGoods')->where($map)->field('linkid,attr_key,ratio')->select();
        foreach($list as $k=>$v){
            $map=array();
            $map['goods_id'] = $v['linkid'];
            $map['shop_id'] = $shop_id;
            $map['status'] = 1;
            $goods_number=M('ShopsGoodsStock')->where($map)->getField('goods_number');
            if($goods_number==false){
                $goodsnum[]=0;
            }else{
                $goods_number=floatval($goods_number);
                $goodsnum[]=intval($goods_number/$v['ratio']);
            }
        }
        return min($goodsnum);
    }
    public function get_other($code){
        switch($code){
            case 1:
                $result = array(
                    array('order'=>'','name'=>'默认排序'),
                    array('order'=>'sell_count','name'=>'销量排序'),
                    array('order'=>'money_desc','name'=>'价格由高到低'),
                    array('order'=>'money_asc','name'=>'价格由低到高')
                );
                break;
            case 2:
                $result = array(
                    array('screen_order'=>'1','name'=>'热卖'),
                    array('screen_order'=>'2','name'=>'新品'),
                    array('screen_order'=>'6','name'=>'精品'),
                    array('screen_order'=>'3','name'=>'限时促销'),
                    array('screen_order'=>'4','name'=>'优惠活动'),
                    array('screen_order'=>'5','name'=>'会员专享')
                );
                break;
            default:
                $result = array();
                break;
        }
        return $result;
    }
    /**
     * 获取购物车已经存在的商品
     * @param array $param 用户信息
     * @return array 返回信息
     */
    public function get_cart($param){
        $return = $map = array();
        if($param['uid']&&$param['shop_id']){
            $map['user_id'] = $param['uid'];
            $map['shop_id'] = $param['shop_id'];
            $map['is_valid'] = 1;
            $result = M('Cart')->where($map)->field(true)->select();
            if($result){
                foreach($result as $k=>$v){
                    if(empty($v['goods_attr'])){
                        $key = $v['goods_id'];
                    }else{
                        $list = unserialize($v['goods_attr']);
                        $key = $list['key'];
                        $return[$key]['spec_format'] = $list;
                    }
                    $return[$key]['id'] = $v['goods_id'];
                    $return[$key]['num'] = $v['goods_num'];
                    $return[$key]['price'] = $v['shop_price'];
                }
            }
        }
        return $return;
	}
    public function cont($param){
        $return=array('status'=>1,'msg'=>'');
        if(empty($param['id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        if($param['shop_id']){
            $map=array();
            $map['id']=$param['shop_id'];
            $shop_name=M("Shops")->where($map)->getField('name');
        }else{
            // $shop_name='暂无配送门店';
            $map['id']=1;
            $shop_name=M("Shops")->where($map)->getField('name');// 默认一个门店
        }
        $goods_id=$param['id'];
        $type=$param['type'];
        $goods_info= D("Common/Goods")->get_goods_item($goods_id,$param['rank_id']);
        if($goods_info['status']==0){
            $return['status']=3;
            $return['msg']=$goods_info['msg'];
            return $return;
        }
        //商品相册
        $where['goods_id']=$goods_id;
        $goods_imgs = M("GoodsGallery")->where($where)->select();
        if (empty($goods_imgs)) $goods_imgs[0]['goods_img'] = $goods_info['data']['img'];
        foreach($goods_imgs as $key=>$val){
            $img=format_url($val['goods_img']);
            $img=str_replace('https','http',$img);
            $goods_imgs[$key]['goods_img']=$img;
            //$goods_imgs[$key]['goods_img']=$val['goods_img'];
        }
        //获取商品属性和规格
        $data = D("Common/GoodsAttr")->get_shop_attr($goods_id);
        //评论列表
        $commlist = D('Mobile/Dp')->get_goods('',$goods_id,0);// zjn 3-14
        if($commlist['dp_list']){
            foreach($commlist['dp_list'] as $key=>$val){
                $commlist['dp_list'][$key]['addtime']=time_format($val['addtime']);
                $commlist['dp_list'][$key]['img']=thumb($val['img']);
                if($val['pl_img']){
                    foreach ($val['pl_img'] as $k => $value) {
                        $img=format_url($value);
                        $img=str_replace('https','http',$img);
                        $commlist['dp_list'][$key]['pl_img'][$k]=$img;
                    }
                }
                if(empty($val['username'])){
                    $map=array();
                    $map['id']=$val['uid'];
                    $member_info=M("Member")->where($map)->field('nickname,mobile')->find();
                    if($member_info['nickname']){
                        $commlist['dp_list'][$key]['username']=$member_info['nickname'];
                    }else if($member_info['mobile']){
                        $commlist['dp_list'][$key]['username']=$member_info['mobile'];
                    }else{
                        $commlist['dp_list'][$key]['username']='';
                    }
                }
            }
        }
        $dp_count=$commlist['count_dp']?$commlist['count_dp']:0;//count($commlist['dp_id']);
        //商品最小价格
        $price_info=D('Common/Takeout')->get_min_price($param['shop_id'],$goods_id);
        $goods_info['data']['stock'] = $this->format_stock($param['shop_id'],$param);//根据当前定位的门店信息取出对门店商品库存
        $goods_info['data']['min_price_format']=format_price($price_info['goods_price']);
        $goods_info['data']['min_price']=$price_info['goods_price'];
        $goods_info['data']['goods_imgs']=$goods_imgs;
        // zjn 3-30
        //获取商品基本信息
        //$price_info=D("Common/PromotExt")->get_fight($param['id']);
       /* if($price_info['status']){//拼团
            if($price_info['data']['remarks']){
                $goods_info['data']['pt_remarks']=format_price($price_info['data']['remarks']);
                $goods_info['data']['pt_group_num']=$price_info['data']['group_number'];
                $goods_info['data']['pt_og_count']=$price_info['data']['og_count'];
            }
        }*/
        // ------end--------
        //判断是否收藏
        $where = $map = array();
        //是否收藏
        $map['uid'] = $param['uid'];
        $map['goods_id'] = $goods_id;
        $map['type'] = $type;
        if ($type == 1) {
            $where['goods_id'] = $goods_id;
            $map['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
        }
        $is_collection = M('GoodsCollect')->where($map)->count();
//限时促销
        $return['promat_info']='';
        if($goods_info['data']['promote_id']>0 && NOW_TIME>=$goods_info['data']['promote_start_time'] && NOW_TIME<$goods_info['data']['promote_end_time']){
            $map=array();
            $map['id']=$goods_info['data']['promote_id'];
            $promat_info=M("PromotAct")->where($map)->field(true)->find();
            if($promat_info['shop_id']==0){
                $return['promat_info']=$promat_info;
            }else{
                $shop_ids=array_filter(explode(',',$promat_info['shop_id']));
                if(in_array($param['shop_id'],$shop_ids)){
                    $return['promat_info']=$promat_info;
                }
            }
        }
        /*
            19-6-25 添加
        */
        $member_map['id'] = $param['uid'];
        $rank_id = M("Member")->where($member_map)->getField('rank_id');
        if($goods_info['data']['promote_id']>0 && NOW_TIME>=$goods_info['data']['promote_start_time'] && NOW_TIME<$goods_info['data']['promote_end_time']){
            $map=array();
            $map['id']=$goods_info['data']['promote_id'];
            /* 19-6-26 */
            $map['user_rank'] = array('elt',$rank_id);
            $promat_info=M("PromotAct")->where($map)->field(true)->find();


            // 3-20 参与成员 zjn
            $parr=$oinfo=array();
            $parr['promot_limit_id'] = $goods_info['data']['promote_id'];
            $parr['goods_id'] = $goods_id;
            $ogoods = M('OrderGoods')->where($parr)->getField('order_id',true);
            if($ogoods){
                $farr=implode(',',$ogoods);
                $oinfo['id']=array('IN',$farr);
                $ouid = M('OrderInfo')->where($oinfo)->getField('uid',true);
                if($ouid){
                    $marr=implode(',',$ouid);
                    $ma['id'] = array('IN',$marr);
                    $minfo= M('Member')->where($ma)->field('header_img')->limit(11)->select();
                    foreach ($minfo as $key => $value) {
                        $minfo[$key]['header_img']=format_url($value['header_img']);
                    }
                    if($minfo) $promat_info['joinuser'] = $minfo;
                }
            }
            if(count($minfo)>0) $promat_info['joincount'] = count($minfo);
            else $promat_info['joincount'] = 0;
            // ---end----
            if($promat_info['shop_id']==0){
                $return['promat_info']=$promat_info;
            }else{
                 $shop_ids=array_filter(explode(',',$promat_info['shop_id']));
                if(in_array($param['shop_id'],$shop_ids)){
                    $return['promat_info']=$promat_info;
                }
            }
        }else{
            //3-20新加普通商品  参与人员
            $parr=$oinfo=array();
            $parr['goods_id'] = $goods_id;
            $ogoods = M('OrderGoods')->where($parr)->getField('order_id',true);

            if($ogoods){
                $farr=implode(',',$ogoods);
                $oinfo['id']=array('IN',$farr);
                $ouid = M('OrderInfo')->where($oinfo)->getField('uid',true);
                if($ouid){
                    $marr=implode(',',$ouid);
                    $ma['id'] = array('IN',$marr);
                    $mcount = M('Member')->where($ma)->field('header_img')->count();
                    $minfo= M('Member')->where($ma)->field('header_img')->limit(11)->select();
                    if($minfo) $goods_info['data']['joinuser'] = $minfo;
                }
            }
            if(count($minfo)>0) $goods_info['data']['joincount'] = $mcount;
            else $goods_info['data']['joincount'] = 0;
            unset($parr,$oinfo);
            //---end===
        }
        //优惠活动
        $active_arr=array();
        $activelist=D("Common/Promot")->goods_to_promot($goods_id,0,3,$param['shop_id']);
        if($activelist){
            foreach($activelist['list'] as $key=>$val){
                if($val['style']!=5){
                    $active_arr = $val;
                }

            }
        }
        // 3-18 zjn 服务
        $reds = array();
        if($goods_info['data']['service_ids']){
            $reds['id'] = array('IN',$goods_info['data']['service_ids']);
            $goods_info['data']['goods_service']=M('GoodsService')->where($reds)->field(true)->select();
        }
        //猜你喜欢 zjn
        $return['recommend'] = $this->recommend($param);
        // -------end-------
        //购物车数量
        $map=array();
        $map['user_id']=$param['uid'];
        $cart_num_list=M("Cart")->where($map)->field('goods_num')->select();
        $cart_num = 0;
        foreach($cart_num_list as $k=>$v){
            $cart_num += $v['goods_num'];
        }
        $goods_info['data']['is_collection']=$is_collection;

        $shareimg=$this->getshareimg($goods_info['data'],$param);
        if($shareimg['status']){
            $return['shareimg']=$shareimg['data'];
        }
        //jxr start 2019.1.22
        $g_info=M('Goods')->find($goods_info['data']['id']);
        $re_data=is_sanji($param['uid'],$g_info);  
        $goods_info['data']['fy_price']=format_price($re_data['price']);

        $l_shop_id=intval(idtoname($param['uid'],'LittleShop','id','uid',false));
        $lmap['shop_id']=$l_shop_id;
        $lmap['goods_id']=$param['id'];
        $lg_info=M('LittleShopGoods')->where($lmap)->find();
        $return['lg_info']=$lg_info;
        if($l_shop_id>0) $return['isshop_show']=1;
        //jxr end 2019.1.22
        $return['goods_info']=$goods_info['data'];
        $return['goods_info']['shop_name']=$shop_name;
        $return['goods_attrs']=$data;
        $return['commlist']=$commlist;
        $return['dp_count']=$dp_count;
        $return['activelist']=$active_arr;
        $return['cart_num']=$cart_num?$cart_num:0;
        return $return;
    }
    public function getshareimg($goods,$param){
        $poster=array (
            'width'  => 800,
            'height' => 640,
        );
        $haibao= new \Common\Vendor\Haibao;
        if(empty($goods['img']))$goods['img']=!is_array($goods['goods_imgs'])?$goods['goods_imgs']:$goods['goods_imgs'][0]['goods_img'];
        $goods_img = format_url($goods['img'],2);
        $params=array();
        $red_height=80;
        $img_height=$poster['height']-$red_height;
        $imgx=intval(($poster['width']-$img_height)/2);
        $params[]=array('path_logo'=>$goods_img,'dst_x'=>$imgx,'dst_y'=>0,'imgWidth'=>$img_height,'imgHeight'=>$img_height);
        $size=40;
        $maxwidth=$poster['width']-20;
        if($goods['group_number']>0){//拼团
            $params[]=array('str'=>'rect','posX'=>0,'poxY'=>$img_height,'color'=>'#fe4a49','width' => $poster['width'], 'height' => $red_height);
            $params[]=array('str'=>'抢购价','posX'=>20,'poxY'=>($img_height+30),'size'=>($size-15),'color'=>'white');
            $params[]=array('str'=>format_price($goods['price_info']['goods_price']),'posX'=>110,'poxY'=>($img_height+15),'size'=>$size,'color'=>'white','fontWeight'=>'bold');
            $params[]=array('str'=>format_price($goods['market_price']),'posX'=>350,'poxY'=>($img_height+30),'size'=>($size-15),'color'=>'white','textDecoration'=>'line-through');
            $params[]=array('str'=>$goods['group_number'].'人团','posX'=>500,'poxY'=>($img_height+30),'size'=>($size-15),'color'=>'white');
        }else if($param['promat_info']){//有活动
            $params[]=array('str'=>'rect','posX'=>0,'poxY'=>$img_height,'color'=>'#fe4a49','width' => $poster['width'], 'height' => $red_height);
            $params[]=array('str'=>'抢购价','posX'=>20,'poxY'=>($img_height+30),'size'=>($size-15),'color'=>'white');
            $params[]=array('str'=>$goods['min_price_format'],'posX'=>110,'poxY'=>($img_height+15),'size'=>$size,'color'=>'white','fontWeight'=>'bold');
            $params[]=array('str'=>format_price($goods['market_price']),'posX'=>350,'poxY'=>($img_height+30),'size'=>($size-15),'color'=>'white','textDecoration'=>'line-through');
            $params[]=array('str'=>'还剩'.$goods['stock']['goods_number'].'件','posX'=>500,'poxY'=>($img_height+30),'size'=>($size-15),'color'=>'white');
        }else{//无活动
            $params[]=array('str'=>$goods['min_price_format'],'posX'=>30,'poxY'=>($poster['height']-$size-30),'size'=>$size,'color'=>'red');
            $params[]=array('str'=>format_price($goods['market_price']),'posX'=>500,'poxY'=>($poster['height']-$size-20),'size'=>($size-10),'color'=>'gray','textDecoration'=>'line-through');
        }

        $return['status']=1;
        $return['data']=$haibao->format_mini($params,$poster);
        return $return;
    }
    //推荐商品
    public function recommend($param){
        if(empty($param)) return false;
        $t_arr=$gmap=array();
        $t_arr['id'] = $param['id'];
        $ginfos = M('Goods')->where($t_arr)->field('cat_id')->find();
        $where=array();
        $gmap['cat_id'] = $ginfos['cat_id'];
        // if($ginfos['label_ids']) $where['label_ids']  = array('IN', ltrim($ginfos['label_ids'], ","));
        
        // $where['_logic'] = 'or';
        // $gmap['_complex'] = $where;
        $gmap['status'] = 1;
        $gmap['is_recom'] = 1;
        $gmap['is_delete']=0;//未删除
        $gmap['is_offline']=1;//线上
        // $gmap['id']=array('neq',$param['id']);
        // $gmap['status'] =1;
        // $gmap['_string'] = ' (limit_starttime=0 or limit_starttime<='.NOW_TIME.')  and (limit_endtime=0 or limit_endtime>='.NOW_TIME.') ';

        $jf_ids = M('GoodsIntegral')->where('status=1')->getField('goods_id',true);
        if($jf_ids){
            $jf_ids = implode(',',$jf_ids);
            // $gmap['id']=array('NOTIN',$jf_ids);
            $gmap['id']  = array(array('neq',$param['id']),array('NOTIN',$jf_ids),'and'); 
        }
        $recommend = M('Goods')->where($gmap)->field(true)->order('sort desc,id desc')->select();
        if($recommend){
            foreach($recommend as $k=>$v){
                $recommend[$k]['img'] = thumb($v['img'],167,167,'noimg_186x186.png');
                //215新加
                if($v['is_promote']){//促销
                    $recommend[$k]['is_promote'] =$v['is_promote'];
                    $recommend[$k]['promote_price'] = $v['promote_price'];
                    // $recommend[$k]['promote_number'] = intval($v['goods_max_number'])-intval($v['goods_number']); //已抢
                    // if($v['goods_number']>0) $recommend[$k]['pover_number'] = intval($v['goods_number']); //仅剩
                    // if($v['goods_number']==0) $recommend[$k]['pover_number'] = 0; //仅剩

                    // if($v['goods_number']==-1) $recommend[$k]['pover_number'] = 99999; //仅剩

                    if($v['promote_end_time']<NOW_TIME) $recommend[$k]['is_overdue'] = 1; //活动结束
                    else $recommend[$k]['is_overdue'] = 0;
                    //end
                    unset($oi_ids,$og_count);
                }                    
                if($v['pt_id']){//促销
                    $ptid = M('PromotAct')->where('id='.$v['pt_id'])->field('id,buy_limit,end_time')->find();
                    $pt_arr=array();
                    $pt_arr['act_id'] = $ptid['id'];
                    $pt_arr['style_ext_id'] = $v['id'];
                    $pt_arr['style'] = 4;
                    $pt_money = M('PromotExt')->where($pt_arr)->getField('remarks');
                    $pt_money = unserialize($pt_money);
                    if($pt_money>0) $recommend[$k]['pt_price'] = format_decimal($pt_money,2);
                    $recommend[$k]['pt_id'] = $v['pt_id'];
                    // $result[$k]['goods_number'] = $v['goods_number'];
                    // if($v['goods_number']>0) $recommend[$k]['goods_number'] = intval($v['goods_number']); //仅剩
                    // if($v['goods_number']==-1) $recommend[$k]['goods_number'] = 99999; //仅剩


                    if($ptid['end_time']<NOW_TIME) $recommend[$k]['is_overdue'] = 1; //拼团已过期
                    else $recommend[$k]['is_overdue'] = 0;           
                    //已拼
                    $oarrs=array();
                    $oarrs['pt_id'] = $v['pt_id'];
                    $oarrs['pay_status'] = 3;
                    $oarrs['status'] = array('neq',4);
                    $oarrs['is_delete'] = 0;
                    $oi_ids = M('OrderInfo')->where($oarrs)->getField('id',true);
                    if($oi_ids){
                        $maph = array();
                        $maph['order_id'] = array('in',$oi_ids);
                        $maph['goods_id'] = $v['id'];
                        $og_count = M('OrderGoods')->where($maph)->sum('goods_number');
                    }else{
                        $og_count = 0;
                    }
                    $recommend[$k]['yp_number'] = intval($og_count);
                }
            }
        }
        return $recommend;
    }

    /**获取商品简介
     * @param $param
     */
    public function get_goods_content($param){
        $return=array('status'=>1);
        if(empty($param['id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        $map=array();
        $map['goods_id']=$param['id'];
        $data=M("GoodsContent")->where($map)->getField('content');
       if($data){
           // $return['data']=h($data);
            $content = h($data);
            $baseurl='https://'.$_SERVER['HTTP_HOST'].__ROOT__.'/';
            $str=array('src="/'=>'src="'.$baseurl);
            $content=strtr($content,$str);
            $return['data']=$content;
       }else{
           $return['data']="";
       }
        return $return;
    }
    public function collect_goods($param){
        $return=array('status'=>1);
        if(empty($param['id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }
        $goods_id=$param['id'];
        $uid=$param['uid'];
        $type=$param['type'];
        $collect = M('GoodsCollect');
        $map_co['goods_id'] = $goods_id;
        $map_co['uid'] = $uid;
        $map_co['type'] = $type;
        if ($type == 1) {
            $where['goods_id'] = $goods_id;
            $map_co['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
        }
        $favinfo = $collect->where($map_co)->count();
        if ($favinfo) {
            $favinfo = $collect->where($map_co)->delete();
            $return['status'] = 2;
            $return['msg'] = '取消收藏成功!';
            return $return;
        } else {
            $postdata['goods_id'] = $goods_id;
            $postdata['uid'] = $uid;
            $postdata['addtime'] = NOW_TIME;
            $postdata['status'] = 1;
            $postdata['type'] = $type;
            if ($type == 1) {
                $where['goods_id'] = $goods_id;
                $postdata['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
            }
            $result = $collect->add($postdata);
            if ($result) {
                $return['status'] = 1;
                $return['msg'] = '收藏成功';
            } else {
                $return['status'] = 3;
                $return['msg'] = '收藏失败!';
            }
            return $return;
        }
    }
    public function add_cart($param=array()){
        $return = array('status'=>3,'msg'=>'参数错误');
        $model='Common/Takeout';
		$data=array();
        $shop_id = $param['shop_id'];
        $param['sub_list'] = json_decode(htmlspecialchars_decode($param['sub_list']),true);
        if(empty($param['sub_list'])){
            $return['msg']='请选择商品';
            return $return;
        }
        if(empty($param['shop_id'])){
            $shop_id=get_wxsmall_shop_id();// 默认一个门店
            // $return['msg']='无门店可配送';
            // return $return;
        }
        // zJn无门店
        if(!$shop_id){
            $shop_infos = D('Wxsmall/Login')->setshopid();
            $shop_id = $shop_infos['bind_shop_id'];
        }
        // -----end------
        $param['sub_list']= array_filter($param['sub_list']);
        foreach($param['sub_list'] as $k=>$v){
            $attr_info = '';
            if ($v['spec_format']) {
                $goodsattr_info = array(
                    'key' => $v['spec_format']['key'],
                    'name' => $v['spec_format']['name']
                );
                $attr_info = serialize($goodsattr_info);
            }
            if($param['add_type']=='cont'){
                $map = array();
                $map['user_id'] = $param['uid'];
                $map['shop_id'] = $shop_id;
                $map['goods_id']=$v['id'];
                if($attr_info){
                    $map['goods_attr'] = $attr_info;
                }
                $goods_num = M('Cart')->where($map)->getField('goods_num');
                if($goods_num>0){
                    $v['num'] = $v['num']+$goods_num;
                }
            }
            $map = array();
            $map['goods_id']=$v['id'];
            $map['shop_id']=$shop_id;
            $map['goods_stock']=$v['spec_format']? $v['spec_format']['key'] : 0;
            $sgsinfo=M('ShopsGoodsStock')->where($map)->field(true)->find();
            $map = array();
            $map['id']=$v['id'];
            $goods_info=M('Goods')->where($map)->field('goods_name,img,market_price,goods_sn,cat_id,promote_id,promote_price,promote_start_time,promote_end_time,sale_type,goods_number,sell_count,goods_max_number,goods_min_number,pt_id')->find();
            // zjn -----3-29-----
            $offline=idtoname($v['id'],'Goods','is_offline','id',false);//是否是线上商品
            if($offline==1){
                if(!$param['lshop_id'] && !cookie('lshop_id') && getconfig('REGISTERBUY_OPEN')==0){//不开放购物 并且不是等级会员
                    $return['msg']='请先晋升等级在购买【'.$goods_info['goods_name'].'】';
                    return $return;
                 }
            }
            // ---end---
            if($v['num']<=0){
                $return['msg'] = '请加入商品【'.$goods_info['goods_name'].'】数量';
                return $return;
            }
            if($goods_info['sale_type']==1){//组合商品库存
                $goods_number = $this->get_group_goods_stock($v['id'],$shop_id);
                if($v['num']>$goods_number){
                    $return['msg'] = $goods_info['goods_name'].'【库存不足，库存量'.$goods_number.'】';
                    return $return;
                }
            }else{
                if($sgsinfo){
                    if($v['num']>$sgsinfo['goods_number']){
                        $return['msg'] = $goods_info['goods_name'].'【库存不足，库存量'.$sgsinfo['goods_number'].'】';
                        return $return;
                    }
                }else{
                    $return['msg'] = $goods_info['goods_name'].'【库存不足】';
                    return $return;
                }
            }
            $savedata[$k]['user_id'] = $param['uid'];
            $savedata[$k]['goods_id']=$v['id'];
            $savedata[$k]['shop_id']=$shop_id;
            $savedata[$k]['goods_name']=$goods_info['goods_name'];
            $savedata[$k]['goods_sn']=$goods_info['goods_sn'];
            $savedata[$k]['goods_img']=$goods_info['img'];
            $savedata[$k]['catid']=$goods_info['cat_id'];
            $savedata[$k]['goods_num']=$v['num'];
			$savedata[$k]['goods_attr']=$attr_info;
            $savedata[$k]['is_valid']=1;
            if($v['actgoodsid']>0) {
                $savedata[$k]['actgoodsid'] = $v['actgoodsid'];
            }
			if($v['spec_format']){
				$map = array();
				$map['attr_key'] = $v['spec_format']['key'];
				$map['goods_id'] = $v['id'];
				$price_info['goods_price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
				$price_info['price_type'] = 6;
                $price_info=D('Common/Takeout')->get_min_price($shop_id,$v['id'],'',$v['spec_format']['key']);
			}else{
				$price_info=D('Common/Takeout')->get_min_price($shop_id,$v['id']);//获取商品最终价格
			}
			$savedata[$k]['shop_price']=$price_info['goods_price'];
			$savedata[$k]['all_price']=$v['num']*$price_info['goods_price'];
			$savedata[$k]['price_type'] = $price_info['price_type'];
			$savedata[$k]['cart_type']=3;
//			//活动id
//			if($savedata[$k]['price_type'] == 3){
//				$savedata[$k]['cart_id'] = $price_info['act_id'];
//			}else{
            if($price_info['price_type']==3 || $price_info['price_type'] == 6){
                $map=array();
                $map['id']=$goods_info['promote_id'];
                $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
                // 查询该会员在此活动下已购数量
                $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$v['id']);
                $p_num=$v['num']+$p_num;
                if($goods_info['goods_min_number']>0 && intval($p_num) > intval($goods_info['goods_min_number'])){
                    //$return['msg'] = '该商品为促销商品，您已达到购买量';
                    $return['msg'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                    return $return;
                }

                //总限量
                $p_num=D("Common/Takeout")->pro_num($promote_info,'',$v['id'],1);
                $p_num=$v['num']+$p_num;
                if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                    $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                    return $return;
                }
            }
            if($goods_info['pt_id']){
                $map=array();
                $map['id']=$goods_info['pt_id'];
                $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();

                $p_num=D("Common/Takeout")->pro_num($promote_info,$param['uid'],$v['id']);
                $p_num=$v['num']+$p_num;
                if($promote_info['buy_limit']>0 && intval($p_num) > $promote_info['buy_limit']){
                    //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                    $return['msg'] = "本拼团单人限量".$promote_info['buy_limit']."您已超过单人限量";
                    $return['status'] = 0;
                    return $return;
                }
                //总限量
                $p_num=D("Common/Takeout")->pro_num($promote_info,'',$v['id'],1);
                $p_num=$v['num']+$p_num;
                if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                    $return['msg'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                    return $return;
                }
            }
			$ret = D('Common/Promot')->goods_to_promot($v['id'],0,$savedata[$k]['cart_type'],$shop_id);
			if($ret['count'] > 0){
				$act_info = current($ret['list']);
				$savedata[$k]['cart_id'] = $act_info['id'];
//				}
			}
        }
        if($param['add_type']!='cont'){
            $map = array();
            $map['user_id'] = $param['uid'];
            $map['shop_id'] = $shop_id;
            M('Cart')->where($map)->delete();
        }
        if($param['add_type']=='cont'){
            foreach($savedata as $k=>$v){
                $map = array();
                $map['user_id'] = $param['uid'];
                $map['shop_id'] = $shop_id;
                $map['goods_id']=$v['goods_id'];
                $map['goods_attr']=$v['goods_attr'];
                $cart_count=M("Cart")->where($map)->count();
                if($cart_count>0){
                    $result = M('Cart')->where($map)->save($v);
                }else {
                    $result = M('Cart')->add($v);
                }
            }
        }else {
            foreach ($savedata as $k => $v) {
                $result = M('Cart')->add($v);
            }
        }
        if($result){
            $map=array();
            $map['user_id']=$param['uid'];
            $cart_num_list=M("Cart")->where($map)->field('goods_num')->select();
            $cart_num = 0;
            foreach($cart_num_list as $k=>$v){
                $cart_num += $v['goods_num'];
            }
            $return['status'] = 1;
            $return['cart_num'] = $cart_num;            
            $return['msg'] = '操作成功';
        }
        return $return;
    }
    public function get_cart_total_info($uid){
        //购物车数量
        $map=array();
        $map['user_id']=$uid;
        $cart_num_list=M("Cart")->where($map)->field('goods_num,shop_price')->select();
        $cart_num = 0;
        $cart_total_price=0;
        foreach($cart_num_list as $k=>$v){
            $cart_num += $v['goods_num'];
            $cart_total_price += $v['goods_num']*$v['shop_price'];
        }
        $return['cart_num']=$cart_num;
        $return['cart_total_price']=format_decimal($cart_total_price);
        return $return;
    }
    //219图文分享海报
    public function cont_tgercode($param){        
        $return=array('status'=>1);
        if(empty($param['id'])){
            $return['status']=3;
            $return['msg']='参数错误';
            return $return;
        }        
        $img = goods_shots($param['uid'],0,$param['id'],$param['lshop_id']);
        return $img;
    }


    //219图文分享海报
    public function cont_tgercodes($param,$is_small=true){
        $return =array('status'=>3,'msg'=>'');
        if(empty($param['id'])){
            $return['msg']='参数错误';
            return $return;
        }
        if($param['is_pt']) $type=$param['is_pt'];
        else $type=0;


        //$img = cont_tgercode($param['id'],$param['invite_key'],'',$type);

        $id=intval($param['id']);$uid=$invite_key=$param['invite_key'];


        $garr=array();
        $garr['status'] = 1;
        $garr['id'] = $id;
        $goods_info = M('Goods')->where($garr)->field(true)->find();
        $show_price = share_name($id,1);
        $cont_price = $show_price*100;
        $yuan_img = ROOT_PATH.'/uploads/image/qrcode/bg.jpg';
        $sell_count = sell_count($id);
        $temp = '已售出'.$sell_count.'份';
        $old_cache_f='';
        $data=array(
            'new_img'=>$yuan_img,
            'goods_img'=>$goods_info['img'],
            'title'=>$goods_info['goods_name'],
            'temp'=>$temp,
            'price_market'=>format_decimal($show_price),
            'price_member'=>$goods_info['market_price'],
        );
        $lshop_id=$param['lshop_id'];
        if($is_small){
            if ($type > 0) $param['path'] = "spellgroup/pages/fightgroup/cont/cont?id=" . $id . "&invite_key=" . $invite_key . "&dg_id=" . $invite_key.'&lshop_id='.$lshop_id;
            else $param['path'] = "pages/takeout/cont/cont?id=" . $id . "&invite_key=" . $invite_key . "&dg_id=" . $invite_key.'&lshop_id='.$lshop_id;

            $codeImg = ROOT_PATH . '/uploads/image/wx_img/' . md5($param['path']) . '_goods_code.jpg';
            //$param['width']=150;//小程序参数
            if (!file_exists($codeImg)) {
                $wxsmall = new \Common\Vendor\Wxsmallopen;
                $result = $wxsmall->get_location_small_code($param);
                preg_match('/(.*)base64,(.*)/', $result, $matches);//print_r($matches);exit;
                $base64 = $matches['2'];
                $base64 = base64_decode($base64);
                //            print_r($matches);
                if (!empty($base64)) {
                    @file_put_contents($codeImg, $base64);
                } else {
                    $return['msg'] = "网络不给力,请稍后再试";
                    return $return;
                }
            }
        }else {
            // 如果是小店店主
            if(cookie('lshop_id')){
                $lshop_id=cookie('lshop_id');
            }
            if($lshop_id){
                $lshop_id=$lshop_id;
                $url=U('Mobile/goods/goods_cont',array('id'=>$id,'eid'=>$uid,'lshop_id'=>$lshop_id),true,true);
                $codeImg = phpgrcode(urlencode($url),'M','3','decca_'.$lshop_id.'_'.$uid);//生成之后的图

            }else{
                $url=U('Mobile/goods/goods_cont',array('id'=>$id,'eid'=>$uid,),true,true);
                $codeImg = phpgrcode(urlencode($url),'M','3','decca_'.'_'.$uid);//生成之后的图
            }
        }
        $backImg = $data['new_img'];
        $new =  format_url($data['new_img'],2);
        $goods_img = format_url($data['goods_img'],2);
        $haibao= new \Common\Vendor\Haibao;
        $params=array();
        $iinfo=getimagesize($new);$imgWidth=$iinfo[0];
        if($codeImg)$params[]=array('path_logo'=>format_url($codeImg),'dst_x'=>100,'dst_y'=>980,'imgWidth'=>210,'imgHeight'=>210);
        $params[]=array('path_logo'=>$goods_img,'dst_x'=>147,'dst_y'=>193,'imgWidth'=>430,'imgHeight'=>430);
        $size=35;
        $maxwidth=intval(($imgWidth*0.7));
        $params[]=array('str'=>$data['title'],'posX'=>100,'poxY'=>670,'lineHeight'=>($size+30),'size'=>$size,'color'=>'black','maxLines'=>2,'width' => $maxwidth, 'textAlign' => 'center');
        // print_r($params);exit;
        $params[]=array('str'=>'￥','posX'=>225,'poxY'=>790,'size'=>($size-5),'color'=>'red');
        $params[]=array('str'=>$data['price_market'],'posX'=>253,'poxY'=>782,'size'=>$size,'color'=>'red');
        $strlength=$haibao->checkStrlength($data['price_market'],$size);
        $danweix=253+$strlength;
        $params[]=array('str'=>'','posX'=>$danweix,'poxY'=>782,'size'=>$size,'color'=>'red');
        $moneygray=$danweix+45;
        $params[]=array('str'=>'￥'.$data['price_member'],'posX'=>$moneygray,'poxY'=>782,'size'=>$size,'color'=>'gray','textDecoration'=>'line-through');
        if($data['temp']){
            $centerx=$haibao->getcenterx($data['temp'],$size,$imgWidth);
            $params[]=array('str'=>$data['temp'],'posX'=>$centerx,'poxY'=>870,'size'=>$size,'color'=>'black');
        }

        $poster=array (
            'background' => $data['new_img'],
            'width'=>$iinfo[0],
            'height'=>$iinfo[1],
        );
        $return['status']=1;
        $return['data']=$haibao->format_mini($params,$poster);

        return $return;
    }
}
