<?php
/**
 * 外卖模型
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <1094186793@qq.com>
 */

namespace Common\Model;
use Think\Model;
class TakeoutModel extends Model
{
    protected $tableName = 'goods';
    public function _initialize(){
        parent::_initialize ();
        $siteinfo=session('siteinfo')?session('siteinfo'):cookie('siteinfo');
        $siteinfo=$siteinfo?$siteinfo:(session('geo')?session('geo'):cookie('geo'));
        $siteinfo['temp_lng']=$siteinfo['temp_lng']?$siteinfo['temp_lng']:$siteinfo['xpoint'];
        $siteinfo['temp_lat']=$siteinfo['temp_lat']?$siteinfo['temp_lat']:$siteinfo['ypoint'];
        $siteinfo['temp_name']=$siteinfo['temp_name']?$siteinfo['temp_name']:$siteinfo['street'];
        unset($siteinfo['xpoint'],$siteinfo['ypoint'],$siteinfo['street']);
        session('siteinfo',$siteinfo);
    }
    /**
     * 获取外卖分类
     */
    public function get_takeout_category_list(){
        GLOBAL $TakeoutCategory;
        if (empty($TakeoutCategory)) $TakeoutCategory=getcache('TakeoutCategory');
        $takeout_category=array();
        foreach($TakeoutCategory as $k=>$v){
            if($v['pid']==0){
                $takeout_category[$v['id']]['id']=$v['id'];
                $takeout_category[$v['id']]['pid']=$v['pid'];
                $takeout_category[$v['id']]['name']=$v['name'];
            } else{
                $takeout_category[$v['pid']]['child'][$v['id']]['id']=$v['id'];
                $takeout_category[$v['pid']]['child'][$v['id']]['pid']=$v['pid'];
                $takeout_category[$v['pid']]['child'][$v['id']]['name']=$v['name'];
            }
        }
        return $takeout_category;
    }
    /**
     *门店列表
     *@return array
     */
    public function get_shops_list($map=array(),$join='',$order='',$p=1,$pagesize=0){
        $module = 'ShopsAccount';
        $join = '';$field = true;$geo=true;
        $map = $order = $result = array();

        if($geo){
            $result = $this->get_position_temp_param();
            if($result['append_field'])$field = array();
            $order = $result['order'];
            $field = $result['append_field'];
        }
        $map['g.status'] = 1;
        $map['a.status'] = 1;
        $map['a.pid'] = 0;
        $join = 'LEFT JOIN __SHOPS__ g ON g.id=a.shop_id';
        // dump($field);exit;
        $result = page_list($module,$map,$order,$field,0,$join);

        if(!empty($result['list'])){
            foreach($result['list'] as $ke=>$va){
                $va['per_avg_point']=($va['avg_point']/5)*100;
                $va['delivery']=$this->get_shops_delivery($va['id'],$va['distance']);
                $result['list'][$ke]=$va;
            }
        }
        return $result;
    }




    /**
     * 获取按距离排序参数  外卖临时数据
     * @param $alias str 表别名
     */
    public function get_position_temp_param($alias='g'){
        $siteinfo=session('siteinfo')?session('siteinfo'):cookie('siteinfo');
        $xpoint=$siteinfo['temp_lng'];
        $ypoint=$siteinfo['temp_lat'];
        // dump($xpoint);dump($ypoint);exit;
        $return = array();
        if($xpoint>0){
            $pi = PI();  //圆周率
            $r = 6378137;  //地球平均半径(米)
            $return['append_field'] = array("(ACOS(SIN(($ypoint * $pi)/180)*SIN(($alias.ypoint*$pi)/180 )+COS(($ypoint*$pi)/180 )* COS(($alias.ypoint*$pi)/180)*COS(($xpoint*$pi)/180-($alias.xpoint*$pi)/180))*$r)"=>"distance",'g.*');
            $return['order'] = array("distance"=>"asc");
        }else{
            $return['order'] = array("$alias.id"=>"desc");
        }
        return $return;
    }

    /**
     * 检查门店信息
     * @param $shop_id
     * @return array
     */
    public function check_location($shop_id){
        $return=$l_map=array();$return['status']=1;
        if(empty($shop_id)){
            $return['status']=0;$return['info']='仓库是空的';
        }
        $l_map['sa.shop_id']=$shop_id;

        $shops_info = M('ShopsAccount')->alias('sa')
            ->join('__SHOPS__ s on s.id = sa.shop_id')
            ->where($l_map)
            ->field('s.xpoint,s.ypoint,sa.shop_id,sa.status,sa.description,s.id,s.name,s.thumb,s.business_hours_start,s.business_hours_end,s.address,s.content,s.business_week_start,s.business_week_end')
            ->find();
        if($shops_info['status'] == 0){
            $return['status']=0;
            $return['info']='仓库未通过审核或者该仓库不存在';
        }else{
            $return['shops_info']=$shops_info;
        }

        return $return;
    }

    /**
     * 获取门店信息
     * @param $shop_id
     * @return array
     */
    public function get_shops_info($shop_id){
        $return=array();
        $return['status']=1;
        $shops = $this->check_location($shop_id);
        if($shops['status']==0){
            return $shops;
        }else{
            $shops_info = $shops['shops_info'];
            // $shops_info['per_avg_point']=($shops_info['avg_point']/5)*100;
            /*$shops_info['is_collect']=D('Common/Shops')->is_shops_collect($shop_id);
            $shops_info['location_active']=$this->get_shops_active($shop_id);
            $location_active=$shops_info['location_active'];
            //活动json开始
            $location_active['is_payonlinediscount']=$location_active['is_payonlinediscount']?$location_active['is_payonlinediscount']:array();
            krsort($location_active['is_payonlinediscount']);
            $location_active['is_payonlinediscount'] = array_values($location_active['is_payonlinediscount']);
            $shops_info['location_active_json']=json_encode($location_active);
            //活动json结束*/
            $return['shops_info'] = $shops_info;
        }
        return $return;
    }
    /**
     * 获取门店参与的平台活动
     * @param $shop_id
     * @param $act_id 活动id
     * @return array
     */
    public function get_shops_active($shop_id,$act_id){
        $return = array();
        if($shop_id){
            $s_where=array();
            $s_where['id']=1;
            $s_where['status']=1;
            $s_where['_string'] = "shop_id like '%,".$shop_id.",%' OR shop_id='0'";
            $s_config_ser=M('TakeoutPromote')->where($s_where)->getField('config');
            if(!empty($s_config_ser)){
                $s_config_info=unserialize($s_config_ser);
                $return['is_firstorderdiscount']=$s_config_info;
                $return['is_firstorderdiscount']['dec']='首单立减'.$s_config_info['discount_amount'].'元';
            }

            $m_where=array();
            $m_where['id']=2;
            $m_where['status']=1;
            $m_where['_string'] = "shop_id like '%,".$shop_id.",%' OR shop_id='0'";
            $config_ser=M('TakeoutPromote')->where($m_where)->getField('config');
            if(!empty($config_ser)) {
                $config_info = unserialize($config_ser);
                $return['is_payonlinediscount']=array();
                foreach($config_info as $ke=>$va){
                    $return['is_payonlinediscount'][$ke]['discount_limit']=$ke;
                    $return['is_payonlinediscount'][$ke]['discount_amount']=$va;
                    $return['is_payonlinediscount'][$ke]['dec'] = '满'.$ke.'元减'.$va.'元';
                }
                ksort($return['is_payonlinediscount']);
            }
        }
        return $return;
    }

    /**
     * 获取门店下的外卖商品
     * @param $shop_id
     * @return array
     */
    public function get_shops_goods_list($shop_id){
        $return=$category=$tl_map=$t_map=array();
        if(empty($shop_id)){$return['status']=0;return $return;}
        $return['status']=1;
        $tl_map['shop_id']=$shop_id;
        $tl_map['goods_number']=array('gt',0);
        $goodsids=M('ShopsGoodsStock')->where($tl_map)->getField('goods_id',true);//该门店下首页商品id
        $goods_ids = array_unique($goodsids);
        if(empty($goods_ids)){$return['status']=0;return $return;}
        $t_map['id']=array('in',$goods_ids);
        $t_map['goods_type']=5;
        $t_map['status']=1;
        $t_map['is_delete']=0;
        $goods_list=M('Goods')->where($t_map)->field(true)->order('sort asc')->select();
        if(empty($goods_list)){
            $return['status']=0;
            return $return;
        }
        foreach($goods_list as $k=>$v){
            $category[] = $v['cat_id'];
            $v['shop_id']=$shop_id;
            $goods_list[$k]=$this->format_takeout_item($v);
        }
        $return['goods_list']=$goods_list;
        $category_ids = array_unique($category);
        if(empty($category_ids)){$return['status']=0;return $return;}
        $tc_map['id']=array('in',$category_ids);
        $tc_map['status']=1;
        $category_list=M('PurchaseCategory')->where($tc_map)->field(true)->order('sort asc')->select();
        if(empty($category_list)){$return['status']=0;return $return;}
        foreach($category_list as $k=>$v){
            $return['category'][$v['id']]=$v;
        }
        return $return;
    }
    /**
     * 获取所有的外卖商品
     * @param $shop_id
     * @return array
     */
    public function get_goods_list($order_arr = array(),$is_format=1){
        $return=$t_map=$where=array();
        $return['status'] = 1;
        if($order_arr){
            if($order_arr['childcatid']){
                $t_map['cat_id'] = $order_arr['childcatid'];
            }else{
                if (!empty($order_arr['catid'])) {
                    GLOBAL $PurchaseCategory;
                    if(empty($PurchaseCategory))$PurchaseCategory=getcache('PurchaseCategory');
                    $catinfo = $PurchaseCategory[$order_arr['catid']];
                    $extension_goods_id = get_extension_goods($catinfo['allson'], 1);
                    if (!empty($catinfo['allson'])) $where['cat_id'] = array('in', $catinfo['allson']);
                    if (!empty($extension_goods_id)) $where['id'] = array('in', $extension_goods_id);
                    if (!empty($where)) {
                        $where['_logic'] = 'or';
                        $t_map['_complex'] = $where;
                        unset($t_map['cat_id']);
                    } else {
                        $t_map['cat_id'] = $order_arr['catid'];
                    }
                }
            }
            
            if($order_arr['order'] == 'sell_count'){
                $order = 'sell_count desc,id desc';
            }else if($order_arr['order'] == 'money_desc'){
                $order = 'shop_price desc,id desc';
            }else if($order_arr['order'] == 'money_asc'){
                $order = 'shop_price asc,id desc';
            }
            $order_arr['screen_order'] = array_unique(explode(',',$order_arr['screen_order']));
            if(in_array('1',$order_arr['screen_order'])){
                $t_map['is_hot'] = 1;
            }else if(in_array('2',$order_arr['screen_order'])){
                $t_map['is_new'] = 1;
            }else if(in_array('3',$order_arr['screen_order'])){
                $t_map['is_promote'] = 1;
                $t_map['promote_id'] = array('gt',0);
                $t_map['promote_start_time'] = array('elt',NOW_TIME);
                $t_map['promote_end_time'] = array('egt',NOW_TIME);
            }else if(in_array('4',$order_arr['screen_order'])){
                $where = array();
                $where['id'] = array('gt',0);
                $where['start_time'] = array('elt',NOW_TIME);
                $where['end_time'] = array('egt',NOW_TIME);
                $cat_ids = M('PromotAct')->where($where)->getField('id',true);
                $t_map['id'] = '';
                if($cat_ids){
                    $p_map = array();
                    $p_map['act_id'] = array('in',$cat_ids);
                    $p_map['style'] = 3;
                    $goods_ids = M('PromotExt')->where($p_map)->getField('style_ext_id',true);
                    if($goods_ids)$t_map['id'] = array('in',$goods_ids);
                }
            }else if(in_array('5',$order_arr['screen_order'])){
                $map = array();
                $map['goods_id'] = array('gt',0);
                $goods_ids = M('MemberPrice')->where($map)->getField('goods_id',true);
                $t_map['id'] = '';
                if($goods_ids)$t_map['id'] = array('in',$goods_ids);
            }else if(in_array('6',$order_arr['screen_order'])){
                $t_map['is_best'] = 1;
            }
            
            if($order_arr['brand_order']){
                $brand_order=array_filter(explode(',',$order_arr['brand_order']));
                if($brand_order)$t_map['brand_id'] =count($brand_order)==1?implode($brand_order): array('in',$brand_order);
            }
            if($order_arr['keyword']){
                $t_map['goods_name'] = array('like','%'.$order_arr['keyword'].'%');
            }
        }
        if(empty($order)){$order = 'sort asc,id desc';}
        $t_map['goods_type']=5;
        $t_map['status']=1;
        $t_map['publish_wait'] = 1;
        $t_map['is_delete']=0;
        $t_map['is_internet']=1;
        $t_map['is_offline']=1;//线上
        $t_map['is_jinsheng']=0;
        $pagesize=20;
        $pagesize = empty($pagesize) ? C('WEB_GOODS_PAGE') : $pagesize;
        $p = $order_arr['p'];
        $p = empty($p) ? 1 : $p;        
        $goods_list=page_list("Goods",$t_map,$order,true,$pagesize,'',$p);
        if(empty($goods_list)){
            $return['status']=0;
            $return['g_status']=0;
            return $return;
        }
        if($goods_list['list']){
            $return['g_status']=1;
            foreach($goods_list['list'] as $k=>$v){
                if($is_format==1) {
                    $goods_list['list'][$k] = $this->format_takeout_item($v);
                }
            }
        }
        $return['goods_list']=$goods_list;
        $return['page']=$p;
        return $return;
    }
    /**
     * 获取门店下的热卖商品
     * @param $shop_id
     * @return array
     */
    public function get_hot_goods_list($shop_id){
        $return=$tl_map=$t_map=array();
        $return['status'] = 0;
        $return['msg'] = '';
        if(empty($shop_id)){$return['msg'] = '参数获取错误!';return $return;}

        $tl_map['shop_id']=$shop_id;
        $tl_map['is_hot']=1;
        $goods_ids=M('ShopsGoods')->where($tl_map)->getField('goods_id',true);//该门店下首页商品id

        if(empty($goods_ids)){return $return;}
        $t_map['g.id']=array('in',$goods_ids);
        $t_map['goods_type']=5;
        $t_map['is_delete']=0;
        $t_map['sg.status']=1;
        $t_map['sg.shop_id']=$shop_id;
        $t_map['sg.goods_number']=array('gt',0);
        $hot_list = M('Goods')->alias('g')
            ->join('__SHOPS_GOODS_STOCK__ sg on g.id = sg.goods_id')
            ->where($t_map)->field('g.*,sg.sell_count s_sell_count')->order('g.sort asc')->select();

        if(empty($hot_list)){
            return $return;
        }else{
            foreach($hot_list as $k=>$v){
                $v['shop_id']=$shop_id;
                $hot_list[$k]=$this->format_takeout_item($v);

            }
            $return['status'] = 1;
            $return['data'] = $hot_list;
        }
        return $return;
    }
    /**
     * 获取门店下的代金券
     * @param $shop_id
     * @return array
     */
    public function get_shops_bonu_list($shop_id){
        $return = $c_map = array();
        $return['status'] = 0;
        $return['msg'] = '';
        if(empty($shop_id)){$return['msg'] = '参数获取错误!';return $return;}
        $member_info = checkuserauthtype();
        if(empty($member_info)){$return['msg'] = '没有登陆!';return $return;}
        $c_map['use_end_date'] = array(array('gt',time()));
        $c_map['every_num'] = array('neq',0);
        $c_map['bonu_type'] = 2;
        $c_map['_string'] = "shop_id like '%,".$shop_id.",%' OR shop_id='0'";
        $coupons_list=M('Bonu')->where($c_map)->field(true)->order('id asc')->select();

        $where_cg=array();
        $where_cg['user_id'] = $member_info['id'];
        $where_cg['used_time'] = 0;
        $where_cg['order_id'] = 0;
        $where_cg['bonus_type'] = 2;
        $where_cg['start_time'] = array('lt',NOW_TIME);
        $where_cg['end_time'] = array('gt',NOW_TIME);
        if(empty($coupons_list)){
            return $return;
        }else{
            foreach ($coupons_list as $k => $v) {
                $where_cg['bonus_id'] = $v['id'];
                $coupons_list[$k]['status'] = M('MemberBonus')->where($where_cg)->count();//判断是否领取
            }
            $return['status'] = 1;
            $return['data']=$coupons_list;
        }
        return $return;
    }
    /**
     * 获取门店下的限时促销商品
     * @param $shop_id
     * @return array
     */
    public function get_promote_goods_list($shop_id){
        $return=$tl_map=$g_map=$goods_ids=array();
        $return['status'] = 0;$return['msg'] = '';
        if(empty($shop_id)){$return['msg'] = '参数获取错误！';}

        $g_map['shop_id'] = $shop_id;
        $g_map['goods_number']=array('gt',0);
        $goodsids=M('ShopsGoodsStock')->where($g_map)->getField('goods_id',true);//该门店下首页商品id
        if(empty($goodsids)){return $return;}
        $goods_ids = array_unique($goodsids);

        $tl_map['status'] = 1;
        $tl_map['start_time'] = array('elt',NOW_TIME);
        $tl_map['end_time'] = array('gt',NOW_TIME);
        $tl_map['_string']="shop_id like '%,".$shop_id.",%' OR shop_id='0'";
        $act_id = M('PromotAct')->where($tl_map)->order('end_time desc')->getField('id');

        if($act_id){
            $t_map=array();
            $t_map['id']=array('in',$goods_ids);
            $t_map['goods_type']=5;
            $t_map['status']=1;
            $t_map['is_delete']=0;
            $t_map['promote_id']=$act_id;
            $t_map['is_promote']=1;
            $t_map['promote_start_time']=array('elt',NOW_TIME);
            $t_map['promote_end_time']=array('gt',NOW_TIME);
            $promote_list=M('Goods')->where($t_map)->field(true)->order('sort asc')->select();

            if(empty($promote_list)){
                return $return;
            }else{
                foreach($promote_list as $k=>$v){
                    $v['shop_id']=$shop_id;
                    $promote_list[$k]=$this->format_takeout_item($v);

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

    /**
     * 获取门店下的服务
     * @param $shop_id
     * @return array
     */
    public function get_shops_service_list($shop_id){
        $return=$tl_map=$t_map=array();

        $map['status']=1;
        $map['is_delete']=0;
        $map['publish_wait']=1;
        $map['goods_type'] = 4;
        $shop_ids = $shop_id.",0";
        $map['shop_id'] = array('IN',$shop_ids);

        $service_list=M('Goods')->field('id,goods_name,img,shop_price,sell_count')->where($map)->select();//该门店下服务
        if(empty($service_list)){
            return $return;
        }
        $return=$service_list;
        return $return;
    }

    /**
     * 获取某门店某商品信息
     * @param $id
     * @param $shop_id
     * @return array
     */
    public function get_goods_info($id,$shop_id){
        $return=$sg_map=$g_map=array();
        $return['status']=1;
        $g_map['id'] = $id;
        $goods_info=M('Goods')->where($g_map)->field(true)->find();
        if(!$goods_info){$return['status']=0;$return['info']='该商品已下架';}
        if($goods_info['goods_type'] != 5){$return['status']=0;$return['info']='该商品不是外卖';}
        elseif($goods_info['is_delete'] == 1){$return['status']=0;$return['info']='该商品已删除';}
        elseif($goods_info['status']==0){$return['status']=0;$return['info']='该商品已下架';}
        elseif($goods_info['publish_wait']==0){$return['status']=0;$return['info']='该商品未审核';}
        elseif($goods_info['publish_wait']==2){$return['status']=0;$return['info']='该商品未通过审核';}
        else{
            $sg_map['goods_id']=$id;
            $sg_map['shop_id']=$shop_id;
            $sg_info=M('ShopsGoods')->where($sg_map)->getField('goods_id');
            if(empty($sg_info)){$goods_info['is_add'] = 0;}
            else{$goods_info['is_add'] = 1;}

            $goods_info['shop_id']=$shop_id;
            $goods_info=$this->format_takeout_item($goods_info);
           
            $return['goods_info']=$goods_info;
        }
        return $return;
    }

    /**
     * 格式化外卖商品信息
     * @param $data
     * @return mixed
     */
    public function format_takeout_item($data){
        $return=$data;
        $data['to_spec'] = array();
        $shop_id = get_wxsmall_shop_id();
        $return['format_shop_price']=format_price($data['shop_price'],false,'<em>¥</em>');
        $return['f_shop_price']=format_price($data['shop_price'],false,'¥');
        $return['format_market_price']=format_price($data['market_price']);
        $return['format_promote_price']=format_price($data['promote_price']);
        $return['is_promote']=$data['is_promote'];
        $price_info=$this->get_min_price($shop_id,$data['id']);
        $return['price_info']=$price_info;
        $return['end_price']=$price_info['goods_price'];
        $return['format_end_price']=format_price($return['end_price']);
        $goods_number=D("Common/Cart")->shopgoodsstock($data['id'],$shop_id,'');
        $return['goods_number']=$goods_number['goods_number'];
        $xmap = array();
        $xmap['goods_id']=$data['id'];
        $xmap['shop_id'] = $shop_id;
        $sellcount=M("ShopsGoodsStock")->where($xmap)->getField('sell_count');
        $sell_count=$sellcount?$sellcount:0;
        $return['sell_count']=floatval($sell_count);
        //判断已抢光
        if($data['is_promote']){// 限时促销
            $return['is_promote'] =$data['is_promote'];
            $return['promote_number'] = intval($data['goods_max_number'])-intval($data['goods_number']); //已抢
            if($data['goods_number']>0) $return['pover_number'] = intval($data['goods_number']); //仅剩
            if($data['goods_number']==0) $return['pover_number'] = 0; //仅剩
            if($data['goods_number']==-1) $return['pover_number'] = 99999; //仅剩
            if($data['promote_end_time']<NOW_TIME) $return['is_overdue'] = 1; //活动结束
            else $return['is_overdue'] = 0;
            $discount=format_decimal($price_info['goods_price']/$data['shop_price']*10,1);
            $return['discount_mark']='限时'.$discount.'折';
            //end
        }
        if($data['pt_id']){
            $ptid = M('PromotAct')->where('id='.$data['pt_id'])->field('id,buy_limit,end_time,group_number')->find();
            $return['pt_id'] = $data['pt_id'];
            $pt_arr=array();
            $pt_arr['act_id'] = $ptid['id'];
            $pt_arr['style_ext_id'] = $data['id'];
            $pt_arr['style'] = 4;
            $pt_money = M('PromotExt')->where($pt_arr)->getField('remarks');
            $pt_money = unserialize($pt_money);
            if($pt_money>0) $return['pt_price'] = format_decimal($pt_money,2);
            // $result[$k]['goods_number'] = $v['goods_number'];
            if($data['goods_number']>0) $return['goods_number'] = intval($data['goods_number']); //仅剩
            if($data['goods_number']==-1) $return['goods_number'] = 99999; //仅剩
            if($ptid['end_time']<NOW_TIME){
                $return['is_ptdue'] = 1; //拼团已过期
            }else{
                $return['is_ptdue'] = 0;
            }
            $return['pin_mark']=$ptid['group_number'].'人团';
        }

        $memberinfo = checkuserauthtype();
        if (!empty($memberinfo)) {
            $c_map = array();
            $c_map['is_valid'] = 1;
            $c_map['user_id'] = $memberinfo['id'];
            $c_map['goods_id'] = $data['id'];
            $c_map['shop_id'] = $shop_id;
            $cart_num=M('Cart')->where($c_map)->getField('goods_num');
        }
        $return['format_spec'] = D("Common/GoodsAttr")->get_shop_attr($data['id']);
        $return['cart_num'] = $cart_num ? $cart_num : 0;
        return $return;
    }

    /**
     * 获取在某门店的购物车外卖商品列表
     * @param $shop_id
     * @param array $address_arr
     * @param array $ids 选中的购物车id
     * @return array
     */
    public function get_cart_goods_list($shop_id,$address_arr=array(),$ids=''){
        $return=$c_map=array();$return['status']=1;
        $shops=$this->check_location($shop_id);
        if($shops['status']==0){return $shops;}
        $return['is_firstorder']=1;
        //配送信息
        $return['delivery']=$this->get_shops_delivery($shop_id,$address_arr);
        if($address_arr && $return['delivery']['status']==0){
            $return=$return['delivery'];return $return;
        }
        $return['cart_count']=$return['cart_total_price']=0;
        $memberinfo = checkuserauthtype();
        if ($memberinfo) {
            $c_map['user_id']=$memberinfo['id'];
        } else {
            $c_map['user_id'] = 0;
            $c_map['cookie_id'] = $this->getcookieid();
        }
        if($ids){
            $c_map['id']=array('in',$ids);
        }
        $c_map['cart_type'] = 3;
        $c_map['is_valid'] = 1;
        $c_map['shop_id'] = $shop_id;
        $return['cart_list'] = M('Cart')->where($c_map)->field(true)->select();
        $return['total_integral_price']=0;
        foreach ($return['cart_list'] as $k => $v) {
            $return['cart_count'] += $v['goods_num'];
            $return['cart_total_price'] += $v['all_price'];
            $return['cart_list'][$k]['cart_goods_attr'] = unserialize($v['goods_attr']);
            $is_integral=idtoname($v['goods_id'],'Goods','is_integral');
            $return['cart_list'][$k]['is_integral']=$is_integral;
            if($is_integral==0){$return['total_integral_price']+=$v['all_price'];}
        }
        $return['ids'] = M('Cart')->where($c_map)->getField('id',true);
        //包装费信息
        $return['package']=$this->get_shops_package($shop_id);
        /*//包装费（餐盒费）
        if(floatval($return['cart_total_price'])>floatval($return['package']['package_start_price'])){
            $return['lunch_box_price']=0;
        }else {
            $return['lunch_box_price'] = format_decimal(floatval($return['package']['package_price']) * intval($return['cart_count']));
        }
        $return['cart_total_price']=format_decimal(floatval($return['cart_total_price'])+floatval($return['lunch_box_price']));*/
        /*$location_active=$this->get_shops_active($shop_id);
        $cart_active=array();
        if(!empty($location_active['is_payonlinediscount'])){
            foreach($location_active['is_payonlinediscount'] as $k=>$v){
                // 满足最高满减活动
                if(floatval($v['discount_limit'])<=floatval($cart_total_price)){
                    $cart_active=$v;continue;
                }
            }
            $cart_total_price=format_decimal(floatval($cart_total_price)-floatval($cart_active['discount_amount']));
            // if($cart_active['discount_amount'] > 0){
                // $return['cart_active'][]=2;
            // }
        }
        $return['promot_list']['is_payonlinediscount']=$cart_active;
        if(!empty($location_active['is_firstorderdiscount'])){
            if(!empty($memberinfo)) {
                $map=array();$map['uid']=$memberinfo['id'];$map['type']=14;
                $order_count=M('OrderInfo')->where($map)->count();
                if($order_count>0){
                    $return['is_firstorder']=0;
                }else{
                  if(floatval($cart_total_price)>floatval($location_active['is_firstorderdiscount']['discount_amount'])){
                      $cart_total_price=format_decimal(floatval($cart_total_price)-floatval($location_active['is_firstorderdiscount']['discount_amount']));
                      // $return['cart_active'][]=1;
                    }
                }
            }
        }
        $return['promot_list']['is_firstorderdiscount']=$location_active['is_firstorderdiscount'];*/
        $cart_total_price=format_decimal(floatval($return['cart_total_price']));
        //差多少元起送
        $return['cart_differences']=format_decimal(floatval($return['delivery']['start_price'])-floatval($return['cart_total_price']));
        $cart_total_price=(floatval($cart_total_price)>0)?$cart_total_price:0;
        // $return['cart_minus_price']=format_decimal(floatval($return['cart_total_price'])-floatval($cart_total_price));
        $return['cart_minus_price']=0;//已优惠多少钱；$return['cart_total_price']是没优惠前购物车总额
        /*计算具体优惠开始
        $cart_minus_price=$return['cart_minus_price'];//php里计算具体优惠使用
        if(floatval($cart_minus_price)>floatval($cart_active['discount_amount'])){
            $cart_minus_price=floatval($cart_minus_price)-floatval($cart_active['discount_amount']);
            $return['promot_list']['is_firstorderdiscount']['discount_amount']=format_decimal($cart_minus_price);
        }else{
            $return['promot_list']['is_payonlinediscount']['discount_amount']=format_decimal($cart_minus_price);
            $return['promot_list']['is_firstorderdiscount']['discount_amount']=0;
        }*/
        /*计算具体优惠结束*/
        // $return['all_total_price']=format_decimal(floatval($return['cart_total_price'])+floatval($return['delivery']['delivery_price']));//订单总额
        $return['all_total_price']=format_decimal(floatval($return['cart_total_price']));//订单总额
        $return['cart_price']=format_decimal($cart_total_price);//购物车费用（不包括邮费）
        // $return['order_total_price']=format_decimal(floatval($cart_total_price)+floatval($return['delivery']['delivery_price']));//订单需支付
        $return['order_total_price']=format_decimal(floatval($cart_total_price));//订单需支付
        return $return;
    }

    /**
     * 门店配送信息（取最近）
     * @param $shop_id
     * @param $address_id   //会员收货地址坐标(如果要用，之前先判断好)
     * @return array
     */
    public function get_shops_delivery($shop_id,$distance,$address_arr=array()){
        $d_map=$return=array();
        $d_map['shop_id']=$shop_id;
        // $distance = D('Common/Shops')->get_member_account_distance($shop_id);
        $distance=intval($distance);
        // $d_map['scale']=array('egt',round($distance/1000));

        $delivery=M('ShopsDelivery')->where($d_map)->field(true)->order('scale asc')->find();
        $return=$delivery;$return['status']=1;
        if(empty($delivery)){
            if($address_arr){
                $return=array();$return['status']=0;
                $return['info']='此地址不在配送区域';
                return $return;
            }else {
                $return['shop_id'] = $shop_id;
                $return['start_price'] = 0;
                $return['delivery_price'] = 0;
            }
        }
        $return['distance']=$distance;
        if($return['distance']>0){
            if($return['distance']>1500){
                $return['distance']=round($return['distance']/1000)."km";;
            }else{
                $return['distance']=round($return['distance'])."m";
            }
        }
        $return['shop_id'] = $shop_id;
        $return['format_start_price']=format_price($delivery['start_price'],false,'');
        $return['format_delivery_price']=format_price($delivery['delivery_price'],false,'');
        return $return;
    }

    /**
     * 根据门店配送信息 计算运费
     * @param $shop_id
     * @param $area_id
     * @param $cartlist 购物车列表
     * @param $allprice 商品总金额
     * @param $configure 配送费
     * @param $type 1同城配送2快递
     * @return array
     */
    public function get_shops_deliveryfee($shop_id,$addre_id,$cartlist,$allprice,$configure,$type,$distance=0){
        $d_map=$return=array();
        if($type==2){
//            判断快递是否配送
            $res = D('Common/Cart')->shipping_fee($allprice, $cartlist, $configure);//获取每个店铺的运费
            $return['status']=1;
            $return['shop_id'] = $shop_id;
            $return['start_price'] = 0;
            $return['delivery_price'] = $res;

        }else{
            $d_map['shop_id']=$shop_id;
            $delivery=M('ShopsDelivery')->where($d_map)->field(true)->order('scale asc')->find();
            if($delivery['start_price'] > 0 && $allprice >= $delivery['start_price']){
                $delivery['delivery_price']=0;
            }else{
                $distance1=$distance/1000;
                if($distance1> $delivery['scale']){
                    $delivery2=M('ShopsDelivery')->where($d_map)->field(true)->order('scale asc')->select();
                    foreach($delivery2 as $k=>$v){
                        if($distance1 < $v['scale']){
                            $delivery['delivery_price']=$v['delivery_price'];
                            break;
                        }
                    }
                }
            }
            $return=$delivery;$return['status']=1;
            $return['shop_id'] = $shop_id;
            $return['format_start_price']=format_price($delivery['start_price'],false,'');
            $return['format_delivery_price']=format_price($delivery['delivery_price'],false,'');
        }
        return $return;
    }
    /**
     * 门店包装费
     * @param $shop_id
     * @return array|mixed
     */
    public function get_shops_package($shop_id){
        $p_map=$return=array();
        $p_map['shop_id']=$shop_id;
        $package=M('ShopsPackage')->where($p_map)->field(true)->find();
        $return=$package;
        $return['format_package_price']=format_price($package['package_price'],false,'');
        $return['format_package_start_price']=format_price($package['package_start_price'],false,'');
        return $return;
    }

    /**
     * 添加购物车
     * @param $param
     * @return array
     */
    public function add_cart_item($param){
        $return=array();$return['status'] = 1;
        if($param['is_wxsmall']){
            $map=array();
            $map['id']=$param['uid'];
            $memberinfo=M("Member")->where($map)->field(true)->find();
        }else{
            $memberinfo = checkuserauthtype();
        }
        $c_map=$s_map=$g_map=$s_data=$cc_map=array();$modelname='Cart';
        $c_map['goods_id']=$param['goods_id'];
        // zjn  2-21 
        if($param['HCshopid']){
            $shop_id=$param['HCshopid'];
        }else{
            $shop_id=get_wxsmall_shop_id();
        }
        // ajn --- end---
        if(!$shop_id){
            $return['info'] = '无仓库可配送!';
            $return['status'] = 0;
            return $return;
        }
        $c_map['shop_id']=$shop_id;
        $s_map=$c_map;
        if ($memberinfo) {
            $s_data['user_id'] = $memberinfo['id'];
            $shop_uid=idtoname($shop_id,'Shops','uid');
            if($shop_uid==$memberinfo['id']){
                $return['info'] = '不允许购买自己店铺的商品！请使用其他账号购买！';
                $return['status'] = 0;
                return $return;
            }
            $c_map['user_id']=$memberinfo['id'];
        } else {
            $s_data['user_id'] = 0;
            $s_data['cookie_id'] = $this->getcookieid();
        }
        $c_map['cart_type']=3;
        $c_map['is_valid']=1;
        $cc_map=$c_map;

        //判断商品是否有属性
        $goods_attr_data = D('Common/GoodsAttr')->getattr($param['goods_id']);
        if($goods_attr_data['newarr']){
            if(empty($param['spec'])){
                $return['info'] = '请选择商品规格';
                $return['status'] = 0;
                $return['app_data'] ='open_attr';
                return $return;
            }
        }
        if ($param['spec']) {
            $goodsattr_info = array(
                'key' => $param['spec'],
                'name' => $param['name']
            );
            $attr_info = serialize($goodsattr_info);
        }
        $s_map['goods_stock']=$param['spec'] ? $param['spec'] : 0;
        $sg_info=D("Common/Cart")->shopgoodsstock($param['goods_id'],$shop_id,$s_map['goods_stock']);
        // 3-29 zjn
        // if($sg_info){
        //     $g_map['id']=$param['goods_id'];
        //     $goods_info=M('Goods')->where($g_map)->field('goods_name,img,market_price,goods_sn,cat_id,promote_id,promote_price,promote_start_time,promote_end_time')->find();
        // }else{
        //     $return['info'] = '没有该规格商品';
        //     $return['status'] = 0;
        //     return $return;
        // }
        if($sg_info['goods_number']){
            $g_map['id']=$param['goods_id'];
            $goods_info=M('Goods')->where($g_map)->field('goods_name,img,market_price,goods_sn,cat_id,promote_id,promote_price,promote_start_time,promote_end_time,goods_number,sell_count,goods_max_number,goods_min_number,pt_id')->find();
        }else{
            $return['info'] = $sg_info['info'];
            $return['status'] = 0;
            return $return;
        }
        // ----zjn  end---
        $count=0;
        $cart_num=0;if(!empty($param['num'])){$cart_num=$param['num'];}
        if(empty($cart_num)){
            $return['info'] = '请加入商品数量';
            $return['status'] = 0;
            return $return;
        }
        $cc_map['goods_attr']=$param['spec'] ? $attr_info : 0;

        $cart=M($modelname)->where($cc_map)->field('id,goods_num')->find();
        if($cart){
            if($param['is_cart']){
                $s_data['goods_num']=$cart_num;
            }else {
                if ($param['is_add'] == 1) {
                    $s_data['goods_num'] = $cart['goods_num'] + $cart_num;
                } else {
                    $s_data['goods_num'] = $cart['goods_num'] - $cart_num;
                }
            }
            if($param['is_add'] == 1 && $s_data['goods_num'] > 0){
                if($sg_info['goods_number'] < $s_data['goods_num']){
                    $return['info'] = '库存不足!';
                    $return['status'] = 0;
                    return $return;
                }
            }
            if($s_data['goods_num'] == 0){
                $count = M($modelname)->where($cc_map)->delete();
            }else {
                if($param['spec']){
                    $map = array();
                    $map['attr_key'] = $param['spec'];
                    $map['goods_id'] = $param['goods_id'];
                   // $price_info['goods_price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
                   // $price_info['price_type'] = 6;
                    $price_info=D('Pad/Cashier')->get_min_price($shop_id,$param['goods_id'],$memberinfo,$param['spec']);
                }else{
                    $price_info=$this->get_min_price($shop_id,$param['goods_id'],$memberinfo);//获取商品最终价格
                }
                // $price_info=$this->get_min_price($shop_id,$param['goods_id']);//获取商品最终价格
                $s_data['shop_price']=$price_info['goods_price'];
                $s_data['all_price']=$s_data['goods_num']*$price_info['goods_price'];
                $s_data['price_type'] = $price_info['price_type'];
                $s_data['is_valid']=1;
                if($price_info['price_type']==3){
                    $map=array();
                    $map['id']=$goods_info['promote_id'];
                    $map['start_time'] = array('elt',NOW_TIME);
                    $map['end_time'] = array('egt',NOW_TIME);
                    $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
                    // 查询该会员在此活动下已购数量
                    $p_num=$this->pro_num($promote_info,$memberinfo['id'],$param['goods_id']);
                    $p_num=$s_data['goods_num']+$p_num;
                    if($goods_info['goods_min_number']>0 && intval($p_num) > $goods_info['goods_min_number']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['info'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=$this->pro_num($promote_info,$memberinfo['id'],$param['goods_id'],1);
                    $p_num=$s_data['goods_num']+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['info'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        $return['status'] = 0;
                        return $return;
                    }
                }
                if($goods_info['pt_id']){
                    $map=array();
                    $map['id']=$goods_info['pt_id'];
                    $map['start_time'] = array('elt',NOW_TIME);
                    $map['end_time'] = array('egt',NOW_TIME);
                    $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
                    $p_num=$this->pro_num($promote_info,$memberinfo['id'],$param['goods_id']);
                    $p_num=$s_data['goods_num']+$p_num;
                    if($promote_info['buy_limit']>0 && intval($p_num) > $promote_info['buy_limit']){
                        //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                        $return['info'] = "本拼团单人限量".$promote_info['buy_limit']."您已超过单人限量";
                        $return['status'] = 0;
                        return $return;
                    }
                    //总限量
                    $p_num=D("Common/Takeout")->pro_num($promote_info,'',$param['goods_id'],1);
                    $p_num=$s_data['goods_num']+$p_num;
                    if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                        $return['info'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                        return $return;
                    }
                }
                $ret = D('Common/Promot')->goods_to_promot($param['goods_id'],0,$s_data['cart_type'],$shop_id);
                if($ret['count'] > 0){
                    $act_info = current($ret['list']);
                    $s_data['cart_id'] = $act_info['id'];// 活动id
                }
                $count = M($modelname)->where($cc_map)->save($s_data);
            }
            $return['cart_id']=$cart['id'];
            $return['cart_num']=$s_data['goods_num'];
        }else{
            if($cart_num > 0){
                if($sg_info['goods_number'] < $cart_num){
                    $return['info'] = '库存不足!';
                    $return['status'] = 0;
                    return $return;
                }
            }
            $s_data['goods_id']=$param['goods_id'];
            $s_data['shop_id']=$shop_id;
            $s_data['goods_name']=$goods_info['goods_name'];
            $s_data['goods_sn']=$goods_info['goods_sn'];
            $s_data['goods_img']=$goods_info['img'];
            $s_data['catid']=$goods_info['cat_id'];
            $s_data['goods_num']=$cart_num;
            $s_data['goods_attr']=$attr_info;

            if($param['spec']){
                $map = array();
                $map['attr_key'] = $param['spec'];
                $map['goods_id'] = $param['goods_id'];
//                $price_info['goods_price'] = M('GoodsAttrStock')->where($map)->getField('attr_price');
//                $price_info['price_type'] = 6;
                $price_info=D('Pad/Cashier')->get_min_price($shop_id,$param['goods_id'],$memberinfo,$param['spec']);
            }else{
                $price_info=$this->get_min_price($shop_id,$param['goods_id']);//获取商品最终价格
            }
            // $price_info=$this->get_min_price($shop_id,$param['goods_id']);//获取商品最终价格
            $s_data['shop_price']=$price_info['goods_price'];
            $s_data['all_price']=$s_data['goods_num']*$price_info['goods_price'];
            $s_data['price_type'] = $price_info['price_type'];
            $s_data['cart_type']=3;
            $s_data['is_valid']=1;
            if($price_info['price_type']==3){
                $map=array();
                $map['id']=$goods_info['promote_id'];
                $map['start_time'] = array('elt',NOW_TIME);
                $map['end_time'] = array('egt',NOW_TIME);
                $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
                // 查询该会员在此活动下已购数量
                $p_num=$this->pro_num($promote_info,$memberinfo['id'],$param['goods_id']);
                $p_num=$s_data['goods_num']+$p_num;
                if($goods_info['goods_min_number']>0 && intval($p_num) > $goods_info['goods_min_number']){
                    //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                    $return['info'] = "本活动单人限量".$goods_info['goods_min_number']."您已超过单人限量";
                    $return['status'] = 0;
                    return $return;
                }
                //总限量
                $p_num=$this->pro_num($promote_info,$memberinfo['id'],$param['goods_id'],1);
                $p_num=$s_data['goods_num']+$p_num;
                if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                    $return['info'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                    $return['status'] = 0;
                    return $return;
                }
            }
            if($goods_info['pt_id']){
                $map=array();
                $map['id']=$goods_info['pt_id'];
                $map['start_time'] = array('elt',NOW_TIME);
                $map['end_time'] = array('egt',NOW_TIME);
                $promote_info=M('PromotAct')->where($map)->field('buy_limit,start_time,end_time')->find();
                $p_num=$this->pro_num($promote_info,$memberinfo['id'],$param['goods_id']);
                $p_num=$s_data['goods_num']+$p_num;
                if($promote_info['buy_limit']>0 && intval($p_num) > $promote_info['buy_limit']){
                    //$return['info'] = '该商品为促销商品，您已达到单人购买量';
                    $return['info'] = "本拼团单人限量".$promote_info['buy_limit']."您已超过单人限量";
                    $return['status'] = 0;
                    return $return;
                }
                //总限量
                $p_num=D("Common/Takeout")->pro_num($promote_info,'',$param['goods_id'],1);
                $p_num=$s_data['goods_num']+$p_num;
                if($goods_info['goods_max_number']>=0 && intval($p_num)>intval($goods_info['goods_max_number'])){
                    $return['info'] = $goods_info['goods_name'].'【已超过总限量，总限量'.$goods_info['goods_max_number'].'】';
                    $return['status'] = 0;
                    return $return;
                }
            }
            $ret = D('Common/Promot')->goods_to_promot($param['goods_id'],0,$s_data['cart_type'],$shop_id);
            if($ret['count'] > 0){
                $act_info = current($ret['list']);
                $s_data['cart_id'] = $act_info['id'];// 活动id
            }
            $count=M($modelname)->add($s_data);
            $return['cart_id']=$count;
            $return['cart_num']=$s_data['goods_num'];
            $return['goods_price']=$price_info['goods_price'];
            $return['pt_id']=$goods_info['pt_id'];
            $return['p_num']=$p_num;
            $return['goods_max_number']=$goods_info['goods_max_number'];
            $return['buy_limit']=$promote_info['buy_limit'];
        }
        if($count < 0){
            $return['info'] = '操作失败';
            $return['status'] = 0;
        }
        return $return;
    }

    /**
     * 清空外卖购物车
     * @param $param
     * @return array
     */
    public function clear_cart_item($param){
        $return=array();$return['status'] = 1;
        $param['shop_id']=session('main_shop_id');
        $memberinfo = checkuserauthtype();
        if (empty($memberinfo)) {
            $return['info'] = '请登录';
            $return['status'] = 0;
            $return['url'] = getjumpurl('JUMP_1');
            return $return;
        }
        $c_map=array();$modelname='Cart';
        $c_map['user_id']=$memberinfo['id'];
        if($param['cart_id']){
            $c_map['id']=$param['cart_id'];
            $cart=M($modelname)->where($c_map)->getField('goods_id');
            $return['goods_id']=$cart;
        }else {
            $c_map['shop_id'] = $param['shop_id'];
            if(!empty($param['goods_id'])){$c_map['goods_id'] = $param['goods_id'];}
            $cart=M($modelname)->where($c_map)->count();
        }
        $count=0;
        if($cart > 0){
            $count = M($modelname)->where($c_map)->delete();
        }
        if($count < 0){
            $return['info'] = '操作失败';
            $return['status'] = 0;
        }
        return $return;
    }

    /**
     * 获取某门店订单信息
     * @param $shop_id
     * @return array
     * @return $ids
     */
    public function get_order_info($shop_id,$addre_id,$ids=''){
        $return=array();$return['status'] = 1;
        $memberinfo = checkuserauthtype();
        if(empty($memberinfo)){
            $return['status']=0;$return['info']='请重新登录';
            $return['url']=getjumpurl('JUMP_1');return $return;
        }
        $shops_info=$this->get_shops_info($shop_id);
        if($shops_info['status']==0){$return['status']=0;$return['info']=$shops_info['shops_info'];return $return;}
        $return['memberinfo']=$memberinfo;
        $return['shops_info']=$shops_info['shops_info'];
        $return['address_info']=D('Member')->get_address_list('','','','',C('MEMBER_RECRIVE_ADDRESS_NUM'));
        $return['addr_info']=$this->get_order_address($return['address_info']['list'],$shop_id,$addre_id);//默认的收货地址
        $return['cart_info']=$cart_info=$this->get_cart_goods_list($shop_id,$return['addr_info']['address_info'],$ids);
        $return['service_time']=$this->get_service_time($cart_info['package']['to_time'],$shops_info['shops_info']['business_hours_start'],$shops_info['shops_info']['business_hours_end'],$shops_info['shops_info']['business_week_start'],$shops_info['shops_info']['business_week_end']);
        return $return;
    }

    /**
     * 配送时间数组
     * @param $to_time  单位是分钟
     * @param $start_time  门店营业开始时间点
     * @param $end_time  门店营业结束时间点
     * @param $week_start  门店营业开始时间
     * @param $week_end  门店营业结束时间
     * @return array
     */
    public function get_service_time($to_time,$starttime,$endtime,$week_start,$week_end){
        $return=array();
        $time=NOW_TIME;
        $week_start=substr($week_start,3);
        $week_end=substr($week_end,3);
        $weekarray=array("日","一","二","三","四","五","六");
        foreach($weekarray as $k=>$v){
            if($week_start == $v){
                $start_week = $k;
            }
            if($week_end == $v){
                $end_week = $k;
            }
        }
        $date=date('Y-m-d',$time);
        $daystarttime=strtotime(("$date $starttime"));
        if($daystarttime>$time){
            $start_time=$daystarttime;
        }else{
            $start_time=$time;
        }
        if($endtime){
            $end_time=strtotime("$date $endtime");
        }else{
            $end_time=strtotime("$date 23:59:59");
        }
        if(date("w") >= $start_week && date("w") <= $end_week && $time<$end_time){
            $res = '立即配送';
        }elseif(date("w") >= $start_week && date("w") <= $end_week && $time>=$end_time){
            if(date("w") == 6){
                $res = "周".$weekarray[date("0")];
            }else{
                $res="周".$weekarray[date("w")+1];
            }
            $day=1;
            $besttime=date('Y-m-d',strtotime('+$day day'));
            $start_time=strtotime("$besttime $starttime");
            $end_time=strtotime("$besttime $endtime");
        }elseif(date("w") < $start_week || date("w") > $end_week){
            $res = "周".$weekarray[date($start_week)];
            if(date("w") < $start_week){
                $day=$start_week-date("w");
            }else{
                $day=6-$end_week+$start_week-1;
            }
            $besttime=date('Y-m-d',strtotime("+$day day"));
            $start_time=strtotime("$besttime $starttime");
            $end_time=strtotime("$besttime $endtime");
        }

        for ($start = $start_time; $start <= $end_time; $start += 1800) {
            if($start == $start_time){
                $return[$start]['start']=$res;
            } else {
                $return[$start]['start']=date("H:i", $start);//配送时间
            }
            $return[$start]['end']=date("H:i", $start + $to_time * 60);//预计送达时间
        }
        return $return;
    }

    /**
     * seo_title
     * @param $param
     * @return array
     */
    public function takeout_seo_info($param){
        $seotitle = $seokeywords = $seodescription = '';
        $return = array();
        if($param['action_name']=='index'){
            $seotitle .= '外卖_';
        }elseif($param['action_name']=='lists'){
            if($param['coid']){
                $coname=idtoname($param['coid'],'TakeoutCategory');
                $seotitle .= $coname.'_';
            }
            if($param['cid']){
                $cname=idtoname($param['cid'],'TakeoutCategory');
                $seotitle .= $cname.'_';
            }
            $seotitle .= '外卖_';
        }elseif($param['action_name']=='location_index'){
            $location_name=idtoname($param['id'],'ShopsLocation');
            $seotitle .= $location_name.'_外卖_';
        }elseif($param['action_name']=='location_info'){
            $location_name=idtoname($param['id'],'ShopsLocation');
            $seotitle .= $location_name.'_外卖_';
        }elseif($param['action_name']=='order'){
            $location_name=idtoname($param['shop_id'],'ShopsLocation');
            $seotitle .= $location_name.'_订单_外卖_';
        }
        $seotitle .= C('WEB_SITE_TITLE');
        $return['tplseo_keywords'] = $seokeywords;
        $return['tplseo_description'] = $seodescription;
        $return['tplseo_title'] = $seotitle;
        return $return;
    }
    //获取cookieid
    private function getcookieid()
    {
        $cookie_id = cookie('u_cookieid');
        if (empty($cookie_id)) {
            $cookie_id = md5(NOW_TIME . C("HANCHAO_KEY"));
            cookie('u_cookieid', $cookie_id, time() + 3600);
        }
        return $cookie_id;
    }
    /**
     * 获取会员购买店铺商品时是否有代金券
     * @param $shopid 店铺id
     * @param $goodstotalmoney 商品总金额
     * @param $totalmoney 订单总金额
     * @return array
     */
    public function mcouponsget($shopid,$goodstotalmoney,$totalmoney){
        if(empty($shopid)){
            return false;
        }
        $return=array();
        $where=$where_cg=array();
        $where['shop_id'] = array('like','%,'.$shopid.',%');
        $where['shop_id'] = 0;
        $where['_logic'] = 'or';
        $where_cg['_complex'] = $where;
        $where_cg['min_goods_money'] = array('elt',$goodstotalmoney);
        $where_cg['money'] = array('lt',$totalmoney);
        $member_info = checkuserauthtype();
        if($member_info){
            $where_cg['user_id'] = $member_info['id'];
            $where_cg['used_time'] = 0;
            $where_cg['bonus_type'] = 2;
            $where_cg['start_time'] = array('lt',NOW_TIME);
            $where_cg['end_time'] = array('gt',NOW_TIME);
            $return['cg_total'] = M('MemberBonus')->where($where_cg)->count();
            $return['cg_list'] = M('MemberBonus')->where($where_cg)->select();
        }
        return $return;

    }
    /**
     * 获取商品最小价格
     * @$memberinfo array('is_tmp'=>1,'id'=>0))
     */

    public function get_min_price1($shop_id,$goods_id,$memberinfo='',$attr_key=''){
        return D('Pad/Cashier')->get_min_price($shop_id,$goods_id,$memberinfo,$attr_key);
    }

    public function get_min_price($shop_id,$goods_id,$memberinfo='',$attr_key=''){
        return D('Pad/Cashier')->get_min_price($shop_id,$goods_id,$memberinfo,$attr_key,1);
    }
    /**
     * 订单选择的收货地址
     * @param $address_list 会员的所有收货地址
     * @param int $shop_id  店铺id
     * @param int $addre_id 选择的收货地址id
     * @return array
     */
    public function get_order_address($address_list,$shop_id=0,$addre_id=0){
        $return=array();$return['status']=0;
        if(empty($address_list)){$return['status']=0;$return['msg']='添加收货地址';return $return;}
        if(empty($shop_id)){$return['status']=2;$return['msg']='店铺参数错误';return $return;}
        foreach($address_list as $key=>$val){
            if($val['xpoint']>0 && $val['ypoint']>0){
                $distribution_area=D('Wxsmall/Login')->judge_shop($val['xpoint'],$val['ypoint'],$shop_id);
                if($distribution_area['status']==3){
                    $dis[$val['id']]=3;
                }else if($distribution_area['status']==1 && $distribution_area['send']==1){
                    $dis[$val['id']]=1;
                }elseif($distribution_area['status']==1 && $distribution_area['send']==2){
                    $dis[$val['id']]=2;
                }
            }

            if(!empty($addre_id)){
                if($val['id']==$addre_id) {
                    $return['address_info'] = $val;
                }
            }elseif($val['status']==1){
                $return['address_info']=$val;
            }
            //如果上面还没有给address_info赋值，那就把当前val默认给address_info
            if(empty($return['address_info'])){$return['address_info']=$val;}
        }
        $return['status']=$dis[$return['address_info']['id']];
        if($return['status']==3){
            if(in_array('1',$dis)){
                $return['status']=1;
                $return['msg']='该地址不在配货区域，请切换收货地址';
            }elseif(in_array('2',$dis)){
                $return['status']=2;
                $return['msg']='该地址不在配货区域，请切换收货地址';
            }else{
                $return['msg']='您的地址均不在配送范围内，请添加新地址';
            }
        }
        return $return;
    }
    /**
     * 订单详情页活动、优惠券、满减显示
     * @param $ids 活动id 数组
     * @param $orderid 订单id
     * @return array
     */
    public function getpromote($ids,$orderid){
        $return=array();
        foreach($ids as $k=>$v){
            $promote = idtoname($v,'PromotAct','act_name,act_type_ext,act_type,max_amount,min_amount,is_addup','id',false);
            $map=array();
            $return[$v]['name']=$promote['act_name'];
            $return[$v]['act_type']=$promote['act_type'];
            $map['order_id']=$orderid;
            $map['promot_id']=$v;
            $map['goods_type']=0;
            $goodsalmoney = M('OrderGoods')->where($map)->sum('goods_price*goods_number');
            switch($promote['act_type']){
                case 1:
                    if ($promote['is_addup'] == 1) {
                        if (!empty($promot_info['max_amount']) && $goodsalmoney >= $promote['max_amount']) {
                            $demo_prices = $promote['max_amount'];
                        }
                        if($promote['max_amount']==0){
                            $demo_prices=$goodsalmoney;
                        }
                        if ($promote['min_amount'] > 0) $act_type_ext = (floor($demo_prices / $promote['min_amount']) * $promote['act_type_ext']);
                    } else {
                        $act_type_ext=$promote['act_type_ext'];
                    }
                    $return[$v]['money']=$act_type_ext;
                    break;
                case 2:
                    $return[$v]['money']=$goodsalmoney*(1-$promote['act_type_ext']/100);
                    break;
                default:
                    $return[$v]['money']=0;
                    break;

            }
        }
        return $return;
    }
    /**
     * 计算限时促销商品 会员已购数量
     * @param $act_array 活动数组
     * @param $uid 会员id
     * @param $goods_id
     * @return array
     */
    public function pro_num($act_array,$uid,$goods_id,$is_all=0){
        $map=array();
        $map['status'] = array('in','1,2,3,6,8');
        $map['pay_status'] = 3;
        $map['type'] = array('in','1,6,11,12,13,14');
        $map['is_delete']=0;
        if($is_all==0){
            $map['uid']=$uid;
        }
        $map['addtime']=array('between',array($act_array['start_time'],$act_array['end_time']));
        $order_id=M('OrderInfo')->where($map)->getField('id',true);
        if($order_id){
            $map=array();
            $map['order_id']=array('in',$order_id);
            $map['goods_id']=$goods_id;
            $p_num = M('OrderGoods')->where($map)->sum('goods_number');
        }else{
            $p_num=0;
        }
        return $p_num;
    }
    /**
     * 检查限时促销商品
     * @param $act_array 活动数组
     * @param $uid 会员id
     * @param $goods_id
     * @return array
     */
    public function check_pro_num($postdata=array()){
        $map=array();
        $map['status'] = array('in','1,2,3,6,8');
        $map['pay_status'] = 3;
        $map['type'] = array('in','1,6,11,12,13,14');
        $map['is_delete']=0;
        if($is_all==0){
            $map['uid']=$uid;
        }
        $map['addtime']=array('between',array($act_array['start_time'],$act_array['end_time']));
        $order_id=M('OrderInfo')->where($map)->getField('id',true);
        if($order_id){
            $map=array();
            $map['order_id']=array('in',$order_id);
            $map['goods_id']=$goods_id;
            $p_num = M('OrderGoods')->where($map)->sum('goods_number');
        }else{
            $p_num=0;
        }
        return $p_num;
    }
}
?>