<?php
/**
 * 统计
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Shop\Controller;
use Think\Controller;
class TongjiController 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->shops_info=$shops_info;
        $this->mendian();
        $auth_code = 'statistics';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}
    }
    // 交接班日结报表start
    /**
    * lss 2018-9-8修改
    * @param bool $is_return
    * @return array
    */
    public function cashier_index($is_return=false){
        $postdata=I('param.');
        $map=array();
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from)$map['start_time'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['date_to'])+86399;
            if($date_to)$map['start_time'][] = 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['start_time']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
         $map['shop_id']=MID;
        if(!empty($postdata['cashier_name'])) $map['cashier_name']=$postdata['cashier_name'];
        $list=$this->lists('TurnOver',$map,'id desc','','',15);
        $list_e=M('TurnOver')->where($map)->select();
        $data=array();
        $field='sum(all_price) as total_price,sum(all_num) as total_num,sum(re_price) as total_re_price,sum(re_num) as total_re_num,sum(recharge_price) as total_recharge_price,sum(recharge_num) as total_recharge_num,sum(on_price) as total_on_price,sum(on_num) as total_on_num,sum(yue_price) as total_yue_price,sum(card_price) as total_card_price,sum(online_price) as total_online_price,sum(weixin_price) as total_weixin_price,sum(alipay_price) as total_alipay_price,sum(cash_price) as total_cash_price,sum(re_alipay_price) as total_re_alipay_price,sum(re_cash_price) as total_re_cash_price,sum(re_weixin_price) as total_re_weixin_price,sum(re_online_price) as total_re_online_price,sum(re_yue_price) as total_re_yue_price,sum(re_card_price) as total_re_card_price,sum(pre_paid_price) as total_pre_paid_price,sum(pre_paid_num) as total_pre_paid_num';
        $data=M('TurnOver')->where($map)->field($field)->find();
        $data['count_total']=M('TurnOver')->where($map)->count();
        $map=array();
        $map['status']=1;
        $shops_list=M('Shops')->where($map)->field('id,name')->order('name')->cache(true)->select();
        $shops_list=format_array2select($shops_list);
        if($is_return==false) {
            $this->assign('shops_list', $shops_list);
            $this->assign('list', $list);
            $this->assign('data',$data);
            $this->assign($postdata);
            $this->display();
        }else{
            $return=array('data'=>$data,'list'=>$list_e);
            return $return;
        }
    }
    /**
     * lss 2018-9-8修改
     */
    public function export_pur(){
        $guide_list=$this->cashier_index(true);
        $title = array('序号', '开始时间', '结束时间','收银员','总销售金额','总订单数','总退款金额','总退款数','会员充值金额','会员充值数','网上订单总金额','网上订单总数','礼品卡订单总金额','礼品卡订单总数','余额','现金','刷卡','线上支付','微信','支付宝','现金退款','余额退款','打印次数');
        $data = array();
        foreach ($guide_list['list'] as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = time_format($v['start_time']);
            $data[$k][] = time_format($v['end_time']);
            $data[$k][] = $v['cashier_name'];
            $data[$k][] = $v['all_price'];
            $data[$k][] = $v['all_num'];
            $data[$k][] = $v['re_price'];
            $data[$k][] = $v['re_num'];
            $data[$k][] = $v['recharge_price'];
            $data[$k][] = $v['recharge_num'];
            $data[$k][] = $v['on_price'];
            $data[$k][] = $v['on_num'];
            $data[$k][] = $v['pre_paid_price'];
            $data[$k][] = $v['pre_paid_num'];
            $data[$k][] = $v['yue_price'];
            $data[$k][] = $v['cash_price'];
            $data[$k][] = $v['card_price'];
            $data[$k][] = $v['online_price'];
            $data[$k][] = $v['weixin_price'];
            $data[$k][] = $v['alipay_price'];
            $data[$k][] = $v['re_cash_price'];
            $data[$k][] = $v['re_yue_price'];
            $data[$k][] = $v['print_num'];
        }
        $data[]=array(
            '总计：',
            '--',
            '--',
            '--',
            $guide_list['data']['total_price'],
            $guide_list['data']['total_num'],
            $guide_list['data']['total_re_price'],
            $guide_list['data']['total_re_num'],
            $guide_list['data']['total_recharge_price'],
            $guide_list['data']['total_recharge_num'],
            $guide_list['data']['total_on_price'],
            $guide_list['data']['total_on_num'],
            $guide_list['data']['total_pre_paid_price'],
            $guide_list['data']['total_pre_paid_num'],
            $guide_list['data']['total_yue_price'],
            $guide_list['data']['total_cash_price'],
            $guide_list['data']['total_card_price'],
            $guide_list['data']['total_online_price'],
            $guide_list['data']['total_weixin_price'],
            $guide_list['data']['total_alipay_price'],
            $guide_list['data']['total_re_cash_price'],
            $guide_list['data']['total_re_yue_price'],
            '共计'.$guide_list['data']['count_total'].'条',
        );
        export_csv('交接班明细.csv',$title,$data);
        unset($title, $data);
        exit;
    }
    /**收银日报表
     *
    */
    public function cashier($is_return=false){
        $postdata=I('param.');
        $map=array();
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from)$map['start_time'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['date_to'])+86399;
            if($date_to)$map['start_time'][] = 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['start_time']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        // if(!empty($postdata['shop_id'])) $map['shop_id']=$postdata['shop_id'];
        $map['shop_id']=MID;
        if(!empty($postdata['cashier_name'])) $map['cashier_name']=$postdata['cashier_name'];
//        $list=$this->lists('TurnOver',$map,'id desc');
        $field="sum(all_price) as total_price,sum(all_num) as total_num,sum(re_price) as total_re_price,sum(re_num) as total_re_num,sum(recharge_price) as total_recharge_price,sum(recharge_num) as total_recharge_num,sum(on_price) as total_on_price,sum(on_num) as total_on_num,sum(yue_price) as total_yue_price,sum(card_price) as total_card_price,sum(online_price) as total_online_price,sum(weixin_price) as total_weixin_price,sum(alipay_price) as total_alipay_price,sum(cash_price) as total_cash_price,sum(re_alipay_price) as total_re_alipay_price,sum(re_cash_price) as total_re_cash_price,sum(re_weixin_price) as total_re_weixin_price,sum(re_online_price) as total_re_online_price,sum(re_yue_price) as total_re_yue_price,sum(re_card_price) as total_re_card_price,sum(print_num) as total_print,start_time,end_time,shop_id";
        $list=M('TurnOver')->where($map)->field($field)->group("DATE_FORMAT(FROM_UNIXTIME(start_time),'%Y年%m月%d天')")->select();
        $data=array();
        $field2="sum(all_price) as total_price,sum(all_num) as total_num,sum(re_price) as total_re_price,sum(re_num) as total_re_num,sum(recharge_price) as total_recharge_price,sum(recharge_num) as total_recharge_num,sum(on_price) as total_on_price,sum(on_num) as total_on_num,sum(yue_price) as total_yue_price,sum(card_price) as total_card_price,sum(online_price) as total_online_price,sum(weixin_price) as total_weixin_price,sum(alipay_price) as total_alipay_price,sum(cash_price) as total_cash_price,sum(re_alipay_price) as total_re_alipay_price,sum(re_cash_price) as total_re_cash_price,sum(re_weixin_price) as total_re_weixin_price,sum(re_online_price) as total_re_online_price,sum(re_yue_price) as total_re_yue_price,sum(re_card_price) as total_re_card_price,sum(print_num) as total_print";
        $data=M('TurnOver')->where($map)->field($field2)->find();
        $map['group']="DATE_FORMAT(FROM_UNIXTIME(start_time),'%Y年%m月%d天')";
        $pagelist=page_list('TurnOver',$map,'id desc',$field,15);
        $data['count_total']=$pagelist['count'];
        $map=array();
        $map['status']=1;
        $shops_list=M('Shops')->where($map)->field('id,name')->order('name')->cache(true)->select();
        $shops_list=format_array2select($shops_list);
        if($is_return==false) {
            $this->assign('shops_list', $shops_list);
            $this->assign($pagelist);
            $this->assign($data);
            $this->assign($postdata);
            $this->display();
        }else{
            $return=array('data'=>$data,'list'=>$list);
            return $return;
        }
    }
    /**
     * 收银日报表导出
     */
    public function export(){
        $guide_list=$this->cashier(true);
        $title = array('序号','门店','当班日期', '开始时间', '结束时间','总销售金额','总订单数','总退款金额','总退款数','会员充值金额','会员充值数','网上订单总金额','网上订单总数','余额','现金','刷卡','线上支付','微信','支付宝','现金退款','余额退款','打印次数');
        $data = array();
        $i=0;
        foreach ($guide_list['list'] as $k => $v) {
            $i++;
            $data[$k][] = $i;
            $data[$k][] = idtoname($v['shop_id'],'Shops');
            $data[$k][] = date('Y-m-d',$v['start_time']);
            $data[$k][] = time_format($v['start_time']);
            $data[$k][] = time_format($v['end_time']);
            $data[$k][] = $v['total_price'];
            $data[$k][] = $v['total_num'];
            $data[$k][] = $v['total_re_price'];
            $data[$k][] = $v['total_re_num'];
            $data[$k][] = $v['total_recharge_price'];
            $data[$k][] = $v['total_recharge_num'];
            $data[$k][] = $v['total_on_price'];
            $data[$k][] = $v['total_on_num'];
            $data[$k][] = $v['total_yue_price'];
            $data[$k][] = $v['total_cash_price'];
            $data[$k][] = $v['total_card_price'];
            $data[$k][] = $v['total_online_price'];
            $data[$k][] = $v['total_weixin_price'];
            $data[$k][] = $v['total_alipay_price'];
            $data[$k][] = $v['total_re_cash_price'];
            $data[$k][] = $v['total_re_yue_price'];
            $data[$k][] = $v['total_print'];
        }
        $data[]=array(
            '总计：',
            '--',
            '--',
            '--',
            '--',
            $guide_list['data']['total_price'],
            $guide_list['data']['total_num'],
            $guide_list['data']['total_re_price'],
            $guide_list['data']['total_re_num'],
            $guide_list['data']['total_recharge_price'],
            $guide_list['data']['total_recharge_num'],
            $guide_list['data']['total_on_price'],
            $guide_list['data']['total_on_num'],
            $guide_list['data']['total_yue_price'],
            $guide_list['data']['total_cash_price'],
            $guide_list['data']['total_card_price'],
            $guide_list['data']['total_online_price'],
            $guide_list['data']['total_weixin_price'],
            $guide_list['data']['total_alipay_price'],
            $guide_list['data']['total_re_cash_price'],
            $guide_list['data']['total_re_yue_price'],
            '共计'.$guide_list['data']['count_total'].'条',
        );
        export_csv('日结报表.csv',$title, $data);
        unset($title, $data);
        exit;
    }
    // 交接班日结报表end
    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;
    }
// 商品销售 start
   /**
    * 商品销售统计
    */
    public function all_goods($is_return=false){
        $postdata=I('param.');
        $postdata['shop_id']=MID;
        $sale_type = array('1'=>'线下','2'=>'线上');
        $goods_ids=$map=$data=array();
        if (!empty($postdata['catid'])) {
            $cat_sons = get_children($postdata['catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = $rg_map=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';
              $where_g['_complex'] = $where;
            }
            $goods_ids = M('Goods')->where($where_g)->getField('id',true);
        }
        if($postdata['shop_id']){
            $map['shop_id']=$postdata['shop_id'];
            $rg_map['shop_id']=$postdata['shop_id'];
        }
        $map['type'] = array('in','1,6,11,13,14');
        $map['pay_status'] = 3;
        $map['status'] = array('in','1,2,3,6,8');
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from){
              $map['addtime'][] = array('egt',$date_from);
              $rg_map['add_time'][]=array('egt',$date_from);
            }
            $date_to = strtotime($postdata['date_to']);
            if($date_to){
              $date_to=$date_to+83699;
              $map['addtime'][] = array('lt',$date_to);
              $rg_map['add_time'][]=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['addtime']=array('between',array($between[0],$between[1]));
              $rg_map['add_time']=array('between',array($between[0],$between[1]));
            }else{
              $postdata['dates']=99;
            }
        }
        if($postdata['in_online']==1){
            $map['in_online']=$postdata['in_online'];
        }else if($postdata['in_online']==2){
            $map['in_online']=0;
        }
        $order_ids = M('OrderInfo')->where($map)->getField('id',true);
        if(!empty($order_ids)){
          $map=$list_e= array();
          if($postdata['keyword']){
              $map['goods_sn|goods_name'] = array('like','%'.$postdata['keyword'].'%');
          }
          $map['order_id'] = array('in',$order_ids);
          // $map['goods_sn'] = array('neq','');
          if($goods_ids){
              $map['goods_id'] = array('in',$goods_ids);
          }
          // $all = M('OrderGoods')->where($map)->field("sum(goods_price*goods_number) as all_price,sum(supplier_price*goods_number) as all_sprice,sum(profit) as all_profit,sum(goods_number) as goodsallnum,sum(attr_price*goods_number) as attr_price")->find();
          // $order = 'sum(goods_number) desc';
          // $field = 'goods_id,goods_sn,goods_name,sum(goods_price*goods_number) as goodsprice,sum(supplier_price*goods_number) as supplierprice,sum(profit) as profits,sum(goods_number) as num,sum(attr_price*goods_number) as attr_price';
          // $lists=M('OrderGoods')->where($map)->field($field)->group('goods_id')->order($order)->select();
            $map['_string']='goods_id > 0';
            $all = M('OrderGoods')->where($map)->field("goods_id,goods_sn,goods_name,sum(goods_price*goods_number) as all_price,sum(supplier_price*goods_number) as all_sprice,sum(profit) as all_profit,sum(goods_number) as goodsallnum,sum(attr_price*goods_number) as attr_price")->find();
            $order = 'sum(goods_number) desc';
            $field = 'goods_id,goods_sn,goods_name,sum(goods_price*goods_number) as goodsprice,sum(supplier_price*goods_number) as supplierprice,sum(profit) as profits,sum(goods_number) as num,sum(attr_price*goods_number) as attr_price';
            $lists=M('OrderGoods')->where($map)->field($field)->group('goods_id')->order($order)->select();
            $map['group'] = 'goods_id';
          // $map['group'] = 'goods_id';
          $map['group'] = 'goods_sn';
          $list = page_list('OrderGoods',$map,$order,$field,20);
        }
        $all_tuimoney=$all_tuinum=$all_sprice=$all_profit=$all_price=$num=0;
        $ret_goodids=array();
        if($lists){
          foreach ($lists as $key => $value) {
              $ret_goodids[]=$value['goods_id'];
          }unset($key,$value);
          if(empty($ret_goodids))$ret_goodids=0;
          $rg_map['type']=0;
          $rg_map['org_id']=array('in',$ret_goodids);
          $return_goods = M('ReturnGoods')->where($rg_map)->field('org_id,goods_info,money')->select();
          $returngoods=array();
          if($return_goods){
              foreach($return_goods as $v){
                if(empty($returngoods[$v['org_id']]['tui_num']))$returngoods[$v['org_id']]['tui_num']=0;
                if(empty($returngoods[$v['org_id']]['tui_money']))$returngoods[$v['org_id']]['tui_money']=0;
                $tui_num=unserialize($v['goods_info']);
                $returngoods[$v['org_id']]['tui_num']+=$tui_num['number'];
                $returngoods[$v['org_id']]['tui_money']+=$v['money'];
              }
          }
          foreach ($lists as $key => $value) {
              $list_e[$key]=$value;
              $tui_num=floatval($returngoods[$value['goods_id']]['tui_num']);
              $tui_money=floatval($returngoods[$value['goods_id']]['tui_money']);
              $list_e[$key]['tui_num']=$tui_num;
              $list_e[$key]['tui_money']=$tui_money;
                $list_e[$key]['avg_price']=format_decimal($value['attr_price']/$value['goods_number']);
                $list_e[$key]['profit_p']=format_decimal($value['profits']*100/$value['supplierprice']).'%';
              if($list['list'][$key]['goods_id']==$value['goods_id']){
            $list['list'][$key]['tui_num']=$tui_num;
            $list['list'][$key]['tui_money']=$tui_money;
              }
              $all_tuinum+=$tui_num;
              $all_tuimoney+=$tui_money;
          }
          $data=$all;
          $data['all_tuinum']=floatval($all_tuinum);
          $data['all_tuimoney']=$all_tuimoney;
          $data['avg_price']=format_decimal($all['attr_price']/$all['goodsallnum']);
          $data['profit_a']=format_decimal($all['all_profit']*100/$all['all_sprice']).'%';
          $orderids=implode(',',$order_ids);
        }
        if($is_return==false){
          $this->assign('orderids',$orderids);
          $this->assign($list);
          $this->assign($data);
          $this->add_getcateTree($postdata['catid'], '');
          $this->assign('sale_type',$sale_type);
          $this->assign($postdata);
          $this->display();
        }else{
            return $return=array('data'=>$data,'list'=>$list_e);
        }
    }
    /**
    * 得到节点树
    */
    private function add_getcateTree($pid = '', $assign = ''){
        $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);
    }
// 单品统计开始 后台照搬
    /**
    *单品统计
    */
    public function single_tu(){
        /*获取时间数组开始*/
        $type = I('type');
        $postdata = I('param.');$postdata['shop_id']=MID;
        if(!$postdata['goods_id']){
            $this->error('数据错误');exit;
        }
        //导购员列表
        $sales_list=D('Admin/Shops')->guider_list();
        //门店列表
        $shops_list=D('Admin/Shops')->shop_list();
        //收银员列表
        // $cashier_list_arr=D('Admin/Shops')->cashier_list();
        $cashier_list_arr=$this->cashier_list();
        $this->assign('sales_list', $sales_list);
        $this->assign('shops_list',$shops_list);
        $this->assign('cashier_list',$cashier_list_arr);
        $this->assign('goods_name',idtoname($postdata['goods_id'],'Goods','goods_name','id',false));
        $day_arr = array();
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        $new_map = $map = array();
        if(!empty($postdata['sale_id'])) $map['oi.guide']=$postdata['sale_id'];
        if(!empty($postdata['shop_id'])) $map['oi.shop_id']=$postdata['shop_id'];
        if(!empty($postdata['cashier_id'])) $map['oi.sa_id']=$postdata['cashier_id'];
        $map['a.goods_id']=$postdata['goods_id'];
        $map['oi.type'] = array('in','1,6,11,13,14');
        $map['oi.pay_status'] = 3;
        $map['oi.status'] = array('in','1,2,3,6,8');
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from){
              $map['oi.addtime'][] = array('egt',$date_from);
            }else{
              $this->error("请选择搜索开始时间");exit;
            }
            $date_to = strtotime($postdata['date_to']);
            if($date_to){
              $map['oi.addtime'][] = array('lt',$date_to+86399);
            }else{
              $this->error("请选择搜索结束时间");exit;
            }
            $type=0;
        }else{
          if(in_array($type,array(7,30))){
              $between=$this->quick_time($type);
              $date_from=$between[0];
              $date_to =$between[1];
              $map['oi.addtime']=array('between',array($between[0],$between[1]));
          }else{
              $type=3;
              $date_from=$now_time-6*86400;
              $date_to =$now_time+86399;
              $map['oi.addtime']=array('between',array($date_from,$date_to));
          }
        }
        $this->assign('type',intval($type));
        if(in_array($type,array(1,2,3,7))){
            $days=7;
        }else if($type ==30){
            $days=30;
        }else{
            $days=ceil(($date_from-$date_to)/86400);
        }
        for($i=0;$i<$days;$i++){
            $day_arr[date('Y-m-d',$now_time-$i*86400)] = date('Y-m-d',$now_time-$i*86400); //每隔一天赋值给数组
        }
        $new_map=$map;
        $ec = new \Common\Vendor\Echarts();
        /*获取时间数组结束*/
        /*单品销售趋势统计开始*/
        $this->goods_trend($new_map,$day_arr,$date_from,$date_to,$ec);unset($map);
        /*单品销售时段统计*/
        $this->goods_time($new_map,$day_arr,$date_from,$date_to,$ec);unset($map);
        $this->single_goods($new_map,$day_arr,$date_from,$date_to);unset($map);
        $this->assign($postdata);
        if($postdata['print']){$this->display('single_tu_print');}else{
            $this->display();
        }
    }
     /**
    * 单品销售统计
    */  
    public function single_goods($newmap,$day_arr,$date_from,$date_to){
          $map=$newmap;
        $list_e= array();
        $join='JOIN __ORDER_INFO__ oi ON oi.id = a.order_id';
        $all = M('OrderGoods')->alias('a')->where($map)->join($join)->field("a.goods_id,sum(a.goods_price*a.goods_number) as all_price,sum(a.supplier_price*a.goods_number) as all_sprice,sum(a.profit) as all_profit,sum(a.goods_number) as goodsallnum,sum(a.attr_price*a.goods_number) as attr_price")->find();
        $order = 'a.goods_number desc';
        $field = 'sum(a.goods_price*a.goods_number) as goodsprice,sum(a.supplier_price*a.goods_number) as supplierprice,sum(a.profit) as profits,sum(a.goods_number) as num,oi.shop_id';
        $lists=M('OrderGoods')->alias('a')->where($map)->join($join)->field("sum(a.goods_price*a.goods_number) as goodsprice,sum(a.supplier_price*a.goods_number) as supplierprice,sum(a.profit) as profits,sum(a.goods_number) as num,oi.shop_id")->group('oi.shop_id')->select();
        $map['group']='oi.shop_id';
        $list = page_list('OrderGoods',$map,$order,$field,20,$join);
        $all_tuimoney=$all_tuinum=$all_sprice=$all_profit=$all_price=$num=0;
        $ret_shopid=$rg_map=array();
        if($list['list']){
      foreach ($list['list'] as $key => $value) {
          $ret_shopid[]=$value['shop_id'];
      }unset($key,$value);
      if(empty($ret_shopid))$ret_shopid[]=0;
      $rg_map['type']=0;
      $rg_map['org_id']=$map['a.goods_id'];
      $rg_map['shop_id']=array('in',$ret_shopid);
      $return_goods = M('ReturnGoods')->where($rg_map)->field('shop_id,goods_info,money')->select();
      $returngoods=array();
      if($return_goods){
          foreach($return_goods as $v){
        if(empty($returngoods[$v['shop_idshop_id']]['tui_num']))$returngoods[$v['shop_id']]['tui_num']=0;
        if(empty($returngoods[$v['shop_id']]['tui_money']))$returngoods[$v['shop_id']]['tui_money']=0;
        $tui_num=unserialize($v['goods_info']);
        $returngoods[$v['shop_id']]['tui_num']+=$tui_num['number'];
        $returngoods[$v['shop_id']]['tui_money']+=$v['money'];
          }
      }
      foreach ($lists as $key => $value) {
          $list_e[$key]=$value;
          $tui_num=floatval($returngoods[$value['goods_id']]['tui_num']);
          $tui_money=floatval($returngoods[$value['goods_id']]['tui_money']);
          $list_e[$key]['avg_price']=format_decimal($value['attr_price']/$value['goods_number']);
          $list_e[$key]['profit_p']=format_decimal($value['profits']*100/$value['supplierprice']).'%';
          $list_e[$key]['tui_num']=$tui_num;
          $list_e[$key]['tui_money']=$tui_money;
          if($list['list'][$key]['shop_id']==$value['shop_id']){
        $list['list'][$key]['tui_num']=$tui_num;
        $list['list'][$key]['tui_money']=$tui_money;
          }
          $all_tuinum+=$tui_num;
          $all_tuimoney+=$tui_money;
      }
      $data=$all;
      $data['all_tuinum']=floatval($all_tuinum);
      $data['all_tuimoney']=$all_tuimoney;
      $data['profit_a']=format_decimal($all['all_profit']*100/$all['all_sprice']).'%';
        }
        $this->assign($data);
        $this->assign('list',$list);
    }
     public function goods_trend($map,$day_arr,$date_from,$date_to,$ec){
        $info=M('OrderGoods')->alias('a')->where($map)->join('__ORDER_INFO__ oi ON a.order_id=oi.id')->field("a.goods_number,(a.goods_number*a.goods_price) as all_money,DATE_FORMAT(FROM_UNIXTIME(a.addtime),'%Y-%m-%d') as mon")->group("DATE_FORMAT(FROM_UNIXTIME(a.addtime),'%Y年%m月%d天')")->select();
        $name = array("销量","金额");
        if($info){
            foreach($info as $key => $value){
                if(!empty($value)){
                    $file_num[$value['mon']]=floatval($value['goods_number']);
                    $file_time[$value['mon']]=$value['mon'];
                    $file_money[$value['mon']]=format_decimal($value['all_money']);
                }
            }unset($value,$key);
        }       
        $new_day=array_diff($day_arr,$file_time);
        foreach($new_day as $v){
            $file_num[$v]=0;
            $file_money[$v]=0;
        }unset($v);
        ksort($file_num);
        ksort($file_money);
        //得到折线图
        $cz_count = array(
            "legend"=>array('data'=>array($name[0],$name[1])),
            "xaxis"=>array("type"=>"category","data"=>array_keys($file_num)),
            "series"=>array(
                0=>array("name"=>$name[0],"type"=>"line","stack"=>$name[0],'itemStyle'=>array(),"data"=>array_values($file_num)),
                1=>array("name"=>$name[1],"type"=>"line","stack"=>$name[1],"data"=>array_values($file_money)),
            ),
        );
        $this->assign('goods_tend',$ec->show('goods_tend',$cz_count,'line'));
    }
    public function goods_time($map,$day_arr,$date_from,$date_to,$ec){
        $count = M('OrderGoods')->alias('a')->where($map)->join('__ORDER_INFO__ oi ON a.order_id=oi.id')->field("a.goods_number,a.addtime as l_month")->group("DATE_FORMAT(FROM_UNIXTIME(a.addtime),'%G')")->select();
        $counts=$datas=$time=array();
        if($count){
        foreach($count as $value){
      $counts[date('G',$value['l_month'])] = floatval($value['goods_number']);
        }
        $count1=$count2=$count3=$count4=$count5=$count6=0;
        for($i=0;$i<24;$i++){
      if($counts[$i]){
          if($i<4 && $i>=0){
        $count1+=$counts[$i];
          }
          if($i<8 && $i>=3){
        $count2+=$counts[$i];
          }
          if($i<12 && $i>=8){
        $count3+=$counts[$i];
          }
          if($i<16 && $i>=12){
        $count4+=$counts[$i];
          }
          if($i<20 && $i>=16){
        $count5+=$counts[$i];
          }
          if($i<24 && $i>=20){
        $count6+=$counts[$i];
          }
      }
        }
        $time=array('00:00-03:59','04:00-07:59','08:00-11:59','12:00-15:59','16:00-19:59','20:00-23:59');
        $datas=array(
          array("value"=>$count1,"name"=>"00:00-03:59"),
          array("value"=>$count2,"name"=>"04:00-07:59"),
          array("value"=>$count3,"name"=>"08:00-11:59"),
          array("value"=>$count4,"name"=>"12:00-15:59"),
          array("value"=>$count5,"name"=>"16:00-19:59"),
          array("value"=>$count6,"name"=>"20:00-23:59"),
        );
        if($count1==0){unset($datas[0]);unset($time[0]);}
        if($count2==0){unset($datas[1]);unset($time[1]);}
        if($count3==0){unset($datas[2]);unset($time[2]);}
        if($count4==0){unset($datas[3]);unset($time[3]);}
        if($count5==0){unset($datas[4]);unset($time[4]);}
        if($count6==0){unset($datas[5]);unset($time[5]);}
        $datas=array_merge($datas);$time=array_merge($time);
        $goods_time = array(
            "legend"=>array('data'=>$time),
            "series"=>array(
          array("name"=>"销售时段分析","type"=>"pie",
              'radius'=>'50%',
              "data"=>$datas,
          ),
            ),
        );
        $this->assign('goods_time',$ec->pie_show('goods_time',$goods_time,'pie',''));
        }
    }
// 单品统计结束
    /**
	* 商品汇总统计
	*
	*/
    public function export_su(){
         $list=$this->all_goods(true);
        $i=0;
        $data=array();
        foreach ($list['list'] as $k => $v) {
            $i++;
            $data[$i]['n']=$i;
            $data[$i]['goods_sn']=$v['goods_sn'];
            $data[$i]['goods_name']=$v['goods_name'];
            $data[$i]['goodsprice']=format_decimal($v['goodsprice']);
            $data[$i]['supplierprice']=format_decimal($v['supplierprice']);
            $data[$i]['num']=floatval($v['num']);
            $data[$i]['tui_num']=floatval($v['tui_num']);
            $data[$i]['profits']=format_decimal($v['goodsprice']-$v['supplierprice']);
            $data[$i]['tui_money']=format_decimal($v['tui_money']);
            $data[$i]['avg_price']=format_decimal($v['attr_price']/$v['num']);
            $data[$i][]=format_decimal($v['profits']);
            $data[$i]['profit_p']=format_decimal($v['profits']*100/$v['supplierprice']).'%';
        }
        $data[]=array('总计','--','--',format_decimal($list['data']['all_price']),format_decimal($list['data']['all_sprice']),$list['data']['goodsallnum'],$list['data']['all_tuinum'],format_decimal($list['data']['all_price']-$list['data']['all_sprice']),format_decimal($list['data']['all_tuimoney']),format_decimal($list['data']['avg_price']),format_decimal($list['data']['all_profit']),$list['data']['profit_a']);
        $title = array('序号', '商品编号', '商品名称','销售额','成本金额','销量','退货数量','实际销售额','退货金额','平均售价','利润','利润率');
        export_csv('商品销售统计.csv',$title,$data);
        exit;
    }
    // 商品销售明细
    public function sale_goods(){
        $postdata=I('param.');
        $postdata['shop_id']=MID;
        $where_g = $map = array();
        $size = 20;
        if($postdata['shop_id']){
            $shop_id = $postdata['shop_id'];
            $map['oi.shop_id'] = $shop_id;
        }
        $sale_type = array('1'=>'线下','2'=>'线上');
        if (!empty($postdata['catid'])) {
            $cat_sons = get_children($postdata['catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['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';
                $where_g['_complex'] = $where;
            }
            $goods_ids = M('Goods')->where($where_g)->getField('id',true);
            if($goods_ids){
                $map['a.goods_id'] = array('in',$goods_ids);
            }
        }
        $map['oi.type'] = array('in','1,6,11,13,14');
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from)$map['a.addtime'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['date_to']);
            if($date_to){$date_to = $date_to +83699;$map['a.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['a.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;
        }
        $map['oi.status'] = 3;
        $join = 'JOIN __ORDER_INFO__ oi ON oi.id = a.order_id';
        $field = 'a.*,a.goods_number*a.goods_price as sum_price,oi.order_sn,oi.goods_amount,oi.uid,oi.type,oi.in_online';
        if($postdata['keyword']){
            $map['a.goods_sn|a.goods_name'] = array('like','%'.$postdata['keyword'].'%');
        }
        $map['a.status'] = array('not in','4,5');
        $order = 'a.id desc';
        $order_goods = page_list('OrderGoods',$map,$order,$field,$size,$join);
         $ys=idtoname(MID,'Shops','is_hide_phone');
        foreach ($order_goods['list'] as $k => $val) {
            $username=show_user_name($val['uid']);
            if(strlen($username)==11 && $ys){
                $order_goods['list'][$k]['username']=str_cutmobile($username);
            }else{
                $order_goods['list'][$k]['username']=$username;
            }
        }
        $all_og = M('OrderGoods')->alias('a')->where($map)->join('__ORDER_INFO__ oi ON a.order_id=oi.id')->field("sum(a.goods_number) as goods_num,sum(a.goods_price) as goods_price,sum(a.goods_number*a.goods_price) as all_money,sum(a.profit) as all_profit")->find();
        $this->assign($order_goods);
        $this->assign($all_og);
        $this->add_getcateTree($postdata['catid'], '');
        $this->assign('sale_type',$sale_type);
        $this->assign($postdata);
        $this->display();
    }
    // 商品销售 end
    // 订单start
    public function shops(){//订单明细
         $this->assign('shop_name',$this->shops_info['name']);
        $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);
        $guider_list=D('Admin/Shops')->guider_list();
        $this->assign('guider_list',$guider_list);
        $map=array();
        $postdata=I('param.');
        $map['type']=array('in','1,6,11,12,13,14');
        $map['is_delete']=0;
        $map['pay_status']=3;
        $map['status']=array('in','1,2,3,6,8');
        if($postdata['order_sn'])$map['order_sn']=$postdata['order_sn'];
        $map['shop_id'] =MID;
        if($postdata['source']){
            $map['source'] = $postdata['source'];
        }
        if($postdata['keyword']){
            $map_m['id|username|nickname|real_name|card_sn']=$postdata['keyword'];
            $uids=M('Member')->where($map_m)->getField('id',true);
            $map['uid'] = array('in',$uids);
        }
        $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['addtime'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['reg_to'])+86399;
            if($date_to)$map['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['addtime']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
         if($postdata['guider_id']){
            $map['guide']=$postdata['guider_id'];
        }
        if($postdata['in_online']==1){
            $map['in_online']=$postdata['in_online'];
        }elseif($postdata['in_online']==2){
            $map['in_online']=0;
        }
        $ys=idtoname(MID,'Shops','is_hide_phone');
        if($postdata['print']==1){
            $list=M('OrderInfo')->where($map)->select();
            foreach ($list as $k => $val) {
                $username=show_user_name($val['uid']);
                if(strlen($username)==11 && $ys){
                    $list[$k]['username']=str_cutmobile($username);
                }else{
                    $list[$k]['username']=$username;
                }
            }
            $this->shop_export($list);
        }
        $list = $this->lists('OrderInfo',$map);
        foreach ($list as $k => $val) {
            $username=show_user_name($val['uid']);
            if(strlen($username)==11 && $ys){
                $list[$k]['username']=str_cutmobile($username);
            }else{
                $list[$k]['username']=$username;
            }
            // ggw 1215推广佣金钱数
            $smap=[];
            $s_map['order_id']=$val['id'];
            $s_map['is_separate']=array('neq','3');
            $fy=M('AffiliateLog')->where($s_map)->getField('sum(money)');
            $list[$k]['affiliate']=$fy?$fy:0;
            // ggw end
        }
        // $orderinfo = M('OrderInfo')->where($map)->field("count(id) as num,sum(bonus_money) as bonus_money,sum(discount) as act_money,sum(member_discount) as member_discount,sum(goods_allmoney) as goodsmoney,sum(order_amount) as order_amount,sum(profit) as profit,sum(first_money) as firstmoney,sum(delivery_fee) as deliveryfee,sum(lunch_box_price) as lb_price")->find();
        // $youhui = $orderinfo['bonus_money']+$orderinfo['act_money']+$orderinfo['member_discount']+$orderinfo['firstmoney'];
        // $ying_money = $orderinfo['goodsmoney']+$orderinfo['deliveryfee']+$orderinfo['lb_price'];
        // $this->assign($orderinfo);
        // $this->assign('youhui',$youhui);
        // $this->assign('ying_money',$ying_money);
        // $this->assign('list',$list);$this->assign($postdata);
        // $this->display();
        $orderinfo = M('OrderInfo')->where($map)->field("count(id) as num,sum(discount) as act_money,sum(member_discount) as member_discount,sum(goods_allmoney) as goodsmoney,sum(order_money) as order_money,sum(profit) as profit,sum(first_money) as firstmoney,sum(delivery_fee) as deliveryfee")->find();
        $youhui = $orderinfo['act_money'];
        $ying_money = $orderinfo['goodsmoney'];
        $this->assign($orderinfo);
        $this->assign('youhui',$youhui);
        $this->assign('ying_money',$ying_money);
        $this->assign('list',$list);$this->assign($postdata);
        $this->display();
    }
    // 导出
    public function shop_export($list){
        $i=0;
        $data=array();
        $order_source=strtoarray(array('1'=>'微信','2'=>'移动收银','3'=>'小程序','4'=>'收银HD'));
        $guider_list=D('Admin/Shops')->guider_list();
        foreach($list as $k=>$v){
            $smap=[];
            $s_map['order_id']=$v['id'];
            $s_map['is_separate']=array('neq','3');
            $fy=M('AffiliateLog')->where($s_map)->cache(true)->getField('sum(money)');
            $v['affiliate']=$fy?$fy:0;
            // $data[$i]=array( $v['id'],"'".$v['order_sn'],date('Y-m-d H:i:s',$v['addtime']),$v['username'],$v['order_amount'],format_decimal($v['profit']),$guider_list[$v['guide']],idtoname($v['sa_id'],'ShopsAccount'),$v['in_online']?'线下':'线上',$v['source']?$order_source[$v['source']]:'PC');
            $data[$i]=array( $v['id'],"'".$v['order_sn'],date('Y-m-d H:i:s',$v['addtime']),$v['username'],$v['goods_amount'],$v['discount'],$v['delivery_fee'],$v['order_amount'],$v['sales_maid'],$v['affiliate'],$guider_list[$v['guide']],idtoname($v['sa_id'],'ShopsAccount'),$v['in_online']?'线下':'线上',$v['source']?$order_source[$v['source']]:'PC');
            $i++;
        }
        // $title = array('ID', '订单号', '下单时间','会员','金额','商品总利润','导购员','收款人','销售方式','来源');
        $title = array('ID', '订单号', '下单时间','会员','商品价格','优惠','运费','实收','导购提成','返佣','导购员','收款人','销售方式','来源');
        export_csv('订单流水.csv',$title,$data);
        exit;
    }
    public function member(){
        $postdata=I('param.');
        /*会员日增长量统计开始*/
        /*获取当月时间数组开始*/
        $type = I('type');
        $day_arr = $map=array();
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        $new_map=$map =$map_z=$only_map=array();
         // 1121 会员共享  + 限定
            $shop_id=MID;
            $is_share_user=idtoname($shop_id,'Shops','is_share_user');
            if(empty($is_share_user)){//不共享会员
                $c_map=$customer=array();
                $c_map['shop_id'] = $shop_id;
                $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                if(empty($customer)){//无顾客
                    $map['user_shop']=$shop_id;
                }else{
                    $where=array();
                    $where['user_shop']=$shop_id;
                    $where['id']  = array('in',$customer);
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                }
            }else{//共享会员
                $smap=array();$cachetime=60*60*24*7;
                $smap['is_share_user']=0;                
                $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                if(!empty($noshareshopids)){
                    $map['user_shop'] = array('notin',$noshareshopids);
                }
            }
        $only_map=$map;
        // 1121 end
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from){
                $map['reg_time'][] = array('egt',$date_from);
                $map_z[] = $date_from;
            }else{
                $this->error("请选择搜索开始时间");exit;
            }
            $date_to = strtotime($postdata['date_to']);
            if($date_to){
                $map['reg_time'][] = array('lt',$date_to+86399);
                $map_z[] = $date_to+86399;
            }else{
                $this->error("请选择搜索结束时间");exit;
            }
            $type=0;
        }else{
              if(in_array($type,array(1,2,7,30))){
                  $map_z=$this->quick_time($type);
              }else{
                  $map_z=array();
              }
            if(in_array($type,array(7,30))){
                $between=$this->quick_time($type);
                $date_from=$between[0];
                $date_to =$between[1];
                $map['reg_time']=array('between',array($between[0],$between[1]));
            }else{
                $type=3;
                $date_from=$now_time-6*86400;
                $date_to =$now_time+86399;
                $map['reg_time']=array('between',array($date_from,$date_to));
            }
        }
        if(in_array($type,array(1,2,3,7))){
            $days=7;
        }else if($type ==30){
            $days=30;
        }else{
            $days=ceil(($date_to-$date_from)/86400);
        }
        for($i=0;$i<$days;$i++){
            $day_arr[date('Y-m-d',$now_time-$i*86400)] = date('Y-m-d',$now_time-$i*86400); //每隔一天赋值给数组
        }
        $new_map=$map;
        $this->info($map_z);//会员概况
        //会员
        $map['status'] = 1;
        $map['is_tmp'] = 0;
        $info['member'] = M('Member')->where($map)->field('count(*) as num,reg_time as mon')->group("DATE_FORMAT(FROM_UNIXTIME(reg_time),'%Y年%m月%d天')")->select();
        unset($map['is_tmp']);
        //粉丝
        $map['is_follow'] = 1;
            // 1122   粉丝限定
            $auth_code = 'fans';
            $ret=D('Shop/Shops')->shop_option(MID,$auth_code);
            if($ret['status']==1){ //显示门店粉丝
                $map['user_shop']=MID;
            }
        $info['fans'] = M('Member')->where($map)->field('count(*) as num,reg_time as mon')->group("DATE_FORMAT(FROM_UNIXTIME(reg_time),'%Y年%m月%d天')")->select();
    //顾客
        $map['is_follow']=0;
        $info['guke'] = M('Member')->where($map)->field('count(*) as num,reg_time as mon')->group("DATE_FORMAT(FROM_UNIXTIME(reg_time),'%Y年%m月%d天')")->select();
        //每个折线的图标代表什么
        $name = array("粉丝","顾客","会员");
        if($info){
            foreach($info as $key => $value){
              if(!empty($value)){
                  foreach($value as $k=>$v){
                    $file[$key][date('Y-m-d',$v['mon'])]=$v['num'];
                    $file_time[$key][]=date('Y-m-d',$v['mon']);
                  }
              }else{
                  $file[$key][date('Y-m-d',$v['mon'])] =0;
                  $file_time[$key][]=date('Y-m-d',$v['mon']);
              }
            }unset($value,$key,$k,$v);
        }
        $new_day=array_diff($day_arr,$file_time['member']);
        foreach($new_day as $v){
            $file['member'][$v]=0;
        }unset($v);
        $new_fans_day=array_diff($day_arr,$file_time['fans']);
        foreach($new_fans_day as $v){
            $file['fans'][$v]=0;
        }unset($v);
        $new_guke_day=array_diff($day_arr,$file_time['guke']);
        foreach($new_guke_day as $v){
            $file['guke'][$v]=0;
        }unset($v);
        ksort($file['member']);
        ksort($file['fans']);
        ksort($file['guke']);
        //得到折线图
        $cz_count = array(
            "legend"=>array('data'=>array($name[0],$name[1],$name[2])),
            "xaxis"=>array("type"=>"category","data"=>array_keys($file['member'])),
            "series"=>array(
                0=>array("name"=>$name[0],"type"=>"line","stack"=>$name[0],"data"=>array_values($file['fans'])),
                1=>array("name"=>$name[1],"type"=>"line","stack"=>$name[1],"data"=>array_values($file['guke'])),
                2=>array("name"=>$name[2],"type"=>"line","stack"=>$name[2],"data"=>array_values($file['member'])),
            ),
        );
        $ec = new \Common\Vendor\Echarts();
        $this->assign('Area_count',$ec->show('Area_count',$cz_count,'line'));
        $this->assign('type',$type);
        /*会员增长量统计结束*/
        /*等级会员占比开始*/
        $map = array();
        $map=$only_map;
        $map['status'] = 1;
        $map['is_tmp'] = 0;
        $member_info = M('Member')->where($map)->getField('rank_id',true);
        $m_style_num=array_count_values($member_info);
        $rank_info = M('MemberRank')->getField('id,name',true);
        $data_rank = M('MemberRank')->getField('name',true);
        $i = 0;
        foreach($m_style_num as $k=>$v){
            $arr[$i]['value'] = $v;
            $arr[$i]['name'] = $rank_info[$k];
            $i++;
        }
        $rank_style_count = array(
            'title'=>array(
                'text'=>'会员等级占比',
                'x'=>'center'
            ),
      "legend"=>array('data'=>$data_rank),
      "series"=>array(
          array("name"=>"会员等级占比","type"=>"pie",
              "data"=>$arr,
          ),
      ),
        );
        $this->assign('Area_count_member',$ec->pie_show('Area_count_member', $rank_style_count,'pie'));
        /*等级会员占比结束*/
        /*会员来源统计开始*/
        $map=array();
        $map=$new_map;
        $source_info = M('Member')->where($map)->getField('source',true);
        $source_style_num=array_count_values($source_info);
        $source_style_count = array(
      "legend"=>array('data'=>array('直接访问','门店办理','消费领卡','全民拓客')),
      "series"=>array(
          array("name"=>"会员来源占比","type"=>"pie",
        "data"=>array(
                array("value"=>$source_style_num['1']+$source_style_num['0'],"name"=>"直接访问"),
                array("value"=>$source_style_num['2'],"name"=>"门店办理"),
                array("value"=>$source_style_num['3'],"name"=>"消费领卡"),
                array("value"=>$source_style_num['4'],"name"=>"全民拓客"),
            ),
                ),
            ),
        );
        $this->assign('Area_count_source',$ec->pie_show('Area_count_source', $source_style_count,'pie'));
        /*会员来源统计结束*/
        /*会员性别占比开始*/
        $map = array();
        $map=$only_map;
        $map['status'] = 1;
        $sex_info = M('Member')->where($map)->getField('sex',true);
        $sex_style_num=array_count_values($sex_info);
        $sex_style_count = array(
            'title'=>array(
                'text'=>'会员性别占比',
                'x'=>'center'
            ),
      "legend"=>array('data'=>array('保密','男','女')),
      "series"=>array(
          array("name"=>"会员性别占比","type"=>"pie",
        "data"=>array(
            array("value"=>$sex_style_num['0'],"name"=>"保密"),
            array("value"=>$sex_style_num['1'],"name"=>"男"),
            array("value"=>$sex_style_num['2'],"name"=>"女"),
        ),
          ),
      ),
        );
        $this->assign('Area_count_sex',$ec->pie_show('Area_count_sex', $sex_style_count,'pie'));
        /*会员性别占比结束*/
        /*会员年龄段人数统计开始*/
        $map = array();
        $map=$only_map;
        // $map['birthday'] = array('neq','');
        $member_info = M('Member')->where($map)->getField('birthday',true);
        $member_count = M('Member')->where($map)->count();
        $year = date('Y',NOW_TIME);
        $a=$b=$c=$d=$e=$f=$g=0;
        foreach($member_info as $k=>$v){
          $str = substr($v,0,4);
          if($str != '0000' && $str){
              if($year-$str < 10){
            $a++;
              }elseif($year-$str < 20 && $year-$str >= 10){
            $b++;
              }elseif($year-$str < 30 && $year-$str >= 20){
            $c++;
              }elseif($year-$str < 40 && $year-$str >= 30){
            $d++;
              }elseif($year-$str < 50 && $year-$str >= 40){
            $e++;
              }elseif(50 <= $year-$str){
            $f++;
              }
          }else{
              $g++;
          }
        }
        $member_age['10岁以下'] =$a;
        $member_age['10-20'] = $b;
        $member_age['20-30'] = $c;
        $member_age['30-40'] = $d;
        $member_age['40-50'] = $e;
        $member_age['50岁以上'] = $f;
        $member_age['未知人数'] = $g;
        $names = "人数";
        $ma_count = array(
            "legend"=>array('data'=>array($names)),
            "xaxis"=>array("type"=>"category","data"=>array_keys($member_age)),
            "series"=>array(
          0=>array("name"=>$names,"type"=>"bar","stack"=>$names,'itemStyle'=>array(),"data"=>array_values($member_age)),
            ),
        );
        $this->assign('MemberAge_count',$ec->show('MemberAge_count',$ma_count,'bar'));
        /*会员年龄段人数统计结束*/
        /*会员复购率分析1-10次 1-20次  1-50次 开始*/
        $map = array();
        if($map_z){
      $map['addtime']=array('between',array($map_z[0],$map_z[1]));
        }
        $map['type'] = array('in','1,6,11,13,14');
        $map['status'] = array('in','1,2,3,6,8');
        $map['shop_id']=MID;
        $buy_info = M('OrderInfo')->where($map)->group('uid')->field('count(id) as num')->select();
        $a=$b=$c=$d=$e=$f=$g=$h=$j=$k=0;
        foreach($buy_info as $ke=>$v){
          switch ($v['num'])
          {
              case 1:
                $a++;
                break;
              case 2:
                $b++;
                break;
              case 3:
                $c++;
                break;
              case 4:
                $d++;
                break;
              case 5:
                $e++;
                break;
              case 6:
                $f++;
                break;
              case 7:
                $g++;
                break;
              case 8:
                $h++;
                break;
              case 9:
                $j++;
                break;
              default:
                $k++;
          }
        }
        $member_buy['1次'] =$a;
        $member_buy['2次'] = $b;
        $member_buy['3次'] = $c;
        $member_buy['4次'] = $d;
        $member_buy['5次'] = $e;
        $member_buy['6次'] = $f;
        $member_buy['7次'] = $g;
        $member_buy['8次'] = $h;
        $member_buy['9次'] = $j;
        $member_buy['10次以上'] = $k;
        $names = "人数";
        $ma_count = array(
            "legend"=>array('data'=>array($names)),
            "xaxis"=>array("type"=>"category","data"=>array_keys($member_buy)),
            "series"=>array(
      0=>array("name"=>$names,"type"=>"bar","stack"=>$names,'itemStyle'=>array(),"data"=>array_values($member_buy)),
            ),
        );
        $this->assign('MemberBuy_count',$ec->show('MemberBuy_count',$ma_count,'bar'));
//        $this->assign('m_buy',$m_buy);
        /*会员复购率分析1-10次 1-20次  1-50次 结束*/
        $this->assign($postdata);
        if($postdata['print']==1){
            $this->display('print');
        }else{
            $this->display();
        }
    }
     public function info($map_z){
        $only_map=$map_oi=$map=array();
         // 1121 会员共享  + 限定
             $shop_id=MID;
             $is_share_user=idtoname($shop_id,'Shops','is_share_user');
            if(empty($is_share_user)){//不共享会员
                $c_map=$customer=array();
                $c_map['shop_id'] = $shop_id;
                $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                if(empty($customer)){//无顾客
                    $map['user_shop']=$shop_id;
                }else{
                    $where=array();
                    $where['user_shop']=$shop_id;
                    $where['id']  = array('in',$customer);
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                }
            }else{//共享会员
                $smap=array();$cachetime=60*60*24*7;
                $smap['is_share_user']=0;                
                $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                if(!empty($noshareshopids)){
                    $map['user_shop'] = array('notin',$noshareshopids);
                }
            }
            $only_map=$map;
        //新增
        if($map_z){
          $map['reg_time']=array('between',array($map_z[0],$map_z[1]));
          $map_oi['addtime']=array('between',array($map_z[0],$map_z[1]));
        }
        $map['status']=1;
        $map['is_tmp']=0;
        // $map['user_shop']=0;
        $map['_string']="user_shop = 0";
        $xs_source=M('Member')->where($map)->count('id');//新增线上会员
        // unset($map['user_shop']);
        // $map['user_shop']=array('gt',0);
        $map['_string']="user_shop > 0 ";
        $xx_source=M('Member')->where($map)->count('id');//新增线下会员
        // unset($map['user_shop']);
        unset($map['_string']);
        unset($map['is_tmp']);
        $map['is_follow']=0;
        $gukex=M('Member')->where($map)->count('id');//新增顾客
        // 总数
        $map=array();
        $map=$only_map;
        $map['status']=1;
        $map['is_tmp']=0;
        // $map['user_shop']=0;
         $map['_string']="user_shop = 0";
        $zxs_source=M('Member')->where($map)->count('id');//线上会员
        // unset($map['user_shop']);
        // $map['user_shop']=array('gt',0);
         $map['_string']="user_shop > 0";
        $zxx_source=M('Member')->where($map)->count('id');//线下会员
        // unset($map['user_shop']);
        unset($map['_string']);
        unset($map['is_tmp']);
        $map['is_follow']=0;
        $gukez=M('Member')->where($map)->count('id');//顾客总数
        $cz_count=$xs_source+$xx_source;
        $this->assign('cz_count',$cz_count);
        $this->assign('xs_source',$xs_source);
        $this->assign('xx_source',$xx_source);
        $zcount=$zxs_source+$zxx_source;
        $this->assign('zcount',$zcount);
        $this->assign('zxs_source',$zxs_source);
        $this->assign('zxx_source',$zxx_source);
        $this->assign('gukex',$gukex);
        $this->assign('gukez',$gukez);
        // 会员粉丝
         //新增粉丝
        $map=array();
        $auth_code = 'fans';
        $ret=D('Shop/Shops')->shop_option(MID,$auth_code);
        if($ret['status']==1){ //显示门店粉丝
            $map['user_shop']=MID;
        }
        $map['status']=1;
        $map['is_follow']=1;
        if($map_z){
            $map['follow_time']=array('between',array($map_z[0],$map_z[1]));
        }
        $g_fans=M('Member')->where($map)->count('id');
        //减少粉丝
        $map['is_follow']=0;
        unset($map['follow_time']);
        $map['unfollow_time']=array('gt',0);
        if($map_z){
            $map['unfollow_time']=array('between',array($map_z[0],$map_z[1]));
        }
        $c_fans=M('Member')->where($map)->count('id');
        $this->assign('g_fans',$g_fans);
        $this->assign('c_fans',$c_fans);
        // 会员复购率
        $map_oi['status'] = array('in','1,2,3,6,8');
        $map_oi['pay_status'] = 3;
        $map_oi['type'] = array('in','1,6,11,12,13,14');
        $map_oi['is_delete']=0;
        $map_oi['uid']=array('gt',0);
        $map_oi['shop_id']=MID;
        $count_order=M('OrderInfo')->where($map_oi)->count('id');//总笔数
        $buy_info = M('OrderInfo')->where($map_oi)->group('uid')->field('count(id) as num')->having('count(id) = 1')->select();//第一次购买人数
        $one_num=count($buy_info);
        $buy_percent=format_decimal(($count_order-$one_num)/$count_order*100).'%';
        $this->assign('buy_percent',$buy_percent);
        // 会员活跃率
        $m_info = M('OrderInfo')->where($map_oi)->group('uid')->field('uid')->select();
        $m_count = count($m_info);//活跃的会员数
        $active_percent=format_decimal($m_count/$zcount*100);
        $this->assign('active_percent',$active_percent.'%');
    }
     public function buy(){//会员消费排行
        $postdata=I('param.');
        $map=array();
        if($postdata['date_from'] || $postdata['date_to']){
      $date_from = strtotime($postdata['date_from']);
      if($date_from){$map['addtime'][] = array('egt',$date_from);}
      $date_to = strtotime($postdata['date_to']);
      if($date_to){$date_to = $date_to+86399;$map['addtime'][] = array('lt',$date_to);}
        }else{
      if(in_array($postdata['type'],array(1,2,7,30))){
          $between=$this->quick_time($postdata['type']);
          $map['addtime']=array('between',array($between[0],$between[1]));
      }
        }
        $map['type'] = array('in','1,11,12,13,14');
        $map['status'] = array('in','1,2,3,6,8');
        $map['is_delete'] =0;
        $map['uid'] = array('gt',0);
        $map['shop_id']=MID;
        $limit=$postdata['buy_top']?$postdata['buy_top']:10;
        $info_list = M('OrderInfo')->where($map)->field("sum(order_money) as allmoney,uid,count(id) as ids")->group('uid')->order('allmoney desc')->limit($limit)->select();
        $ys=idtoname(MID,'Shops','is_hide_phone');
        foreach ($info_list as $k => $val) {
            $username=show_user_name($val['uid']);
            if(strlen($username)==11 && $ys){
                $info_list[$k]['username']=str_cutmobile($username);
            }else{
                $info_list[$k]['username']=$username;
            }
        }
        $this->assign('info_list',$info_list);
        $list_html=$this->fetch('index_list');
        $return['html']=str_replace("\n",'',$list_html);
        $this->ajaxReturn($return);
    }
    public function chong(){//会员消费排行
        $postdata=I('param.');
        $map=array();
        if($postdata['date_from'] || $postdata['date_to']){
          $date_from = strtotime($postdata['date_from']);
          if($date_from){$map['addtime'][] = array('egt',$date_from);}
          $date_to = strtotime($postdata['date_to']);
          if($date_to){$date_to = $date_to+86399;$map['addtime'][] = array('lt',$date_to);}
            }else{
          if(in_array($postdata['type'],array(1,2,7,30))){
              $between=$this->quick_time($postdata['type']);
              $map['addtime']=array('between',array($between[0],$between[1]));
          }
        }
        $map['type'] = array('in','2,5');
        $map['status'] = 3;
        $map['is_delete'] =0;
        $map['uid'] = array('gt',0);
        $map['shop_id']=MID;
        $limit=$postdata['chong_top']?$postdata['chong_top']:10;
        $info_list = M('OrderInfo')->where($map)->field("sum(order_money) as allmoney,uid,count(id) as ids")->group('uid')->order('allmoney desc')->limit($limit)->select();
         $ys=idtoname(MID,'Shops','is_hide_phone');
        foreach ($info_list as $k => $val) {
            $username=show_user_name($val['uid']);
            if(strlen($username)==11 && $ys){
                $info_list[$k]['username']=str_cutmobile($username);
            }else{
                $info_list[$k]['username']=$username;
            }
        }
        $this->assign('info_list',$info_list);
        $list_html=$this->fetch('index_list');
        $return['html']=$list_html;
        $this->ajaxReturn($return);
    }
    //站长统计
    public function cnzz(){
        $site= new \Common\Vendor\Matomo;
        $result=$site->getviewurl();
        if(empty($result) )$this->error('获取统计信息错误');
        $configpassword=C('STATS_CODE');
        if(strlen($configpassword)!=32){
            $this->success('请稍后,统计代码生成中',U('cnzz'));
        }else{
            echo "<script type='text/javascript'>location.href='".$result."';</script>";
        }
    }
    public function biao_member(){
        $type = I('type')?I('type'):3;
        $date_from = $date_to= '';
        $array_day = array(1,2,7,3);
        if(in_array($type, $array_day)){
            $riqi = 7;
        }elseif($type == 99){
            $riqi = 7;
            $date_from = I('date_from');
            $date_to = I('date_to');
            if(!$date_from || !$date_to){
                $riqi = 7;
                $type = 7;
                $date_from = '';$date_to = '';
            }
        }else{
            $riqi = $type;
        }
        //会员增长表开始
        $this->num_count($riqi,$date_from,$date_to);
        //会员增长表结束
        //年龄表开始
        $this->age_count();
        //年龄表结束
        //性别表开始
        $map = array();
        // 1120 start
            $shop_id=MID;
             $is_share_user=idtoname($shop_id,'Shops','is_share_user');
            if(empty($is_share_user)){//不共享会员
                $c_map=$customer=array();
                $c_map['shop_id'] = $shop_id;
                $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                if(empty($customer)){//无顾客
                    $map['user_shop']=$shop_id;
                }else{
                    $where=array();
                    $where['user_shop']=$shop_id;
                    $where['id']  = array('in',$customer);
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                }
            }else{//共享会员
                $smap=array();$cachetime=60*60*24*7;
                $smap['is_share_user']=0;                
                $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                if(!empty($noshareshopids)){
                    $map['user_shop'] = array('notin',$noshareshopids);
                }
            }
            // $map['user_shop']=MID;
        //1120会员共享
        $map['status'] = 1;
        $map['sex'] = 1;
        $sex_count['boy'] = M('Member')->where($map)->count();
        $map['sex'] =2;
        $sex_count['girl'] = M('Member')->where($map)->count();
        $map['sex'] = '';
        $sex_count['baomi'] = M('Member')->where($map)->count();
        $this->assign('sex_count',$sex_count);
        //性别表结束
        //复购率开始
        $this->buy_count($riqi,$date_from,$date_to);
        //复购率结束
        //等级分析开始
        $this->rank_count();
        //等级分析结束
        //会员来源分析开始
        $this->source_count($riqi,$date_from,$date_to);
        //会员来源分析结束
        $map = array();
        if($type == '时间'){
            $date_from = strtotime(I('date_from'));
            if($date_from)$map['addtime'][] = array('egt',$date_from);
            $date_to = strtotime(I('date_to'));
            if($date_to)$map['addtime'][] = array('lt',$date_to);
        }elseif($type == 1){
            $map['addtime'][] = array('egt',mktime(0,0,0,date('m'),date('d'),date('Y')));
            $map['addtime'][] = array('lt',NOW_TIME);
        }elseif($type == 2){
            $map['addtime'][] = array('egt',mktime(0,0,0,date('m'),date('d')-1,date('Y')));
            $map['addtime'][] = array('lt',mktime(0,0,0,date('m'),date('d'),date('Y'))-1);
        }elseif($type == 7){
            $map['addtime'][] = array('egt',mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')));
            $map['addtime'][] = array('lt',mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y')));
        }elseif($type == 30){
            $map['addtime'][] = array('egt',mktime(0,0,0,date('m'),1,date('Y')));
            $map['addtime'][] = array('lt',mktime(23,59,59,date('m'),date('t'),date('Y')));
        }
        $map['type'] = array('in','1,11,12,13,14');
        $map['status'] = 3;
        $map['shop_id']=MID;
        $map['uid']=array('neq',0);//1120
        $info_list = M('OrderInfo')->where($map)->field("sum(order_amount) as allmoney,uid,count(id) as ids")->group('uid')->order('allmoney desc')->limit(20)->select();
        $this->assign('info_list',$info_list);
        $list_html=$this->fetch('index_list');
        $this->assign('list_html',$list_html);
        $this->assign('type',$type);
        $this->assign('date_from',$date_from);
        $this->assign('date_to',$date_to);
        $this->display();
    }
    /**
      *注册数统计
      */
    private function num_count($riqi=7,$date_from=0,$date_to=0,$is_return=0){
        if($riqi == -1){
            $now_time = strtotime($date_to);
            $count=$map=array();
            $map['status']=1;
            // $map['shop_id']=MID;
            // 1120 start
                $shop_id=MID;
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $map['user_shop']=$shop_id;
                    }else{
                        $where=array();
                        $where['user_shop']=$shop_id;
                        $where['id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $map['user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
            $start_time=strtotime(date('Y-m-d',$now_time));
            $riqi = (strtotime($date_to) - strtotime($date_from))/86400+1;
            for($i=0;$i<$riqi;$i++){
                if($i == 0){
                    $today = $start_time;
                    $tomorrow = $start_time+86400;
                }else{
                    $today = $start_time - $i*86400;
                    $tomorrow = $start_time-($i-1)*86400;
                }
                $count[$i]['time'] = date('Y-m-d',$now_time-$i*86400);
                $map['is_follow'] = 1;
                 // 1122   粉丝限定
                    $auth_code = 'fans';
                    $ret=D('Shop/Shops')->shop_option(MID,$auth_code);
                    if($ret['status']==1){ //显示门店粉丝
                        $map['_string']="user_shop=".MID;
                    }
                $map['reg_time']=array('between',array($today,$tomorrow));
                $count[$i]['f_count'] = M('Member')->where($map)->count();unset($map['_string']);
                $map['is_follow'] = 0;
                $count[$i]['g_count']=M('Member')->where($map)->count();
                unset($map['is_follow']);
                $map['is_tmp'] = 0;
                $count[$i]['m_count']=M('Member')->where($map)->count();
                unset($map['is_tmp']);
                $count[$i]['sum'] = $count[$i]['f_count'] + $count[$i]['g_count'] + $count[$i]['m_count'];
            }
        }else{
            $now_time = NOW_TIME;
            $count=$map=array();
            $map['status']=1;
             // $map['shop_id']=MID;
             // 1120 start
                $shop_id=MID;
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $map['user_shop']=$shop_id;
                    }else{
                        $where=array();
                        $where['user_shop']=$shop_id;
                        $where['id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $map['user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
            $start_time=strtotime(date('Y-m-d',NOW_TIME));
            for($i=0;$i<$riqi;$i++){
                if($i == 0){
                    $today = $start_time;
                    $tomorrow = $start_time+86400;
                }else{
                    $today = $start_time - $i*86400;
                    $tomorrow = $start_time-($i-1)*86400;
                }
                $count[$i]['time'] = date('Y-m-d',$now_time-$i*86400);
                $map['is_follow'] = 1;
                    $auth_code = 'fans';
                    $ret=D('Shop/Shops')->shop_option(MID,$auth_code);
                    if($ret['status']==1){ //显示门店粉丝
                        $map['_string']="user_shop=".MID;
                    }
                $map['reg_time']=array('between',array($today,$tomorrow));
                $count[$i]['f_count'] = M('Member')->where($map)->count();
                $map['is_follow'] = 0;unset($map['_string']);
                $count[$i]['g_count']=M('Member')->where($map)->count();
                unset($map['is_follow']);
                $map['is_tmp'] = 0;
                $count[$i]['m_count']=M('Member')->where($map)->count();
                unset($map['is_tmp']);
                $count[$i]['sum'] = $count[$i]['f_count'] + $count[$i]['g_count'] + $count[$i]['m_count'];
            }
        }
        $this->assign('count',$count);
        if($is_return == 1){
            return $count;
        }
    }
    /**
      *年龄数统计
      */
    private function age_count($is_return=0){
        $map = array();
         // $map['shop_id']=MID;
         // 1120 start
                $shop_id=MID;
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $map['user_shop']=$shop_id;
                    }else{
                        $where=array();
                        $where['user_shop']=$shop_id;
                        $where['id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $map['user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
        $map['birthday'] = array('neq','');
        $member_info = M('Member')->where($map)->getField('birthday',true);
        $year = date('Y',NOW_TIME);
        $a=$b=$c=$d=$e=$f=$g=0;
        foreach($member_info as $k=>$v){
            $str = substr($v,0,4);
            if($str != '0000'){
                if($year-$str < 10){
                    $a++;
                }elseif($year-$str < 20 && $year-$str > 10){
                    $b++;
                }elseif($year-$str < 30 && $year-$str > 20){
                    $c++;
                }elseif($year-$str < 40 && $year-$str > 30){
                    $d++;
                }elseif($year-$str < 50 && $year-$str > 40){
                    $e++;
                }elseif(50 < $year-$str){
                    $f++;
                }
            }else{
                $g++;
            }
        }
        $age_count['0'] = $a; 
        $age_count['1'] = $b;
        $age_count['2'] = $c;
        $age_count['3'] = $d;
        $age_count['4'] = $e;
        $age_count['5'] = $f;
        $age_count['6'] = $g;
        $this->assign('age_count',$age_count);
        if($is_return == 1){
            return $age_count;
        }
    }
    private function buy_count($riqi,$date_from,$date_to,$is_return=0){
        $map = array();
        $map['type'] = array('in','1,6,11,13,14');
        $map['status'] = 3;
         $map['shop_id']=MID;
        if($riqi==-1){
            $map['addtime'] = array('between',array($date_from,$date_to));
        }else{
            $start_time=strtotime(date('Y-m-d',NOW_TIME));
            $today = $start_time - ($riqi-1)*86400;
            $tomorrow = $start_time+86400;
            $map['addtime'] = array('between',array($today,$tomorrow));
        }
        $buy_info = M('OrderInfo')->where($map)->group('uid')->field('count(id) as num')->select();
        $a=$b=$c=$d=$e=$f=$g=$h=$j=$k=0;
        foreach($buy_info as $ke=>$v){
            switch ($v['num'])
            {
                case 1:
                  $a++;
                  break;  
                case 2:
                  $b++;
                  break;
                case 3:
                  $c++;
                  break;
                case 4:
                  $d++;
                  break;
                case 5:
                  $e++;
                  break;
                case 6:
                  $f++;
                  break;
                case 7:
                  $g++;
                  break;
                case 8:
                  $h++;
                  break;
                case 9:
                  $j++;
                  break;
                default:
                  $k++;
            }
        }
        $buy_count['1'] =$a; 
        $buy_count['2'] = $b;
        $buy_count['3'] = $c;
        $buy_count['4'] = $d;
        $buy_count['5'] = $e;
        $buy_count['6'] = $f;
        $buy_count['7'] = $g;
        $buy_count['8'] = $h;
        $buy_count['9'] = $j;
        $buy_count['10'] = $k;
        $this->assign('buy_count',$buy_count);
        if($is_return == 1){
            return $buy_count;
        }
    }
    private function rank_count(){
        $map = array();
        $map['status']=1;
        $map['is_tmp']=0;
        $rank_info = M('MemberRank')->field('id,name')->select();
        foreach($rank_info as $k=>$v){
            $map['rank_id'] = $v['id'];
             // $map['shop_id']=MID;
             // 1120 start
                $shop_id=MID;
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $map['user_shop']=$shop_id;
                    }else{
                        $where=array();
                        $where['user_shop']=$shop_id;
                        $where['id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $map['user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
            $rank_info[$k]['count'] = M('Member')->where($map)->count();
        } 
        $list['name'] = i_array_column($rank_info,'name');
        $list['count'] = i_array_column($rank_info,'count');
        $this->assign('list',$list);
    }
    private function source_count($riqi=7,$date_from=0,$date_to=0,$is_return=0){
        if($riqi == -1){
            $now_time = strtotime($date_to);
            $scurce_list=$map=array();
             // 1120 start
                $shop_id=MID;
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $map['user_shop']=$shop_id;
                    }else{
                        $where=array();
                        $where['user_shop']=$shop_id;
                        $where['id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $map['user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
            $startime=strtotime(date('Y-m-d',$now_time));
            $today=strtotime(date('Y-m-d',$now_time));
            $riqi = (strtotime($date_to) - strtotime($date_from))/86400+1;
            for($i=0;$i<$riqi;$i++){
                if($i == 0){
                    $tomorrow = $startime+86400;
                }else{
                    $today = $startime - $i*86400;
                    $tomorrow = $startime+($i-1)*86400;
                }
                 // $map['shop_id']=MID; 
                // $map['user_shop']=MID;1120
                $scurce_list[$i]['time'] = date('Y-m-d',$now_time-$i*86400);
                $map['source'] = array('in','0,1');
                $map['reg_time']=array('between',array($today,$tomorrow));
                $scurce_list[$i]['zhijie'] = M('Member')->where($map)->count();
                unset($map['source']);
                $map['source'] = 2;
                $scurce_list[$i]['mendian'] = M('Member')->where($map)->count();
                unset($map['source']);
                $map['source'] = 3;
                $scurce_list[$i]['lingka'] = M('Member')->where($map)->count();
                unset($map['source']);
                $map['source'] = 4;
                $scurce_list[$i]['tuoke'] = M('Member')->where($map)->count();
                $scurce_list[$i]['sum'] = $scurce_list[$i]['zhijie'] + $scurce_list[$i]['mendian'] + $scurce_list[$i]['lingka'] + $scurce_list[$i]['tuoke'];
            }
        }else{
            $now_time = NOW_TIME;
            $scurce_list=$map=array();
             // 1120 start
                $shop_id=MID;
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $map['user_shop']=$shop_id;
                    }else{
                        $where=array();
                        $where['user_shop']=$shop_id;
                        $where['id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $map['user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
            $startime=strtotime(date('Y-m-d',NOW_TIME));
            for($i=0;$i<$riqi;$i++){
                if($i == 0){
                    $tomorrow = $startime+86400;
                }else{
                    $today = $startime - $i*86400;
                    $tomorrow = $startime+($i-1)*86400;
                }
                $scurce_list[$i]['time'] = date('Y-m-d',$now_time-$i*86400);
                $map['source'] = array('in','0,1');
                 // $map['shop_id']=MID;
                // $map['user_shop']=MID;1120
                $map['reg_time']=array('between',array($today,$tomorrow));
                $scurce_list[$i]['zhijie'] = M('Member')->where($map)->count();
                unset($map['source']);
                $map['source'] = 2;
                $scurce_list[$i]['mendian'] = M('Member')->where($map)->count();
                unset($map['source']);
                $map['source'] = 3;
                $scurce_list[$i]['lingka'] = M('Member')->where($map)->count();
                unset($map['source']);
                $map['source'] = 4;
                $scurce_list[$i]['tuoke'] = M('Member')->where($map)->count();
                unset($map['source']);
                $scurce_list[$i]['sum'] = $scurce_list[$i]['zhijie'] + $scurce_list[$i]['mendian'] + $scurce_list[$i]['lingka'] + $scurce_list[$i]['tuoke'];
            }
        }
        $this->assign('scurce_list',$scurce_list);
        if($is_return == 1){
            return $scurce_list;
        }
    }
    public function membertong_detail_export(){
        $null = array();
        $postdata=I('param.');
        if($postdata){
            $type = $postdata['type'];
            $date_from = $date_to= '';
            $array_day = array(1,2,7,3);
            if(in_array($type, $array_day)){
                $riqi = 7;
            }elseif($type == 99){
                $riqi = 7;
                $date_from = I('date_from');
                $date_to = I('date_to');
                if(!$date_from || !$date_to){
                    $riqi = 7;
                    $type = 7;
                    $date_from = '';$date_to = '';
                }
            }else{
                $riqi = $type;
            }
            //表一开始（新增会员分析）
            $one_count = $this->num_count($riqi,$date_from,$date_to,1);
            $one_title=array('日期','粉丝','顾客','会员','用户总数');
            $title_name = array('新增会员分析');
            export_xls($title_name,$null,'utf8');
            export_xls($one_title,$one_count,'utf8');
            export_xls(array(),$null,'utf8');
            //表一结束
            //表二开始（会员来源分析）
            $two_count = $this->source_count($riqi,$date_from,$date_to,1);
            $two_title=array('日期','直接访问','门店办理','消费领卡','全名拓客','用户总数');
            $title_name = array('会员来源分析');
            export_xls($title_name,$null,'utf8');
            export_xls($two_title,$two_count,'utf8');
            export_xls(array(),$null,'utf8');
            //表二结束
            //表三开始（会员年龄段分析）
            $three_info = $this->age_count(1);
            $three_count[0][] = $three_info[0];
            $three_count[0][] = $three_info[1];
            $three_count[0][] = $three_info[2];
            $three_count[0][] = $three_info[3];
            $three_count[0][] = $three_info[4];
            $three_count[0][] = $three_info[5];
            $three_count[0][] = $three_info[6];
            $three_title=array('10岁以下','10-20','20-30','30-40','40-50','50岁以上','未知人数');
            $title_name = array('会员年龄段分析');
            export_xls($title_name,$null,'utf8');
            export_xls($three_title,$three_count,'utf8');
            export_xls(array(),$null,'utf8');
            //表三结束
            //表四开始（会员性别占比分析）
            $map = array();
            $map['status'] = 1;
            $map['sex'] = 1;
            // $map['shop_id']=MID;
             // 1120 start
                $shop_id=MID;
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $map['user_shop']=$shop_id;
                    }else{
                        $where=array();
                        $where['user_shop']=$shop_id;
                        $where['id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $map['user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
            $four_count[0][] = M('Member')->where($map)->count();
            $map['sex'] =2;
            $four_count[0][] = M('Member')->where($map)->count();
            $map['sex'] = '';
            $four_count[0][] = M('Member')->where($map)->count();
            $four_title=array('男','女','保密');
            $title_name = array('会员性别占比分析');
            export_xls($title_name,$null,'utf8');
            export_xls($four_title,$four_count,'utf8');
            export_xls(array(),$null,'utf8');
            //表四结束
            //表五开始（会员等级占比分析）
            $map = array();
            $rank_info = M('MemberRank')->field('id,name')->select();
            $map['status']=1;
            $map['is_tmp']=0;
            foreach($rank_info as $k=>$v){
                $map['rank_id'] = $v['id'];
                // $map['shop_id']=MID;
                 // 1120 start
                    $shop_id=MID;
                     $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                    if(empty($is_share_user)){//不共享会员
                        $c_map=$customer=array();
                        $c_map['shop_id'] = $shop_id;
                        $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                        if(empty($customer)){//无顾客
                            $map['user_shop']=$shop_id;
                        }else{
                            $where=array();
                            $where['user_shop']=$shop_id;
                            $where['id']  = array('in',$customer);
                            $where['_logic'] = 'or';
                            $map['_complex'] = $where;
                        }
                    }else{//共享会员
                        $smap=array();$cachetime=60*60*24*7;
                        $smap['is_share_user']=0;                
                        $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                        if(!empty($noshareshopids)){
                            $map['user_shop'] = array('notin',$noshareshopids);
                        }
                    }
                    // $map['user_shop']=MID;
                //1120 end
                $five_count[0][] = M('Member')->where($map)->count();
            }
            $five_title=i_array_column($rank_info,'name');
            $title_name = array('会员等级占比分析');
            export_xls($title_name,$null,'utf8');
            export_xls($five_title,$five_count,'utf8');
            export_xls(array(),$null,'utf8');
            //表五结束
            //表六开始（会员复购率分析）
            $six_info = $this->buy_count($riqi,$date_from,$date_to,1);
            $six_count[0][] = $six_info[1];
            $six_count[0][] = $six_info[2];
            $six_count[0][] = $six_info[3];
            $six_count[0][] = $six_info[4];
            $six_count[0][] = $six_info[5];
            $six_count[0][] = $six_info[6];
            $six_count[0][] = $six_info[7];
            $six_count[0][] = $six_info[8];
            $six_count[0][] = $six_info[9];
            $six_count[0][] = $six_info[10];
            $six_title=array('1次','2次','3次','4次','5次','6次','7次','8次','9次','10次以上');
            $title_name = array('会员复购率分析');
            export_xls($title_name,$null,'utf8');
            export_xls($six_title,$six_count,'utf8');
            export_xls(array(),$null,'utf8');
            //表六结束
            // $name = CONTROLLER_NAME;
            $map=array();
            if($postdata['date_from'])$map['addtime'][] = array('egt',$date_from);
            if($postdata['date_to'])$map['addtime'][] = array('lt',$date_to);
            $map['type'] = array('in','1,11,12,13,14');
            $map['status'] = 3;
            $map['shop_id']=MID;
            $map['uid']=array('neq',0);
            $result = M('OrderInfo')->where($map)->field("sum(order_amount) as allmoney,uid,count(id) as ids")->group('uid')->order('allmoney desc')->limit($limit)->select();
            $title=array('序号','会员名','订单数','订单金额');
            foreach($result as $k => $v){
                $data[$k][]=$k+1;
                $data[$k][]=idtoname($v['uid'],'Member','nickname;username;mobile');
                $data[$k][]=$v['ids'];
                $data[$k][]=$v['allmoney']?$v['allmoney']:'0.00';
            }
            $title_name = array('会员消费排行');
            export_xls($title_name,$null,'utf8');
            export_xls($title,$data,'utf8');
            export_xls(array(),$null,'utf8');
            unset($title,$data);exit;
        }
    }
    // 会员end
    // 充值记录
    public function member_recharge(){
        $postdata=I('param.');
        $status_pay=array(1=>'未付款',2=>'付款中',3=>'已付款');
          $this->assign('status_pay',$status_pay);
        $map = array();$map['type']=2;
        if(!empty($postdata['date_from']))$map['addtime'][]=array('EGT',strtotime($postdata['date_from']));
        if(!empty($postdata['date_to']))$map['addtime'][]=array('elt',strtotime($postdata['date_to']));
        if(!empty($postdata['keyword'])){
            $whereor['uid']=$postdata['keyword'];
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
        }
         $ys=idtoname(MID,'Shops','is_hide_phone');
        $map['shop_id']=MID;
        if($postdata['print']=='print'){
            $member_list=M('OrderInfo')->where($map)->field(true)->select();    
                foreach ($member_list as $k => $val) {
                    $username=show_user_name($val['uid']);
                    if(strlen($username)==11 && $ys){
                        $member_list[$k]['username']=str_cutmobile($username);
                    }else{
                        $member_list[$k]['username']=$username;
                    }
                }
            $this->export_member_recharge($member_list);
        }
        // $member_list = M('OrderInfo')->where($map)->field(true)->order('id desc')->select();
        $member_list = $this->lists('OrderInfo',$map);
        foreach ($member_list as $k => $val) {
            $username=show_user_name($val['uid']);
            if(strlen($username)==11 && $ys){
                $member_list[$k]['username']=str_cutmobile($username);
            }else{
                $member_list[$k]['username']=$username;
            }
        }
        $this->assign('member_list',$member_list);
        $this->assign($postdata);
        $this->display();
    }
    public function export_member_recharge($list){
        $title = array('ID', '会员', '收银员','充值金额','提交时间','状态');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = $v['username'];
            $data[$k][] = idtoname($v['sa_id'],'ShopsAccount');
            $data[$k][] = $v['order_amount'];
            $data[$k][] = time_format($v['addtime']);
            $data[$k][] =$v['pay_status']==1?'未付款':$v['pay_status']==2?'付款中':"已付款";
        }
        export_csv('充值明细.csv',$title,$data);
        unset($title, $data);
        exit;
    }
   // 导购员明细
    public function guide_detail($is_return=false){
        $postdata = I('param.');
        $map=array();
        $map['guide']=array('gt',0);
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['data_from'] || $postdata['data_to']){
            $date_from = strtotime($postdata['data_from']);
            if($date_from)$map['addtime'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['data_to']);
            if($date_to){$date_to = $date_to+86399;$map['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['addtime']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        if($postdata['in_online']==1){$map['in_online']=0; $map['source']=array('in','0,1');}
        elseif($postdata['in_online']==2){$map['_string']='in_online = 1 or source = 2 or source = 4';}
        if($postdata['status']==1){$map['status']=array('neq','3');}
        elseif($postdata['status']==2){$map['status']=3;}
        if($postdata['type']==1){
            $map['type']=array('not in','2,15');
        }elseif($postdata['type']==2){
            $map['type']=2;
        }elseif($postdata['type']==15){
            $map['type']=15;
        }
         $map['is_delete']=0;
        $map['pay_status']=3;
        if(!empty($postdata['sale_id'])) $map['guide']=$postdata['sale_id'];
        // if(!empty($postdata['shop_id'])) $map['shop_id']=$postdata['shop_id'];
        $field='id,order_sn,in_online,goods_allmoney,shop_id,source,guide,sales_maid,addtime,status,sign_building,type';
        $map['shop_id']=MID;
        $list=$this->lists('OrderInfo',$map,'id desc','',$field);
        $list_e=M('OrderInfo')->where($map)->order('id desc')->field($field)->select();
        $data=array();
        $data['goods_allmoney']=M('OrderInfo')->where($map)->sum('goods_allmoney');
        $data['all_sale_maid']=M('OrderInfo')->where($map)->sum('sales_maid');
        $data['all_count']=M('OrderInfo')->where($map)->count();
        if(empty($data['all_sale_maid'])) $data['all_sale_maid']=0.00;
        if(empty($data['goods_allmoney'])) $data['goods_allmoney']=0.00;
        $map=array();
        $map['s.status']=1;
        $map['s.is_delete']=0;
        $map['a.role_id']=2;
        // $map['s.shop_id']=MID;
        $sales_list=M('ShopsRoleAccount')->alias('a')->where($map)->join('LEFT JOIN __SHOPS_ACCOUNT__ s ON a.account_id=s.id')->field('s.id,s.name')->cache(true)->select();
        $sales_list=format_array2select($sales_list);
        $map=array();
        $map['status']=1;
        $shops_list=M('Shops')->where($map)->field('id,name')->order('name')->cache(true)->select();
        $shops_list=format_array2select($shops_list);
        if($is_return==false) {
            $pay_type=array('1'=>'线上','2'=>'线下');
            $affif_status=array('1'=>'未分成','2'=>'已分成');
            $daogou_status=array('1'=>'商品购买','2'=>'充值','15'=>'礼品卡');
            $this->assign('pay_type',$pay_type);
            $this->assign('affif_status',$affif_status);
            $this->assign('daogou_status',$daogou_status);
            $this->assign('sales_list', $sales_list);
            $this->assign('shops_list',$shops_list);
            $this->assign('list', $list);
            $this->assign('data', $data);
            $this->assign($postdata);
            $this->display();
        }else{
            $return=array('data'=>$data,'list'=>$list_e);
            return $return;
        }
    }
    /**
     * 导购明细导出
     */
    public function export_guide_detail(){
        $guide_list=$this->guide_detail(true);
        $title = array('序号', '订单号', '订单总金额','导购员名称','消费门店','提成金额','收银员','下单方式','导购类型','状态','变更时间');
        $data = array();
        foreach ($guide_list['list'] as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = format_xml_num($v['order_sn']);
            $data[$k][] = $v['goods_allmoney'];
            $data[$k][] = idtoname($v['guide'],'ShopsAccount','name','id',false);
            $data[$k][] = idtoname($v['shop_id'],'Shops','name','id',false);
            $data[$k][] = $v['sales_maid'];
            $data[$k][] = $v['sign_building'];
            if($v['in_online']==0 && ($v['source']==0 || $v['source']==1))$data[$k][] = '线上';
            elseif($v['in_online']==1 || $v['source']==2 || $v['source']==4)$data[$k][] = '线下';
            if($v['type']==2) $data[$k][] = '充值';
            elseif($v['type']==15) $data[$k][] = '礼品卡';
            else $data[$k][] = '商品购买';
            if($v['status']==3) $data[$k][] = '已分成';
            else $data[$k][] = '未分成';
            $data[$k][] = time_format($v['addtime']);
        }
        $data[]=array(
            '总计：',
            '--',
            $guide_list['data']['goods_allmoney'],
            '--',
            '--',
            $guide_list['data']['all_sale_maid'],
            '--',
            '--',
            '--',
            '共计'.$guide_list['data']['all_count'].'条',
        );
        export_csv('导购员明细.csv',$title,$data);
        unset($title, $data);
        exit;
    }
     /**资金明细
    * @param bool $is_return
    * lss 2018-9-7
    */
    public function capital_flow($is_return=false){
        $postdata = I('param.');
        $map=array();
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['data_from'] || $postdata['data_to']){
            $date_from = strtotime($postdata['data_from']);
            if($date_from)$map['create_time'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['data_to']);
            if($date_to){$date_to = $date_to+86399;$map['create_time'][] = 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['create_time']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        if($postdata['in_online']==1){$map['in_online']=0;}
        elseif($postdata['in_online']==2){$map['in_online']=1;}
        switch($postdata['type']){
            case 2:$map['type']=$postdata['type'];
                 break;
            case 3:$map['type']=array('in','1,3,6,10,11,12,13,14,25');
                 break;
            case 5:$map['type']=$postdata['type'];
                 break;
            case 11:$map['type']=array('in','11,12');
                 break;
            case 15:$map['type']=$postdata['type'];
                 break;
            case 20:$map['type']=array('in','20,21,31');
                 break;
            default:
                $map['type']=array('neq','30');
                break;
        }
        if(!empty($postdata['sale_id'])) $map['guide']=$postdata['sale_id'];
        // if(!empty($postdata['shop_id'])) $map['shop_id']=$postdata['shop_id'];
        $map['shop_id']=MID;
        $map['is_paid']=1;
        if(!empty($postdata['cashier_name'])) $map['cashier_name']=$postdata['cashier_name'];
        $list=$this->lists('PayLog',$map,'id desc');
        if($list){
            foreach ($list as $key => $value) {
                $list[$key]=D('App/ShopbalanceLog')->format_cont($value);
            }
        }
        $field='sum(order_total_price) as goods_allmoney,sum(use_money) as all_use_money,sum(need_pay) as all_need_pay,sum(cash_money) as all_cash_money,sum(scan_money) as all_scan_money,sum(bank_money) as all_bank_money,sum(card_money) as all_card_money,sum(use_score) as all_use_score,sum(use_score_money) as all_score_money,count(id) as all_count';
        $data=M('PayLog')->where($map)->field($field)->find();
        if(empty($postdata['type'])){
                $maptui=$map;
                $maptui['type']=array('in','20,21,31');
                $datatui=M('PayLog')->where($maptui)->field($field)->find();
                if($datatui){
                $data['goods_allmoney']=$data['goods_allmoney']-$datatui['goods_allmoney']*2;
                $data['all_use_money']=$data['all_use_money']-$datatui['all_use_money']*2;
                $data['all_use_score']=$data['all_use_score']-$datatui['all_use_score']*2;
                $data['all_cash_money']=$data['all_cash_money']-$datatui['all_cash_money']*2;
                $data['all_scan_money']=$data['all_scan_money']-$datatui['all_scan_money']*2;
                $data['all_bank_money']=$data['all_bank_money']-$datatui['all_bank_money']*2;
                $data['all_card_money']=$data['all_card_money']-$datatui['all_card_money']*2;
                $data['all_score_money']=$data['all_score_money']-$datatui['all_score_money']*2;}
        }
        //导购员列表
        $map=array();
        $map['s.status']=1;
        $map['s.is_delete']=0;
        $map['a.role_id']=2;
        $sales_list=M('ShopsRoleAccount')->alias('a')->where($map)->join('LEFT JOIN __SHOPS_ACCOUNT__ s ON a.account_id=s.id')->field('s.id,s.name')->cache(true)->select();
        $sales_list=format_array2select($sales_list);
        //门店列表
        $map=array();
        $map['status']=1;
        $shops_list=M('Shops')->where($map)->field('id,name')->order('name')->cache(true)->select();
        $shops_list=format_array2select($shops_list);
        if($is_return==false) {
            $pay_type=array('1'=>'线上','2'=>'线下');
            $order_type=array('2'=>'储值','3'=>'商品销售','5'=>'门店充值','11'=>'服务','15'=>'礼品卡销售','20'=>'退款');
            $this->assign('pay_type',$pay_type);
            $this->assign('order_type',$order_type);
            $this->assign('sales_list', $sales_list);
            $this->assign('shops_list',$shops_list);
            $this->assign('list', $list);
            $this->assign('data', $data);
            $this->assign($postdata);
            $this->display();
        }else{
            $list_e=M('PayLog')->where($map)->order('id desc')->select();
            $return=array('data'=>$data,'list'=>$list_e);
            return $return;
        }
    }
    /**
     * 资金流水导出
     * lss 2018-9-7
     */
    public function export_capital_flow(){
        $guide_list=$this->capital_flow(true);
        $title = array('序号', '门店', '收银员名称','导购员名称','订单号','总金额','余额','现金','扫码','台卡','刷卡','使用积分','积分抵扣','下单方式','类型','变更时间');
        $data = array();
        foreach ($guide_list['list'] as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = idtoname($v['shop_id'],'Shops','name','id',false);
            $data[$k][] = $v['cashier_name'];
            $data[$k][] = idtoname($v['guide'],'ShopsAccount','name','id',false);
            if(is_numeric($v['order_id'])){
                $order_id=$v['order_id'];
            }else{
                $orderid=explode(',',$v['order_id']);
                $order_id=$orderid[1];
            }
            $data[$k][] = format_xml_num($v['order_sn']).'('.$order_id.')';
            $data[$k][] = format_price($v['order_total_price']);
            $data[$k][] = format_price($v['use_money']);
            $data[$k][] = format_price($v['cash_money']);
            $data[$k][] = format_price($v['scan_money']);
            $data[$k][] = format_price($v['bank_money']);
            $data[$k][] = format_price($v['card_money']);
            $data[$k][] = $v['use_score'];
            $data[$k][] = format_price($v['use_score_money']);
            if($v['in_online']==0)$data[$k][] = '线上';
            elseif($v['in_online']==1)$data[$k][] = '线下';
            if($v['type']==2) $data[$k][] = '充值';
            elseif($v['type']==3) $data[$k][] = '积分购买';
            elseif($v['type']==13) $data[$k][] = '收银';
            elseif($v['type']==14) $data[$k][] = '商品购买';
            elseif($v['type']==20) $data[$k][] = '取消订单';
            elseif($v['type']==21) $data[$k][] = '退货';
            $data[$k][] = time_format($v['create_time']);
        }
        $data[]=array(
            '总计：',
            '--',
            '--',
            '--',
            '--',
            format_price($guide_list['data']['goods_allmoney']),
            format_price($guide_list['data']['all_use_money']),
            format_price($guide_list['data']['all_cash_money']),
            format_price($guide_list['data']['all_scan_money']),
            format_price($guide_list['data']['all_bank_money']),
            format_price($guide_list['data']['all_card_money']),
            format_price($guide_list['data']['all_use_score']),
            format_price($guide_list['data']['all_score_money']),
            '--',
            '--',
            '共计'.$guide_list['data']['all_count'].'条',
        );
        export_csv('资金流水.csv',$title,$data);
        unset($title, $data);
        exit;
    }
     /**余额明细*/
    public function balance_flow(){
        $this->assign('account_type',array('1'=>'营业总额','2'=>'未结算','3'=>'待结算','4'=>'冻结','5'=>'代扣服务费','6'=>'销售额'));
        $this->assign('account_status',array('1'=>'充值','2'=>'提现','3'=>'订单结算','4'=>'系统结算','5'=>'下单','10'=>'店铺订货'));
        $change_types = array(0=>'增加',1=>'减少');$this->assign('change_types',$change_types);
        $type=I('type');
        $postdata=I('param.');
        $t_map=$xh_map=$c_map=$money_map=$map = array();
        if($postdata['status'])$map['status'] = $postdata['status'];
        // 限定开始
       $map['shop_id']=$map['']=MID;
        // 限定结束
        if($type){
            $map['type'] = array('eq',$type);
        }else{
            $map['type'] = 1;//array('not in','7');//去掉积分
        }
        if($postdata['reg_from'] || $postdata['reg_to']){
            $date_from = strtotime($postdata['reg_from']);
            if($date_from){
                $map['change_time'][] = array('egt',$date_from);
            }
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){
                $date_to = $date_to+86399;
                $map['change_time'][] = 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['change_time']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        if($postdata['change_type'] === '0' || $postdata['change_type'] == 1)$map['change_type'] = array('eq',$postdata['change_type']);
        $list = $this->lists('ShopbalanceLog',$map);
        //      当前余额
        $m_map['id']=MID;
        $d_money = M('Shops')->where($m_map)->getField('total_revenues');
        //  充值
        $money_map['shop_id']=MID;
        $money_map['status']=1;
        // 12 6 兼容后台充值也能减钱
        // $chongzhi = M('ShopbalanceLog')->where($money_map)->field('sum(change_num) as money,count(id) as num')->find();
        $money_map['change_type']=1;
        $chongzhi1 = M('ShopbalanceLog')->where($money_map)->field('sum(change_num) as money,count(id) as num')->find();
        $money_map['change_type']=0;
        $chongzhi2 = M('ShopbalanceLog')->where($money_map)->field('sum(change_num) as money,count(id) as num')->find();
        $chongzhi['money']=$chongzhi2['money']-$chongzhi1['money']; $chongzhi['num']=$chongzhi2['num']+$chongzhi1['num'];
        // 12 6 end
        //   提现
         $money_map['status']=2;
        $xh = M('ShopbalanceLog')->where($money_map)->field('sum(change_num) as used_money,count(id) as num')->find();
        //订货
        $money_map=[];
         $money_map['shop_id']=MID;
        $money_map['status']=10;
        $money_map['type']=1;
        $money_map['chang_type']=1;
        $t_info = M('ShopbalanceLog')->where($money_map)->field('sum(change_num) as refund_money')->find();
        $this->assign('d_money',$d_money);
        $this->assign('chongzhi',$chongzhi);
        $this->assign('xh',$xh);
        $this->assign('t_info',$t_info);
        $this->assign('list',$list);
        $this->assign($postdata);
        $this->display();
    }
    // 积分明细
    public function point_flow(){
        $change_types = array(0=>'增加',1=>'减少');$this->assign('change_types',$change_types);
        $account_status=array('1'=>'充值','3'=>'订单结算');
        $this->assign('account_status',$account_status);
        $postdata=I('param.');
        $dk_map['shop_id']=$map['shop_id']=MID;
        $map['type']=7;
        if($postdata['change_type'] === '0' || $postdata['change_type'] == 1){$map['change_type'] = $postdata['change_type'];}
        if($postdata['status'])$map['status'] = $postdata['status'];
        if($postdata['reg_from'] || $postdata['reg_to']){
            $date_from = strtotime($postdata['reg_from']);
            if($date_from){
                $map['change_time'][] = array('egt',$date_from);
                 $dk_map['addtime'][] = array('egt',$date_from);
            }
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){
                $date_to = $date_to+86399;
                $map['change_time'][] = array('lt',$date_to);
                 $dk_map['change_time'][] = 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['change_time']=array('between',array($between[0],$between[1]));
                $dk_map['addtime'] = array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        $list = $this->lists('ShopbalanceLog',$map);
            //当前积分
        $d_points = M('Shops')->where('id='.MID)->getField('total_point');
        //      累计获得
        unset($map['change_type']);
        $map['change_type']=0;
        $get_points = M('ShopbalanceLog')->where($map)->sum('change_num');
        //      累计消耗
        unset($map['change_type']);
        $map['change_type']=1;
        $xh_points = M('ShopbalanceLog')->where($map)->sum('change_num');
        //      积分抵扣
        $dk_map['status']=3;
        $dk_points=M('OrderInfo')->where($dk_map)->field('sum(used_score) as used_score')->find();
        $this->assign('d_points',$d_points);
        $this->assign('get_points',$get_points);
        $this->assign('xh_points',$xh_points);
        $this->assign('dk_points',$dk_points);
        $this->assign('list',$list);
        $this->assign($postdata);
        $this->display();
    }
    // 商品分类开始
    public function cate_list(){
        $postdata=I('param.');
        $where_s['status']=1;
        $shops_info = M('Shops')->where($where_s)->order('convert(name using gb2312) ASC')->field('id,name')->select();
        $shops_op = '';
        if (!empty($shops_info)) {
            foreach ($shops_info as $k => $v) {
                if ($postdata['shop_id'] == $v['id']) {
                    $shops_op .= "<option selected='selected' value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                } else {
                    $shops_op .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                }
            }
        }
        $this->assign('select_shops', $shops_op);
        $result=$this->catelist($postdata);
        $ec = new \Common\Vendor\Echarts();
        $pay_style_count = array(
        'title'=>array(
        'text'=>'分类统计',
        'x'=>'center'
        ),
            "legend"=>array('orient'=>'vertical','left'=>'left','data'=>$result['catename']),
            "series"=>array(
                array("name"=>"分类分析",
                    "type"=>"pie",
                    'radius'=>'60%',
                    "data"=>$result['data'],
                ),
            ),
        );
        $this->assign('Area_count_pay',$ec->pie_show('Area_count_pay', $pay_style_count,'pie',''));
        $this->assign('cate_count',$result['cate_count']);
        $this->assign('count',$result['count']);
        $this->assign('allnum',$result['allnum']);
        if(!strpos('1,2,7,30', $postdata['dates']) && $postdata['dates']!=1){
            $postdata['dates']=99;
        }
        $postdata['dates']=intval($postdata['dates']);
        $this->assign($postdata);
        $this->display();
    }
    public function export_cate(){
        $null=array();
        $postdata=I('param.');
        $count=$this->catelist($postdata);
        $title=array('分类','销量','百分比');
        $title_name = array('商品分类统计');
        export_csv('分类统计.csv',$title,$count['cate_count']);
        exit;
    }
    private function catelist($postdata){
        $return=$cate_count=$data=$og_map=$map=$map_c=$g_map=$catename=array();
        $map_c['status']=1;
        $map_c['pid']=0;
        $carids = M('PurchaseCategory')->where($map_c)->field('id,name')->select();
        unset($map_c['pid']);
        if($carids){
            $map['type'] = array('in','1,6,13,14');
            $map['pay_status'] = 3;
            $now_time=strtotime(date('Y-m-d',NOW_TIME));
            if($postdata['date_from'] || $postdata['date_to']){
                $date_from = strtotime($postdata['date_from']);
                if($date_from)$map['addtime'][] = array('egt',$date_from);
                $date_to = strtotime($postdata['date_to']);
                if($date_to){$date_to = $date_to+86399;$map['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['addtime']=array('between',array($between[0],$between[1]));
                }else{
                    $postdata['dates']=99;
                }
            }
            // if($postdata['shop_id']){
            //     $map['shop_id']=$postdata['shop_id'];
            // }
            $map['shop_id']=MID;
            $orderid=M('OrderInfo')->where($map)->getField("id",true);
            if($orderid){
                foreach($carids as $k=>$v){
                    $catename[]=$v['name'];
                    $map_c['pid']=$v['id'];
                    $child_catid = M('PurchaseCategory')->where($map_c)->getField('id',true);
                    if($child_catid){
                        $child_catid[]=$v['id'];
                        $g_map['cat_id']=array('in',$child_catid);
                    }else{
                        $g_map['cat_id']=$v['id'];
                    }
                    $goods_ids = M('Goods')->where($g_map)->getField('id',true);
                    if($goods_ids){
                        $og_map['goods_id']=array('in',$goods_ids);
                        $og_map['order_id']=array('in',$orderid);
                        $goods_num=M('OrderGoods')->where($og_map)->sum('goods_number');
                        $goodsnum[]=floatval($goods_num);
                    }else{
                        $goodsnum[]=0;
                    }
                }
            }
        }
        $allnum=array_sum($goodsnum);
        $i=0;
        if(count($catename) > 0){
            foreach ($catename as $key => $value) {
                $data[]=array("value"=>$goodsnum[$key],"name"=>$value);
                $cate_count[$key]['catename']=$value;
                $cate_count[$key]['num']=$goodsnum[$key];
                $cate_count[$key]['percent']=number_format(($goodsnum[$key]/$allnum)*100,2).'%';
                $i++;
            }
        }
        $return['data']=$data;
        $return['catename']=$catename;
        $return['cate_count']=$cate_count;
        $return['allnum']=$allnum;
        $return['count']=$i;
        return $return;
    }
    // 商品分类结束
    // 优惠活动效果
    public function sale_index(){
        // 优惠信息
        //promot_id//活动id promot_money_json   {"12":{"type":"4","money":"0.00"},"18":{"type":"3","money":"50.00"}}
        // discount折扣金额 =bonus_money红包金额+member_discount会员等级折扣+used_score_money积分抵扣现金+promot_money活动总金额 +custom_discount自定义折扣+moling_discount抹零信息
        //$map['bonus_id']='';//红包id
        $postdata=I('param.');
        $map=array();
        //优惠活动开始
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from)$map['addtime'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['date_to'])+86399;
            if($postdata['date_to'])$map['addtime'][] = array('lt',$date_to);
        }else{
            if(in_array($postdata['dates'],array(1,2,7,30))){
                $between=$this->quick_time($postdata['dates']);
                $map['addtime']=array('between',array($between[0],$between[1]));
            }
        }
        $map['shop_id']=MID;
        $d_map=$j_map=$z_map=$b_map=$map;
        $this->assign($postdata);
        if($postdata['promot_id']){
            $map['promot_id']=array('like',array($postdata['promot_id'],'%,'.$postdata['promot_id'],'%,'.$postdata['promot_id'].',%'),'or');
        }else {$map['promot_id']=array('gt','0');}
        $data=M('OrderInfo')->where($map)->field('uid,promot_money,promot_money_json')->select();
        $all=0;$p_all=[];//总优惠 各个活动总优惠array
        $all_p=0;
        foreach($data as $key=>$val){
            $all_p++; 
            $all+=$val['promot_money'];
            if($val['promot_money_json']){
                $js=json_decode($val['promot_money_json'],true); 
                foreach($js as $k=> $v){
                    if(!$k>0) continue;
                    $p_all[$k]['money']+=$v['money'];
                    $p_all[$k]['penson']++;
                    $p_all[$k]['uid'][$val['uid']]++;
                }
            }
        }
        // $return['data']=$data;//所有数据
        $return['p_all']=$p_all;//各活动优惠钱数
        $return['all']=$all;//总钱数
        $return['all_p']=$all_p;//总订单数
        $this->assign($return);
        // 红包优惠
        $b_map['bonus_id']=array('gt','0');
        $b_data=M('OrderInfo')->where($b_map)->field('uid,sum(bonus_money) as money,count(uid) as num')->group('uid')->order('money')->limit(5)->select();
        $this->assign('b_data',$b_data);
        // 自定义折扣
        $z_map['custom_discount']=array('gt',0);
          $z_data=M('OrderInfo')->where($z_map)->field('uid,sum(custom_discount) as money,count(uid) as num')->group('uid')->order('money')->limit(5)->select();
        $this->assign('z_data',$z_data);
        // 积分抵扣
        $j_map['used_score_money']=array('gt',0);
        $j_data=M('OrderInfo')->where($j_map)->field('uid,sum(used_score_money) as money,count(uid) as num,sum(used_score) as score_num')->group('uid')->order('money')->limit(5)->select();
        $this->assign('j_data',$j_data);
        //等级优惠
        $d_map['member_discount']=array('gt',0);
        $rank=M('MemberRank')->where('status=1')->getField('id,name');
        $this->assign('rank',$rank);
        $d_data=M('OrderInfo')->alias('oi')->where($j_map)->field('uid,sum(member_discount) as money,count(uid) as num')->group('uid')->order('money')->limit(5)->select();
        foreach($d_data as $k=>$v){
            $d_data[$k]['rank_id']=idtoname($v['uid'],'Member','rank_id');
        }
        $this->assign('d_data',$d_data);
        $this->display();
    }
    // 充值明细
    public function member_edit(){
        $status_type=array(0=>'未处理',1=>'已处理',2=>'已关闭');
        $status_pay=array(1=>'未付款',2=>'付款中',3=>'已付款');
        $this->assign('status_type',$status_type);
        $this->assign('status_pay',$status_pay);
         $id=I('param.id');
        $map['id'] = $id;
        $map['type'] = 2;
        $member_info = M('OrderInfo')->where($map)->field(true)->find();
        $ys=idtoname(MID,'Shops','is_hide_phone');
        $username=show_user_name($member_info['uid']);
         if(strlen($username)==11 && $ys){
                $member_info['username']=str_cutmobile($username);
            }else{
                $member_info['username']=$username;
            }
        $this->assign($member_info);
        $this->display();
    }
    // 奖品明细
    // 自己会员的所有核销门店是0或者自己的， 或者核销门店是自己的
    public function win_gift(){
        $win_type_arr = array('1'=>'积分商城','2'=>'小票抽奖','3'=>'推广活动','4'=>'全民发券','5'=>'签到');
        $check_status_arr = array('1'=>'已领取','2'=>'未领取');
        $this->assign('win_type_arr',$win_type_arr);
        $this->assign('check_status_arr',$check_status_arr);
        $postdata = I('param.');
        $map = array();
        if($postdata['win_type']){
            $map['a.win_type'] = $postdata['win_type'];
        }
        if($postdata['keyword']){
            $u_map = array();
            $u_map['id|username|nickname|real_name|mobile'] = array('like','%'.$postdata['keyword'].'%');
            $uids = M('Member')->where($u_map)->getField('id',true);
            if($uids) $map['a.user_id'] = array('in',$uids);
            else $map['a.user_id'] = array('in','');
        }
        if($postdata['check_status']){
            if($postdata['check_status'] == 1) $map['a.check_status'] = 1;
            else $map['a.check_status'] = 0;
        }
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from)$map['a.add_time'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['date_to'])+86399;
            if($date_to)$map['a.add_time'][] = array('lt',$date_to);
            $postdata['dates']=0;
        }else{
            $now_time=strtotime(date('Y-m-d',NOW_TIME));
            if($postdata['dates']==1){
                $start_time=$now_time;
                $end_time=$now_time+86399;
                $map['a.add_time']=array('between',array($start_time,$end_time));
            }else if($postdata['dates']==2){
                $start_time=$now_time-86400;
                $end_time=$now_time-1;
                $map['a.add_time']=array('between',array($start_time,$end_time));
            }else if($postdata['dates']==7){
                $start_time=$now_time-86400*6;
                $end_time=$now_time+86399;
                $map['a.add_time']=array('between',array($start_time,$end_time));
            }else if($postdata['dates']==30){
                $start_time=$now_time-86400*29;
                $end_time=$now_time+86399;
                $map['a.add_time']=array('between',array($start_time,$end_time));
            }else{
                $postdata['dates']=99;
            }
        }
        $map['a.id'] = array('gt',0);
        $order = 'a.id desc';
        // $zj_map['m.user_shop']=MID;
        // $zj_map['location_id']=arrray('in','0,'.MID);
        // $other_map['location_id']=MID;
        $map['_string']="(m.user_shop=".MID." and a.location_id in(0,".MID."))or a.location_id= ".MID;
        $join="__MEMBER__ as m on m.id=a.user_id";
         // echo  $return['list'] = M('WinGift')->alias('a')->where($map)->order('create_time')->join($join)->field('a.*')->order($order)->limit($limit)->fetchSql(true)->select();
        $list=page_list('WinGift',$map,$order,'a.*',20,$join);
        $ys=idtoname(MID,'Shops','is_hide_phone');
        foreach($list['list'] as $k=>$v){
            $username=show_user_name($v['user_id']);
            if($ys){
              if(strlen($username)==11){$v['username']=str_cutmobile($username); }
              else{$v['username']=$username;} 
            }else{
                $v['username']=$username;
            }
            if($v['win_type'] != 5){
                $map = array();$map['id'] = $v['gift_id'];
                $prize_info = M('Prize')->where($map)->field('prize_type,prize_goods')->find();
                if($prize_info['prize_type'] == 1){
                    $gift_name = $prize_info['prize_goods'];
                }else if($prize_info['prize_type'] == 2){
                    $gift_name = '现金+'.$prize_info['prize_goods'];
                }else if($prize_info['prize_type'] == 3){
                    $gift_name = '积分+'.$prize_info['prize_goods'];
                }else if($prize_info['prize_type'] == 4){
                    $c_map = array();$c_map['id'] = $prize_info['prize_goods'];
                    $coupons_name = M('Coupons')->where($c_map)->getField('title');
                    $gift_name = $coupons_name.'优惠券+1';
                }
                $v['gift_name'] = $gift_name;
                if($v['win_type'] == 1){
                    $v['win_name'] = '积分商品';
                }else if($v['win_type'] == 2){
                    $v['win_name'] = '小票抽奖';
                }else if($v['win_type'] == 3){
                    $v['win_name'] = '推广活动';
                }else if($v['win_type'] == 4){
                    $v['win_name'] = '全民发券';
                }
            }else{
                $v['gift_name'] = $v['gift_name'].'+'.$v['gift_number'];
                $v['win_name'] = '签到';
            }
            $list['list'][$k] = $v;
        }
        $this->assign($list);
        $this->assign($postdata);
        $this->display();
    }
        // 订单开始  直接和后台同步 加shop_id
    public function order($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();
         $shop_list[MID] = idtoname(MID,'Shops','name');
        $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.');$postdata['shopid']=MID;
        $map['a.type']=$map_oi['type']=array('in','1,6,11,13,14');
        $map['a.pay_status']=$map_oi['pay_status']=3;
        $map['a.is_delete']=$map_oi['is_delete']=0;
        $map['a.status']=$map_oi['status']=array('in','1,2,3,6,8');
        if($postdata['shopid'])$map['a.shop_id'] =$map_oi['shop_id']= $postdata['shopid'];
        if($postdata['source']){
            $map['a.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['a.addtime'][] = array('egt',$date_from);$map_oi['addtime'][] = array('egt',$date_from);}
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){$date_to = $date_to+86399;$map['a.addtime'][] = array('lt',$date_to);$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['a.addtime']=$map_oi['addtime']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        if($postdata['in_online']==1){
            $map['a.in_online']=$map_oi['in_online']=$postdata['in_online'];
        }elseif($postdata['in_online']==2){
            $map['a.in_online']=$map_oi['in_online']=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,shop_id,addtime,(sum(order_money)/count(id)) as avg_num";
            $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->field($field)->select();
            $ordergoods = M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->field("sum(g.goods_number) as goods_num,a.addtime")->group("DATE_FORMAT(FROM_UNIXTIME(a.addtime),'%k')")->select();
          $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
          $orderinfo['avg_price']=$orderinfo['goods_num']=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'])]['goods_num']=$ordergoods[$k]['goods_num'];
            $list[date('G',$v['addtime'])]['num']=$v['num'];
            $list[date('G',$v['addtime'])]['avg_price']=format_decimal($v['order_money']/$ordergoods[$k]['goods_num']);
            $list[date('G',$v['addtime'])]['avg_num']=format_decimal($v['avg_num']);
            $list[date('G',$v['addtime'])]['percent_money']=number_format(($v['order_money']/$orderinfo['order_money'])*100,2).'%';
            $orderinfo['goods_num']+=$ordergoods[$k]['goods_num'];
            $list_time[]=date('G',$v['addtime']);
        }unset($k,$v);
        $orderinfo['avg_price']=$orderinfo['order_money']/$orderinfo['goods_num'];
        $orderinfo['avg_num']=$orderinfo['order_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]['goods_num']=0;
            $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,shop_id,addtime,(sum(order_money)/count(id)) as avg_num";
          $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%e')")->field($field)->select();
          $ordergoods = M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->field("sum(g.goods_number) as goods_num,a.addtime")->group("DATE_FORMAT(FROM_UNIXTIME(a.addtime),'%e')")->select();
          $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
          $orderinfo['avg_price']=$orderinfo['goods_num']=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'])]['goods_num']=floatval($ordergoods[$k]['goods_num']);
            $list[date('j',$v['addtime'])]['num']=floatval($v['num']);
            $list[date('j',$v['addtime'])]['avg_price']=format_decimal($v['order_money']/$ordergoods[$k]['goods_num']);
            $list[date('j',$v['addtime'])]['avg_num']=format_decimal($v['avg_num']);
            $list[date('j',$v['addtime'])]['percent_money']=number_format(($v['order_money']/$orderinfo['order_money'])*100,2).'%';
            $orderinfo['goods_num']+=$ordergoods[$k]['goods_num'];
            $list_time[]=date('j',$v['addtime']);
        }unset($k,$v);
        $orderinfo['avg_price']=$orderinfo['order_money']/$orderinfo['goods_num'];
        $orderinfo['avg_num']=$orderinfo['order_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]['goods_num']=0;
        $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,shop_id,addtime,(sum(order_money)/count(id)) as avg_num";
          $list_t=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%c')")->field($field)->select();
          $ordergoods = M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->field("sum(g.goods_number) as goods_num,a.addtime")->group("DATE_FORMAT(FROM_UNIXTIME(a.addtime),'%c')")->select();
          $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
          $orderinfo['avg_price']=$orderinfo['goods_num']=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'])]['goods_num']=floatval($ordergoods[$k]['goods_num']);
            $list[date('n',$v['addtime'])]['num']=floatval($v['num']);
            $list[date('n',$v['addtime'])]['avg_price']=format_decimal($v['order_money']/$ordergoods[$k]['goods_num']);
            $list[date('n',$v['addtime'])]['avg_num']=format_decimal($v['avg_num']);
            $list[date('n',$v['addtime'])]['percent_money']=number_format(($v['order_money']/$orderinfo['order_money'])*100,2).'%';
            $orderinfo['goods_num']+=$ordergoods[$k]['goods_num'];
            $list_time[]=date('n',$v['addtime']);
        }unset($k,$v);
        $orderinfo['avg_price']=$orderinfo['order_money']/$orderinfo['goods_num'];
        $orderinfo['avg_num']=$orderinfo['order_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]['goods_num']=0;
        $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,shop_id,addtime,(sum(order_money)/count(id)) as avg_num";
          $list_s=M('OrderInfo')->where($map_oi)->group("shop_id")->field($field)->select();
          $ordergoods = M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->field("sum(g.goods_number) as goods_num,a.addtime,a.shop_id")->group("a.shop_id")->select();
          $orderinfo=M('OrderInfo')->where($map_oi)->field($field)->find();
          $orderinfo['avg_price']=$orderinfo['goods_num']=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']]['goods_num']=floatval($ordergoods[$k]['goods_num']);
            $list[$v['shop_id']]['num']=floatval($v['num']);
            $list[$v['shop_id']]['avg_price']=format_decimal($v['order_money']/$ordergoods[$k]['goods_num']);
            $list[$v['shop_id']]['avg_num']=format_decimal($v['avg_num']);
            $list[$v['shop_id']]['percent_money']=number_format(($v['order_money']/$orderinfo['order_money'])*100,2).'%';
            $orderinfo['goods_num']+=$ordergoods[$k]['goods_num'];
            $list_time[]=$v['shop_id'];
        }unset($k,$v);
        $orderinfo['avg_price']=$orderinfo['order_money']/$orderinfo['goods_num'];
        $orderinfo['avg_num']=$orderinfo['order_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]['goods_num']=0;
        $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_order(){
        $rest=$this->order(true);
        $data=array();
        $data=$rest['list'];
        $data[]=array('总计',$rest['info']['order_money'],floatval($rest['info']['goods_num']),$rest['info']['num'],format_decimal($rest['info']['avg_price']),format_decimal($rest['info']['avg_num']),'--');
        export_csv('订单统计.csv',$rest['title'],$data);
        exit;
    }
    // 销售占比
    public function sale_analiysis($is_return=false){
        // $shop_list=D('Shops')->shop_list();
        // $this->assign('shop_list',$shop_list);
        $sou_type=strtoarray(array('1'=>'按商品分类','2'=>'按商品品牌','3'=>'按导购员','4'=>'按收银员','5'=>'按支付方式'));
        $this->assign('sou_type',$sou_type);
        $sou_title=strtoarray(array('1'=>'商品分类','2'=>'商品品牌','3'=>'导购员','4'=>'收银员','5'=>'支付方式'));
        $this->assign('sou_title',$sou_title);
        $map=$map_oi=array();
        $postdata=I('param.');
        $map_oi['order_id']=array('gt','0');
        $postdata['shopid']=MID;//1115+
        if($postdata['shopid'])$map_oi['shop_id']= $postdata['shopid'];
        $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['a.addtime'][] = array('egt',$date_from);$map_oi['addtime'][] = array('egt',$date_from);}
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){$date_to = $date_to+86399;$map['a.addtime'][] = array('lt',$date_to);$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['a.addtime']=$map_oi['addtime']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        $map['a.type']=$map_oi['type']=array('in','1,6,11,13,14');
        $map['a.pay_status']=$map_oi['pay_status']=3;
        $map['a.is_delete']=$map_oi['is_delete']=0;
        $map['a.status']=$map_oi['status']=array('in','1,2,3,6,8');
        $list=$cat_ida=$all=array();
        $all['num']=$all['goods_number']=$all['yuan_price']=$all['goods_price']=$all['profit']=0;
        if(!$postdata['sou_value']){
            $postdata['sou_value']=1;
        }
        if(F('shoplist'.$postdata['sou_value'].','.$postdata['shopid'].','.$postdata['dates'].','.$postdata['reg_from'].','.$postdata['reg_to'])){
            $list=F('shoplist'.$postdata['sou_value'].','.$postdata['shopid'].','.$postdata['dates'].','.$postdata['reg_from'].','.$postdata['reg_to']);
            $all=F('shopall'.$postdata['sou_value'].','.$postdata['shopid'].','.$postdata['dates'].','.$postdata['reg_from'].','.$postdata['reg_to']);
        }else{
            switch($postdata['sou_value']){
                case 2://按商品品牌
                    $map_c=array();
                    $map_c['status']=1;
                    $brandids = M('Brand')->where($map_c)->field('id,brand_name')->select();
                    $orderid=M('OrderInfo')->where($map_oi)->getField('id',true);
                    if(empty($orderid)){
                        break;
                    }
                    $og_map['order_id']=array('in',$orderid);
                    $goods_oids=M('OrderGoods')->where($og_map)->field('goods_id,goods_number,attr_price*goods_number as yuan_price,goods_price*goods_number as goods_price,profit,order_id')->select();
                    if($brandids){
                        foreach($brandids as $k=>$v){
                            $g_map=array();
                            $list[$v['id']]['name']=$v['brand_name'];
                            $list[$v['id']]['profit']=$list[$v['id']]['goods_price']=$list[$v['id']]['yuan_price']=$list[$v['id']]['goods_number']=$list[$v['id']]['num']=0;
                            $g_map['brand_id']=$v['id'];
                            $goods_ids = M('Goods')->where($g_map)->getField('id',true);
                            $cat_ida[$v['id']]=$goods_ids;
                        }unset($k,$v);
                        foreach($cat_ida as $k=>$v){
                            if($v){
                                $map_n=array();
                                $map_n['a.id']=array('in',$orderid);
                                $map_n['g.goods_id']=array('in',$v);
                                $list[$k]['num']=M('OrderInfo')->alias('a')->join('__ORDER_GOODS__ g ON g.order_id=a.id')->where($map_n)->count('a.id');
                                $goods_number=$yuan_price=$goods_price=$profit=0;
                                foreach($goods_oids as $kg=>$vg){
                                    if($v && in_array($vg['goods_id'],$v)){
                                        $goods_number +=$vg['goods_number'];
                                        $yuan_price+=$vg['yuan_price'];
                                        $goods_price+=$vg['goods_price'];
                                        $profit+=$vg['profit'];
                                    }
                                }
                                $list[$k]['goods_number']=floatval($goods_number);
                                $list[$k]['yuan_price']=format_decimal($yuan_price);
                                $list[$k]['goods_price']=format_decimal($goods_price);
                                $list[$k]['profit']=format_decimal($profit);
                            }
                            $all['num']+=$list[$k]['num'];
                            $all['goods_number']+=$list[$k]['goods_number'];
                            $all['yuan_price']+=$list[$k]['yuan_price'];
                            $all['goods_price']+=$list[$k]['goods_price'];
                            $all['profit']+=$list[$k]['profit'];
                        }
                    }
                    break;
                case 3://导购员
                    $guider_list=D('Admin/Shops')->guider_list();
                    if($guider_list){
                        $guide_ids=array_keys($guider_list);
                        $map['guide']=array('in',$guide_ids);  
                        $map['a.shop_id']=MId;//1115+
                        $field="count(a.id) as num,sum(a.goods_allmoney) as yuan_price,sum(a.profit) as profit,sum(a.order_money) as goods_price,a.guide,sum(g.goods_number) as goods_number";
                        $list_o=M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->group("guide")->field($field)->select();
                        $all=M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->field($field)->find();
                        $list_time=array();
                        foreach ($list_o as $k => $v) {
                            $list[$v['guide']]['name']=$guider_list[$v['guide']];
                            $list[$v['guide']]['num']=$v['num'];
                            $list[$v['guide']]['goods_number']=floatval($v['goods_number']);
                            $list[$v['guide']]['yuan_price']=format_decimal($v['yuan_price']);
                            $list[$v['guide']]['goods_price']=format_decimal($v['goods_price']);
                            $list[$v['guide']]['profit']=format_decimal($v['profit']);
                            $list_time[]=$v['guide'];
                        }unset($k,$v);
                        $new_day=array_diff($guide_ids,$list_time);
                        foreach($new_day as $vt){
                            $list[$vt]['name']=$guider_list[$vt];
                            $list[$vt]['num']=0;
                            $list[$vt]['goods_number']=0;
                            $list[$vt]['yuan_price']=0;
                            $list[$vt]['goods_price']=0;
                            $list[$vt]['profit']=0;
                        }
                        if($all['num']==0){
                            $all['num']=$all['goods_number']=$all['yuan_price']=$all['goods_price']=$all['profit']=0;
                        }
                    }
                    break;
                case 4://按收银员
                    // $cashier_list=D('Admin/Shops')->cashier_list();
                    $cashier_list=$this->cashier_list();
                    $cashier_ids=array_keys($cashier_list);
                    if($cashier_list){
                        $map['sa_id']=array('in',$cashier_ids);
                        $field="count(a.id) as num,sum(a.goods_allmoney) as yuan_price,sum(a.profit) as profit,sum(a.order_money) as goods_price,a.sa_id,sum(g.goods_number) as goods_number";
                        $list_o=M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->group("sa_id")->field($field)->select();
                        $all=M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->field($field)->find();
                        $list_time=array();
                        foreach ($list_o as $k => $v) {
                            $list[$v['sa_id']]['name']=$cashier_list[$v['sa_id']];
                            $list[$v['sa_id']]['num']=$v['num'];
                            $list[$v['sa_id']]['goods_number']=floatval($v['goods_number']);
                            $list[$v['sa_id']]['yuan_price']=format_decimal($v['yuan_price']);
                            $list[$v['sa_id']]['goods_price']=format_decimal($v['goods_price']);
                            $list[$v['sa_id']]['profit']=format_decimal($v['profit']);
                            $list_time[]=$v['sa_id'];
                        }unset($k,$v);
                        $new_day=array_diff($cashier_ids,$list_time);
                        foreach($new_day as $vt){
                            $list[$vt]['name']=$cashier_list[$vt];
                            $list[$vt]['num']=0;
                            $list[$vt]['goods_number']=0;
                            $list[$vt]['yuan_price']=0;
                            $list[$vt]['goods_price']=0;
                            $list[$vt]['profit']=0;
                        }
                        if($all['num']==0){
                            $all['num']=$all['goods_number']=$all['yuan_price']=$all['goods_price']=$all['profit']=0;
                        }
                    }
                    break;
                case 5://按支付方式
                    $pay_type=array('CHINAUMSPOS'=>'银联','weixinpay'=>'微信','weixinsmall'=>'微信小程序','HANCHAO'=>'余额','HANCHAO_XIANJIN'=>'现金','HANCHAO_CARD'=>'刷卡');
                    $pay_typek=array_keys($pay_type);
                    $field="count(a.id) as num,sum(a.goods_allmoney) as yuan_price,sum(a.profit) as profit,sum(a.order_money) as goods_price,a.pay_code,sum(g.goods_number) as goods_number";
                    $map['a.shop_id']=MID;//1115+
                    $list_o=M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->group("pay_code")->field($field)->select();
                    $all=M('OrderInfo')->alias('a')->where($map)->join('__ORDER_GOODS__ g ON g.order_id=a.id')->field($field)->find();
                    $list_time=array();
                    foreach ($list_o as $k => $v) {
                        if($v['pay_code']=='CHINAUMSPOS'){
                            $list['CHINAUMSPOS']['name']=$pay_type['CHINAUMSPOS'];
                            $list['CHINAUMSPOS']['num']=$v['num'];
                            $list['CHINAUMSPOS']['goods_number']=floatval($v['goods_number']);
                            $list['CHINAUMSPOS']['yuan_price']=format_decimal($v['yuan_price']);
                            $list['CHINAUMSPOS']['goods_price']=format_decimal($v['goods_price']);
                            $list['CHINAUMSPOS']['profit']=format_decimal($v['profit']);
                            $list_time[]='CHINAUMSPOS';
                        }
                        if($v['pay_code']=='weixinpay'){
                            $list['weixinpay']['name']=$pay_type['weixinpay'];
                            $list['weixinpay']['num']=$v['num'];
                            $list['weixinpay']['goods_number']=floatval($v['goods_number']);
                            $list['weixinpay']['yuan_price']=format_decimal($v['yuan_price']);
                            $list['weixinpay']['goods_price']=format_decimal($v['goods_price']);
                            $list['weixinpay']['profit']=format_decimal($v['profit']);
                            $list_time[]='weixinpay';
                        }
                        if($v['pay_code']=='weixinsmall'){
                            $list['weixinsmall']['name']=$pay_type['weixinsmall'];
                            $list['weixinsmall']['num']=$v['num'];
                            $list['weixinsmall']['goods_number']=floatval($v['goods_number']);
                            $list['weixinsmall']['yuan_price']=format_decimal($v['yuan_price']);
                            $list['weixinsmall']['goods_price']=format_decimal($v['goods_price']);
                            $list['weixinsmall']['profit']=format_decimal($v['profit']);
                            $list_time[]='weixinsmall';
                        }
                        if(!$v['pay_code']||$v['pay_code']==''||$v['pay_code']=='Hanchao'||$v['pay_code']=='HANCHAO'){
                            $list['HANCHAO']['name']=$pay_type['HANCHAO'];
                            $list['HANCHAO']['num']+=$v['num'];
                            $list['HANCHAO']['goods_number']+=floatval($v['goods_number']);
                            $list['HANCHAO']['yuan_price']+=format_decimal($v['yuan_price']);
                            $list['HANCHAO']['goods_price']+=format_decimal($v['goods_price']);
                            $list['HANCHAO']['profit']+=format_decimal($v['profit']);
                            $list_time[]='HANCHAO';
                        }
                        if($v['pay_code']=='HANCHAO_XIANJIN'){
                            $list['HANCHAO_XIANJIN']['name']=$pay_type['HANCHAO_XIANJIN'];
                            $list['HANCHAO_XIANJIN']['num']=$v['num'];
                            $list['HANCHAO_XIANJIN']['goods_number']=floatval($v['goods_number']);
                            $list['HANCHAO_XIANJIN']['yuan_price']=format_decimal($v['yuan_price']);
                            $list['HANCHAO_XIANJIN']['goods_price']=format_decimal($v['goods_price']);
                            $list['HANCHAO_XIANJIN']['profit']=format_decimal($v['profit']);
                            $list_time[]='HANCHAO_XIANJIN';
                        }
                    }unset($k,$v);
                    $list_time=array_filter(array_unique($list_time));
                    $new_day=array_diff($pay_typek,$list_time);
                    foreach($new_day as $vt){
                        $list[$vt]['name']=$pay_type[$vt];
                        $list[$vt]['num']=0;
                        $list[$vt]['goods_number']=0;
                        $list[$vt]['yuan_price']=0;
                        $list[$vt]['goods_price']=0;
                        $list[$vt]['profit']=0;
                    }
                    if($all['num']==0){
                        $all['num']=$all['goods_number']=$all['yuan_price']=$all['goods_price']=$all['profit']=0;
                    }
                    break;
                default://按商品分类
                    $postdata['sou_value']=1;
                    $map_c=array();
                    $map_c['status']=1;
                    $map_c['pid']=0;
                    $carids = M('PurchaseCategory')->where($map_c)->field('id,name')->select();
                    $orderid=M('OrderInfo')->where($map_oi)->getField('id',true);
                    $list=$cat_ida=array();
                    if(empty($orderid)){
                        break;
                    }
                    $og_map['order_id']=array('in',$orderid);
                    $goods_oids=M('OrderGoods')->where($og_map)->field('goods_id,goods_number,attr_price*goods_number as yuan_price,goods_price*goods_number as goods_price,profit,order_id')->select();
                        foreach($carids as $k=>$v){
                            $g_map=array();
                            $list[$v['id']]['name']=$v['name'];
                            $list[$v['id']]['profit']=$list[$v['id']]['goods_price']=$list[$v['id']]['yuan_price']=$list[$v['id']]['goods_number']=$list[$v['id']]['num']=0;
                            $child_catid =get_children($v['id'], 1,5);
                            if($child_catid){
                                $child_catid[]=$v['id'];
                                $g_map['cat_id']=array('in',$child_catid);
                            }else{
                                $g_map['cat_id']=$v['id'];
                            }
                            $goods_ids = M('Goods')->where($g_map)->getField('id',true);
                            $cat_ida[$v['id']]=$goods_ids;
                        }unset($k,$v);
                    foreach($cat_ida as $k=>$v){
                        if($v){
                            $map_n=array();
                            $map_n['a.id']=array('in',$orderid);
                            $map_n['g.goods_id']=array('in',$v);
                            $list[$k]['num']=M('OrderInfo')->alias('a')->join('__ORDER_GOODS__ g ON g.order_id=a.id')->where($map_n)->count('a.id');
                            $goods_number=$yuan_price=$goods_price=$profit=0;
                            foreach($goods_oids as $kg=>$vg){
                                if($v && in_array($vg['goods_id'],$v)){
                                    $goods_number +=$vg['goods_number'];
                                    $yuan_price+=$vg['yuan_price'];
                                    $goods_price+=$vg['goods_price'];
                                    $profit+=$vg['profit'];
                                }
                            }
                            $list[$k]['goods_number']=floatval($goods_number);
                            $list[$k]['yuan_price']=format_decimal($yuan_price);
                            $list[$k]['goods_price']=format_decimal($goods_price);
                            $list[$k]['profit']=format_decimal($profit);
                        }
                        $all['num']+=$list[$k]['num'];
                        $all['goods_number']+=$list[$k]['goods_number'];
                        $all['yuan_price']+=$list[$k]['yuan_price'];
                        $all['goods_price']+=$list[$k]['goods_price'];
                        $all['profit']+=$list[$k]['profit'];
                    }
                    break;
            }
            F('shoplist'.$postdata['sou_value'].','.$postdata['shopid'].','.$postdata['dates'].','.$postdata['reg_from'].','.$postdata['reg_to'],$list);
            F('shopall'.$postdata['sou_value'].','.$postdata['shopid'].','.$postdata['dates'].','.$postdata['reg_from'].','.$postdata['reg_to'],$all);
        }
        if($is_return){
            $return['list']=$list;
            $return['info']=$all;
            $return['title'] = array($sou_title[$postdata['sou_value']],'销售单数','商品数量','商品原价','实收金额','利润');
            return $return;
        }else{
            $this->assign($all);
            $this->assign($postdata);
            $this->assign('list',$list);
            $this->display();
        }
    }
 //    获取本门店收银员列表
    public function cashier_list(){
        $map=$cashier_list=array();
        $map['role_id']=1;
        $sa__id=M('ShopsRoleAccount')->where($map)->getField('account_id',true);
        $mapg['status']=1;
        $mapg['is_delete']=0;
        $mapg['shop_id']=MID;
        if($sa__id){
            $mapg['id']=array('in',$sa__id);
            $cashier_list_arr=M('ShopsAccount')->where($mapg)->field('id,name')->select();
            foreach($cashier_list_arr as $k=>$v) {
                $cashier_list[$v['id']] = $v['name'];
            }
        }
        return $cashier_list;
    }
    /**
    * 销售占比分析导出
    *
    */
    public function sale_analiysis_export(){
        $rest=$this->sale_analiysis(true);
        $data=array();
        $data=$rest['list'];
        $data[]=array('总计',$rest['info']['num'],$rest['info']['goods_number'],$rest['info']['yuan_price'],$rest['info']['goods_price'],$rest['info']['profit']);
        export_csv('销售占比分析.csv',$rest['title'],$data);
        exit;
    }
// 销售占比结束
// 礼品卡销售
    public function gift_index($is_return=false){
        $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.');
        $postdata['shopid']=MID;
        $map_oi['order_id']=array('gt','0');
        if($postdata['shopid'])$map_oi['shop_id']= $postdata['shopid'];
        $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['sell_time'][] = array('egt',$date_from);}
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){$date_to = $date_to+86399;$map_oi['sell_time'][] = 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['sell_time']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        $field="count(id) as num,sum(card_money) as card_money,sum(shop_price) as shop_price,shop_id,sell_time";
        switch($postdata['sou_value']){
            case 2://按小时
                for($i=0;$i<24;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $list_t=M('GiftCard')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(sell_time),'%k')")->field($field)->select();
                $orderinfo=M('GiftCard')->where($map_oi)->field($field)->find();
                $list_time=array();
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('G',$v['sell_time'])]['sell_time']=date('G',$v['sell_time']).'点';
                        $list[date('G',$v['sell_time'])]['num']=$v['num'];
                        $list[date('G',$v['sell_time'])]['shop_price']=$v['shop_price'];
                        $list[date('G',$v['sell_time'])]['card_money']=format_decimal($v['card_money']);
                        $list_time[]=date('G',$v['sell_time']);
                    }unset($k,$v);
                    $new_day=array_diff($day_arr,$list_time);
                    foreach($new_day as $vt){
                        $list[$vt]['sell_time']=$vt.'点';
                        $list[$vt]['card_money']=0.00;
                        $list[$vt]['shop_price']=0.00;
                        $list[$vt]['num']=0;
                    }
                    ksort($list);
                }
                break;
            case 3://按日
                for($i=1;$i<32;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $list_t=M('GiftCard')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(sell_time),'%e')")->field($field)->select();
                $orderinfo=M('GiftCard')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('j',$v['sell_time'])]['sell_time']=date('j',$v['sell_time']).'日';
                        $list[date('j',$v['sell_time'])]['num']=$v['num'];
                        $list[date('j',$v['sell_time'])]['shop_price']=$v['shop_price'];
                        $list[date('j',$v['sell_time'])]['card_money']=format_decimal($v['card_money']);
                        $list_time[]=date('j',$v['sell_time']);
                    }unset($k,$v);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['sell_time']=$vt.'日';
                    $list[$vt]['card_money']=0.00;
                    $list[$vt]['shop_price']=0.00;
                    $list[$vt]['num']=0;
                }
                ksort($list);
                break;
            case 4://月
                for($i=1;$i<13;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $list_t=M('GiftCard')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(sell_time),'%c')")->field($field)->select();
                $orderinfo=M('GiftCard')->where($map_oi)->field($field)->find();
                $orderinfo['avg_price']=0;
                if($list_t){
                    foreach ($list_t as $k => $v) {
                        $list[date('n',$v['sell_time'])]['sell_time']=date('n',$v['sell_time']).'月';
                        $list[date('n',$v['sell_time'])]['num']=$v['num'];
                        $list[date('n',$v['sell_time'])]['shop_price']=$v['shop_price'];
                        $list[date('n',$v['sell_time'])]['card_money']=format_decimal($v['card_money']);
                        $list_time[]=date('n',$v['sell_time']);
                    }unset($k,$v);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['sell_time']=$vt.'月';
                    $list[$vt]['num']=0;
                    $list[$vt]['shop_price']=0.00;
                    $list[$vt]['card_money']=0.00;
                }
                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;
                $list_s=M('GiftCard')->where($map_oi)->group("shop_id")->field($field)->select();
                $orderinfo=M('GiftCard')->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']]['shop_name']=$shoplist[$v['shop_id']];
                        $list[$v['shop_id']]['num']=$v['num'];
                        $list[$v['shop_id']]['shop_price']=format_decimal($v['shop_price']);
                        $list[$v['shop_id']]['card_money']=format_decimal($v['card_money']);
                        $list_time[]=$v['shop_id'];
                    }unset($k,$v);
                }else{
                    $list[MID]['shop_name']=$shoplist[MID];
                    $list[MID]['num']=0;
                    $list[MID]['shop_price']=0.00;
                    $list[MID]['card_money']=0.00;
                }
                // $new_day=array_diff($shop_ids,$list_time);
                // foreach($new_day as $vt){
                //     // $list[$vt]['shop_name']=$shop_list[$vt];
                //     $list[$vt]['num']=0;
                //     $list[$vt]['shop_price']=0.00;
                //     $list[$vt]['card_money']=0.00;
                // }
                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 gift_index_export(){
        $rest=$this->gift_index(true);
        $data=array();
        $data=$rest['list'];
        $data[]=array('总计',$rest['info']['num'],$rest['info']['shop_price'],$rest['info']['card_money']);
        export_csv('礼品卡销售统计.csv',$rest['title'],$data);
        exit;
    }
// 礼品卡结束
    //    获取自己店导购员列表
    public function guider_list(){
        $map=$guider_list=array();
        $map['role_id']=2;
        $guider_id=M('ShopsRoleAccount')->where($map)->getField('account_id',true);
        $mapg['status']=1;
        $mapg['is_delete']=0;
        if($guider_id){
            $mapg['id']=array('in',$guider_id);
            $mapg['shop_id']=MID;
            $guider_list_arr=M('ShopsAccount')->where($mapg)->field('id,name')->select();
            foreach($guider_list_arr as $k=>$v) {
                $guider_list[$v['id']] = $v['name'];
            }
        }
        return $guider_list;
    }
// 导购员绩效开始
 public function guider_index($is_return=false){
        $mapg=$guiderlist=$map=$map_oi=$list=$list_new=array();
        $guider_list=$this->guider_list();
        if($guider_list){
            $postdata=I('param.');
            $guiderlist=$guider_list;
            $map_oi['pay_status']=3;
            $map_oi['is_delete']=0;
            $map_oi['status']=3;
            if($postdata['sale_id']){
                $mapg=array();
                $mapg['id']=$map_oi['guide']= $postdata['sale_id'];
                $guiderlist=M('ShopsAccount')->where($mapg)->getField('id,name');//搜索导购员只显示搜索的的导购员
            }else{
                // $map_oi['guide']=array('gt',0);
                $map_oi['guide']=array('in',array_keys($guider_list));
            }
            $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['confirm_time'][] = array('egt',$date_from);}
                $date_to = strtotime($postdata['reg_to']);
                if($date_to){$date_to = $date_to+86399;$map_oi['confirm_time'][] = 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['confirm_time']=array('between',array($between[0],$between[1]));
                }else{
                    $postdata['dates']=99;
                }
            }
            $sales_maid=M('OrderInfo')->where($map_oi)->group("guide")->field('sum(sales_maid) as sales_maid,guide')->select();
            $totalsales_maid=M('OrderInfo')->where($map_oi)->sum('sales_maid');
            $goods=$chongzhi=$giftcard=array();
            $map_oi['type']=array('in','1,6,11,12,13,14');
            $field="count(id) as num,sum(goods_allmoney) as goods_allmoney,guide,sum(profit) as profit,sum(order_money) as order_money,sum(sales_maid) as sales_maid";
            $goods=M('OrderInfo')->where($map_oi)->group("guide")->field($field)->select();//销售提成
            $all_goods=M('OrderInfo')->where($map_oi)->field($field)->find();
            unset($map_oi['type']);
            $map_oi['type']=array('in','2,5');
            $chongzhi=M('OrderInfo')->where($map_oi)->group("guide")->field('count(id) as cnum,sum(order_amount) as order_amount,sum(sales_maid) as sales_maid,guide')->select();//充值提成
            $all_chongzhi=M('OrderInfo')->where($map_oi)->field('count(id) as cnum,sum(order_amount) as order_amount,sum(sales_maid) as sales_maid')->find();
            unset($map_oi['type']);
            $map_oi['type']=15;
            $giftcard=M('OrderInfo')->where($map_oi)->group("guide")->field('count(id) as fnum,sum(order_amount) as order_amount,sum(sales_maid) as sales_maid,guide')->select();//礼品卡提成
            $all_gift=M('OrderInfo')->where($map_oi)->field('count(id) as fnum,sum(order_amount) as order_amount,sum(sales_maid) as sales_maid')->find();
            foreach($guiderlist as $k=>$v){
                $list[$k]['name']=$v;
                if($goods){
                    foreach($goods as $kg=>$vg){
                        if($k==$vg['guide']){
                            $list[$k]['num']=$vg['num'];
                            $list[$k]['goods_allmoney']=format_decimal($vg['goods_allmoney']);
                            $list[$k]['order_money']=format_decimal($vg['order_money']);
                            $list[$k]['profit']=format_decimal($vg['profit']);
                            $list[$k]['sales_maid']=format_decimal($vg['sales_maid']);
                        }
                    }
                }
                if($chongzhi){
                    foreach($chongzhi as $kc=>$vc){
                        if($k==$vc['guide']){
                            $list[$k]['cnum']=$vc['cnum'];
                            $list[$k]['cmoney']=format_decimal($vc['order_amount']);
                            $list[$k]['csales_maid']=format_decimal($vc['sales_maid']);
                        }
                    }
                }
                if($giftcard){
                    foreach($giftcard as $kf=>$vf){
                        if($k==$vf['guide']){
                            $list[$k]['fnum']=$vf['fnum'];
                            $list[$k]['fmoney']=format_decimal($vf['order_amount']);
                            $list[$k]['fsales_maid']=format_decimal($vf['sales_maid']);
                        }
                    }
                }
                if($sales_maid){
                    foreach($sales_maid as $ka=>$va){
                        if($k==$va['guide']){
                            $list[$k]['asales_maid']=format_decimal($va['sales_maid']);
                        }
                    }
                }
            }
            $i=0;//为导出的excel做处理
            foreach($list as $kl=>$vl){
                $list_new[$i]['name']=$vl['name'];
                if(empty($vl['num'])){
                    $list_new[$i]['num']=0;
                }else{
                    $list_new[$i]['num']=$vl['num'];
                }
                if(empty($vl['goods_allmoney'])){
                    $list_new[$i]['goods_allmoney']=0;
                }else{
                    $list_new[$i]['goods_allmoney']=$vl['goods_allmoney'];
                }
                if(empty($vl['order_money'])){
                    $list_new[$i]['order_money']=0;
                }else{
                    $list_new[$i]['order_money']=$vl['order_money'];
                }
                if(empty($vl['profit'])){
                    $list_new[$i]['profit']=0;
                }else{
                    $list_new[$i]['profit']=$vl['profit'];
                }
                if(empty($vl['sales_maid'])){
                    $list_new[$i]['sales_maid']=0;
                }else{
                    $list_new[$i]['sales_maid']=$vl['sales_maid'];
                }
                if(empty($vl['cnum'])){
                    $list_new[$i]['cnum']=0;
                }else{
                    $list_new[$i]['cnum']=$vl['cnum'];
                }
                if(empty($vl['cmoney'])){
                    $list_new[$i]['cmoney']=0;
                }else{
                    $list_new[$i]['cmoney']=$vl['cmoney'];
                }
                if(empty($vl['csales_maid'])){
                    $list_new[$i]['csales_maid']=0;
                }else{
                    $list_new[$i]['csales_maid']=$vl['csales_maid'];
                }
                if(empty($vl['fnum'])){
                    $list_new[$i]['fnum']=0;
                }else{
                    $list_new[$i]['fnum']=$vl['fnum'];
                }
                if(empty($vl['fmoney'])){
                    $list_new[$i]['fmoney']=0;
                }else{
                    $list_new[$i]['fmoney']=$vl['fmoney'];
                }
                if(empty($vl['fsales_maid'])){
                    $list_new[$i]['fsales_maid']=0;
                }else{
                    $list_new[$i]['fsales_maid']=$vl['fsales_maid'];
                }
                if(empty($vl['asales_maid'])){
                    $list_new[$i]['asales_maid']=0;
                }else{
                    $list_new[$i]['asales_maid']=$vl['asales_maid'];
                }
                $i++;
            }
            //总计
            $total=array();
            $total['z']='总计';
            $total['allnum']=floatval($all_goods['num'])?$all_goods['num']:0;
            $total['allmoney']=floatval($all_goods['goods_allmoney'])?format_decimal($all_goods['goods_allmoney']):0.00;
            $total['shi_money']=floatval($all_goods['order_money'])?format_decimal($all_goods['order_money']):0.00;
            $total['allprofit']=floatval($all_goods['profit'])?format_decimal($all_goods['profit']):0.00;
            $total['allgsales_maid']=floatval($all_goods['sales_maid'])?format_decimal($all_goods['sales_maid']):0.00;
            $total['allcnum']=intval($all_chongzhi['cnum'])?intval($all_chongzhi['cnum']):0;
            $total['allcmoney']=floatval($all_chongzhi['order_amount'])?format_decimal($all_chongzhi['order_amount']):0.00;
            $total['allcsales_maid']=floatval($all_chongzhi['sales_maid'])?format_decimal($all_chongzhi['sales_maid']):0.00;
            $total['allfnum']=intval($all_gift['fnum'])?intval($all_gift['fnum']):0;
            $total['allfmoney']=floatval($all_gift['order_amount'])?format_decimal($all_gift['order_amount']):0.00;
            $total['allfsales_maid']=floatval($all_gift['sales_maid'])?format_decimal($all_gift['sales_maid']):0.00;
            $total['allsales_maid']=$totalsales_maid;
        }
        if($is_return==false){
            $this->assign('sales_list',$guider_list);
            $this->assign($postdata);
            $this->assign('list',$list_new);
            $this->assign($total);
            $this->display();
        }else{
            $return=array('data'=>$list_new,'total'=>$total);
            return $return;
        }
    }
    /**
    * 导购员绩效导出
    *
    */
    public function guider_index_export(){
        $rest=$this->guider_index(true);
        $data=array();
        $data=$rest['data'];
        $data[]=$rest['total'];
        $title = array('导购员', '订单量', '商品总金额','实收','利润','提成金额','充值总数','充值金额','充值提成金额','礼品卡总数','礼品卡金额','礼品卡提成金额','提成总金额');
        export_csv('导购员绩效.csv',$title,$data);
        exit;
    }
// 导购员绩效结束
    //沉睡会员
    public function dead_sleep($is_return=false){
        $sou_type=strtoarray(array('1'=>'日','2'=>'月','3'=>'年'));
        $this->assign('sou_type',$sou_type);
        $map=array();
        $postdata=I('param.');
        if($postdata['day'] && $postdata['sou_value']){
            if(intval($postdata['day'])<=0){
              $this->error('请输入大于0的整数');exit;
            }
            $start_time=strtotime(date('Y-m-d',NOW_TIME));
            if($postdata['sou_value']==1){
              $date_from=$start_time-$postdata['day']*86400;
              $date_to =$start_time+86399;
              $map['oi.addtime']=array('between',array($date_from,$date_to));
            }
            if($postdata['sou_value']==2){
              $date_from=$start_time-$postdata['day']*86400*30;
              $date_to =$start_time+86399;
              $map['oi.addtime']=array('between',array($date_from,$date_to));
            }
            if($postdata['sou_value']==3){
              $date_from=$start_time-$postdata['day']*86400*365;
              $date_to =$start_time+86399;
              $map['oi.addtime']=array('between',array($date_from,$date_to));
            }
        }
            // 1120 start
                $shop_id=MID;$only_map=[];
                 $is_share_user=idtoname($shop_id,'Shops','is_share_user');
                if(empty($is_share_user)){//不共享会员
                    $c_map=$customer=array();
                    $c_map['shop_id'] = $shop_id;
                    $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                    if(empty($customer)){//无顾客
                        $only_map['user_shop']=$map['a.user_shop']=$shop_id;
                    }else{
                        $where=$where_only=array();
                        $where['a.user_shop']=$shop_id;
                        $where['a.id']  = array('in',$customer);
                        $where['_logic'] = 'or';
                        $map['_complex'] = $where;
                        $where_only['user_shop']=$shop_id;
                        $where_only['id']  = array('in',$customer);
                        $where_only['_logic'] = 'or';
                        $only_map['_complex']=$where_only;
                    }
                }else{//共享会员
                    $smap=array();$cachetime=60*60*24*7;
                    $smap['is_share_user']=0;                
                    $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                    if(!empty($noshareshopids)){
                        $only_map['user_shop']=$map['a.user_shop'] = array('notin',$noshareshopids);
                    }
                }
                // $map['user_shop']=MID;
            //1120 end
        $map['oi.type']=$map_oi['type']=array('in','1,6,11,13,14');
        $map['oi.pay_status']=$map_oi['pay_status']=3;
        $map['oi.is_delete']=$map_oi['is_delete']=0;
        $map['oi.status']=$map_oi['status']=array('in','1,2,3,6,8');
        $list=M('Member')->alias('a')->where($map)->join('__ORDER_INFO__ oi ON a.id=oi.uid')->group('oi.uid')->field('a.id')->select();
        $ids=array_map('array_shift', $list);
        $map=array();
        $map=$only_map;
        if($ids){
        $map['id']=array('not in',$ids);
        }else{
        $map['id']=0;
        }
        $map['status']=1;
        $map['is_tmp']=0;
        $field='id,card_sn,mobile,rank_id,usepoints,money';
        $uids=page_list('Member',$map,'','',20);
        foreach($uids['list'] as $k=>$v){
          $map_oi['uid']=$v['id'];
          $orderinfo=M('OrderInfo')->where($map_oi)->order('addtime desc')->field('addtime,order_amount,shop_id,in_online')->find();
          if($orderinfo){
              $uids['list'][$k]['addtime']=time_format($orderinfo['addtime']);
              $uids['list'][$k]['order_amount']=$orderinfo['order_amount'];
              $uids['list'][$k]['shopname']=idtoname($orderinfo['shop_id'],'Shops');
              $uids['list'][$k]['in_online']=$orderinfo['in_online']==1?'线下':'线上';
          }else{
              $uids['list'][$k]['addtime']='没有购买记录';
              $uids['list'][$k]['in_online']='';
          }
        }unset($k,$v);
        $list_e=M('Member')->where($map)->field($field)->select();
            $ys=idtoname(MID,'Shops','is_hide_phone');
        if($is_return){
          $return=$list_new=array();
          if($list_e){
              $i=0;
              foreach($list_e as $k=>$v){
                $i++;
                $list_new[$i]['n']=$i;
                $list_new[$i]['card_sn']=$v['card_sn'];
                $username=show_user_name($v['id']);
                if(strlen($username)==11 && $ys){
                    $list_new[$i]['name']=str_cutmobile($username);
                }else{
                    $list_new[$i]['name']=$username;
                }
                if($ys){$list_new[$i]['mobile']=str_cutmobile($v['mobile']);}else{
                    $list_new[$i]['mobile']=$v['mobile'];
                }
                $list_new[$i]['rank_name']=idtoname($v['rank_id'],'MemberRank');
                $list_new[$i]['usepoints']=$v['usepoints'];
                $list_new[$i]['money']=$v['money'];
                $map_oi['uid']=$v['id'];
                $orderinfo=M('OrderInfo')->where($map_oi)->order('addtime desc')->field('addtime,order_amount,shop_id,in_online')->find();
                if($orderinfo){
                    $list_new[$i]['addtime']=time_format($orderinfo['addtime']);
                    $list_new[$i]['order_amount']=$orderinfo['order_amount'];
                    $list_new[$i]['shopname']=idtoname($orderinfo['shop_id'],'Shops');
                    $list_new[$i]['in_online']=$orderinfo['in_online']==1?'线下':'线上';
                }else{
                    $list_new[$i]['addtime']='没有购买记录';
                    $list_new[$i]['order_amount']='';
                    $list_new[$i]['shopname']='';
                    $list_new[$i]['in_online']='';
                }
              }
          }
          $return['list']=$list_new;
          return $return;
        }else{
          $this->assign($postdata);
          foreach($uids['list'] as $k=>$v){
           $username=show_user_name($v['id']);
            if($ys){
              if(strlen($username)==11){$uids['list'][$k]['username']=str_cutmobile($username); }
              else{$uids['list'][$k]['username']=$username;} 
                $uids['list'][$k]['mobile']=str_cutmobile($uids['list'][$k]['mobile']);
            }else{
                $uids['list'][$k]['username']=$username;
            }
          }
          $this->assign($uids);
          $this->display();
        }
    }
    public function sleep_explode(){
        $rest=$this->dead_sleep(true);
        $data=array();
        $data=$rest['list'];
        $title=array('序号','会员卡号','会员姓名','手机号','会员等级','积分','余额','上次消费时间','消费金额','消费门店','消费类型');
        export_csv('沉睡会员.csv',$title,$data);
        exit;
    }
    // 会员FRM
    public function member_frm($is_return=false){//会员FRM
        $shop_list=D('Admin/Shops')->shop_list();
        $this->assign('shop_list',$shop_list);
        $list=$map=$map_oi=array();
        $postdata=I('param.');
        // 共享会员问题
            $shop_id=MID;
            $is_share_user=idtoname($shop_id,'Shops','is_share_user');
            if(empty($is_share_user)){//不共享会员
                $c_map=$customer=array();
                $c_map['shop_id'] = $shop_id;
                $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                if(empty($customer)){//无顾客
                    $map['a.user_shop']=$shop_id;
                }else{
                    $where=$where_only=array();
                    $where['a.user_shop']=$shop_id;
                    $where['a.id']  = array('in',$customer);
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                }
            }else{//共享会员
                $smap=array();$cachetime=60*60*24*7;
                $smap['is_share_user']=0;                
                $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                if(!empty($noshareshopids)){
                    $map['a.user_shop'] = array('notin',$noshareshopids);
                }
            }
        // if($postdata['shopid'])$map['a.user_shop']= $postdata['shopid'];
        // end
        $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);$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);$map_oi['addtime'][] = array('lt',$date_to);}
          $postdata['dates']=0;
        }else{
          if(in_array($postdata['dates'],array(7,14,30,60))){
              $between=$this->quick_time($postdata['dates']);
              $map['oi.addtime']=$map_oi['addtime']=array('between',array($between[0],$between[1]));
          }else{
              $postdata['dates']=99;
          }
        }
        $having='';
        if($postdata['num_from'] || $postdata['num_to']){
          if(is_numeric($postdata['num_from']) && $postdata['num_from']>0){
              $having.= 'count(oi.id) >= '.$postdata['num_from'].' and ';
          }else{
              $this->error('消费次数不为空且必须为正数');exit;
          }
          if(is_numeric($postdata['num_to']) && $postdata['num_to']>0){
              $having.= 'count(oi.id) <= '.$postdata['num_to'];
          }else{
              $this->error('消费次数不为空且必须为正数');exit;
          }
          if($postdata['num_from']>$postdata['num_to']){
              $this->error('消费次数输入范围异常');exit;
          }
          $postdata['nums']=0;
        }else{
          switch($postdata['nums']){
              case 3:
            $having.='2 < count(oi.id) and count(oi.id) <6';
            break;
              case 6:
            $having.='5 < count(oi.id) and count(oi.id) <11';
            break;
              case 11:
            $having.='11 < count(oi.id) and count(oi.id) <21';
            break;
              default:
            $postdata['nums']=99;
            break;
          }
        }
        if($postdata['price_from'] || $postdata['price_to']){
            if(is_numeric($postdata['price_from']) && $postdata['price_from']>0){
              if(strlen($having) > 0){
                $having.= ' and ';
              }
              $having.= 'sum(oi.order_amount)/count(oi.id) >= '.$postdata['price_from'].' and ';
            }else{
              $this->error('订单均价必须为正数');exit;
            }
            if($postdata['price_to']){
              $having.= 'sum(oi.order_amount)/count(oi.id) <= '.$postdata['price_to'];
            }else{
              $this->error('订单均价必须为正数');exit;
            }
            if($postdata['price_from']>$postdata['price_to']){
              $this->error('订单均价输入范围异常');exit;
            }
            $postdata['price']=0;
        }else{
            switch($postdata['price']){
              case 3:
            if(strlen($having) > 0){
                $having.= ' and ';
            }
            $having.='3 <= (sum(oi.order_amount)/count(oi.id)) and (sum(oi.order_amount)/count(oi.id)) <=15';
              break;
              case 16:
            if(strlen($having) > 0){
                $having.= ' and ';
            }
            $having.='16 <= (sum(oi.order_amount)/count(oi.id)) and (sum(oi.order_amount)/count(oi.id)) <=25';
            break;
              case 26:
            if(strlen($having) > 0){
                $having.= ' and ';
            }
            $having.='26 <= (sum(oi.order_amount)/count(oi.id)) and (sum(oi.order_amount)/count(oi.id)) <=45';
            break;
              default:
            $postdata['price']=99;
            break;
            }
        }
        $map['oi.type']=$map_oi['type']=array('in','1,6,11,13,14');
        $map['oi.pay_status']=$map_oi['pay_status']=3;
        $map['oi.is_delete']=$map_oi['is_delete']=0;
        $map['oi.status']=$map_oi['status']=array('in','1,2,3,6,8');
        $map['oi.shop_id']=$map_oi['shop_id']=MID;//1121
        $field='a.id,a.card_sn,a.mobile,a.rank_id,a.usepoints,a.money,sum(oi.order_amount) as order_amount,sum(oi.order_amount)/count(oi.id) as avg_money,count(oi.id) as num';
        $list_e='';// 只有returned时用 查所有指定会员在商店下的单
        if($is_return){
            $list_e=M('Member')->alias('a')->where($map)->join('__ORDER_INFO__ oi ON a.id=oi.uid')->group('oi.uid')->field($field)->having($having)->select();
        }
        $join='JOIN __ORDER_INFO__ oi ON a.id=oi.uid';
        $map['group']='oi.uid';
          $ys=idtoname(MID,'Shops','is_hide_phone');
        $list=$this->page_lists('Member',$map,'',$field,20,$join,1,$having);
        foreach($list['list'] as $k=>$v){
            $map_oi['uid']=$v['id'];
            $addtime=M('OrderInfo')->where($map_oi)->order('addtime desc')->field('addtime')->find();
            $list['list'][$k]['addtime']=$addtime['addtime'];
            $list['list'][$k]['day']=intval((NOW_TIME-$addtime['addtime'])/24/3600);
            $username=show_user_name($v['id']);
             if($ys){
                  if(strlen($username)==11){ $list['list'][$k]['username']=str_cutmobile($username); }
                  else{$list['list'][$k]['username']=$username;} 
                  $list['list'][$k]['mobile']=str_cutmobile($v['mobile']);
            }else{
                $list['list'][$k]['username']=$username;
            }
        }unset($k,$v);
        if($is_return){
            $list_new=array();
            if($list_e){
                $i=0;
                foreach($list_e as $k=>$v){
                    $i++;
                    $list_new[$i]['n']=$i;
                    $list_new[$i]['card_sn']=$v['card_sn'];
                    $username=show_user_name($v['id']);
                     if($ys){
                        if(strlen($username)==11){$list_new[$i]['name']=str_cutmobile($username); }
                        else{$list_new[$i]['name']=$username;} 
                        $list_new[$i]['mobile']=str_cutmobile($v['mobile']);
                    }else{
                        $list_new[$i]['name']=$username;
                        $list_new[$i]['mobile']=$v['mobile'];
                    }
                    // $list_new[$i]['name']=show_user_name($v['id']);
                    // $list_new[$i]['mobile']=$v['mobile'];
                    $list_new[$i]['rank_name']=idtoname($v['rank_id'],'MemberRank');
                    $list_new[$i]['usepoints']=$v['usepoints'];
                    $list_new[$i]['money']=$v['money'];
                    $list_new[$i]['order_amount']=$v['order_amount'];
                    $list_new[$i]['avg_money']=format_decimal($v['avg_money']);
                    $list_new[$i]['num']=$v['num'];
                    $map_oi['uid']=$v['id'];
                    $addtime=M('OrderInfo')->where($map_oi)->order('addtime desc')->field('addtime')->find();
                    $list_new[$i]['addtime']=time_format($addtime['addtime']);
                    $list_new[$i]['day']=intval((NOW_TIME-$addtime['addtime'])/24/3600);
                }
            }
            $return['list']=$list_new;
            return $return;
        }else{
            $this->assign($postdata);
            $this->assign($list);
            $this->display();
        }
    }
    public function member_frm_export(){
        $rest=$this->member_frm(true);
        $data=array();
        $data=$rest['list'];
        $title=array('序号','会员卡号','会员姓名','会员等级','手机号','积分','余额','订单总价','订单均价','消费次数','最后消费日期','距今天日期(天)');
        export_csv('会员FRM分析.csv',$title,$data);
        exit;
    }
    private function page_lists($module,$map=array(),$order='',$field=true,$pagesize=0,$join='',$REQUEST=1,$having=''){
        if(empty($module))return false;if(empty($pagesize))$pagesize=C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        if($REQUEST>=1)$REQUEST = (array)I('request.');
        if(!isset($REQUEST['p'])&&isset($REQUEST['page']))$REQUEST['p']=$REQUEST['page'];
        if(intval($REQUEST['p'])<=0)$REQUEST['p']=1;
        $group = '';
        if(isset($map['group'])&&!empty($map['group'])){$group = $map['group'];unset($map['group']);}
        $model = M($module);
        $preve = (intval($REQUEST['p'])-1)*$pagesize;
        $limit = "$preve,$pagesize";
        if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
      $order = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }
        $return = array();
        if($group){
      $distinct='distinct '.$group;
      $return['count'] = $model->alias('a')->where($map)->join($join)->having($having)->count($distinct);
      if(is_array($return['count'])){
          $count_key=array_keys($return['count']);$return['count'] =$count_key[0];
      }
        }else{
      $return['count'] = $model->alias('a')->where($map)->join($join)->having($having)->count();
        }
        $Page = new \Common\Vendor\Page($return['count'],$pagesize,$REQUEST);
        $return['page'] = $Page->show();
        $return['firstRow'] = $Page->firstRow;
        $return['listRows'] = $Page->listRows;
        $return['totalPages'] = $Page->totalPages;
        $return['list'] = $model->alias('a')->where($map)->order('create_time')->join($join)->field($field)->group($group)->having($having)->order($order)->limit($limit)->select();
        return $return;
    }
    // 会员增长 会员共享，但下单统计自己的
     public function increase($is_return=false){
        $sou_type=strtoarray(array('1'=>'按门店','2'=>'按小时','3'=>'按日','4'=>'按月'));
        $this->assign('sou_type',$sou_type);
        $shop_list=D('Admin/Shops')->shop_list();
        $this->assign('shop_list',$shop_list);
        $postdata=I('param.');
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        $map=$map_oi=array();
        if($postdata['reg_from'] || $postdata['reg_to']){
            $date_from = strtotime($postdata['reg_from']);
            if($date_from){$map['reg_time'][]=array('egt',$date_from);$map_oi['addtime'][] = array('egt',$date_from);}
            $date_to = strtotime($postdata['reg_to']);
            if($date_to){$date_to = $date_to+86399;$map['reg_time'][]=array('egt',$date_from);$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['reg_time']=$map_oi['addtime']=array('between',array($between[0],$between[1]));
            }else{
              $postdata['dates']=99;
            }
        }
        // 共享会员问题
            $shop_id=MID;
            $is_share_user=idtoname($shop_id,'Shops','is_share_user');
            if(empty($is_share_user)){//不共享会员
                $c_map=$customer=array();
                $c_map['shop_id'] = $shop_id;
                $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
                if(empty($customer)){//无顾客
                    $map['user_shop']=$shop_id;
                }else{
                    $where=$where_only=array();
                    $where['user_shop']=$shop_id;
                    $where['id']  = array('in',$customer);
                    $where['_logic'] = 'or';
                    $map['_complex'] = $where;
                }
            }else{//共享会员
                $smap=array();$cachetime=60*60*24*7;
                $smap['is_share_user']=0;                
                $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
                if(!empty($noshareshopids)){
                    $map['user_shop'] = array('notin',$noshareshopids);
                }
            }
            //end
        $map['is_tmp']=0;
        $map['status']=1;
        $z_ids=M('Member')->where($map)->getField('count(id)');//会员数
        // unset($map_oi);  //1123+
        $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');
        $map_oi['shop_id']=MID;//自己店的订单
        $field='count(id) as num,reg_time';
        $all=$list=array();
        $all['m_numb']=$all['o_numb']=$all['precent']=0;
        switch($postdata['sou_value']){
            case 2://按小时
                for($i=0;$i<24;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $member=M('Member')->where($map)->field('id,reg_time')->select();//时间段内uid 注册时间
                if($member){
                    $uids=array();
                    foreach($member as $k=>$v){
                        $new_m[date('G',$v['reg_time'])][]= $v['id'];//分段人数集合
                        $uids[]=$v['id'];
                    }unset($k,$v);
                    $list_t=M('Member')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(reg_time),'%k')")->field($field)->select();  //分段段  人数
                    // echo M('Member')->getLastSql();
                    $new_list=$o_list=array();
                    foreach($list_t as $k=>$v){
                        $new_list[date('G',$v['reg_time'])]=$v['num'];
                    }unset($k,$v);
                    $list_time=array();
                    // var_dump($new_m);
                    foreach ($new_m as $k => $v) {
                        $list[$k]['reg_time']=$k.'点';
                        $list[$k]['m_num']=$new_list[$k];
                        $map_oi['uid']=array('in',$v);
                        // $num=M('OrderInfo')->where($map_oi)->group('uid')->field('uid,addtime')->select();//指定时间段内人下单数  
                        $num=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->having("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k') = $k")->field('uid,addtime')->select();
                        // echo M('OrderInfo')->getLastSql();
                        if(count($num)>0){
                            $list[$k]['o_num']=count($num);//获取新增会员下单的会员数
                        }else{
                            $list[$k]['o_num']=0;
                        }
                        $list[$k]['percent']=format_decimal($list[$k]['o_num']*100/$new_list[$k]).'%';
                        $m_num+=$new_list[$k];
                        $o_num+=$list[$k]['o_num'];
                        $list_time[]=$k;
                    }unset($k,$v);
                    $new_day=array_diff($day_arr,$list_time);
                    foreach($new_day as $vt){
                        $list[$vt]['reg_time']=$vt.'点';
                        $list[$vt]['m_num']=0;
                        $list[$vt]['o_num']=0;
                        $list[$vt]['percent']='0.00%';
                    }
                    ksort($list);
                    $all['m_numb']=$m_num;
                    $all['o_numb']=$o_num;
                    $all['precent']=format_decimal($all['o_numb']*100/$all['m_numb']).'%';
                  }
              break;
            case 3://按日
                for($i=1;$i<32;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $member=M('Member')->where($map)->field('id,reg_time')->select();
                if($member){
                    $uids=array();
                    foreach($member as $k=>$v){
                        $new_m[date('j',$v['reg_time'])][]= $v['id'];
                        $uids[]=$v['id'];
                    }unset($k,$v);
                    $list_t=M('Member')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(reg_time),'%e')")->field($field)->select();
                    $new_list=$o_list=array();
                    foreach($list_t as $k=>$v){
                        $new_list[date('j',$v['reg_time'])]=$v['num'];
                    }unset($k,$v);
                    $list_time=array();
                    foreach ($new_m as $k => $v) {
                        $list[$k]['reg_time']=$k.'日';
                        $list[$k]['m_num']=$new_list[$k];
                        $map_oi['uid']=array('in',$v);
                        $num=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%e')")->having("DATE_FORMAT(FROM_UNIXTIME(addtime),'%e') = $k")->field('uid,addtime')->select();
                        // $num=M('OrderInfo')->where($map_oi)->group('uid')->field('uid,addtime')->select();//指定时间段内人下单数
                        if(count($num)>0){
                            $list[$k]['o_num']=count($num);//获取新增会员下单的会员数
                        }else{
                            $list[$k]['o_num']=0;
                        }
                        $list[$k]['percent']=format_decimal($list[$k]['o_num']*100/$new_list[$k]).'%';
                        $list_time[]=$k;
                        $m_num+=$new_list[$k];
                        $o_num+=$list[$k]['o_num'];
                    }unset($k,$v);
                    $new_day=array_diff($day_arr,$list_time);
                    foreach($new_day as $vt){
                        $list[$vt]['reg_time']=$vt.'日';
                        $list[$vt]['m_num']=0;
                        $list[$vt]['o_num']=0;
                        $list[$vt]['percent']='0.00%';
                    }
                    ksort($list);
                    $all['m_numb']=$m_num;
                    $all['o_numb']=$o_num;
                    $all['precent']=format_decimal($all['o_numb']*100/$all['m_numb']).'%';
                }
            break;
            case 4://月
                for($i=1;$i<13;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $member=M('Member')->where($map)->field('id,reg_time')->select();
                if($member){
                $uids=array();
                foreach($member as $k=>$v){
                    $new_m[date('n',$v['reg_time'])][]= $v['id'];
                    $uids[]=$v['id'];
                }unset($k,$v);
                $list_t=M('Member')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(reg_time),'%c')")->field($field)->select();
                $new_list=$o_list=array();
                foreach($list_t as $k=>$v){
                    $new_list[date('n',$v['reg_time'])]=$v['num'];
                }unset($k,$v);
                $list_time=array();
                foreach ($new_m as $k => $v) {
                    $list[$k]['reg_time']=$k.'月';
                    $list[$k]['m_num']=$new_list[$k];
                    $map_oi['uid']=array('in',$v);
                    $num=M('OrderInfo')->where($map_oi)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%c')")->having("DATE_FORMAT(FROM_UNIXTIME(addtime),'%c') = $k")->field('uid,addtime')->select();
                    // $num=M('OrderInfo')->where($map_oi)->group('uid')->field('uid,addtime')->select();//指定时间段内人下单数
                    if(count($num)>0){
                        $list[$k]['o_num']=count($num);//获取新增会员下单的会员数
                    }else{
                        $list[$k]['o_num']=0;
                    }
                    $list[$k]['percent']=format_decimal($list[$k]['o_num']*100/$new_list[$k]).'%';
                    $list_time[]=$k;
                     $m_num+=$new_list[$k];
                    $o_num+=$list[$k]['o_num'];
                }unset($k,$v);
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['reg_time']=$vt.'月';
                    $list[$vt]['m_num']=0;
                    $list[$vt]['o_num']=0;
                    $list[$vt]['percent']='0.00%';
                }
                ksort($list);
                $all['m_numb']=$m_num;
                $all['o_numb']=$o_num;
                $all['precent']=format_decimal($all['o_numb']*100/$all['m_numb']).'%';
              }
              break;
          default://按店
              $postdata['sou_value']=1;
              // $shoplist=$shop_list;
              // $shop_ids=array_keys($shoplist);
              $shop_ids=MID;
              if($shop_ids){
                // $map['user_shop']=array('in',$shop_ids);
                // $new_m=$new_list=array();
                // $member=M('Member')->where($map)->field('id,user_shop')->select();
                // if($member){
                //     $uids=array();
                //     foreach($member as $k=>$v){
                //         $new_m[$v['user_shop']][]= $v['id'];
                //         $uids[]=$v['id'];
                //     }unset($k,$v);
                //     $list_s=M('Member')->where($map)->group("user_shop")->field('count(id) as num,id,user_shop')->select();
                //     foreach($list_s as $k=>$v){
                //         $new_list[$v['user_shop']]=$v['num'];
                //     }unset($k,$v);
                //     foreach ($new_m as $k => $v) {
                //         $list[$k]['shop_name']=$shop_list[$k];
                //         $list[$k]['m_num']=$new_list[$k];
                //         $map_oi['uid']=array('in',$v);
                //         $map_oi['shop_id']=$k;
                //         $num=M('OrderInfo')->where($map_oi)->group('uid')->field('count(id) as onum')->select();
                //         if(count($num)>0){
                //             $list[$k]['o_num']=count($num);//获取新增会员下单的会员数
                //         }else{
                //             $list[$k]['o_num']=0;
                //         }
                //         $list[$k]['percent']=format_decimal($list[$k]['o_num']*100/$new_list[$k]).'%';
                //         $list_time[]=$k;
                //     }unset($k,$v);
                //     unset($map_oi['uid']);unset($map_oi['shop_id']);
                //     $map_oi['uid']=array('in',$uids);$map_oi['shop_id']=array('in',$shop_ids);
                //     $all['m_numb']=count($uids);
                //     $all['o_numb']=count(M('OrderInfo')->where($map_oi)->group('uid')->field('count(id) as onum')->select());
                //     $all['precent']=format_decimal($all['o_numb']*100/$all['m_numb']).'%';
                // }
                // $new_day=array_diff($shop_ids,$list_time);
                // foreach($new_day as $vt){
                //     $list[$vt]['shop_name']=$shop_list[$vt];
                //     $list[$vt]['m_num']=0;
                //     $list[$vt]['o_num']=0;
                //     $list[$vt]['percent']='0.00%';
                // }
                // 1123新改
                // 会员数
                    $c_map=[];
                    if($z_ids){
                        // $c_map['id']=array('in',$z_ids);where(c_map)
                        $x_ids=M('Member')->where($map)->group('id')->getField("id",true);//新增加的会员id
                        $count=count($x_ids);//会员数
                        $map_oi['uid']=array('in',$x_ids);//限定是新增会员下单
                        // 获取下单的新增会员
                        $order_num=M('OrderInfo')->where($map_oi)->group('uid')->getField('count(id)',true);
                        $m_num=$o_num=0;
                        foreach ($order_num as $k => $val) {
                            $m_num++;
                            // $o_num+=$val;
                        }
                        $list[0]['shop_name']=$shop_list[MID];
                        $all['m_numb']=$list[0]['m_num']=$count;
                        $all['o_numb']=$list[0]['o_num']=$m_num;
                        $all['precent']=$list[0]['percent']=format_decimal($m_num*100/$count).'%';
                    }else{
                        $list[0]['shop_name']=$shop_list[MID];
                        $all['m_numb']=$list[0]['m_num']=0;
                        $all['o_numb']=$list[0]['o_num']=0;
                        $all['precent']=$list[0]['percent']='0%';
                    }
                   $this->assign($zj);
              }
              break;
            }
        if($is_return){
            $return['list']=$list;
            $return['info']=$all;
            if($postdata['sou_value']==1){
                $return['title'] = array('门店','新增会员数','下单人数','会员转化率');
            }else{
                $return['title'] = array('时间','新增会员数','下单人数','会员转化率');
            }
        return $return;
        }else{
          $this->assign($postdata);
          $this->assign($all);
          $this->assign('list',$list);
          $this->display();
        }
    }
    public function increase_explode(){
        $rest=$this->increase(true);
        $data=array();
        $data=$rest['list'];
        $data[]=array('总计',$rest['info']['m_numb'],$rest['info']['o_numb'],$rest['info']['precent']);
        export_csv('会员增长率.csv',$rest['title'],$data);
        exit;
    }
}