<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 2017/5/27
 * Time: 下午5:09
 */

namespace statistics;

use Log;

class statorder extends stat_base
{
    public function __construct($stime)
    {
        parent::__construct($stime);
    }

    /*
    order_total_num int default '0' null comment '订单总数',
	order_amount decimal(10,2) default '0.00' null comment '订单总额',
	order_member_num int default '0' null comment '下单人员数',
	order_price_avg decimal(10,2) default '0.00' null comment '客单价',
	order_goods_num int default '0' null comment '订单总商品数目',
	goods_num int default '0' null comment '商品总数',
     */
    public function daily()
    {
        $this->order_info();
        $this->user_order();
    }

    private function order_info()
    {
        $model = Model('stat');
        $this->calc_time(stat_base::cur_date_type);

        $where = array();
        $where['order_isvalid'] = 1;//计入统计的有效订单
        $where['order_add_time'] = ['between',"{$this->mStartm},{$this->mEndtm}"];
        $field = ' COUNT(*) as ordernum, SUM(order_amount) as orderamount, COUNT(DISTINCT buyer_id) as ordermembernum, AVG(order_amount) as orderavg ';
        $stat_order = $model->getoneByStatorder($where, $field);

        if(empty($stat_order)) {
            return false;
        }
        else
        {
            $result = $this->mModel->get_one($this->mDateId,'invite_user_count',true);
            $fEdit = empty($result) ? false : true;

            $datas['order_total_num'] = ($t = $stat_order['ordernum'])?$t:0;
            $datas['order_amount'] = ncPriceFormat(($t = $stat_order['orderamount'])?$t:(0));
            $datas['order_member_num'] = ($t = $stat_order['ordermembernum'])?$t:0;
            $datas['order_price_avg'] = ncPriceFormat(($t = $stat_order['orderavg'])?$t:0);
            return $this->save($fEdit,$datas);
        }
    }

    private function user_order()
    {
        $this->calc_time(stat_base::cur_date_type);
        $mod_member = Model('member');

        $cond['payment_time'] = ['between',"{$this->mStartm},{$this->mEndtm}"];
        $cond['order_state']  = array('in',[20,30,40]);

        $i = 0;
        while (true)
        {
            $start = $i * 1000;
            $items = Model()->table('order')->field('buyer_id,payment_time')->where($cond)->order('payment_time asc')->limit("{$start},1000")->select();

            if(empty($items)) {
                return;
            }
            $i++;

            foreach ($items as $item)
            {
                $member_id = intval($item['buyer_id']);
                if($member_id <= 0) continue;

                $payment_time = intval($item['payment_time']);
                if($payment_time <= 0) continue;

                $mod_member->editMember(['member_id' => $member_id],['order_num' => array('exp', 'order_num+1'),'lastest_order' => $payment_time]);
            }
        }
    }
}
