<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 订单管理
 */
namespace app\smartbc\controller;
use app\smartbc\controller\Common;
use app\smartbc\model\SmartbcOrder;
use think\facade\Request;
use think\helper\Time;

class Order extends Common{

    public function initialize() {
        parent::initialize();
        $this->assign('pathMaps', [['name'=>'买单帐单','url'=>url("order/index")]]);
    }

    /**
     * 用户订单
     * @access public
     */
    public function Index(int $state = 1){
        $condition   = [];
        $condition[] = ['member_miniapp_id', '=', $this->member_miniapp_id];
        $store_id    = Request::param('store_id/d', '');
        $store_name  = Request::param('store_name');
        if ($store_id) {
            $condition[] = ['store_id', '=', $store_id];
        }
        $time = Request::param('time/d',0);
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['paid_time','>=',$start];
            $condition[] = ['paid_time','<=',$end];
        }
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($starttime){
            $condition[] = ['paid_time','>=',strtotime($starttime)];
        }
        if($endtime){
            $condition[] = ['paid_time','<=',strtotime($endtime)];
        }
        $view['orders']          = SmartbcOrder::where($condition)->where(['state' => $state ? 1 : 0])->order('id desc')->paginate(20, false, ['query' => ['store_id' => $store_id, 'store_name' => $store_name, 'time' => $time, 'starttime' => $starttime, 'endtime' => $endtime]]);
        $view['order_num']       = SmartbcOrder::where($condition)->where(['state' => 1])->count();
        $view['user_amount']     = SmartbcOrder::where($condition)->where(['state' => 1])->sum('amount');
        $view['order_amount']    = SmartbcOrder::where($condition)->where(['state' => 1])->sum('price');
        $view['coupon_price']    = money($view['user_amount'] - $view['order_amount']);
        $view['time']            = $time;
        $view['starttime']       = $starttime;
        $view['endtime']         = $endtime;
        $view['store_id']        = $store_id;
        $view['store_name']      = $store_name;
        return view()->assign($view);
    }    
}