<?php
/**
 * 店铺营销
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <zhao@qq.com>
 */

namespace Shop\Controller;
use Think\Controller;
class PromotController extends BaseController {
	public function _initialize()
    {
        parent::_initialize();
        $shops_info=session('shops_info');
        if(empty($shops_info['id']))$this->error('身份过期，请重新登录',U('Shop/Register/shop_login'));
		$this->mendian();
        $map=array();
        $map['id']=$shops_info['shop_id'];
        $shop_type=M("Shops")->where($map)->getField('shop_type');
        $this->assign('shop_type',$shop_type);
        // 1117 ggw
         $suc=D('Shops')->shop_option(MID,'promot');
        if(!$suc){$this->error('该店铺没有此权限，请联系管理员授权！');die;}
    }
	//限时促销
    public function index(){
		$postdata=I('param.');
		$tabid=$postdata['tabid'];
        if(empty($tabid)){
			$list=D('Shop/Promot')->sale_list();
			foreach($list['list'] as $k=>$v){
				if($v['is_part'] == 1){
					if(in_array(MID, array_filter(explode(',',$v['shop_id'])))){
						$list['list'][$k]['is_cy'] = 0;
					}else{
						$list['list'][$k]['is_cy'] = 1;
					}
				}
			}
			$this->assign($list);
		}elseif($tabid=='add_sale'){
			$return=D('Shops')->option(7,STYPE);
			if($return == 0){
				$this->error('你还没添加限时促销的权限，请联系管理员！');
				$tabid = 'index';
			}
		}elseif($tabid=='show_sale'){
			if($postdata['id']){
				$act_info = M('PromotAct')->field(true)->find($postdata['id']);
				$this->assign($act_info);
				$map['promote_id']=$act_info['id'];
				$list=M('Goods')->where($map)->field('id,goods_name,market_price,promote_price')->select();
				$this->assign("list",$list);
				$this->assign($postdata);
			}
		}
		
        $this->assign('menu_tab','');
		$tabid=$tabid?$tabid:'index';
        $this->display($tabid);
    }
	//获取限时促销信息
	public function get_promot_info(){
		$act_id=I('param.act_id');
		$map_p['id']=$act_id;
		$info=M('PromotAct')->where($map_p)->field('id,start_time,end_time')->find();
		$data['start_time']=time_format($info['start_time']);
		$data['end_time']=time_format($info['end_time']);
	
		$map_g['promote_id']=$act_id;
		$list=M('Goods')->where($map_g)->field('id,goods_name,market_price,promote_price')->select();
		$html = '';
		foreach($list as $k=>$v){
			$html .= "<tr id='tr_".$v['id']."'><td class='ta_c'>".$v['goods_name']."</td><td class='ta_c'>".$v['market_price']."</td><td class='ta_c'>".$v['promote_price']."</td></tr>";
		}
		$data['act_id'] = $act_id;
		$data['list'] = $html;
		$this->ajaxReturn($data);
	}
	//获取代金券信息
	public function get_bonu_info(){
		$coupons_id=I('param.coupons_id');
		$map_p['id']=$coupons_id;
		$info=M('Coupons')->where($map_p)->field('id,reduce_cost,least_cost,type,quantity,use_limit,get_limit,begin_timestamp,end_timestamp,fixed_term,fixed_begin_term,add_time')->find();
		$info['begin_timestamp']=time_format($info['begin_timestamp']);
		$info['end_timestamp']=time_format($info['end_timestamp']);
		$info['add_time']=time_format($info['add_time']);

		$data['coupons_id'] = $coupons_id;
		$data['info'] = $info;
		$this->ajaxReturn($data);
	}
	//搜索商品
	public function ajaxgetgoods(){
        $result=array();
		if(!MID){$this->ajaxReturn($result);}
		$map_id['shop_id']=MID;
		$map_id['status']=1;
		$ids = M("ShopsGoods")->where($map_id)->getField('goods_id',true);
		$keyword=I('keyword');
		if(is_numeric($keyword)){
            $map['id|goods_name']=array(intval($keyword),array('like', '%' . $keyword . '%'), '_multi' => true);
        }else if(!empty($keyword)) {
            $map['goods_sn|goods_name'] = array('like', '%' . (string)$keyword . '%');
        }
        $map['is_delete']=0;
        $map['goods_type']=5;
        $map['publish_wait']=1;
		$map['id']=array('in',$ids);
		$list_goods=M("Goods")->field('goods_name,id,market_price')->where($map)->select();
		$data_goods="<option value=''>请选择商品</option>";
		foreach($list_goods as $val){
			$data_goods.='<option data="'.$val['market_price'].'" value="'.$val['id'].'">'.$val['goods_name'].'</option>';
		}
		$result['list']=$data_goods;
		$this->ajaxReturn($result);
	}
	/*搜索店铺商品*/
    public function ajaxgetshopgoods(){
        $keyword = I('keyword');
		$goods_ids = M('ShopsGoods')->where('shop_id = '.MID)->getField('goods_id',true);
        $map = array();
        $map['goods_type'] = 5;
        $map['is_delete'] = 0;
        $map['publish_wait'] = 1;
		$map['id'] = array('in',$goods_ids);
        if (trim($keyword) != '') $map['goods_name'] = array('like', '%' . $keyword . '%');
        $list_goods = M("Goods")->field('goods_name,id,market_price')->where($map)->select();
        $data_goods = "<option value=''>请选择商品</option>";
        foreach ($list_goods as $val_goods) {
            $data_goods .= '<option value="' . $val_goods['id'] . '" data="' . $val_goods['market_price'] . '">' . $val_goods['goods_name'] . '</option>';
        }
        $result['list'] = $data_goods;
        $this->ajaxReturn($result);
    }
	//添加,修改限时促销
	public function insert_sale(){
		$result=array();
		$post=I('param.');
		if(!MID){$this->ajaxReturn($result);}
		$post['shop_ids'] = array('0'=>MID);
		$result=D('Common/Promot')->add_update($post);
		$this->ajaxReturn($result);exit;
	}
	//参与限时促销
	public function xscx_cy(){
		$post=I('param.');
		$id=$post['id'];
		$name = 'PromotAct';
		$this->public_cy($id,$name);
	}
	//删除限时促销
    public function del_sale(){
		$return=array('status'=>0,'info'=>'');
		$postdata=I('param.');
		$id=I('check_id');
		if(!empty($id) && is_array($id)){
			foreach($id as $k=>$v){
				$result=check_delete($v,8);
				if(!$result['status'])unset($id[$k]);
			}
			$postdata['check_id']=$id;
			if(empty($id)){$return['info']='请先清除活动下商品';$this->ajaxReturn($return);exit;}
		}elseif(!empty($id)){
			$result=check_delete($id,8);
			if(!$result['status']){$return['info']='请先清除活动下商品';$this->ajaxReturn($return);exit;}
		}
		$return=D('Promot')->del_promot($postdata);
		if($return['status']){$return['url']=U('Promot/index');}
        $this->ajaxReturn($return);
    }
	
	
	//优惠活动
	public function promot(){
		

		$this->assign('type_type',array('is_online'=>'线上','is_offline'=>'线下'));
		$this->assign('type_status',array('1'=>'已审核','2'=>'已拒绝','3'=>'待审核'));
		$postdata=I('param.');
		$this->assign($postdata);
		$tabid=$postdata['tabid'];
        
        if(empty($tabid)){
        	$auth_code = 'promot_list';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
			// $list=D('Promot')->promot_list();
			// $this->assign($list);
			// 1017替换开始
		        $keyword = I('keyword');
		        if (is_numeric($keyword)) {
		            $map['id|act_name'] = array(intval($keyword), array('like', '%' . $keyword . '%'), '_multi' => true);
		        } else if ($keyword) {
		            $map['act_name'] = array('like', '%' . (string)$keyword . '%');
		        }
		        if($postdata['start_time']){$map['start_time']=array('gt',strtotime($postdata['start_time']));}
		        if($postdata['end_time']){$map['end_time']=array('lt',strtotime($postdata['end_time']));}
		        if($postdata['type'])$map[$postdata['type']]=1;
		        if($postdata['status']){
		        	$map['is_check']=$postdata['status'];
		        	if($postdata['status']==3)$map['is_check']=array('in','0,3');
		    	}
		        $map['is_group'] = 0;
		        $map['is_limit_time'] = 0;
		        $map['shop_id'] = MID;
		        $map['is_pt'] = 0;
		        $list = $this->lists('PromotAct', $map, 'id desc');
		        $this->assign('list', $list);
		        // 1017结束

		}elseif($tabid=='edit_promot'){
			$auth_code = 'promot_edit';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}

			$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/promot');
			}else{
				$promot_info=D('Promot')->promot_info($id);
				$this->getcateTree($promot_info['style_ext_id']);
				$this->assign($promot_info);
				$this -> assign('range_list',$promot_info['rang_list']);
				// 1017新增
				$act_goods = array();
				$info['act_good_ids'] = array_filter(explode(',',$promot_info['act_good_ids']));
				$count = count($info['act_good_ids'])-1;
				if($count <= 0){
					$count = 0;
				}else{
					$count = $count;
				}
				$this->assign('count',$count);
				foreach ($info['act_good_ids'] as $key => $val) {
					$act_goods[$key]['act_good_ids'] = $val;
					if(strpos($val,"-")){
						$new_arr = $arr = array();
						$new_arr = explode('-',$val);
						$arr['attr_key'] = $new_arr[1];
						$arr['goods_id'] = $new_arr[0];
						$act_goods[$key]['goods_id'] = $new_arr[0];
						$act_goods[$key]['attr']='('.attr_key2name($arr['attr_key'],$arr['goods_id']).')';
						$act_goods[$key]['shop_price']=idtoname($arr['attr_key'],'GoodsAttrStock','attr_price','attr_key',false);
						$act_goods[$key]['goods_sn']=idtoname($arr['attr_key'],'GoodsAttrStock','goods_attr_sn','attr_key',false);
					}else{
						$act_goods[$key]['goods_id'] = $val;
						$act_goods[$key]['shop_price']=idtoname($val,'Goods','shop_price','id',false);
						$act_goods[$key]['goods_sn']=idtoname($val,'Goods','goods_sn','id',false);
					}
				}
				$this->assign('act_goods',$act_goods);
				// 1017 end
			}
		}elseif($tabid=='add_promot'){
			$auth_code = 'promot_add';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
			$this->getcateTree();
		}elseif($tabid=='promot_statistics'){
			$this->promot_statistics();exit;
		}
        $this->assign('menu_tab','');
		// $tabid=$tabid?$tabid:'promot';
		$tabid=$tabid?$tabid:'promot_new';//1017
        $this->display($tabid);
	}

	//添加活动
	public function insert_promot(){
		$auth_code = 'promot_add';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$ret['info']=$ret['msg'];	$this->ajaxReturn($ret);}
		$post=I('param.');
		if($post['act_type'] == 4||$post['act_type'] == 3){
			$ids=implode(',', $post['act_good_ids']);
			if(!($ids && (strpos(',',$ids)!==0 || strpos(',',$ids)===false)&& strpos(',,',$ids)===false)){$return['status']=0;$return['info']='请选择活动的商品！'; $this->ajaxReturn($return);}; $post['act_good_ids'] = ','.implode(',',$post['act_good_ids']).',';
		}else{$post['act_good_ids'] ='';}
		if(!$post['act_rang_ext']){$return['status']=0;$return['info']='请选择优惠商品！'; $this->ajaxReturn($return);}
		$return=D('Promot')->add_promot($post);
		if($return['status']){$return['url']=U('Promot/promot');}
		$this->ajaxReturn($return);
	}
	//编辑活动
	public function update_promot(){
		$auth_code = 'promot_edit';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$ret['info']=$ret['msg'];	$this->ajaxReturn($ret);}
		$post=I('param.');
		// if($post['act_type'] == 4||$post['act_type'] == 3){$post['act_good_ids'] = ','.implode(',',$post['act_good_ids']).',';}
		if($post['act_type'] == 4||$post['act_type'] == 3){
			$ids=implode(',', $post['act_good_ids']);
			if(!($ids && (strpos(',',$ids)!==0 || strpos(',',$ids)===false)&& strpos(',,',$ids)===false)){$return['status']=0;$return['info']='请选择活动的商品！'; $this->ajaxReturn($return);}; $post['act_good_ids'] = ','.implode(',',$post['act_good_ids']).',';
		}
		else{$post['act_good_ids'] ='';}
		if(!$post['act_rang_ext']){$return['status']=0;$return['info']='请选择优惠商品！'; $this->ajaxReturn($return);}
		if($post['act_type_ext'] && !preg_match('/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/', $post['act_type_ext']) ){
			$return['status']=0;$return['info']='优惠方式填写不正确！'; $this->ajaxReturn($return);
		}
		$return=D('Promot')->edit_promot($post);
		if($return['status']){$return['url']=U('Promot/promot');}
		$this->ajaxReturn($return);
	}
	//删除优惠活动
    public function del_promot(){
    	$auth_code = 'promot_del';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$ret['info']=$ret['msg'];	$this->ajaxReturn($ret);}
		$postdata=I('param.');
		$return=D('Promot')->del_promot($postdata);
		if($return['status']){$return['url']=U('Promot/promot');}
        $this->ajaxReturn($return);
    }
	
	//代金券
	public function bonus(){
		$postdata=I('param.');
		$tabid=$postdata['tabid'];
        if(empty($tabid)){
			$list=D('Promot')->bonus_list();
			foreach($list['list'] as $k=>$v){
				if($v['is_part'] == 1){
					if(in_array(MID, array_filter(explode(',',$v['shop_id'])))){
						$list['list'][$k]['is_cy'] = 0;
					}else{
						$list['list'][$k]['is_cy'] = 1;
					}
				}
			}
			$this->assign($list);
		}elseif($tabid=='edit_bonus'){
			$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/bonus');
			}else{
				$info=M('Bonu')->where('id='.$id)->field(true)->find();
				if($info['shop_id']){
					$shopids = array_filter(explode(',', $info['shop_id']));
					foreach($shopids as $k=>$v){
						$info['shop_arr'][$v] = idtoname($v,'Shops','name');
					}
					$info['shop_check'] = implode(',',array_keys($info['shop_arr']));
				}
				$this->assign($info);
			}
		}elseif($tabid=='add_bonus'){
			$return=D('Shops')->option(8,STYPE);
			if($return == 0){
				$this->error('你还没添加代金券的权限，请联系管理员！');
				$tabid = 'bonus';
			}
		}
        $this->assign('menu_tab','');
		$tabid=$tabid?$tabid:'bonus';
        $this->display($tabid);
	}
	
	//添加代金券
	public function insert_bonus(){
		$post=I('param.');
		$return=D('Promot')->add_bonus($post);
		if($return['status']){$return['url']=U('Promot/bonus');}
		$this->ajaxReturn($return);
	}
	//修改代金券
	public function update_bonus(){
		$post=I('param.');
		$return=D('Promot')->edit_bonus($post);
		if($return['status']){$return['url']=U('Promot/bonus');}
		$this->ajaxReturn($return);
	}
	//参与代金券
	public function djq_cy(){
		$post=I('param.');
		$id = $post['id'];
		$name = 'Bonu';
		$this->public_cy($id,$name);
	}
	//删除代金券
    public function del_bonus(){
		$postdata=I('param.');
		$return=D('Promot')->del_bonus($postdata);
		if($return['status']){$return['url']=U('Promot/bonus');}
        $this->ajaxReturn($return);
    }
	
	//推荐展位
	public function extend(){
		$tabid=$postdata['tabid'];
		if(empty($tabid)){
			$all_order=D('Common/Shops')->shop_all_order($postdata);
			$this->assign($all_order);
		}
		$tabid=$tabid?$tabid:'extend';
        $this->display($tabid);
	}
	
	private function getcateTree($pid = '',$assign='') {
        //需要只显示该店铺申请成功的分类
        $cate_ids=idtoname(MID,'Shops','cate_ids');
        $cate_ids=explode(',',$cate_ids);
        // $GoodsCategory = getcache('GoodsCategory');
		 $GoodsCategory = getcache('PurchaseCategory');
        // foreach($GoodsCategory as $ke=>$va){
        //     $show=0;
        //     $allprarent=explode(',',$va['allparent']);
        //     foreach($allprarent as $kk=>$vv){
        //         if(in_array($vv,$cate_ids)) $show=1;
        //     }
        //     if(!in_array($ke,$cate_ids) && empty($show)) unset($GoodsCategory[$ke]);
        // }
		$Tree = new \Common\Vendor\Tree();
		$select_categorys='';
		$treemini=$Tree->treemini($GoodsCategory);
		$select_categorys.= $Tree->treeminioption($treemini,$pid);
		if($assign)return $select_categorys;
		else $this->assign('select_categorys',$select_categorys);
		$wh['status']=1;
		$brand=M('Brand')->where($wh)->field('id,brand_name')->select();
		$this->assign('brand_list',$brand);

	}
	private function get_promot_list() {
		$map['act_type']=array('in',array(1,2));
		$map['shop_id']=MID;
		$promot=M('PromotAct')->where($map)->field('id,act_name')->select();
		$this->assign('promot_list',$promot);
	}
    //线下发放处理
    public function send_oline(){
        $postdata = I('post.');
        $use_start_date = strtotime($postdata['use_start_date']);
        $use_end_date = strtotime($postdata['use_end_date']);
        $arr['type_name'] = $postdata['type_name'];
        $arr['type_money'] = $postdata['type_money'];
        $arr['min_goods_amount'] = $postdata['min_goods_amount'];
        $arr['use_start_date'] = $use_start_date;
        $arr['use_end_date'] = $use_end_date;
        $arr['shop_id']=MID;
        $bonus_sum = !empty($_POST['bonus_sum'])?$_POST['bonus_sum']:1;
        if(!$bonus_sum)$this->error('请添加数量！');
        if($bonus_sum>10)$this->error('请填写小于10的数量！');
        //随机生成红包序列号
        $info = M('member_bonus');
        $infos = $info->field(max('bonus_sn'))->find();
        $num = $infos[0];
        $num = $num ? floor($num / 10000) : 100000;
        for ($i = 0, $j = 0; $i < $bonus_sum; $i++){
            $arr['bonus_name'] = $postdata['type_name'];
            $bonus_sn = ($num + $i) . str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
            $arr['bonus_type_id'] = 4;
            $arr['bonus_sn']=$bonus_sn;
            $arr['send_time']=NOW_TIME;
            $arr['money'] = $postdata['type_money'];
            $arr['min_goods_money'] = $postdata['min_goods_amount'];
            $arr['start_time'] = $use_start_date;
            $arr['end_time'] = $use_end_date;
            $sql = $info->add($arr);
        }
        if($sql!==false){
            $url = U('Promot/down_bonus');
            $this->success('发放成功！',$url);
        } else {
            $this->error('发放失败！');
        }
    }
    //线下红包
    public function down_bonus(){
        $where['bonus_type_id']=4;
        $where['shop_id']=MID;
        $info=page_list('MemberBonus',$where,$order,$field,$page_num,'',1);
        foreach($info['list'] as $k=>$v){
            if($v['order_id']){
                $order=M('OrderInfo')->where('id='.$v['order_id'])->field('order_sn')->find();
                $info['list'][$k]['order_sn']=$order['order_sn'];
            }else{
                $info['list'][$k]['order_sn']=0;
            }
        }
        $this->assign($info);
        $this->display();
    }
    //生成线下红包的页面
    public function down_index_add(){
        $bonu=M('Bonu')->where('id=4')->find();
        $this->getcateTree($bonu['cat_id']);
        $this->assign('edit',$bonu);
        $this->assign('menu_action','down_bonus');
        $this->assign('menu_tab','');
        $this->display();
    }
    //删除已发放的红包
    public function delete_user(){
        $para  = I('param.');
		if(empty($para['id'])){$this->error('请选择要删除的项！');}
        $where['id']=array('in',$para['id']);
        $deletes=M('MemberBonus')->where($where)->delete();
        if($deletes){
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！');
        }
    }
    /**
     * 加入权限申请
     * @Author xiaol
     */
    public function apply_contract(){
        $return=$l_map=$m_map=$map=$data=array();$return['status']=0;
        $id=I('param.id');//label_id
        if(is_null($id)){
            $return['msg']='参数错误';
            $this->ajaxReturn($return);
        }
        $l_map['id']=$id;
        $deposit=M('ProjectLabel')->where($l_map)->getField('price');
        $data['publish_wait']=0;
        $data['apply_time']=NOW_TIME;
        $data['deposit']=$deposit;
        $data['label_id']=$id;
        $data['shop_id']=MID;
        $count=M('ProjectLabelLink')->data($data)->add();
        if($count>0){
            $return['status']=1;
        } else{
            $return['msg']='申请加入('.idtoname($id,'ProjectLabel','label_name').')权限失败，请稍候重试！';
        }
        $this->ajaxReturn($return);
    }

    /*拼团*/
    public function fight_group(){
    	$postdata=I('param.');
		$tabid=$postdata['tabid'];
    	if($tabid == 'add_fight_group'){
    		$this->display('Promot/add_fight_group');
    	}else if($tabid == 'edit_fight_group'){
    		$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/fight_group');
			}else{
				$promot_info=D('Promot')->promot_info($id);
				$this->getcateTree($promot_info['style_ext_id']);
				$group_price = unserialize($promot_info['remarks']);
				$this->assign($promot_info);
				$this->assign('group_price',$group_price);
				$this->assign('range_list',$promot_info['rang_list']);
			}
    		$this->display('Promot/edit_fight_group');
    	}else if($tabid == 'select_all'){
    		$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/fight_group');
			}else{
				//团长列表
				$map['pid'] = 0;
				$map['pt_id'] = $id;
				$map['pay_status'] = 3;
				$sum_num = idtoname($id,'PromotAct','group_number');
				$list = $this->lists('OrderInfo', $map, 'id desc');
				if(!empty($list)){
					foreach ($list as $key => $value) {
						$where['pid'] = $value['id'];
						$where['status'] = 2;
						$where['pay_status'] = 3;
						$where['confirm_time'] = array('neq',0);
						$count = M('OrderInfo')->where($where)->count();
						$list[$key]['number'] = $count;
					}
				}
				$this->assign('list',$list);
				$this->display('Promot/select_all');
			}
    	}else if($tabid == 'select_all_son'){
    		$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/select_all_son');
			}else{
				$where['pid'] = $id;
				$where['status'] = 2;
				$where['pay_status'] = 3;
				$where['confirm_time'] = array('neq',0);
				$list = $this->lists('OrderInfo', $where, 'id desc');
				$this->assign('list',$list);
				$this->display('Promot/select_all_son');
			}
    	}else{
    		$map['is_pt'] = 1;
	        $map['is_limit_time'] = 0;
	        $map['is_group'] = 0;
	        $map['shop_id'] = MID;
	        $list = $this->lists('PromotAct', $map, 'id desc');
	        if(!empty($list)){
		        foreach ($list as $key => $value) {
		        	$list[$key]['goods_id'] = M('PromotExt')->where('act_id='.$value['id'])->getField('style_ext_id');
		        	$price = M('PromotExt')->where('act_id='.$value['id'])->getField('remarks');
		        	$list[$key]['group_price'] = unserialize($price);
		        }
	        }
	        $this->assign('list', $list);
    		$this->display();	
    	}
    	
    }
    /*添加*/
    public function add_fight_group(){
  		$post=I('param.');
  		if(empty($post)){
  			$this->error('请录入正确的活动信息');
  		}
		$return=D('Promot')->add_promot($post);
		if($return['status']){$return['url']=U('Promot/fight_group');}
		$this->ajaxReturn($return);
    }

    /*编辑*/
    public function edit_fight_group(){
    	$post=I('param.');
		$return=D('Promot')->edit_promot($post);
		if($return['status']){$return['url']=U('Promot/fight_group');}
		$this->ajaxReturn($return);
    }

    public function del_fight_group(){
    	$postdata=I('param.');
		$return=D('Promot')->del_promot($postdata);
		if($return['status']){$return['url']=U('Promot/fight_group');}
        $this->ajaxReturn($return);
    }

    public function del_team(){
    	$postdata=I('param.');
    	$shops_info=session('shops_info');
		$shop_id=$shops_info['id'];
		if(!$shop_id){$return['info']='登录信息错误';return $return;}
		
		$ids=$postdata['check_id'];
		if(!$ids){$return['info']='请选择要删除的选项';return $return;}

    	$map['id']=array('in',$ids);
		$res=M('OrderInfo')->where($map)->delete();
		if($res){
			if(is_array($ids)){
				foreach($ids as $k=>$v){action_log('shop_del_promot', 'Shop', $v, $shop_id);}
			}else{
				action_log('shop_del_promot', 'Shop', $ids, $shop_id);
			}
		}
    }
	//首单立减活动
	public function first(){
		$this->is_have(1);
		$this->assign('title_ass','首单立减');
		$this->display();
	}
	//首单立减参与
	public function first_cy(){
		$post=I('param.');
		$id=$post['id'];
		$name = 'TakeoutPromote';
		$this->public_cy($id,$name);
	}
	//满减活动
	public function manjian(){
		$this->is_have(2);
		$this->assign('title_ass','满减');
		$this->display();
	}
	//满减活动参与
	public function manjian_cy(){
		$post=I('param.');
		$id=$post['id'];
		$name = 'TakeoutPromote';
		$this->public_cy($id,$name);
	}
	private function is_have($id){
		$shop_ids = ','.MID.',';
		$map['id'] = $id;
		$map['status'] = 1;
		$map['_string'] = "(shop_id like '%".$shop_ids."%' and is_part=0) OR shop_id='0' OR is_part=1";
		$list = M('TakeoutPromote')->where($map)->field(true)->find();
		if($list['shop_id'] === $shop_ids){
			$list['s_edit'] = 1;
		}
		$config_info=unserialize($list['config']);
        $this->assign('config_info',$config_info);
		if($list['is_part'] == 1){
			if(in_array(MID, array_filter(explode(',',$list['shop_id'])))){
				$list['is_cy'] = 0;
			}else{
				$list['is_cy'] = 1;
			}
		}
		$this->assign($list);
	}
	//公共参与
	private function public_cy($id,$name){
		$map['id']=$id;
		$res = M($name)->where($map)->find();
		if($res && MID){
			$arr['shop_id'] = $res['shop_id'].MID.',';
			$return['status'] = M($name)->where($map)->save($arr);
			if($return['status']){
				$return['info']='参与成功';
			}else{
				$return['info']='参与失败！';
			}
		}
		if($return['status']){
			if($name == 'PromotAct'){
				action_log('shop_edit_sale', 'Shop', $id, $shop_id);
				$return['url']=U('Promot/index');
			}elseif($name == 'Bonu'){
				$return['url']=U('Promot/bonus');
			}elseif($name == 'TakeoutPromote' && $id == 1){
				$return['url']=U('Promot/first');
			}elseif($name == 'TakeoutPromote' && $id == 2){
				$return['url']=U('Promot/manjian');
			}
		}
		$this->ajaxReturn($return);
	}

	// 微信卡券开始
    public function wx_coupon(){
    	$this->assign('is_check_status',array('1'=>'已审核','2'=>'已拒绝','3'=>'待审核'));
    	$this->assign('rank_array',array('CASH'=>'代金券','DISCOUNT'=>'折扣券'));
        $postdata = I('post.');$this->assign($postdata);
       	$tabid=I('tabid');
       	if($tabid== 'wx_statistics'){
       		$this->wx_statistics();exit;
       	}elseif($tabid== 'wx_coupon_edit'){
       		$this->wx_coupon_edit();exit;
       	}elseif($tabid =='wx_coupon_add' ){
        	$auth_code = 'wxcoupon_add';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
            $shops_info=session('shops_info');
            $shop_id=$shops_info['shop_id'];
            $map=array();
            $map['id']=$shop_id;
            $shop_name=M("Shops")->where($map)->field("name,poi_id")->find();
        	 $this->assign('shop_arr',$shop_id);
        	 $this->assign('poi_id',$shop_name['poi_id']);
        	$this->assign('shop_name',$shop_name['name']);
        }else{
        	$auth_code = 'wxcoupon_list';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}

	        $map=array();   
	        if($postdata['keyword'])$map['title'] = array('like','%'.$postdata['keyword'].'%');
	        if($postdata['reg_from'] && !$postdata['reg_to'])$map['add_time'] = array(array('gt',strtotime($postdata['reg_from'])));
	        if($postdata['reg_to'] && !$postdata['reg_from'])$map['add_time'] = array(array('lt',strtotime($postdata['reg_to'])));
	        if($postdata['reg_from'] && $postdata['reg_to'])$map['add_time'] = array(array('gt',strtotime($postdata['reg_from'])),array('lt',strtotime($postdata['reg_to'])));
	        if($postdata['is_check']){
	        	$map['is_check']=$postdata['is_check'];
		        if($postdata['is_check']==3)$map['is_check']=array('in','0,3');
	        }
	        if($postdata['rank_id'])$map['rank_id']=$postdata['rank_id'];
	        $map['coupons_type'] = 1;
	//      $map['status'] = 1;
	        $map['is_show']=array('in',array(MID,','.MID.',',','.MID,MID.','));//数据库存的貌似有不确定的，
	        $info=$this->lists('Coupons',$map);
	        $coupon_record = $this->coupon_record();
	        foreach ($info as $k => $v) {
	            $info[$k]['coupon_get'] = $coupon_record[$v['id']]['coupon_get'];
	            $info[$k]['coupon_past'] = $coupon_record[$v['id']]['coupon_past'];
	            $info[$k]['coupon_make'] = $coupon_record[$v['id']]['coupon_make'];
	            $info[$k]['coupon_use'] = $coupon_record[$v['id']]['coupon_use'];
	        }
	        $this->assign('info', $info);
	        $this->assign('postdata', $postdata);
	    }
	        $this->display($tabid);
    }

    // 优惠券  总领取 总转赠 已过期 已使用  统计
    public function coupon_record(){
        $map = array();
        $map['status'] = 1;
        // $map['is_show']=array('in',array(MID,','.MID.',',','.MID,MID.','));//数据库存的貌似有不确定的，
        $coupon = M('Coupons')->where($map)->field('id')->select();
        foreach ($coupon as $k => $v) {         
            $map = array();
            $map['coupons_id'] = $v['id'];
            //总领取
            $data = M('CouponsGet')->where($map)->field('count(id) as coupon_get')->find();
            $return[$v['id']]['coupon_get'] = $data['coupon_get'];
            //已过期
            $map['end_timestamp'] = array(array('lt',NOW_TIME));
            $data = M('CouponsGet')->where($map)->field('count(id) as coupon_past')->find();
            $return[$v['id']]['coupon_past'] = $data['coupon_past'];
            //总转赠
            $map = array();
            $map['coupons_id'] = $v['id'];
            $data = M('CouponsDonation')->where($map)->field('count(id) as coupon_make')->find();
            $return[$v['id']]['coupon_make'] = $data['coupon_make'];
            //已使用
            $map = array();
            $map['coupons_id'] = $v['id'];
            $map['status'] = 1;
            $data = M('CouponsGet')->where($map)->field('count(id) as coupon_use')->find();
            $return[$v['id']]['coupon_use'] = $data['coupon_use'];
        }
        return $return;
    }
   
     //创建新卡券
    public function wx_coupon_insert(){
        $postdata=I('post.');
        $auth_code = 'wxcoupon_add';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}

        $postdata['brand_name'] = C('WEB_SITE_NAME');
        $postdata['logo_url'] = C('WEB_SMALL_LOGO');
        if(empty($postdata['logo_url']))$postdata['logo_url']= C('WEB_SITE_LOGO');
        // if($postdata['is_show'] == 0){
        //     $postdata['location_id_list'] = 0;
        // }else{
        //     // if($postdata['location_id_list'])$postdata['location_id_list'] = implode(',',$postdata['location_id_list']);
        // }
        $shops_info=session('shops_info');
        $shop_id=$shops_info['shop_id'];
        $map=array();
        $map['id']=$shop_id;
        $shop_poi_id=M("Shops")->where($map)->getField("poi_id");
        $postdata['is_show']=1;
        $postdata['location_id_list']=$shop_id;
        if(!$shop_poi_id){$this->error('门店未绑定微信小程序');}
        if(!$postdata['use_limit'] || $postdata['use_limit'] <= 0){
            $postdata['use_limit'] = 50;
        }
        if(!$postdata['get_limit'] || $postdata['get_limit'] <= 0){
            $postdata['get_limit'] = 50;
        }
        if(!$postdata['logo_url']){
            $post_status = 1;
            $msg = '商户LOGO不能为空!';
        }
        if($postdata['rank_id'] == '选择类型'){
            $post_status = 1;
            $msg = '请选择卡券类型!';
        }
        if($postdata['rank_id'] == 'GENERAL_COUPON' && !$postdata['default_detail']){
            $post_status = 1;
            $msg = '优惠详情不能为空!';
        }elseif($postdata['rank_id'] == 'DISCOUNT' && !$postdata['discount']){
            $post_status = 1;
            $msg = '折扣额度不能为空!';
        }elseif($postdata['rank_id'] == 'GIFT'  &&!$postdata['gift']){
            $post_status = 1;
            $msg = '礼品名称不能为空!';
        }elseif($postdata['rank_id'] == 'CASH' && !$postdata['reduce_cost']){
            $post_status = 1;
            $msg = '减免金额不能为空!';
        }elseif($postdata['rank_id'] == 'GROUPON' && !$postdata['deal_detail']){
            $post_status = 1;
            $msg = '团购详情不能为空!';
        }
        if($postdata['reduce_cost']&&!preg_match('/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/', $postdata['reduce_cost'])){$post_status = 1;$msg = '减免金额填写不正确!';}
        if($postdata['discount']&&!preg_match('/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/', $postdata['discount'])){$post_status = 1;$msg = '折扣额度填写不正确!';}

        if($postdata['type']==1){
        	if(!$postdata['begin_timestamp']||!$postdata['end_timestamp']){$post_status = 1;$msg = '固定日期不能为空!';}
        }else{
        	if(!$postdata['fixed_begin_term']||!$postdata['fixed_term']){$post_status = 1;$msg = '固定时长不能为空!';}
        }
        if($post_status == 1){
            echo "<script language=\"javascript\">alert('$msg');location.href = 'javascript:history.back()'</script>";
            exit();
        }
      
        if($postdata['is_show'] == 1){
            $map = array();
            $map['poi_id'] = array('in',$postdata['location_id_list']);
            $arr = M('Shops')->where($map)->getField('id',true);
            $postdata['is_show'] =$arr? ','.implode(',',$arr).',':'';
        }
        //验证是否审核
        $is_check_bonu=C("IS_CHECK_BONU");
        $shops_info=session('shops_info');
        $shop_id=$shops_info['shop_id'];
        $map=array();
        $map['id']=$shop_id;
        $shop_type=M("Shops")->where($map)->getField('shop_type');
        if($shop_type==2 && $is_check_bonu==1){
            $postdata['is_check']=3;
        }
        if(empty($is_check_bonu)){
            $postdata['is_check']=1;
        }
        $Weixin = new \Common\Vendor\WeixinCoupon();
        // 添加优惠券

        $add_coupon = $Weixin->add_coupon($postdata);
        if($add_coupon['status'] == 1){
            $url = U('wx_coupon');
            $this->success('添加成功！',$url);
        }else{
            $url = U('wx_coupon_insert');
            $this->error('添加失败！',$url);
        }
    }
    // 删除微信代金券
    public function wx_coupon_delete(){
    	$auth_code = 'wxcoupon_del';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}
        $id  = I('get.id');
        $url = U('wx_coupon');
        $card_id = M('Coupons')->where('id='.$id)->field('card_id')->find();

        $Weixin = new \Common\Vendor\WeixinCoupon();
        $del_coupon = $Weixin->del_coupon($card_id['card_id']);
        $deletes = M('Coupons')->where('id='.$id)->order('id desc')->delete();
        if($deletes && $del_coupon['errmsg'] == 'ok'){
            $this->success('删除成功！',$url);
        }elseif($deletes){
            $this->success('删除成功！',$url);
        }else {
            $this->error('删除失败！',$url);
        }       

    }
        //编辑微信代金券
    public function wx_coupon_edit(){
    	$auth_code = 'wxcoupon_edit';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}
        $this->assign('shop_arr',MID);
        $this->assign('shop_name',$this->shops_info['name']);
        $id=I('id');
        $map = array();$map['id'] = $id;
        $edits = M('Coupons')->where($map)->field(true)->find();
        if($edits['card_id']){
            $card_id = 1;
        }else{
            $card_id = 0;
        }
        if($edits['location_id_list']){
            $where_shop['poi_id'] = array('in',$edits['location_id_list']);
            $shop = M('Shops')->where($where_shop)->field('name')->select();
            $this->assign('shop',$shop);
        }
        $this->assign('id',$id);
        $this->assign('card_id',$card_id);
        $this->assign('edit', $edits);
        $this->display('wx_coupon_update');       

    }
        // 二维码
    public function get_code(){
        $get=I('get.');
        $get['card_id'] = idtoname($get['id'],'Coupons','card_id');
        $Weixin = new \Common\Vendor\WeixinCoupon();
        $get_code = $Weixin->get_code($get);
        if($get_code['status'] == 1){
            $result['status'] = 1;
            $result['url'] = $get_code['show_qrcode_url'];
        }
        $this->ajaxReturn($result);
    }
    // 修改库存
    public function modifystock(){
        $get=I('get.');
        $get['card_id'] = idtoname($get['id'],'Coupons','card_id');
        $Weixin = new \Common\Vendor\WeixinCoupon();
        $modifystock = $Weixin->modifystock($get);
        // print_r($modifystock);exit();
        if($modifystock['status'] == 1){
            $result['status'] = '1';
            $result['shu'] = $modifystock['shu'];
            $result['id'] = $modifystock['id'];
        }else{
            $result['status'] = '0';
        }
        $this->ajaxReturn($result);
    }
    //修改代金券信息
    public function wx_coupon_update(){
    	$auth_code = 'wxcoupon_edit';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
        $postdata=I('post.');
        $Weixin = new \Common\Vendor\WeixinCoupon();
        $map = array();
        $map['id'] = $postdata['id'];
        $coupon = M('Coupons')->where($map)->field(true)->find();
        //验证是否审核
        $is_check_bonu=C("IS_CHECK_BONU");
        $shops_info=session('shops_info');
        $shop_id=$shops_info['shop_id'];
        $map=array();
        $map['id']=$shop_id;
        $shop_type=M("Shops")->where($map)->getField('shop_type');
        if($shop_type==2 && $is_check_bonu==1){
            $postdata['is_check']=3;
        }
        if(empty($is_check_bonu)){
            $postdata['is_check']=1;
        }
        if($coupon['card_id']){
            $card = $Weixin->update_coupon($postdata["rank_id"],$postdata,$coupon['card_id']);
        }else{
            $coupon['logo_url'] = $postdata['logo_url'];
            $coupon['notice'] = $postdata['notice'];
            $coupon['description'] = $postdata['description'];
            // add中日期用了strtotime()所以转一下
            $coupon['begin_timestamp']=date('Y-m-d H:i:s',$postdata['begin_timestamp']);
            $coupon['end_timestamp']=date('Y-m-d H:i:s',$postdata['end_timestamp']);
            $coupon['is_type'] = $postdata['is_type'];
            $coupon['color'] = $postdata['color'];
            $coupon['service_phone'] = $postdata['service_phone'];
            $card = $Weixin->add_coupon($coupon);
        }
        $url = U('wx_coupon');
        if($card['status'] == 1){
            $this->success('编辑成功！',$url);
        }else{
            $this->error('编辑失败！',$url);
        }
    }
    /*搜索店铺商品*/
    public function choose_goods(){
        $postdata=I('post.');
		$this->getcateTree();
        $type=!empty($postdata['type'])?$postdata['type']:1;//1单选 2多选
		
		$map=array();
        $map['status']=1;
        $map['is_delete']=0;
        //$map['is_internet']=1;
        $map['publish_wait']=1;
        //$map自行扩展
        $map['goods_type']=5;
        if(!isset($postdata['keywords'])){
            $postdata['keywords']='';
        }
        if (is_numeric($postdata['keywords'])) {
            $map['id|goods_name'] = array(intval($postdata['keywords']), array('like', '%' . $postdata['keywords'] . '%'), '_multi' => true);
        } else if (!empty($postdata['keywords'])) {
            $map['goods_sn|goods_name'] = array('like', '%' . (string)$postdata['keywords'] . '%');
        }
        if (!empty($postdata['search_catid'])) {
            $cat_sons = get_children($postdata['search_catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['search_catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = array();
            if (!empty($cat_sons) && !empty($catstr)) {
                $where['cat_id'] = array('in', $cat_sons);
            }
            if (!empty($extension_goods_id) && !empty($extensionstr)) {
                $where['id'] = array('in', $extension_goods_id);
            }
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }
		if($type == 2){
			$where = array();
			$where['id'] = array('gt',0);
			$cat_ids = M('PromotAct')->where($where)->getField('id',true);
            if($cat_ids){
				$p_map = array();
                $p_map['act_id'] = array('in',$cat_ids);
				$p_map['style'] = 3;
				$have_ids = M('PromotExt')->where($p_map)->getField('style_ext_id',true);
				if($have_ids)$map['id'] = array('NOT IN',$have_ids);
            }
			//echo "<pre>";print_r($have_ids);exit;
		}

		// 限定自己卖的
		$ids=M('ShopsGoods')->where('shop_id ='.MID.'and status=1 and is_delete = 0')->getField('goods_id',true);
		$map['id']=array('in',$ids);
        $total=M('Goods')->where($map)->count();
        
        if(empty($total)){
            $return['status']=2;
            $return['info']='没有查询到商品';
            $this->ajaxReturn($return);//返回查询商品为空
        }
        
        $listRows=!empty($postdata['pagesize'])?$postdata['pagesize']:8;
        $page = new \Common\Vendor\Page($total, $listRows);
        $pageconfig='%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%';
        $page->setConfig('theme',$pageconfig);
        $page->rollPage=6;
        $pagehtml = $page->show();
        $list=array();
        //echo "<pre>";print_r($map);exit;
        $list=M('Goods')->alias('g')->where($map)->field('id,goods_name,img,goods_sn')->limit($page->firstRow.','.$listRows)->select();

        $html='';
        if(!in_array($type,array(1,2)))$type=1;
        foreach($list as $k=>$v){
            $input=$type==2?'<input type="checkbox" value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" class="f_l" />':'<input value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" type="radio" class="f_l" />';
            $html.=
            '<div class="choose_goods_item clearfix" title="'.$v['goods_name'].'" attr_data="'.$v['attr_key'].'" attr_name="'.$v['attr'].'" goods_sn="'.$v['goods_sn'].'"><label>'.$input.
                '<img src="'.thumb($v['img']).'" />'.
                '<p>'.str_cut($v['goods_name'],70).'【'.$v['goods_sn'].'】</p><span>'.str_cut($v['attr'],70).'</span></label>'.
            '</div>';
        }        
        $return['status']=1;
        $return['data']=$html;
        $return['page']=$pagehtml;
        $return['totalpages']=$page->totalPages;
        $this->ajaxReturn($return);
	}
	/**
     * 获取商品信息
     */
	public function get_goods(){
        $return=$where=$map = array();
        $postdata = I('param.');
        $id= intval($postdata['id']);
        $html='';
        if($id){
            $map['id'] = $id;
            $map['goods_type']=5;
            $info = M('Goods')->where($map)->field('id,shop_price,supply_price,goods_sn,unit_id,is_type,goods_name')->find();
            $where['goods_id'] =$id;
            $attr_key = M('GoodsAttrStock')->where($where)->field('attr_key,attr_price,goods_attr_sn')->select();
            if($attr_key){

                $html='<select class=\'form-control\' name=\'attr_key[]\' onchange=\'shopprice('.this.')\'>';
                foreach($attr_key as $k=>$v){
                    $attr = attr_key2name($v['attr_key'],$id);
                    $html.='<option value='.$id.'-'.$v['attr_key'].' attrprice='.$v['attr_price'].' goodssn='.$v['goods_attr_sn'].'>'.$attr.'</option>';
                }
                $html.='</select>';
                $info['shop_price']=$attr_key[0]['attr_price'];
                $info['goods_sn']=$attr_key[0]['goods_attr_sn'];
                $info['attr_keys']=$html;
            }else{
                $info['attr_keys']='';
            }
            $info['unit_name']=idtoname($info['unit_id'],'GoodsUnit','name','id',false);
            $return['status'] = 1;
            $return['info'] = $info;
        }else{
            $return['status'] = 0;
            $return['info'] = '数据获取错误';
        }

        $this->ajaxReturn($return);
	}
	  /*搜索添加包装选择商品*/
    public function choose_goodsp(){
        $postdata=I('post.');
        
        $type=!empty($postdata['type'])?$postdata['type']:1;//1单选 2多选
        
        $map=array();
        $map['status']=1;
        $map['is_delete']=0;
        $map['publish_wait']=1;
        $map['sale_type']=0;
        //$map自行扩展
        $map['goods_type']=5;
        if(!isset($postdata['keywords'])){
            $postdata['keywords']='';
        }
        if (is_numeric($postdata['keywords'])) {
            $map['id|goods_name'] = array(intval($postdata['keywords']), array('like', '%' . $postdata['keywords'] . '%'), '_multi' => true);
        } else if (!empty($postdata['keywords'])) {
            $map['goods_sn|goods_name'] = array('like', '%' . (string)$postdata['keywords'] . '%');
        }
        if (!empty($postdata['search_catid'])) {
            $cat_sons = get_children($postdata['search_catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['search_catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = array();
            if (!empty($cat_sons) && !empty($catstr)) {
                $where['cat_id'] = array('in', $cat_sons);
            }
            if (!empty($extension_goods_id) && !empty($extensionstr)) {
                $where['id'] = array('in', $extension_goods_id);
            }
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }
        // 加判断 自己店有售
        $s_map['shop_id']=MID;
        $s_map['status']=1;
        $s_map['is_delete']=0;
        $ids=M('ShopsGoods')->where($s_map)->getField('goods_id',true);
        $ids_str='';
        foreach($ids as $v){
        	$ids_str.=$v.',';
        }
        if(!$ids_str){
        	 $return['status']=2;
            $return['info']='没有查询到商品';
            $this->ajaxReturn($return);//返回查询商品为空
        }
        $map['id']=array('in',trim($ids_str,','));
        // 加判断结束


        $total=M('Goods')->where($map)->count();
        
        if(empty($total)){
            $return['status']=2;
            $return['info']='没有查询到商品';
            $this->ajaxReturn($return);//返回查询商品为空
        }
        
        $listRows=!empty($postdata['pagesize'])?$postdata['pagesize']:8;
        $page = new \Common\Vendor\Page($total, $listRows);
        $pageconfig='%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%';
        $page->setConfig('theme',$pageconfig);
        $page->rollPage=6;
        $pagehtml = $page->show();
        $list=array();
        //echo "<pre>";print_r($map);exit;
        $list=M('Goods')->alias('g')->where($map)->field('id,goods_name,img,goods_sn')->limit($page->firstRow.','.$listRows)->select();

        $html='';
        if(!in_array($type,array(1,2)))$type=1;
        foreach($list as $k=>$v){
            $input=$type==2?'<input type="checkbox" value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" class="f_l" />':'<input value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" type="radio" class="f_l" />';
            $html.=
            '<div class="choose_goods_item clearfix" title="'.$v['goods_name'].'" attr_data="'.$v['attr_key'].'" attr_name="'.$v['attr'].'" goods_sn="'.$v['goods_sn'].'"><label>'.$input.
                '<img src="'.format_url($v['img']).'" />'.
                '<p>'.str_cut($v['goods_name'],70).'【'.$v['id'].'】</p><span>'.str_cut($v['attr'],70).'</span></label>'.
            '</div>';
        }        
        $return['status']=1;
        $return['data']=$html;
        $return['page']=$pagehtml;
        $return['totalpages']=$page->totalPages;
        $this->ajaxReturn($return);
    }
    /*搜索店铺商品*/
    public function choose_goodsg(){
        $postdata=I('post.');
        
        $type=!empty($postdata['type'])?$postdata['type']:1;//1单选 2多选
        
        $map=array();
        $map['status']=1;
        $map['is_delete']=0;
        $map['publish_wait']=1;
        $map['sale_type']=0;
        //$map自行扩展
        $map['goods_type']=5;
        if(!isset($postdata['keywords'])){
            $postdata['keywords']='';
        }
        if (is_numeric($postdata['keywords'])) {
            $map['id|goods_name'] = array(intval($postdata['keywords']), array('like', '%' . $postdata['keywords'] . '%'), '_multi' => true);
        } else if (!empty($postdata['keywords'])) {
            $map['goods_sn|goods_name'] = array('like', '%' . (string)$postdata['keywords'] . '%');
        }
        if (!empty($postdata['search_catid'])) {
            $cat_sons = get_children($postdata['search_catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['search_catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = array();
            if (!empty($cat_sons) && !empty($catstr)) {
                $where['cat_id'] = array('in', $cat_sons);
            }
            if (!empty($extension_goods_id) && !empty($extensionstr)) {
                $where['id'] = array('in', $extension_goods_id);
            }
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }
        // 加判断 自己店有售
        $s_map['shop_id']=MID;
        $s_map['status']=1;
        $s_map['is_delete']=0;
        $ids=M('ShopsGoods')->where($s_map)->getField('goods_id',true);
        $ids_str='';
        foreach($ids as $v){
        	$ids_str.=$v.',';
        }
        if(!$ids_str){
        	 $return['status']=2;
            $return['info']='没有查询到商品';
            $this->ajaxReturn($return);//返回查询商品为空
        }
        $map['id']=array('in',trim($ids_str,','));
        // 加判断结束
        $total=M('Goods')->where($map)->count();
        
        if(empty($total)){
            $return['status']=2;
            $return['info']='没有查询到商品';
            $this->ajaxReturn($return);//返回查询商品为空
        }
        
        $listRows=!empty($postdata['pagesize'])?$postdata['pagesize']:8;
        $page = new \Common\Vendor\Page($total, $listRows);
        $pageconfig='%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%';
        $page->setConfig('theme',$pageconfig);
        $page->rollPage=6;
        $pagehtml = $page->show();
        $list=array();
        //echo "<pre>";print_r($map);exit;
        $list=M('Goods')->alias('g')->where($map)->field('id,goods_name,img,goods_sn')->limit($page->firstRow.','.$listRows)->select();

        $html='';
        if(!in_array($type,array(1,2)))$type=1;
        foreach($list as $k=>$v){
            $input=$type==2?'<input type="checkbox" value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" class="f_l" />':'<input value="'.$v['id'].'" name="choose_goods" data-id="'.$v['id'].'" type="radio" class="f_l" />';
            $html.=
            '<div class="choose_goods_item clearfix" title="'.$v['goods_name'].'" attr_data="'.$v['attr_key'].'" attr_name="'.$v['attr'].'" goods_sn="'.$v['goods_sn'].'"><label>'.$input.
                '<img src="'.format_url($v['img']).'" />'.
                '<p>'.str_cut($v['goods_name'],70).'【'.$v['id'].'】</p><span>'.str_cut($v['attr'],70).'</span></label>'.
            '</div>';
        }        
        $return['status']=1;
        $return['data']=$html;
        $return['page']=$pagehtml;
        $return['totalpages']=$page->totalPages;
        $this->ajaxReturn($return);
    }

    public function wx_statistics($is_return=false){
        $this->order_type=strtoarray(C('ORDER_TYPE'));$this->assign('order_type',$this->order_type);
        $order_source=strtoarray(array('1'=>'微信','2'=>'移动收银','3'=>'小程序','4'=>'收银HD'));
        $this->assign('order_source',$order_source);
        $sale_type = array('1'=>'线下','2'=>'线上');
        $this->assign('sale_type',$sale_type);
        $s_map = array();$s_map['id'] = array('gt',0);$s_map['status'] = 1;
        $shop_list=D('Admin/Shops')->shop_list();
        $this->assign('shop_list',$shop_list);

        $sou_type=strtoarray(array('1'=>'按门店','2'=>'按小时','3'=>'按日','4'=>'按月'));
        $this->assign('sou_type',$sou_type);

        $map=$map_oi=array();
        $postdata=I('param.');
        $map_oi['type']=array('in','1,6,11,13,14');
        $map_oi['pay_status']=3;
        $map_oi['is_delete']=0;
        $map_oi['status']=array('in','1,2,3,6,8');
        $postdata['shopid']=MID;
        if($postdata['shopid'])$map_oi['shop_id']= $postdata['shopid'];
        if($postdata['source']){
            $map_oi['source']= $postdata['source'];
        }
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['reg_from'] || $postdata['reg_to']){
            $date_from = strtotime($postdata['reg_from']);
            if($date_from){$map_oi['addtime'][] = array('egt',$date_from);}
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){$date_to = $date_to+86399;$map_oi['addtime'][] = array('lt',$date_to);}
            $postdata['dates']=0;
        }else{
            if(in_array($postdata['dates'],array(1,2,7,30))){
                $between=$this->quick_time($postdata['dates']);
                $map_oi['addtime']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        if($postdata['in_online']==1){
            $map_oi['in_online']=$postdata['in_online'];
        }elseif($postdata['in_online']==2){
            $map_oi['in_online']=0;
        }
        if($postdata['id']){
            $map=array();
            $map_c['coupons_id']= $postdata['id'];
            $bonus_ids=M('CouponsGet')->where($map_c)->getField('id',true);
            if($bonus_ids){
                $map_oi['bonus_id']= array('in',$bonus_ids);
            }else{
                if($is_return){
                    $return['list']=array();
                    $return['info']=array();
                    if($postdata['sou_value']==1){
                        $return['title'] = array('门店','总金额','优惠券金额','订单量','客单优惠占比','优惠金额占比','门店优惠占比');
                    }else{
                        $return['title'] = array('时间','总金额','优惠券金额','订单量','客单优惠占比','优惠金额占比'.'时间优惠占比');
                    }

                    return $return;
                }else{
                    $this->assign($postdata);
                    $this->assign('list',array());
                    $this->display('wx_statistics');exit;
                }
            }
        }
        switch($postdata['sou_value']){
            case 2://按小时
                for($i=0;$i<24;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="count(id) as num,sum(order_money) as order_money,sum(bonus_money) as bonus_money,shop_id,addtime,(sum(bonus_money)/count(id)) as avg_num";
                $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                $list_time=array();
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('G',$v['addtime'])]['addtime']=date('G',$v['addtime']).'点';
                        $list[date('G',$v['addtime'])]['order_money']=format_decimal($v['order_money']);
                        $list[date('G',$v['addtime'])]['bonus_money']=$v['bonus_money'];
                        $list[date('G',$v['addtime'])]['num']=$v['num'];
                        $list[date('G',$v['addtime'])]['avg_price']=format_decimal($v['bonus_money']/$v['order_money']);
                        $list[date('G',$v['addtime'])]['avg_num']=format_decimal($v['avg_num']);
                        $list[date('G',$v['addtime'])]['percent_money']=number_format(($v['bonus_money']/$orderinfo['bonus_money'])*100,2).'%';
                        $list_time[]=date('G',$v['addtime']);
                    }unset($k,$v);
                    $orderinfo['avg_price']=format_decimal($orderinfo['bonus_money']/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($orderinfo['bonus_money']/$orderinfo['num']);
                    $new_day=array_diff($day_arr,$list_time);
                    foreach($new_day as $vt){
                        $list[$vt]['addtime']=$vt.'点';
                        $list[$vt]['order_money']=0.00;
                        $list[$vt]['bonus_money']=0.00;
                        $list[$vt]['num']=0;
                        $list[$vt]['avg_price']=0;
                        $list[$vt]['avg_num']=0;
                        $list[$vt]['percent_money']=0;
                    }
                    ksort($list);
                }
                break;
            case 3://按日
                for($i=1;$i<32;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="count(id) as num,sum(order_money) as order_money,sum(bonus_money) as bonus_money,shop_id,addtime,(sum(bonus_money)/count(id)) as avg_num";
                $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('j',$v['addtime'])]['addtime']=date('j',$v['addtime']).'日';
                        $list[date('j',$v['addtime'])]['order_money']=format_decimal($v['order_money']);
                        $list[date('j',$v['addtime'])]['bonus_money']=$v['bonus_money'];
                        $list[date('j',$v['addtime'])]['num']=$v['num'];
                        $list[date('j',$v['addtime'])]['avg_price']=format_decimal($v['bonus_money']/$v['order_money']);
                        $list[date('j',$v['addtime'])]['avg_num']=format_decimal($v['avg_num']);
                        $list[date('j',$v['addtime'])]['percent_money']=number_format(($v['bonus_money']/$orderinfo['bonus_money'])*100,2).'%';
                        $list_time[]=date('j',$v['addtime']);
                    }unset($k,$v);
                    $orderinfo['avg_price']=format_decimal($orderinfo['bonus_money']/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($orderinfo['bonus_money']/$orderinfo['num']);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['addtime']=$vt.'日';
                    $list[$vt]['order_money']=0.00;
                    $list[$vt]['bonus_money']=0.00;
                    $list[$vt]['num']=0;
                    $list[$vt]['avg_price']=0;
                    $list[$vt]['avg_num']=0;
                    $list[$vt]['percent_money']=0;
                }
                ksort($list);
                break;
            case 4://月
                for($i=1;$i<13;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="count(id) as num,sum(order_money) as order_money,sum(bonus_money) as bonus_money,shop_id,addtime,(sum(bonus_money)/count(id)) as avg_num";
                $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('n',$v['addtime'])]['addtime']=date('n',$v['addtime']).'月';
                        $list[date('n',$v['addtime'])]['order_money']=format_decimal($v['order_money']);
                        $list[date('n',$v['addtime'])]['bonus_money']=$v['bonus_money'];
                        $list[date('n',$v['addtime'])]['num']=$v['num'];
                        $list[date('n',$v['addtime'])]['avg_price']=format_decimal($v['bonus_money']/$v['order_money']);
                        $list[date('n',$v['addtime'])]['avg_num']=format_decimal($v['avg_num']);
                        $list[date('n',$v['addtime'])]['percent_money']=number_format(($v['bonus_money']/$orderinfo['bonus_money'])*100,2).'%';
                        $list_time[]=date('n',$v['addtime']);
                    }unset($k,$v);
                    $orderinfo['avg_price']=format_decimal($orderinfo['bonus_money']/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($orderinfo['bonus_money']/$orderinfo['num']);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['addtime']=$vt.'月';
                    $list[$vt]['order_money']=0.00;
                    $list[$vt]['bonus_money']=0.00;
                    $list[$vt]['num']=0;
                    $list[$vt]['avg_price']=0;
                    $list[$vt]['avg_num']=0;
                    $list[$vt]['percent_money']=0;
                }
                ksort($list);
                break;
            default://按店
                $shoplist=$shop_list;
                if($postdata['shopid']){
                    $map_s=array();
                    $map_s['id']=$postdata['shopid'];
                    $shoplist=M('Shops')->where($map_s)->getField('id,name');
                }
                $shop_ids=array_keys($shoplist);
                $postdata['sou_value']=1;
                $field="count(id) as num,sum(order_money) as order_money,sum(bonus_money) as bonus_money,shop_id,addtime,(sum(bonus_money)/count(id)) as avg_num";
                $list_s=M('OrderInfo')->where($map_oi)->group("shop_id")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_s){
                    foreach ($list_s as $k => $v) {
                        $list[$v['shop_id']]['shop_name']=$shop_list[$v['shop_id']];
                        $list[$v['shop_id']]['order_money']=format_decimal($v['order_money']);
                        $list[$v['shop_id']]['bonus_money']=$v['bonus_money'];
                        $list[$v['shop_id']]['num']=$v['num'];
                        $list[$v['shop_id']]['avg_price']=format_decimal($v['bonus_money']/$v['order_money']);
                        $list[$v['shop_id']]['avg_num']=format_decimal($v['avg_num']);
                        $list[$v['shop_id']]['percent_money']=number_format(($v['bonus_money']/$orderinfo['bonus_money'])*100,2).'%';
                        $list_time[]=$v['shop_id'];
                    }unset($k,$v);
                    $orderinfo['avg_price']=format_decimal($orderinfo['bonus_money']/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($orderinfo['bonus_money']/$orderinfo['num']);
                }
                $new_day=array_diff($shop_ids,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['shop_name']=$shop_list[$vt];
                    $list[$vt]['order_money']=0.00;
                    $list[$vt]['bonus_money']=0.00;
                    $list[$vt]['num']=0;
                    $list[$vt]['avg_price']=0;
                    $list[$vt]['avg_num']=0;
                    $list[$vt]['percent_money']=0;
                }
                break;

        }

        if($is_return){
            $return['list']=$list;
            $return['info']=$orderinfo;
            if($postdata['sou_value']==1){
                $return['title'] = array('门店','总金额','优惠券金额','订单量','客单优惠占比','优惠金额占比','门店优惠占比');
            }else{
                $return['title'] = array('时间','总金额','优惠券金额','订单量','客单优惠占比','优惠金额占比'.'时间优惠占比');
            }

            return $return;
        }else{
            $this->assign($orderinfo);
            $this->assign($postdata);
            $this->assign('list',$list);
            $this->display('wx_statistics');
        }
    }
    // 微信优惠券分析导出
     public function wx_statistics_export(){
        $rest=$this->wx_statistics(true);
        $data=array();
        $data=$rest['list'];
        $data[]=array('总计',$rest['info']['order_money'],floatval($rest['info']['bonus_money']),$rest['info']['num'],format_decimal($rest['info']['avg_price']),format_decimal($rest['info']['avg_num']),'--');
        export_csv('优惠券统计.csv',$rest['title'],$data);
        exit;
    }
    // 优惠活动统计
     public function promot_statistics($is_return=false){
         $this->order_type=strtoarray(C('ORDER_TYPE'));$this->assign('order_type',$this->order_type);
        $order_source=strtoarray(array('1'=>'微信','2'=>'移动收银','3'=>'小程序','4'=>'收银HD'));
        $this->assign('order_source',$order_source);
        $sale_type = array('1'=>'线下','2'=>'线上');
        $this->assign('sale_type',$sale_type);
        $s_map = array();$s_map['id'] = array('gt',0);$s_map['status'] = 1;
        $shop_list=D('Admin/Shops')->shop_list();
        $this->assign('shop_list',$shop_list);

        $sou_type=strtoarray(array('1'=>'按门店','2'=>'按小时','3'=>'按日','4'=>'按月'));
        $this->assign('sou_type',$sou_type);

        $map=$map_oi=array();
        $postdata=I('param.');
        $map_oi['type']=array('in','1,6,11,13,14');
        $map_oi['pay_status']=3;
        $map_oi['is_delete']=0;
        $map_oi['status']=array('in','1,2,3,6,8');
        $postdata['shopid']=MID;
        if($postdata['shopid'])$map_oi['shop_id']= $postdata['shopid'];
        if($postdata['source']){
            $map_oi['source']= $postdata['source'];
        }
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['reg_from'] || $postdata['reg_to']){
            $date_from = strtotime($postdata['reg_from']);
            if($date_from){$map_oi['addtime'][] = array('egt',$date_from);}
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){$date_to = $date_to+86399;$map_oi['addtime'][] = array('lt',$date_to);}
            $postdata['dates']=0;
        }else{
            if(in_array($postdata['dates'],array(1,2,7,30))){
                $between=$this->quick_time($postdata['dates']);
                $map_oi['addtime']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        if($postdata['in_online']==1){
            $map_oi['in_online']=$postdata['in_online'];
        }elseif($postdata['in_online']==2){
            $map_oi['in_online']=0;
        }
        if($postdata['id']){
            $map_oi['promot_money_json']=array('like','%"'.$postdata['id'].'":%');
        }else{
            if($is_return){
                $return['list']=array();
                $return['info']=array();
                if($postdata['sou_value']==1){
                    $return['title'] = array('门店','总金额','优惠券金额','订单量','客单优惠占比','优惠金额占比','门店优惠占比');
                }else{
                    $return['title'] = array('时间','总金额','优惠券金额','订单量','客单优惠占比','优惠金额占比'.'时间优惠占比');
                }

                return $return;
            }else{
                $this->assign($postdata);
                $this->assign('list',array());
                $this->display('promot_statistics');exit;
            }
        }
        $all_promot_money=0;
        switch($postdata['sou_value']){
            case 2://按小时
                for($i=0;$i<24;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="count(id) as num,sum(order_money) as order_money,promot_money_json,shop_id,addtime";
                $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                $list_time=array();
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('G',$v['addtime'])]['addtime']=date('G',$v['addtime']).'点';
                        $list[date('G',$v['addtime'])]['order_money']=format_decimal($v['order_money']);
                        $promot=json_decode($v['promot_money_json'],true);
                        $all_promot_money+=$promot[$postdata['id']]['money'];
                        $list[date('G',$v['addtime'])]['promot_money']=$promot[$postdata['id']]['money'];
                        $list[date('G',$v['addtime'])]['num']=$v['num'];
                        $list[date('G',$v['addtime'])]['avg_price']=format_decimal($promot[$postdata['id']]['money']/$v['order_money']);
                        $list[date('G',$v['addtime'])]['avg_num']=format_decimal($promot[$postdata['id']]['money']/$v['num']);
                        $list_time[]=date('G',$v['addtime']);
                    }unset($k,$v);
                    foreach ($list as $k => $v) {
                        $list[$k]['percent_money']=number_format(($v['promot_money']/$all_promot_money)*100,2).'%';
                    }unset($k,$v);
                    $orderinfo['promot_money']=format_decimal($all_promot_money);
                    $orderinfo['avg_price']=format_decimal($all_promot_money/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($all_promot_money/$orderinfo['num']);
                    $new_day=array_diff($day_arr,$list_time);
                    foreach($new_day as $vt){
                        $list[$vt]['addtime']=$vt.'点';
                        $list[$vt]['order_money']=0.00;
                        $list[$vt]['promot_money']=0.00;
                        $list[$vt]['num']=0;
                        $list[$vt]['avg_price']=0;
                        $list[$vt]['avg_num']=0;
                        $list[$vt]['percent_money']=0;
                    }
                    ksort($list);
                }
                break;
            case 3://按日
                for($i=1;$i<32;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="count(id) as num,sum(order_money) as order_money,promot_money_json,shop_id,addtime";
                $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('j',$v['addtime'])]['addtime']=date('j',$v['addtime']).'日';
                        $list[date('j',$v['addtime'])]['order_money']=format_decimal($v['order_money']);
                        $promot=json_decode($v['promot_money_json'],true);
                        $all_promot_money+=$promot[$postdata['id']]['money'];
                        $list[date('j',$v['addtime'])]['promot_money']=$promot[$postdata['id']]['money'];
                        $list[date('j',$v['addtime'])]['num']=$v['num'];
                        $list[date('j',$v['addtime'])]['avg_price']=format_decimal($promot[$postdata['id']]['money']/$v['order_money']);
                        $list[date('j',$v['addtime'])]['avg_num']=format_decimal($promot[$postdata['id']]['money']/$v['num']);
                        $list_time[]=date('j',$v['addtime']);
                    }unset($k,$v);
                    foreach ($list as $k => $v) {
                        $list[$k]['percent_money']=number_format(($v['promot_money']/$all_promot_money)*100,2).'%';
                    }unset($k,$v);
                    $orderinfo['promot_money']=format_decimal($all_promot_money);
                    $orderinfo['avg_price']=format_decimal($all_promot_money/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($all_promot_money/$orderinfo['num']);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['addtime']=$vt.'日';
                    $list[$vt]['order_money']=0.00;
                    $list[$vt]['promot_money']=0.00;
                    $list[$vt]['num']=0;
                    $list[$vt]['avg_price']=0;
                    $list[$vt]['avg_num']=0;
                    $list[$vt]['percent_money']=0;
                }
                ksort($list);
                break;
            case 4://月
                for($i=1;$i<13;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="count(id) as num,sum(order_money) as order_money,promot_money_json,shop_id,addtime";
                $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('n',$v['addtime'])]['addtime']=date('n',$v['addtime']).'月';
                        $list[date('n',$v['addtime'])]['order_money']=format_decimal($v['order_money']);
                        $promot=json_decode($v['promot_money_json'],true);
                        $all_promot_money+=$promot[$postdata['id']]['money'];
                        $list[date('n',$v['addtime'])]['promot_money']=$promot[$postdata['id']]['money'];
                        $list[date('n',$v['addtime'])]['num']=$v['num'];
                        $list[date('n',$v['addtime'])]['avg_price']=format_decimal($promot[$postdata['id']]['money']/$v['order_money']);
                        $list[date('n',$v['addtime'])]['avg_num']=format_decimal($promot[$postdata['id']]['money']/$v['num']);
                        $list_time[]=date('n',$v['addtime']);
                    }unset($k,$v);
                    foreach ($list as $k => $v) {
                        $list[$k]['percent_money']=number_format(($v['promot_money']/$all_promot_money)*100,2).'%';
                    }unset($k,$v);
                    $orderinfo['promot_money']=format_decimal($all_promot_money);
                    $orderinfo['avg_price']=format_decimal($all_promot_money/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($all_promot_money/$orderinfo['num']);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['addtime']=$vt.'月';
                    $list[$vt]['order_money']=0.00;
                    $list[$vt]['promot_money']=0.00;
                    $list[$vt]['num']=0;
                    $list[$vt]['avg_price']=0;
                    $list[$vt]['avg_num']=0;
                    $list[$vt]['percent_money']=0;
                }
                ksort($list);
                break;
            default://按店
                $shoplist=$shop_list;
                if($postdata['shopid']){
                    $map_s=array();
                    $map_s['id']=$postdata['shopid'];
                    $shoplist=M('Shops')->where($map_s)->getField('id,name');
                }
                $shop_ids=array_keys($shoplist);
                $postdata['sou_value']=1;

                $field="count(id) as num,sum(order_money) as order_money,promot_money_json,shop_id,addtime";
                $list_s=M('OrderInfo')->where($map_oi)->group("shop_id")->field($field)->select();
                $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_s){
                    foreach ($list_s as $k => $v) {
                        $list[$v['shop_id']]['shop_name']=$shop_list[$v['shop_id']];
                        $list[$v['shop_id']]['order_money']=format_decimal($v['order_money']);
                        $promot=json_decode($v['promot_money_json'],true);
                        $all_promot_money+=$promot[$postdata['id']]['money'];
                        $list[$v['shop_id']]['promot_money']=$promot[$postdata['id']]['money'];
                        $list[$v['shop_id']]['num']=$v['num'];
                        $list[$v['shop_id']]['avg_price']=format_decimal($promot[$postdata['id']]['money']/$v['order_money']);
                        $list[$v['shop_id']]['avg_num']=format_decimal($promot[$postdata['id']]['money']/$v['num']);
                        $list_time[]=$v['shop_id'];
                    }unset($k,$v);
                    foreach ($list as $k => $v) {
                        $list[$k]['percent_money']=number_format(($v['promot_money']/$all_promot_money)*100,2).'%';
                    }unset($k,$v);
                    $orderinfo['promot_money']=format_decimal($all_promot_money);
                    $orderinfo['avg_price']=format_decimal($all_promot_money/$orderinfo['order_money']);
                    $orderinfo['avg_num']=format_decimal($all_promot_money/$orderinfo['num']);
                }
                $new_day=array_diff($shop_ids,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['shop_name']=$shop_list[$vt];
                    $list[$vt]['order_money']=0.00;
                    $list[$vt]['promot_money']=0.00;
                    $list[$vt]['num']=0;
                    $list[$vt]['avg_price']=0;
                    $list[$vt]['avg_num']=0;
                    $list[$vt]['percent_money']=0;
                }
                break;

        }

        if($is_return){
            $return['list']=$list;
            $return['info']=$orderinfo;
            if($postdata['sou_value']==1){
                $return['title'] = array('门店','总金额','活动优惠金额','订单量','客单优惠占比','优惠金额占比','门店优惠占比');
            }else{
                $return['title'] = array('时间','总金额','活动优惠金额','订单量','客单优惠占比','优惠金额占比'.'时间优惠占比');
            }

            return $return;
        }else{
            $this->assign($orderinfo);
            $this->assign($postdata);
            $this->assign('list',$list);
            $this->display('promot_statistics');
        }
    }
    /**
     * 代金券导出
     *
     */
    public function promot_statistics_export(){
        $rest=$this->promot_statistics(true);
        $data=array();
        $data=$rest['list'];
        $data[]=array('总计',$rest['info']['order_money'],floatval($rest['info']['promot_money']),$rest['info']['num'],format_decimal($rest['info']['avg_price']),format_decimal($rest['info']['avg_num']),'--');
        export_csv('活动优惠统计.csv',$rest['title'],$data);
        exit;
    }






	function quick_time($type){
	    $map=array();
	    $start_time = strtotime(date('Y-m-d',NOW_TIME)); 
	    if($type == 1){
	        $date_from=$start_time;
	        $date_to =$start_time+86399;
	        $map[] = $date_from;
	        $map[] = $date_to;
	    }elseif($type == 2){
	        $date_from=$start_time-86400;
	        $date_to =$start_time-1;
	        $map[] = $date_from;
	        $map[] = $date_to;
	    }elseif($type == 7){
	        $date_from=$start_time-6*86400;
	        $date_to =$start_time+86399;
	        $map[] = $date_from;
	        $map[] = $date_to;
	    }elseif($type == 14){
	        $date_from=$start_time-23*86400;
	        $date_to =$start_time+86399;
	        $map[] = $date_from;
	        $map[] = $date_to;
	    }elseif($type == 30){
	        $date_from=$start_time-29*86400;
	        $date_to =$start_time+86399;
	        $map[] = $date_from;
	        $map[] = $date_to;
	    }elseif($type == 60){
	        $date_from=$start_time-59*86400;
	        $date_to =$start_time+86399;
	        $map[] = $date_from;
	        $map[] = $date_to;
	    }
	    return $map;
	}


}
?>