<?php
namespace Smi\Controller;
use Think\Controller;
class SupportController extends BaseController 
{
  /**
   * [sales_statistics 销售统计]
   * @AuthorHTL
   * @DateTime  2018-03-19T11:09:12+0800
   * @return    [type]                   [description]
   */
  public function sales_statistics()
  {
    $op = I('op');
    $yy = I('yy')?:date('Y');
    $mm = I('mm');
    $dd = I('dd');
    $type = I('type');
    $ymd = $yy."年";
    if($mm) $ymd .= $mm."月";
    if($mm&&$dd) $ymd .= $dd."日";

    $map = " type = 'SHP' and fee > 0 and status = 2 ";
    // if($type == 2) $map .= " and LENGTH(order_sn) < 18 ";  // 交易量是否统计续租
    $log = M('wxpay_log')->where($map)->select();
    $money_sum = 0;
    $count_sum = 0;
    if($yy && !$mm){
      $this->assign('title_name',"月份");
      for ($i=1; $i <= 12; $i++) {
        $a = mktime(0,0,0,$i,1,$yy);
        $z = mktime(0,0,0,$i+1,1,$yy)-1;
        $data[$i]['title'] = $i."月";
        $data[$i]['money'] = $this->calc_fee($log,$a,$z);
        $data[$i]['count'] = $this->calc_count($log,$a,$z);
        $money_sum += $data[$i]['money'];
        $count_sum += $data[$i]['count'];
      }
    }else if($yy && $mm && !$dd){
      $this->assign('title_name',"日期");
      $days = date('t',mktime(0,0,0,$mm,1,$yy));
      for ($i=1; $i <= $days; $i++) {
        $a = mktime(0,0,0,$mm,$i,$yy);
        $z = mktime(0,0,0,$mm,$i+1,$yy)-1;
        $data[$i]['title'] = $i."日";
        $data[$i]['money'] = $this->calc_fee($log,$a,$z);
        $data[$i]['count'] = $this->calc_count($log,$a,$z);
        $money_sum += $data[$i]['money'];
        $count_sum += $data[$i]['count'];
      }
    }else if($yy && $mm && $dd){
      $this->assign('title_name',"时间");
      for ($i=0; $i <= 23; $i++) {
        $a = mktime($i,0,0,$mm,$dd,$yy);
        $z = mktime($i+1,0,0,$mm,$dd,$yy)-1;
        $data[$i]['title'] = $i."点 - ".($i+1)."点";
        $data[$i]['money'] = $this->calc_fee($log,$a,$z);
        $data[$i]['count'] = $this->calc_count($log,$a,$z);
        $money_sum += $data[$i]['money'];
        $count_sum += $data[$i]['count'];
      }
    }
    if($data){
      foreach($data as $k=>$val){
        $data[$k]['money_scale'] = round($val['money']/$money_sum*100,2);
        $data[$k]['count_scale'] = round($val['count']/$count_sum*100,2);
      }
      $this->assign('money_sum',number_format($money_sum,2,'.',''));
      $this->assign('count_sum',$count_sum);
      $this->assign('data',$data);
    }

    if($op == 'export'){
      $xls = array(array($title_name,$type==2?'交易量':'交易额','所占比例(%)'));
      unset($val);
      foreach($data as $val){
        $xls[] = array(
          $val["title"],
          $type==2?$val["count"]:$val["money"],
          strval($type==2?$val["count_scale"]:$val["money_scale"])
          );
      }
      $xls[] = $type==2?
        array('总交易量',$count_sum):
        array('总交易额',$money_sum);

      $xls[] = array($ymd);
      create_xls($xls,'销售统计_'.date("Y-m-d H:i"));
      die;
    }

    $this->display();
  }

  public function calc_fee($log,$a,$z){
    foreach($log as $val){
      if($val['create_time'] >= $a && $val['create_time'] <= $z){
        $fee += $val['fee'];
      }
    }
    return number_format($fee/100,2,'.','');
  }

  public function calc_count($log,$a,$z){
    $count = 0;
    foreach($log as $val){
      if($val['create_time'] >= $a && $val['create_time'] <= $z){
        $count += 1;
      }
    }
    return $count;
  }

  /**
   * [sales_subsidiary 销售明细]
   * @AuthorHTL
   * @DateTime  2018-03-19T11:02:18+0800
   * @return    [type]                   [description]
   */
  public function sales_subsidiary()
  {
        $op = I('op');
        // dump(I());die;
        $map = " o.admin_id = a.id  ";

        $business_id = session('admin_id');

        $map.=" and o.admin_id=".$business_id;

        if($ctstar = I('ctstar')) $map .= " and o.create_time > ".strtotime($ctstar); //开始时间

        if($ctend = I('ctend')) $map .= " and o.create_time < ".strtotime($ctend); //结束时间

        if($order_sn = I('order_sn')) $map .= " and o.order_sn like '%{$order_sn}%' "; //订单号

        if($nickname = I('nickname')) $map .= " and u.nickname like '%{$nickname}%' "; //用户名

        if($address = I('address')) $map .= " and o.address like '%{$address}%' "; //收货人

        $map .= ' and o.uid = u.id';

        $map = '('.$map.' AND o.status = 2 ) OR ('.$map.' AND o.status = 3)';

        // EXCEL表导出
        if($op == 'export'){
          //订单列表
          $list = M()->table("am_order o,am_users u,am_admin a")->field('o.*,u.nickname')->where($map)->limit($limit)->order('o.create_time desc')->select();
          foreach($list as $k=>&$val){
              $map = "order_sn = '{$val['order_sn']}'";
              $list[$k]['goods'] = M('car')->where($map)->limit(1)->select()[0];
              $list[$k]['goods'] = unserialize($list[$k]['goods']['car_content']);
              $sum_gold=0;
              foreach($list[$k]['goods'] as $i=>&$vol){
                  $vol['title']=M('goods')->where('id='.$vol['goods_id'])->getField('title');
              }
          }
          $xls = array(array('订单号','商品名称', '数量/件', '单价/￥','下单时间'));
          unset($val);
          foreach($list as $val){
            foreach ($val['goods'] as $vo) {
               $xls[] = array(
                  $val["order_sn"],
                  $vo["title"],
                  $vo['goods_num'],
                  $vo["price"],
                  cdate(0,$val["create_time"])
                );
            }
          }
          create_xls($xls,'商品销售明细_'.date("Y-m-d H:i"));die;
        }
        $count = M()->table("am_order o,am_users u, am_admin a")->where($map)->count();

        $Page = new \Think\Page($count,15);

        $show = $Page->show();

        $limit = $Page->firstRow.','.$Page->listRows;

        //订单列表
        $list = M()->table("am_order o,am_users u,am_admin a")->field('o.*,u.nickname')->where($map)->limit($limit)->order('o.create_time desc')->select();

        foreach($list as $k=>&$val){

            $map = "order_sn = '{$val['order_sn']}'";

            $list[$k]['goods'] = M('car')->where($map)->limit(1)->select()[0];
            $list[$k]['goods'] = unserialize($list[$k]['goods']['car_content']);
            $sum_gold=0;
            foreach($list[$k]['goods'] as $i=>&$vol){
                $vol['img']=M('goods')->where('id='.$vol['goods_id'])->getField('img');
                $vol['title']=M('goods')->where('id='.$vol['goods_id'])->getField('title');
            }
        }

        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('count',$count);
        $this->display();

  }

  /**
   * [conversion_rate 商品销售转化率]
   * @AuthorHTL
   * @DateTime  2018-03-19T11:05:02+0800
   * @return    [type]                   [description]
   */
  public function conversion_rate()
  {
    $business_id = session('admin_id');
    $map = " admin_id = ".$business_id;
    if($title = I('title')) $map .= " and title like '%{$title}%' ";
    $op = I('op');

    // EXCEL表导出
    if($op == 'export'){
      $list = M('goods')->where($map)->field('id,title,sales,browse_num,sales/browse_num as scale')->order('scale desc')->select();

      $xls = array(array('商品id','商品名称','浏览量','销量','转化率'));
      foreach($list as $val){
        $xls[] = array(
          $val["id"],
          $val["title"],
          $val["browse_num"],
          $val['sales'],
          $val["scale"]
          );
      }
      create_xls($xls,'商品销售转化率_'.date("Y-m-d H:i"));die;
    }

    $count = M('goods')->where($map)->count();
    $Page = new \Think\Page($count,15);
    $show = $Page->show();
    $limit = $Page->firstRow.','.$Page->listRows;

    $list = M('goods')->where($map)->field('id,title,sales,browse_num,sales/browse_num as scale')->order('scale desc')->limit($limit)->select();
    // dump($list);die;
    $this->assign('list',$list);
    $this->assign('page',$show);
    $this->display();
  }

  /**
   * [member_consumption_rank 会员消费排行]
   * @AuthorHTL
   * @DateTime  2018-03-19T11:06:28+0800
   * @return    [type]                   [description]
   */
  public function member_consumption_rank()
  {
    $map = " u.nickname != '' ";
    if($nickname = I('nickname')) $map .= " and u.nickname like '%{$nickname}%' ";
    $op = I('op');
    $count = M('users')->count();
    $Page = new \Think\Page($count,15);
    $show = $Page->show();
    $limit = $Page->firstRow.','.$Page->listRows;
    $list = M('wxpay_log l')->join('RIGHT JOIN am_users u ON l.uid = u.uid')->where($map)->field('u.*,sum(l.fee) as fees')->group('u.uid')->order('fees desc')->limit($limit)->select();
    foreach($list as $k=>$val){
      $list[$k]['order_count'] = M('order')->where("uid = {$val['uid']} and status > 0")->count();
    }

    $this->assign('list',$list);
    $this->assign('page',$show);
    $this->display();
  }

  /**
   * [membership_growth_trend 会员增长趋势]
   * @AuthorHTL
   * @DateTime  2018-03-19T11:07:47+0800
   * @return    [type]                   [description]
   */
  public function membership_growth_trend()
  {
    $yy = I('yy')?:date('Y');
    $mm = I('mm');
    $map = "";
    if($yy && !$mm){
      for ($i=1; $i <= 12; $i++) {
        $a = mktime(0,0,0,$i,1,$yy);
        $z = mktime(0,0,0,$i+1,1,$yy)-1;
        $data['title'][$i] = "'".$i."月'";
        $data['count'][$i] = M('users')->where("create_time BETWEEN {$a} AND {$z}")->count();
      }
    }else if($yy && $mm){
      $days = date('t',mktime(0,0,0,$mm,1,$yy));
      for ($i=1; $i <= $days; $i++) {
        $a = mktime(0,0,0,$mm,$i,$yy);
        $z = mktime(0,0,0,$mm,$i+1,$yy)-1;
        $data['title'][$i] = "'".$i."日'";
        $data['count'][$i] = M('users')->where("create_time BETWEEN {$a} AND {$z}")->count();
      }
    }
    $this->assign('data',$data);
    $this->display();
  }

  //订单统计
  public function order_statistics()
  {
    $map = " 1 ";
    $timea = I('timea');
    $timez = I('timez');
    if($timea) $map .= " and create_time >= ".strtotime($timea);
    if($timez) $map .= " and create_time <= ".strtotime($timez);

    $data['order_num']=M('order')->where($map.' and status >1 and status <4 ')->count('id');
    if($data['order_num']==""){
        $data['order_num']=0;
      }
    $data['order_gold']=M('order')->where($map.' and status >1 and status <4 ')->sum('gold');
    if($data['order_gold']==""){
        $data['order_gold']=0;
      }
    // var_dump($data);exit;
    
    if($op == 'export'){
      $xls = array(array('订单数','订单金额数','开始时间','结束时间'));

        $xls[] = array(
          $data['order_num'],
          $data['order_gold'],
          strtotime($timea),
          strtotime($timez),
          );

      create_xls($xls,'订单统计'.date("Y-m-d H:i"));
      die;
    }

    $this->assign('data',$data);
    $this->display();
  }

  //商品销售排行
  public function sales_ranking()
  {
    $business_id = session('admin_id');

    $op = I('op');

    // EXCEL表导出
    if($op == 'export'){
      $list=M('goods')->where(array('admin_id' => $business_id))->field('id,title,img,status,sales')->order('sales DESC')->select();
      $xls = array(array('商品id','商品名称','销售量/件'));
      unset($val);
      foreach($list as $val){
        $xls[] = array(
          $val["id"],
          $val["title"],
          $val["sales"]
          );
      }
      create_xls($xls,'商品销售排行'.date("Y-m-d H:i"));die;
    }

    $count = M('goods')->where(array('admin_id' => $business_id))->count();
    $Page = new \Think\Page($count, 20);
    $show = $Page->show();
    $limit = $Page->firstRow.','.$Page->listRows;

    $list=M('goods')->where(array('admin_id' => $business_id))->field('id,title,img,status,sales')->order('sales DESC')->limit($limit)->select();

    $this->assign('list',$list);
    $this->assign('page', $show);
    $this->display();
  }
}