<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/12/1
 * Time: 11:37
 */

namespace App\Http\Controllers\Channel\Trade;

use App\Http\Controllers\Channel\BaseController;
use App\Http\Controllers\Channel\Trade\Transformers\OrderTransformer;
use App\Modules\Trade\Services\OrderService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\Activity\Services\ActivityService;
use Illuminate\Http\Request;

class OrderController extends BaseController
{
    /**
     * @apiDefine Trade 订单
     */

    /**
     * @apiVersion 1.0.0
     * @api {GET} trade/orders 获取订单列表
     * @apiGroup Trade
     * @apiName getOrders
     * @apiParam   {Number}  [send_order_id] 派单ID
     * @apiParam   {String}  [begin_time] 开始时间
     * @apiParam   {String}  [end_time] 结束时间
     * @apiSuccess {Number}  uid 用户id.
     * @apiSuccess {String}  price 价格.
     * @apiSuccess {String}  status '状态 PAID：已支付 UNPAID未支付'.
     * @apiSuccess {String}  trade_no 平台交易ID.
     * @apiSuccess {String}  pay_end_at 支付完成时间.
     * @apiSuccess {Number}  send_order_id 派单id
     * @apiSuccess {String}  send_order_name 派单名称
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *
     *         "data": [
     *            {
     *              "uid": 1,
     *              "price": "1.00",
     *              "status": "PAID",
     *              "trade_no": "201711301125401585459852216605",
     *              "pay_end_at": "2017-12-01 10:20:04",
     *              "send_order_id": 0,
     *              "send_order_name": "",
     *              "created_at": 1512094804,
     *            }
     *        ]
     *     }
     */
    function getOrders(Request $request)
    {
        $params = [];
        $request->has('start_time') && $request->input('start_time') && $params['begin_time'] = trim($request->input('start_time'));
        $request->has('end_time') && $request->input('end_time') && $params['end_time'] = date('Y-m-d H:i:s', strtotime(trim($request->input('end_time'))) + 86400 - 1);
        $request->has('send_order_id') && $request->input('send_order_id') && $params['send_order_id'] = (int)$request->input('send_order_id');
        $name = $request->has('activity_name') && trim($request->input('activity_name')) ? trim($request->input('activity_name')) : '';
        // 模板
        $from_custom_id = $request->has('from_custom_id') && trim($request->input('from_custom_id')) ? trim($request->input('from_custom_id')) : '';
        $params['inner_send_order_id'] = $from_custom_id;
        
        if(!$params['begin_time'] || !$params['end_time'] ){
            return response()->error('PARAM_ERROR');
        }

        if( strtotime($params['end_time']) - strtotime($params['begin_time']) >= 31*86400 ){
            return response()->error('PARAM_ERROR');
        }

        //活动
        if ($name) $params['activity_id'] = ActivityService::getActivityIds(compact('name'));

        if ($request->has('status') && $request->input('status') && in_array(strtoupper($request->input('status')), ['UNPAID', 'PAID'])) {
            $params['status'] = strtoupper($request->input('status'));
        }

        $params['distribution_channel_id'] = $this->getChannelId();
        $orders = OrderService::search($params);
        return response()->pagination(new OrderTransformer(), $orders);
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} trade/exportOrders 导出订单列表
     * @apiGroup Trade
     * @apiName exportOrders
     * @apiParam   {Number}  [send_order_id] 派单ID
     * @apiParam   {String}  [begin_time] 开始时间
     * @apiParam   {String}  [end_time] 结束时间
     * @apiSuccess {Number}  uid 用户id.
     * @apiSuccess {String}  price 价格.
     * @apiSuccess {String}  status '状态 PAID：已支付 UNPAID未支付'.
     * @apiSuccess {String}  trade_no 平台交易ID.
     * @apiSuccess {String}  pay_end_at 支付完成时间.
     * @apiSuccess {Number}  send_order_id 派单id
     * @apiSuccess {String}  send_order_name 派单名称
     * @apiSuccess {String}  created_at 创建时间
     */
    function exportOrders(Request $request)
    {
        $params = [];
        $request->has('start_time') && $request->input('start_time') && $params['begin_time'] = trim($request->input('start_time'));
        $request->has('end_time') && $request->input('end_time') && $params['end_time'] = date('Y-m-d H:i:s', strtotime(trim($request->input('end_time'))) + 86400 - 1);
        $request->has('send_order_id') && $request->input('send_order_id') && $params['send_order_id'] = (int)$request->input('send_order_id');
        if ($request->has('status') && $request->input('status') && in_array(strtoupper($request->input('status')), ['UNPAID', 'PAID'])) {
            $params['status'] = strtoupper($request->input('status'));
        }

        if(!$params['begin_time'] || !$params['end_time'] ){
            return response()->error('PARAM_ERROR');
        }

        if( strtotime($params['end_time']) - strtotime($params['begin_time']) >= 31*86400 ){
            return response()->error('PARAM_ERROR');
        }

        $name = $request->has('activity_name') && trim($request->input('activity_name')) ? trim($request->input('activity_name')) : '';
        //活动
        if ($name) $params['activity_id'] = ActivityService::getActivityIds(compact('name'));

        $params['distribution_channel_id'] = $this->getChannelId();

        $orders = OrderService::search($params, true);

        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . "订单列表" . date("YmdHis") . ".csv");
        echo iconv("UTF-8", "GBK", "\"商户订单号\",\"用户ID\",\"金额\",\"支付状态\",\"创建时间\",\"支付时间\",\"派单id\",\"派单名称\",\"活动名称\"\r\n");
        if ($orders) {
            foreach ($orders as $order) {

                echo("\"" . iconv("UTF-8", "GBK", $order->trade_no) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", $order->uid) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", $order->price) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", $order->status == 'PAID' ? '已支付' : '未支付') . "\",");
                echo("\"" . $order->created_at . "\",");
                echo("\"" . $order->pay_end_at . "\",");
                echo("\"" . iconv("UTF-8", "GBK", $order->send_order_id) . "\",");
                echo("\"" . iconv("UTF-8", "GBK//IGNORE", (string)$order->send_order_name) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", $order->name) . "\"\r\n");
            }
        }
        exit();
    }


    /**
     * @apiVersion 1.0.0
     * @api {GET} trade/getChannelToday 获取当日订单数据
     * @apiGroup Trade
     * @apiName getChannelToday
     * @apiSuccess {Number}  paid_number  成功订单数
     * @apiSuccess {Number}  success_amount 成功总额
     * @apiSuccess {Number}  unpaid_number 未支付订单数
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *            {
     *              "paid_number": 2,
     *              "unpaid_number": 112,
     *              "success_amount": 120212,
     *            }
     *        ]
     *     }
     */
    function channelTodayStat()
    {

        $today_data = OrderService::getChannelToday($this->getChannelId());
        $data = [
            'unpaid_number' => (float)$today_data['total_num'] - (float)$today_data['paid_number'],
            'success_amount' => (float)$today_data['success_amount'],
            'paid_number' => (int)$today_data['paid_number'],
        ];
        return response()->success($data);

    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} trade/getChannelTodayData 获取当日订单数据
     * @apiGroup Trade
     * @apiName getChannelTodayData
     * @apiSuccess {Number}  amount  总成功总额
     * @apiSuccess {Number}  paid_num 总成功订单数
     * @apiSuccess {Number}  total_order_num 总订单数
     * @apiSuccess {Number}  recharge_unpaid_number 普通未支付订单数
     * @apiSuccess {Number}  recharge_paid_number 普通已支付订单数
     * @apiSuccess {Number}  recharge_success_amount 普通充值总额
     * @apiSuccess {Number}  total_order_num 总订单数
     * @apiSuccess {Number}  total_order_num 总订单数
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *            {
     *              "paid_number": 2,
     *              "unpaid_number": 112,
     *              "success_amount": 120212,
     *            }
     *        ]
     *     }
     */
    function channelTodayData()
    {
        $distribution_channel_id = $this->getChannelId();
        $data = self::getChannelTodayData($distribution_channel_id);
       
        return response()->success($data);

    }

    /**
     * 账号级别的今日数据
     */
    function accountChannelTodayData()
    {
    	$channel_user_id = $this->getChannelUserId();
    	$channels = ChannelService::getByChannelUserId($channel_user_id);
    	$data = [
	    	'amount' => 0,
	    	'paid_num' => 0,
	    	'total_order_num' => 0,
	    	'recharge_unpaid_number' => 0,
	    	'recharge_paid_number' => 0,
	    	'recharge_success_amount' => 0,
	    	'year_unpaid_number' => 0,
	    	'year_paid_number' => 0,
	    	'year_success_amount' => 0,
	    	'new_user_num' => 0,
	    	'new_subscribe_user_num' => 0
    	];
    	foreach($channels as $channel){
    		$distribution_channel_id = $channel->id;
    		\Log::info('getChannelTodayData:'.$distribution_channel_id);
    		$one_data = self::getChannelTodayData($distribution_channel_id);
    		$data['amount'] += $one_data['amount'];
    		$data['paid_num'] += $one_data['paid_num'];
    		$data['total_order_num'] += $one_data['total_order_num'];
    		$data['recharge_unpaid_number'] += $one_data['recharge_unpaid_number'];
    		$data['recharge_paid_number'] += $one_data['recharge_paid_number'];
    		$data['recharge_success_amount'] += $one_data['recharge_success_amount'];
    		$data['year_unpaid_number'] += $one_data['year_unpaid_number'];
    		$data['year_paid_number'] += $one_data['year_paid_number'];
    		$data['year_success_amount'] += $one_data['year_success_amount'];
    		$data['new_user_num'] += $one_data['new_user_num'];
    		$data['new_subscribe_user_num'] += $one_data['new_subscribe_user_num'];
    	}
    	$data['amount'] = round($data['amount'],2);
    	$data['recharge_success_amount'] = round($data['recharge_success_amount'],2);
    	$data['year_success_amount'] = round($data['year_success_amount'],2);
    	
    	return response()->success($data);
    
    }
    
    public static function  getChannelTodayData($distribution_channel_id){
    	$date = date('Y-m-d');
    	$today_data = OrderService::getChannelTodayData($distribution_channel_id);
    	$uv_pv = SendOrderService::getChannelPromotionTotalUvPv($distribution_channel_id, $date);
    	$force_user_num = ForceSubscribeService::forceSubscribeUserCountByChannelIdAndDate($distribution_channel_id, $date, '');
    	
    	$data = [
	    	'amount' => $today_data['amount'],
	    	'paid_num' => $today_data['paid_num'],
	    	'total_order_num' => $today_data['total_order_num'],
	    	
	    	'recharge_unpaid_number' => $today_data['recharge_unpaid_number'],
	    	'recharge_paid_number' => $today_data['recharge_paid_number'],
	    	'recharge_success_amount' => $today_data['recharge_success_amount'],
	    	
	    	'year_unpaid_number' => $today_data['year_unpaid_number'],
	    	'year_paid_number' => $today_data['year_paid_number'],
	    	'year_success_amount' => $today_data['year_success_amount'],
	    	
	    	'new_user_num' => $uv_pv['uv'],
	    	'new_subscribe_user_num' => $force_user_num
    	];
    	return $data;
    }
    
}