<?php
namespace app\api\controller;
use think\facade\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 店铺销量统计控制器
 */
class Statisticsgeneral extends MobileSeller
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        include_once root_path(). 'extend/mall/statistics.php';
        Lang::load(base_path().'home/lang/'.config('lang.default_lang').'/statistics.lang.php');
    }


    /**
     * @api {POST} api/Statisticsgeneral/index 近30天销售数据
     * @apiVersion 1.0.0
     * @apiGroup Statisticsgeneral
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.goodstop30_arr  30天销售排行商品列表
     * @apiSuccess {Int} result.goodstop30_arr.goods_id  商品ID
     * @apiSuccess {Int} result.goodstop30_arr.goods_name  商品名称
     * @apiSuccess {Int} result.goodstop30_arr.ordergoodsnum  销量
     * @apiSuccess {Int} result.stat_time  统计时间
     * @apiSuccess {Object} result.statnew_arr  统计信息
     * @apiSuccess {Float} result.statnew_arr.avggoodsprice  评价商品价格
     * @apiSuccess {Float} result.statnew_arr.avgorderamount  平均订单价格
     * @apiSuccess {Int} result.statnew_arr.gcollectnum  商品收藏数量
     * @apiSuccess {Int} result.statnew_arr.goodsnum  商品总数
     * @apiSuccess {String} result.statnew_arr.hothour  热销时间
     * @apiSuccess {Float} result.statnew_arr.orderamount  订单总金额
     * @apiSuccess {Int} result.statnew_arr.ordergoodsnum  商品总销量
     * @apiSuccess {Int} result.statnew_arr.ordermembernum  用户总数
     * @apiSuccess {Int} result.statnew_arr.ordernum  订单总数
     * @apiSuccess {Int} result.statnew_arr.store_collect  店铺收藏量
     * @apiSuccess {String} result.stattoday_json  统计json数据
     */
    public function index(){
        $stat_model = model('stat');
        //统计的日期0点
        $stat_time = strtotime(date('Y-m-d',TIMESTAMP)) - 86400;
        /*
         * 近30天
         */
        $stime = $stat_time - (86400*29);//30天前
        $etime = $stat_time + 86400 - 1;//昨天23:59

        $statnew_arr = array();

        //查询订单表下单量、下单金额、下单客户数
        $where = array();
        $where[]=array('order_isvalid','=',1);//计入统计的有效订单
        $where[]=array('store_id','=',session('store_id'));
        $where[] = array('order_add_time','between',array($stime,$etime));
        $field = ' COUNT(*) as ordernum, SUM(order_amount) as orderamount, COUNT(DISTINCT buyer_id) as ordermembernum, AVG(order_amount) as avgorderamount ';
        $stat_order = $stat_model->getoneByStatorder($where, $field);
        $statnew_arr['ordernum'] = ($t = $stat_order['ordernum'])?$t:0;
        $statnew_arr['orderamount'] = ds_price_format(($t = $stat_order['orderamount'])?$t:(0));
        $statnew_arr['ordermembernum'] = ($t = $stat_order['ordermembernum']) > 0?$t:0;
        $statnew_arr['avgorderamount'] = ds_price_format(($t = $stat_order['avgorderamount'])?$t:(0));
        unset($stat_order);

        //下单高峰期
        $where = array();
        $where[]=array('order_isvalid','=',1);//计入统计的有效订单
        $where[]=array('store_id','=',session('store_id'));
        $where[] = array('order_add_time','between',array($stime,$etime));
        $field = ' HOUR(FROM_UNIXTIME(order_add_time)) as hourval,COUNT(*) as ordernum ';
        $orderlist = $stat_model->statByStatorder($where, $field, 0, 0, 'ordernum desc,hourval asc', 'hourval');

        foreach ((array)$orderlist as $k=>$v){
            if ($k < 2){//取前两个订单量高的时间段
                if (!isset($statnew_arr['hothour'])){
                    $statnew_arr['hothour'] = ($v['hourval'].":00~".($v['hourval']+1).":00");
                } else {
                    $statnew_arr['hothour'] .= ("，".($v['hourval'].":00~".($v['hourval']+1).":00"));
                }
            }
        }
        unset($orderlist);

        //查询订单商品表下单商品数
        $where = array();
        $where[]=array('order_isvalid','=',1);//计入统计的有效订单
        $where[]=array('store_id','=',session('store_id'));
        $where[] = array('order_add_time','between',array($stime,$etime));
        $field = ' SUM(goods_num) as ordergoodsnum, AVG(goods_pay_price/goods_num) as avggoodsprice ';
        $stat_ordergoods = $stat_model->getoneByStatordergoods($where, $field);
        $statnew_arr['ordergoodsnum'] = ($t = $stat_ordergoods['ordergoodsnum'])?$t:0;
        $statnew_arr['avggoodsprice'] = ds_price_format(($t = $stat_ordergoods['avggoodsprice'])?$t:(0));
        unset($stat_ordergoods);

        //商品总数、收藏量
        $goods_list = $stat_model->statByGoods(array('store_id'=>session('store_id')),'COUNT(*) as goodsnum, SUM(goods_collect) as gcollectnum');
        $statnew_arr['goodsnum'] = ($t = $goods_list[0]['goodsnum']) > 0?$t:0;
        $statnew_arr['gcollectnum'] = ($t = $goods_list[0]['gcollectnum']) > 0?$t:0;

        //店铺收藏量
        $store_list = $stat_model->getOneByStore(array('store_id'=>session('store_id')),'store_collect');
        $statnew_arr['store_collect'] = ($t = $store_list['store_collect']) > 0?$t:0;

        /*
         * 销售走势
         */
        //构造横轴数据
        for($i=$stime; $i<$etime; $i+=86400){
            //当前数据的时间
            $timetext = date('n',$i).'-'.date('j',$i);
            //统计图数据
            $stat_list[$timetext] = 0;
            //横轴
            $stat_arr['xAxis']['categories'][] = $timetext;
        }
        $where = array();
        $where[]=array('order_isvalid','=',1);//计入统计的有效订单
        $where[]=array('store_id','=',session('store_id'));
        $where[] = array('order_add_time','between',array($stime,$etime));
        $field = ' order_add_time,SUM(order_amount) as orderamount,MONTH(FROM_UNIXTIME(order_add_time)) as monthval,DAY(FROM_UNIXTIME(order_add_time)) as dayval ';
        $stat_order = $stat_model->statByStatorder($where, $field, 0, 0, '','monthval,dayval');
        if($stat_order){
            foreach($stat_order as $k => $v){
                $stat_list[$v['monthval'].'-'.$v['dayval']] = floatval($v['orderamount']);
            }
        }
        $stat_arr['legend']['enabled'] = false;
        $stat_arr['series'][0]['name'] = lang('place_order_amount');
        $stat_arr['series'][0]['data'] = array_values($stat_list);
        //得到统计图数据
        $stat_arr['title'] = lang('sales_trends_last_days');
        $stat_arr['yAxis'] = lang('place_order_amount');
        $stattoday_json = getStatData_LineLabels($stat_arr);
        unset($stat_arr);

        /*
         * 7日内商品销售TOP30
         */
        $stime = $stat_time - 86400*6;//7天前0点
        $etime = $stat_time + 86400 - 1;//今天24点
        $where = array();
        $where[]=array('order_isvalid','=',1);//计入统计的有效订单
        $where[]=array('store_id','=',session('store_id'));
        $where[] = array('order_add_time','between',array($stime,$etime));
        $field = ' sum(goods_num) as ordergoodsnum, goods_id, goods_name ';
        $goodstop30_arr = $stat_model->statByStatordergoods($where, $field, 0, 30,'ordergoodsnum desc', 'goods_id');

        $result = array(
            'goodstop30_arr'=>$goodstop30_arr,
            'stattoday_json'=>$stattoday_json,
            'statnew_arr'=>$statnew_arr,
            'stat_time'=>$stat_time,
        );
        ds_json_encode(10000, '',$result);
    }

}