<?php
/**
 * 后台基础控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */

namespace Admin\Controller;
class PromotActController extends BaseController
{
    public function _initialize()
    {
        parent::_initialize();
        $this->PromotAct = getcache('PromotAct');
        /*$is_auth=check_use_auth("WEBSHOP");
        if($is_auth['status']==0){
            $this->error('该版本没有此权限',$is_auth['url']);return;
        }*/
    }

    public function index()
    {
        $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 . '%');
        }
        $shop_id=I("shop_id");
        $this->assign('shop_id',$shop_id);
        if($shop_id){
            $map['shop_id']=$shop_id;
        }
        $is_check=I('is_check');
        $this->assign('check',$is_check);
        if($is_check){
            $map['is_check']=$is_check;
        }
        $map['is_group'] = 0;
        $map['is_limit_time'] = 0;
        $map['is_pt'] = 0;
        $list = $this->lists('PromotAct', $map, 'id desc');
        $map=array();
        $map['status']=1;
        $shop_info=M("Shops")->where($map)->field('id,name')->select();
        $is_check=array(1=>'已审核',2=>'已拒绝',3=>'待审核');
        $this->assign('list', $list);
        $this->assign('shop_info', $shop_info);
        $this->assign('is_check', $is_check);
        $this->display();
    }

    /**
     * 店铺活动
     */
    public function index_shops()
    {
        $keyword = I('keyword');
        $postdata = I('post.');
        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 . '%');
        }
        $s_id_map=$this->get_shop_ids($postdata);
        if ($s_id_map) {
            $map['shop_id'] = $s_id_map;
        } else {
            $map['shop_id'] = array('gt', 0);
        }
        $map['is_group'] = 0;
        $map['is_limit_time'] = 1;
        $list = $this->lists('PromotAct', $map, 'id desc');
        $this->assign('list', $list);
        $this->display();
    }

    public function group_index()
    {
        $keyword = I('keyword');
		$map = array();
        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 . '%');
        }
        $map['is_pt'] = 1;
        $map['is_limit_time'] = 0;
        $map['is_group'] = 0;
        $list = $this->lists('PromotAct', $map, 'id desc');
        $this->assign('list', $list);
        $this->display();
    }

    /*搜索店铺商品*/
    public function ajaxgetshopgoods()
    {
        $keyword = I('keyword');
        // $shop_id = I('shop_id');
        $is_pt = I('is_pt');
        $map = array();
        // if($is_pt == 1){
            // $map['pt_id']=0;
        // }
        // $map['shop_id'] = $shop_id;
        $map['goods_type'] = 5;
        $map['is_delete'] = 0;
        $map['is_internet'] = 1;
        $map['publish_wait'] = 1;
        $map['status'] = 1;
        $map['pt_id'] = 0;
        $map['promote_id'] = 0;
        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 choose_goods(){
        $postdata=I('post.');
		
        $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;
        $map['is_offline']=1;//线上
        $map['pt_id'] = 0;
        $map['promote_id'] = 0;
        if(!isset($postdata['keywords'])){
            $postdata['keywords']='';
        }
        if (is_numeric($postdata['keywords'])) {
            $map['id|goods_sn|goods_name'] = array(intval($postdata['keywords']), array('like', '%' . $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);
            $where['end_time'] = array('GT',NOW_TIME);
            $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;
        }
        $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 limit_time()
    {
        $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 . '%');
        }
        $map['is_group'] = 0;
        $map['is_limit_time'] = 1;
        $map['status'] = 0;
        $list = $this->lists('PromotAct', $map, 'id desc');
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 店铺促销
     */
    public function limit_time_shop()
    {
        $keyword = I('keyword');
        $postdata = I('post.');
        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 . '%');
        }
        $s_id_map=$this->get_shop_ids($postdata);
        if ($s_id_map) {
            $map['shop_id'] = $s_id_map;
        }
        $map['is_group'] = 0;
        $map['is_limit_time'] = 1;
        $map['status'] = 1;
        $list = $this->lists('PromotAct', $map, 'id desc');
        $this->assign('list', $list);
        $this->display();
    }
    private function get_shop_ids($postdata){
        $s_id_map='';
        if (isset($postdata['shops_keyword'])) {
            if(!empty($postdata['shops_keyword'])) {
                $shop_ids = array();
                if (is_numeric($postdata['shops_keyword'])) {
                    $shop_map['id|name'] = array(intval($postdata['shops_keyword']), array('like', '%' . $postdata['shops_keyword'] . '%'), '_multi' => true);
                } else if (!empty($postdata['shops_keyword'])) {
                    $shop_map['name'] = array('like', '%' . (string)$postdata['shops_keyword'] . '%');
                }
                $shops = M('Shops')->field('id')->where($shop_map)->select();
                foreach ($shops as $k => $v) {
                    $shop_ids[$k] = $v['id'];
                }
                if (empty($shop_ids)) {
                    $s_id_map = array('lt', 0);
                } else {
                    $s_id_map = array('in', $shop_ids);
                }
            }else{
                $s_id_map = array('gt', 0);
            }
        } else {
            $s_id_map = 0;
        }
        return $s_id_map;
    }
    public function add_limit_time()
    {
        $id = I('id');
        if ($id) {
            $info = M('PromotAct')->field(true)->find($id);
			if($info){
				$list = M('Goods')->where('promote_id=' . $id)->field('id,goods_name,shop_price,promote_price')->select();
				$this->assign('list', $list);
				$this->assign($info);
			}
        }
        $this->display();
    }
    public function add_shop_limit_time(){
        $id = I('id');
        if ($id) {
            $info = M('PromotAct')->field(true)->find($id);

			if($info){
				if($info['pid'] == 0){
					$cat_id = $info['id'];
				}else{
					$cat_id = $info['pid'];
				}

                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']));
                }

				$list = M('Goods')->where('promote_id=' . $cat_id)->field('id,goods_name,goods_sn,shop_price,promote_price,goods_max_number as goods_number,goods_min_number')->select();
				$this->assign('list', $list);
				$this->assign($info);	
			}
        }
        $this->getGroup(1);
        $shopsData = getShops();
        $this->getcateTree();
        $this->assign('shopsData',$shopsData);
        $this->display();
    }

    public function delete_promote()
    {
        $id = I('id');
        $return = array();
        $map = array();
        $map['id'] = $id;
        $data = array();
        $data['promote_id'] = 0;
        $data['promote_price'] = 0;
        $data['promote_start_time'] = 0;
        $data['promote_end_time'] = 0;
        M("Goods")->where($map)->save($data);
        $return['status'] = 1;
        $this->ajaxReturn($return);
    }

    public function edit(){
        $id = I('id');
        if ($id) {
            $is_check=array(1=>'审核',2=>'拒绝',3=>'待审核');
            $this->assign("check_info",$is_check);
            $info = M('PromotAct')->field(true)->find($id);
            $list = M('PromotExt')->where('act_id=' . $id)->select();
            $rang_list = '';
            $goods_list = "<option value=''>请选择商品</option>";
            foreach ($list as $k => $v) {
                if ($info['is_group'] == 0) {
                    if ($v['style'] == 1) {//分类
                        $rang_list .= "<label class='checkbox-inline'><input type='checkbox' checked='checked' name='act_rang_ext[]' value='" . $v['style_ext_id'] . "' />" . idtoname($v['style_ext_id'], 'PurchaseCategory', 'name', 'id', false) . "</label>&nbsp;&nbsp;";
                    } elseif ($v['style'] == 2) {//品牌
                        $rang_list .= "<label class='checkbox-inline'><input type='checkbox' checked='checked' name='act_rang_ext[]' value='" . $v['style_ext_id'] . "' />" . idtoname($v['style_ext_id'], 'Brand', 'brand_name', 'id', false) . "</label>&nbsp;&nbsp;";
                    } elseif ($v['style'] == 3 || $v['style'] == 4) {//商品
                        $rang_list .= "<div class='ml10'><label class='checkbox-inline'><input type='checkbox' checked='checked' name='act_rang_ext[]' value='" . $v['style_ext_id'] . "' />" . idtoname($v['style_ext_id'], 'Goods', 'goods_name', 'id', false) . "【". idtoname($v['style_ext_id'], 'Goods', 'goods_sn', 'id', false) ."】</label></div>";
                        $remarks = unserialize($v['remarks']);
                    }
                } else {
                    $goods_id = $v['style_ext_id'];
                    $goods_list = "<option value='" . $v['style_ext_id'] . "'>" . idtoname($v['style_ext_id'], 'Goods', 'goods_name', 'id', false) . "</option>";
                }
            }
            if($info['is_pt'] == 1){
                $goods_id = $v['style_ext_id'];
                $goods_list = "<option value='" . $v['style_ext_id'] . "'>" . idtoname($v['style_ext_id'], 'Goods', 'goods_name', 'id', false) . "</option>";
            }
              // $goods_ids = '';
              // foreach($select_goods as $v){
                        // $goods_ids .= "<label class='checkbox-inline'><input type='checkbox' checked='checked' name='act_good_ids[]' value='" . $v . "' />" . idtoname($v, 'Goods', 'goods_name', 'id', false) . "</label>&nbsp;&nbsp;";
              // }

            $info['act_good_ids'] = array_filter(explode(',',$info['act_good_ids']));
            $count = count($info['act_good_ids'])-1;
            if($count <= 0){
                $count = 0;
            }else{
                $count = $count;
            }
              // print_r($count);exit;
            $act_goods = array();
            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);
                        }
            }
              // echo "<pre>";
              // print_r($act_goods);exit;
            
            
            if ($list) {
                if ($list[0]['style'] == 1) {
                    $this->getcateTree($list[0]['style_ext_id']);
                } elseif ($list[0]['style'] == 2) {
                    $this->getcateTree();
                    $info['brand_id'] = $list[0]['style_ext_id'];
                } else {
                    $this->getcateTree();
                }
                $info['act_rang'] = $list[0]['style'];
                $info['remarks'] = $remarks;
            } else {
                $info['act_rang'] = 0;
                $this->getcateTree();
            }
            $map=array();
            $map['pt_id']=$id;
            $goods_number=M("Goods")->where($map)->getField('goods_max_number');
            //echo $goods_id;
            $this->getGroup(1);
            $this->assign('act_rang_ext', $goods_id);
            // print_r($info);echo $rang_list;
            $this->assign($info);
            $this->assign('count', $count);
            $this->assign('act_goods', $act_goods);
            $this->assign('goods_list', $goods_list);
            $this->assign('range_list', $rang_list);
            $this->assign('goods_number', $goods_number);
            $this->assign('id', $id);
            if($info['is_pt'] == 1){
                    $this->display('pt_edit');
            }else{
                    $this->display();
            }
        }

    }

    public function _before_add()
    {
        // $info['is_group'] = I('is_group');
        $info['is_pt'] = I('is_pt');
        $goods_list = "<option value=''>请选择商品</option>";
        $this->assign('goods_list', $goods_list);
        $this->assign($info);
        $this->getcateTree();
        $shop_arr=M('Shops')->where('status=1')->getField('id,name');
        $this->assign('shop_arr',$shop_arr);
    }
    public function pt_add(){
        $this->getGroup(1);
        $info['is_pt'] = I('is_pt');
        $this->assign($info);
        $this->getcateTree();
        if($info['is_pt'] == 1){
            $this->display('pt_edit');
        }
    }

    /***
     ***
     * 添加
     ***/
    public function insert()
    {
        $model = M(CONTROLLER_NAME);
        $post = I('post.');
        if ($post['is_group']) {
            
        } else {
            $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/add');
        }
        if (empty($post['promot_price']) && $post['is_limit_time'] == 1) {
            $this->error('请选择促销的商品', $jumpUrl);
        }
        if (empty($post['big_img'])) {
            $this->error('请选择活动页大图', $jumpUrl);
        }
        if(empty($post['act_rang_ext'])  && $post['is_limit_time'] != 1){
            $this->error('请选择促销的商品', $jumpUrl);
        }
        if ($post) {
            $data['act_name'] = $post['act_name'];
            $data['img'] = $post['img'];
            $data['big_img'] = $post['big_img'];
            $data['start_time'] = strtotime($post['start_time']);
            $data['end_time'] = strtotime($post['end_time']);
            $data['min_amount'] = $post['min_amount'];
            $data['max_amount'] = $post['max_amount'];
            $data['act_type'] = $post['act_type'];
            $data['is_addup'] = $post['is_addup'];
            $data['is_group'] = $post['is_group'];
            $data['is_pt'] = $post['is_pt'];
            $data['is_online'] = intval(implode(',',$post['is_online']));
            $data['is_offline'] = intval(implode(',',$post['is_offline']));
            $data['is_limit_time'] = $post['is_limit_time'];
            $data['group_number'] = $post['group_number'];
            $data['group_time_limit'] = $post['group_time_limit'];
            $data['buy_limit'] = $post['buy_limit'];
            $data['head_commission_rate'] = $post['head_commission_rate'];
            $data['shop_id']=$post['shop_id'];
            // 19-6-25 添加
            $data['user_rank']=$post['user_rank'];
            if($post['act_type'] == 1 || $post['act_type'] == 2){
                $data['act_type_ext'] = $post['act_type_ext'];
                $data['act_good_ids'] = '';
            }elseif($post['act_type'] == 4 ){
                $data['act_type_ext'] = $post['act_type_ext'];
                foreach($post['attr_key'] as $k => $v){
                    if(!empty($v)){
                        $post['act_good_ids'][$k] = $v;
                    }
                }
                $data['act_good_ids'] = ','.implode(',',$post['act_good_ids']).',';
            }elseif($post['act_type'] == 3 ){
                $data['act_type_ext'] = 0;
                if(isset($post['attr_key'])){
                    foreach($post['attr_key'] as $k => $v){
                        if(!empty($v)){
                            $post['act_good_ids'][$k] = $v;
                        }
                    }
                }
                $data['act_good_ids'] = ','.implode(',',$post['act_good_ids']).',';
            }else{
                $data['act_type_ext'] = 0;
                $data['act_good_ids'] = 0;
            }
            $res = M('PromotAct')->add($data);
            if (is_array($post['act_rang_ext']) && $post['is_pt'] != 1) {
                foreach ($post['act_rang_ext'] as $k => $v) {
                    $add['act_id'] = $res;
                    $add['style'] = $post['act_range'];
                    $add['style_ext_id'] = $v;
                    M('PromotExt')->add($add);
                }
                $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
            }else {
                if ($post['is_pt']) {
                    // foreach ($post['group_price'] as $k => $v) {
                        $re_array = array();
                        $add['act_id'] = $res;
                        $add['style'] = $post['act_range'];
                        $add['style_ext_id'] = $post['act_rang_ext'][0];
                        // $re_array['group_price'][$k] = $v;
                        $add['remarks'] = serialize($post['remarks']);
                        M('PromotExt')->add($add);
                        $goods['id'] = $post['act_rang_ext'][0];
                        $change['pt_id'] = $res;
                        $change['goods_max_number'] = $post['goods_number'];
                        M('Goods')->where($goods)->save($change);
                    // }
                    $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/group_index');
                }
                if ($post['is_limit_time']) {
                    foreach ($post['promot_price'] as $k => $v) {
                        $re_array = array();
                        $add['act_id'] = $res;
                        $add['style'] = $post['act_range'];
                        $add['style_ext_id'] = $post['act_rang_ext'];
                        $re_array['promot_price'][$k] = $v;
                        $add['remarks'] = serialize($re_array);
                        M('PromotExt')->add($add);
                    }
                    $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/limit_time');
                }
            }
            $msg = array_merge(array('success' => L('ADD_OK'), 'error' => L('ADD_ERROR'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
            if ($res !== false) {
                if (in_array(CONTROLLER_NAME, $this->cache_model)) {
                    savecache(CONTROLLER_NAME);
                }
                $this->success($msg['success'], $msg['url'], $msg['ajax']);
            } else {
                $this->error($msg['error'], $msg['url'], $msg['ajax']);
            }
        }
    }

    /***
     ***
     * 修改
     ***/
    public function update(){
        $model = M(CONTROLLER_NAME);
        $post = I('post.');
        if (empty($post['promot_price']) && $post['is_limit_time'] == 1) {
            $this->error('请选择促销的商品');
        }
        if (empty($post['big_img'])) {
            $this->error('请选择活动页大图');
        }
        if(empty($post['act_rang_ext'])  && $post['is_limit_time'] != 1){
            $this->error('请选择促销的商品');
        }
        $where_ext = array();
        $where_ext['act_id'] = $post['id'];
        if($post['is_pt'] == 1){
            $goodsids = M('PromotExt')->where($where_ext)->getField('style_ext_id');
            $save['pt_id'] = 0;
            $map=array();
            $map['id'] = $goodsids;
            $update = M('Goods')->where($map)->save($save);
        }
        M('PromotExt')->where($where_ext)->delete();
        $id = I('id');
        $data['act_name'] = $post['act_name'];
        $data['img'] = $post['img'];
        $data['big_img'] = $post['big_img'];
        $data['start_time'] = strtotime($post['start_time']);
        $data['end_time'] = strtotime($post['end_time']);
        $data['min_amount'] = $post['min_amount'];
        $data['max_amount'] = $post['max_amount'];
        $data['act_type'] = $post['act_type'];
        $data['is_addup'] = $post['is_addup'];
        $data['act_type_ext'] = $post['act_type_ext'];
        $data['is_group'] = $post['is_group'];
        $data['is_pt'] = $post['is_pt'];
        $data['is_online'] = intval(implode(',',$post['is_online']));
        $data['is_offline'] = intval(implode(',',$post['is_offline']));
        $data['group_number'] = $post['group_number'];
        $data['group_time_limit'] = $post['group_time_limit'];
        $data['buy_limit'] = $post['buy_limit'];
        $data['is_check'] = $post['is_check'];
        $data['user_rank'] = $post['user_rank'];
        $data['head_commission_rate'] = $post['head_commission_rate'];
        if($post['act_type'] == 1 || $post['act_type'] == 2){
            $data['act_type_ext'] = $post['act_type_ext'];
            $data['act_good_ids'] = '';
        }elseif($post['act_type'] == 4 ){
            $data['act_type_ext'] = $post['act_type_ext'];
            if(isset($post['attr_key'])) {
                foreach ($post['attr_key'] as $k => $v) {
                    if (!empty($v)) {
                        $post['act_good_ids'][$k] = $v;
                    }
                }
            }
            $data['act_good_ids'] = ','.implode(',',$post['act_good_ids']).',';
        }elseif($post['act_type'] == 3 ){
            $data['act_type_ext'] = 0;
            
            if(isset($post['attr_key'])){
                foreach($post['attr_key'] as $k => $v){
                    if(!empty($v)){
                        $post['act_good_ids'][$k] = $v;
                    }
                }
            }
            $data['act_good_ids'] = ','.implode(',',$post['act_good_ids']).',';
        }else{
            $data['act_type_ext'] = 0;
            $data['act_good_ids'] = 0;
        }
        $where['shop_id'] = $post['shop_id'];
        $where['id'] = $id;
        $res = M('PromotAct')->where($where)->save($data);
        if($post['is_pt'] != 1){
            $post['act_rang_ext'] = array_unique($post['act_rang_ext']);
        }
        if (is_array($post['act_rang_ext']) && $post['is_pt'] != 1) {
            foreach ($post['act_rang_ext'] as $k => $v) {
                $add['act_id'] = $id;
                $add['style'] = $post['act_range'];
                $add['style_ext_id'] = $v;
                M('PromotExt')->add($add);
            }
            $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
        } else {
            if ($post['is_pt']) {
                // foreach ($post['group_price'] as $k => $v) {
                    $re_array = array();
                    $add['act_id'] = $id;
                    $add['style'] = $post['act_range'];
                    $add['style_ext_id'] = $post['act_rang_ext'][0];
                    // $re_array['group_price'][$k] = $v;
                    $add['remarks'] = serialize($post['remarks']);
                    
                    M('PromotExt')->add($add);
                    $save['pt_id'] = $id;
                    $save['goods_max_number'] = $post['goods_number'];
                    $map=array();
                    $map['id'] = $post['act_rang_ext'][0];
                    $update = M('Goods')->where($map)->save($save);
                // }
                $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/group_index');
            }
            if ($post['is_limit_time']) {
                foreach ($post['promot_price'] as $k => $v) {
                    $re_array = array();
                    $add['act_id'] = $id;
                    $add['style'] = $post['act_range'];
                    $add['style_ext_id'] = $post['goods'][$k];
                    $re_array['promot_price'][$k] = $v;
                    $add['remarks'] = serialize($re_array);
                    M('PromotExt')->add($add);
                }
                $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/limit_time');
            }
        }
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($res !== false) {
            if (in_array(CONTROLLER_NAME, $this->cache_model)) {
                savecache(CONTROLLER_NAME);
            }
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
	/**
     * 添加、修改限时促销
     */
    public function insert_limit_time(){
        $postdata = I('param.');
        $result = D('Common/Promot')->add_update($postdata);
        if ($result['status'] == 1) {
            $this->success($result['info'],U('PromotAct/limit_time'));
        }else{
			$this->error($result['info']);
		}
    }
    /**
     * 添加、修改限时促销
     */
    public function insert_shop_limit_time(){
        $postdata = I('param.');
        //时间
        $start_time=$postdata['start_time'];
        $end_time=$postdata['end_time'];
        if(empty($postdata['start_time']) || empty($postdata['end_time'])){
            $this->error('开始时间或结束时间必填,请重新填写！',U('PromotAct/add_shop_limit_time'));exit;
        }elseif(strtotime($postdata['end_time']) < strtotime($postdata['start_time'])){
            $this->error('结束时间应大于开始时间,请重新填写！',U('PromotAct/add_shop_limit_time'));exit;
        }
        foreach($postdata['promot_price'] as $k=>$v){
            if(floatval($v[$k]) < 0){
                $this->error('促销金额必须大于0,请重新填写！',U('PromotAct/add_shop_limit_time'));exit;
            }
        }
        $result = D('Common/Promot')->add_update($postdata);
        if ($result['status'] == 1) {
            $this->success($result['info'],U('PromotAct/limit_time_shop'));
        }else{
            $this->error($result['info']);
        }
    }

    /**
     * Ajax搜索商品
     */
    public function ajaxgetgoods()
    {
        $keyword = I('keyword');
        $map = array();
        $map['shop_id'] = 0;
        $map['is_delete'] = 0;
        $map['publish_wait'] = 1;
        $map['goods_type'] = 1;
        if (trim($keyword) != '') $map['goods_name'] = array('like', '%' . $keyword . '%');
        $list_goods = M("Goods")->field('goods_name,id,shop_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['shop_price'] . '">' . $val_goods['goods_name'] . '</option>';
        }
        $result['list'] = $data_goods;
        $this->ajaxReturn($result);
    }

    private function getcateTree($pid = '', $assign = '')
    {
        // $GoodsCategory = getcache('GoodsCategory');
        $GoodsCategory = getcache('PurchaseCategory');
        $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);

    }

    /**
     * Ajax展示商品属性
     */
    public function get_goods_attr_stock()
    {
        $post = I('param.');
        if (!isset($post['goods_id'])) return true;
        $model = M('GoodsAttrStock');
        $where['goods_id'] = $post['goods_id'];
        $check = $model->where($where)->count();
        $is_edit = false;
        if (isset($post['act_id'])) {
            $is_edit = true;
            $get_goods_edit_val = $this->get_goods_edit_val($post['act_id']);
        }
        if ($check > 0) {//有商品属性库存等
            $list = $model->alias('gas')->where($where)->JOIN('LEFT JOIN __GOODS__ g ON gas.goods_id=g.id')->field('gas.*,g.shop_price')->select();
            foreach ($list as $k => $v) {
                $val = $this->get_goods_attr_stock_val($v['attr_key']);
                $listformat[$k]['id'] = $v['id'];//规格名称
                $listformat[$k]['name'] = $val['name'];//规格名称
                $listformat[$k]['price'] = $val['price'] + $v['shop_price'];//原价 商品价+属性递加结算价
                $listformat[$k]['stock_cfg'] = $v['stock_cfg'];//库存 属性库存
                if ($is_edit) $listformat[$k]['group_price'] = $get_goods_edit_val[$v['id']];
            }
        } else {
            $list = M('Goods')->where('id=' . $post['goods_id'])->field('goods_name,shop_price,goods_number,id')->find();
            $listformat[0]['id'] = $list['id'];//商品名称
            $listformat[0]['name'] = $list['goods_name'];//商品名称
            $listformat[0]['price'] = $list['shop_price'];//原价
            $listformat[0]['stock_cfg'] = $list['goods_number'];//库存 属性库存
            if ($is_edit) $listformat[0]['group_price'] = $get_goods_edit_val[$list['id']];
        }
        $result['list'] = $listformat;
        $this->assign($result);
        $this->display('goods_group_attr_val');
    }

    /**
     * 获取商品属性对应规格名称
     */
    public function get_goods_attr_stock_val($attr_key = '', $type = '')
    {
        $attr_key_array = explode('_', $attr_key);
        $model = M('GoodsAttr');
        $where['g.id'] = array('in', $attr_key_array);
        $price = $name = '';
        if (count($attr_key_array) > 0) {
            $list = $model->alias('g')->where($where)->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ ga ON g.attr_id=ga.id')->field('g.attr_price,g.attr_value,ga.options')->select();
            foreach ($list as $k => $v) {
                $price += $v['attr_price'];
                $options = strtoarray($v['options']);
                $name .= $options[$v['attr_value']] . " ";
            }
        }
        $result['price'] = $price;
        $result['name'] = $name;
        return $result;
    }

    /**
     * 获取拼团内容
     */
    public function get_goods_edit_val($act_id)
    {
        $model = M('PromotExt');
        $where['act_id'] = $act_id;
        $where['style'] = 4;
        $list = $model->where($where)->field('style_ext_id,remarks')->select();
        $arr = array();
        foreach ($list as $k => $v) {
            $arr = unserialize($v['remarks']);
            foreach ($arr['group_price'] as $key => $val) {
                $listformat[$key] = $val;
            }
        }
        return $listformat;
    }

    /**
     * 获取促销价格
     */
    public function get_goods_edit_price($act_id)
    {
        $model = M('PromotExt');
        $where['act_id'] = $act_id;
        $where['style'] = 5;
        $list = $model->where($where)->field('style_ext_id,remarks')->select();
        $arr = array();
        foreach ($list as $k => $v) {
            $arr = unserialize($v['remarks']);
            foreach ($arr['promot_price'] as $key => $val) {
                $listformat[$key] = $val;
            }
        }
        return $listformat;
    }

    /**
     * 获取商品信息
     */
    public function get_goods_info()
    {
        $get = I('get.');
        $array_id = array();
        if ($get['ides'] || $get['str_goods']) {
            $str_goods = $get['str_goods'] ? $get['str_goods'] : $get['ides'];
            $array_id = explode(',', $str_goods);
        }
        $is_edit = false;
        if (isset($get['act_id'])) {
            $is_edit = true;
            $get_goods_edit_price = $this->get_goods_edit_price($get['act_id']);
        }
        if ($get['goods_id']) {
            array_push($array_id, $get['goods_id']);
        }
        foreach ($array_id as $k => $v) {
            $info = idtoname($v, 'Goods', 'id,goods_name,shop_price', 'id', false);
            $listformat[$k] = $info;
            if ($is_edit) $listformat[$k]['promot_price'] = $get_goods_edit_price[$v];
        }
        $ids = implode(',', $array_id);
        $result['list'] = $listformat;
        $this->assign($result);
        $this->assign('ids', $ids);
        $this->display('goods_limit_time_info');
    }

    public function _before_delete()
    {
        $id = I('id');
        if (isset($id) && is_array($id)) {
            foreach ($id as $k => $v) {
                $result = check_delete($v, 8);
                if (!$result['status']) unset($id[$k]);
            }
            if (empty($id)) {
                $this->error($result['info']);
                exit;
            }
        } else {
            $result = check_delete($id, 8);
            if (!$result['status']) {
                $this->error($result['info']);
                exit;
            }
        }
        $this->id = $id;
    }

    public function view(){
        $id = I('get.id');
        //团长列表
        $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['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();
    }

    public function view_son(){
        $id = I('get.id');
        $team_mes = M('OrderInfo')->where('id='.$id)->find();
        $where['pid'] = $id;
        $where['pay_status'] = 3;
        $where['confirm_time'] = array('neq',0);
        $list = $this->lists('OrderInfo', $where, 'id desc');
        $this->assign('list',$list);
        $this->assign('team_mes',$team_mes);
        $this->display();
    }
    /*搜索添加包装选择商品*/
    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['is_offline']=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;
            }
        }
        $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')->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'].'"><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;
        $map['is_offline']=1;//线上
        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;
            }
        }
        $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 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('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');
        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=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();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();
        }
    }
    /**
     * 代金券导出
     *
     */
    public function export(){
        $rest=$this->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;
    }
      /* 得到所属组 */
      private function getGroup($type = ''){
        $groupData = M('MemberRank')->where('status=1')->field(true)->order('sort,id desc')->select();
        if ($type == 1) {
            foreach ($groupData as $v) {
                $newgroupData[$v['id']] = $v['name'];
            }$groupData=$newgroupData;
        }
        $this->assign('groupData', $groupData);
    }


}
?>