<?php
/**
* 商品统计
* @Copyright (C) 2016 汉潮 All rights reserved.
* @License http://www.hanchao9999.com
* @Author xiaogg <xiaogg@sina.cn>
*/

namespace Admin\Controller;
class GoodsOrderController extends BaseController{
/**
* 商品销售统计
*/
    public function index($is_return=false){
        $postdata=I('param.');
        // $sale_type = array('1'=>'线下','2'=>'线上');
        $sale_type = array('2'=>'线上');
        $adminid=UID;
        $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);
        }
        $shop_list=D('Shops')->shop_list();
        $this->assign('shop_list',$shop_list);
        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=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;
        }
        //118 begin
        else{
        	$map['in_online']=0;
        }
        //118
        $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);
	  }
	  $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")->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';
	  $lists=M('OrderGoods')->where($map)->field($field)->group('goods_id')->order($order)->select();
	  $map['group'] = 'goods_id';
//	  $map['group'] = 'goods_sn';
	  $list = page_list('OrderGoods',$map,$order,$field,20);
	  $list_goods=array();
	  foreach($list['list'] as $k=>$v){
	      $list_goods[$v['goods_id']]=$v;
	  }unset($k,$v);
        }
        $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;
	  if($ret_goodids){
	      $rg_map['org_id']=array('in',$ret_goodids);
	  }else{
	      $rg_map['org_id']=$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['goodsprice']/$value['num']);
	      $list_e[$key]['profit_p']=format_decimal($value['profits']*100/$value['supplierprice']).'%';
	      if($list_goods[$value['goods_id']]){
		$list_goods[$value['goods_id']]['tui_num']=$tui_num;
		$list_goods[$value['goods_id']]['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['avgprice']=format_decimal($all['all_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);
	  unset($list['list']);
	  $this->assign($list);
	  $this->assign('list',$list_goods);
	  $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);
	}
    }
    /**
    * 单品销售统计
    */	
    public function single_goods($newmap,$day_arr,$date_from,$date_to){
    	$map=array();
        $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")->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,goods_price';
        $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,goods_price")->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_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['shop_id']]['tui_num']);
	      $tui_money=floatval($returngoods[$value['shop_id']]['tui_money']);
	      // $list_e[$key]['avg_price']=format_decimal($value['goodsprice']/$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['avgprice']=format_decimal($all['all_price']/$all['goodsallnum']);
	  $data['profit_a']=format_decimal($all['all_profit']*100/$all['all_sprice']).'%';
        }
        $this->assign($data);
        $this->assign('list',$list);
    }
    public function single_tu(){
        /*获取时间数组开始*/
        $type = I('type');
        $postdata = I('param.');
        if(!$postdata['goods_id']){
        	$this->error('数据错误');exit;
        }
        //导购员列表
        $sales_list=D('Shops')->guider_list();
        //仓库列表
        $shops_list=D('Shops')->shop_list();
        //收银员列表
        $cashier_list_arr=D('Shops')->cashier_list();

        $this->assign('sales_list', $sales_list);
        $this->assign('shops_list',$shops_list);
        $this->assign('cashier_list',$cashier_list_arr);
        $postdata=I('param.');
        $this->assign('goods_name',idtoname($postdata['goods_id'],'Goods','goods_name','id',false));
        $day_arr = $map_z = 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);
        		$map_z[] = $date_from;
        	}else{
        		$this->error("请选择搜索开始时间");exit;
        	}
	  $date_to = strtotime($postdata['date_to']);
	  if($date_to){
	      $map['oi.addtime'][] = 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=quick_time($type);
	  }
	  if(in_array($type,array(7,30))){
	      $between=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);
        /*单品销售时段统计*/
        unset($new_map['oi.addtime']);
        if($map_z){
        	$new_map['oi.addtime']=array('between',array($map_z[0],$map_z[1]));
        }
        $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);
        $this->display();
    }
    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("sum(a.goods_number) as number,sum(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['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("sum(a.goods_number) as 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['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',''));
        }

    }
    /**
    * 得到节点树
    */
    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 export_su(){
        $list=$this->index(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']=$v['num'];
	  $data[$i]['tui_num']=floatval($v['tui_num']);
	  $data[$i]['tui_money']=format_decimal($v['tui_money']);
	  $data[$i]['shi_price']=floatval($data[$i]['goodsprice']-$data[$i]['tui_money']);
	  $data[$i]['avg_price']=format_decimal($v['avg_price']);
	  $data[$i]['profits']=format_decimal($v['profits']);
	  $data[$i]['profit_p']=format_decimal($v['profit_a']);
        }
        $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_tuimoney']),format_decimal($list['data']['all_price']-$list['data']['all_tuimoney']),$list['data']['avgprice'],format_decimal($list['data']['all_profit']),format_decimal($list['data']['profit_a']));
        $title = array('序号', '商品编号', '商品名称','销售额','成本金额','销量','退货数量','退货金额','实际销售金额','平均售价','利润','利润率');
        export_csv('商品销售统计.csv',$title,$data);
        exit;
    }
}