<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2018/1/9
 * Time: 13:37
 */

namespace App\Http\Controllers\Manage\Trade;

use App\Http\Controllers\Controller;
use App\Modules\Product\Models\Product;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\Trade\Services\OrderService;
use Illuminate\Http\Request;

class ConsumerController extends Controller
{
    /**
     * @apiDefine Trade 交易订单
     */
    /**
     * @apiVersion 1.0.0
     * @api {GET} trade/getBookConsumerInfoByUserId 获取用户的消费的书本信息
     * @apiGroup Trade
     * @apiName getBookConsumerInfoByUserId
     * @apiParam  {Number}  [userId]  用户id(可不传)
     * @apiParam {String}  [start_time] 开始时间(可不传)
     * @apiParam {String}  [end_time] 结束时间(可不传)
     *
     * @apiSuccess {Number}  id 订购id.
     * @apiSuccess {Number}  distribution_channel_id 渠道id
     * @apiSuccess {Number}  bid 书本id
     * @apiSuccess {String}  book_name 图书名称
     * @apiSuccess {Number}  uid 用户id
     * @apiSuccess {Number}  u u参数
     * @apiSuccess {Number}  fee 订购费用
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {Number}  send_order_id 派单id
     * @apiSuccess {Number}  charge_balance 充值币余额
     * @apiSuccess {Number}  reward_balance 奖励币余额
     * @apiSuccess {Number}  total_get_amount 累计获取书币
     * @apiSuccess {Number}  total_consume_amount 累计消费书币
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {
     *            "list": {
     *             "current_page": 1,
     *             "data": [
     *                        {
     *                          "id": 6,
     *                          "distribution_channel_id": 1,
     *                          "bid": 256,
     *                          "book_name": "金牌红娘",
     *                          "uid": 1,
     *                          "u": 123545,
     *                          "fee": "1.00",
     *                          "created_at": "2017-12-02 19:15:56",
     *                          "updated_at": "2017-12-01 15:26:50",
     *                          "send_order_id": 5,
     *                          "charge_balance": 44,
     *                          "reward_balance": 66
     *                        },
     *                       {
     *                           "id": 6,
     *                           "distribution_channel_id": 1,
     *                           "bid": 256,
     *                           "book_name": "金牌红娘",
     *                           "uid": 1,
     *                           "u": 123545,
     *                           "fee": "1.00",
     *                           "created_at": "2017-12-02 19:15:56",
     *                           "updated_at": "2017-12-01 15:26:50",
     *                           "send_order_id": 5,
     *                           "charge_balance": 44,
     *                           "reward_balance": 66
     *                       }
     *                    ],
     *               "first_page_url": "http://test.manage.zhuishuyun.com/api/trade/getBookConsumerInfoByUserId?page=1",
     *               "from": 1,
     *               "last_page": 1,
     *               "last_page_url": "http://test.manage.zhuishuyun.com/api/trade/getBookConsumerInfoByUserId?page=1",
     *              "next_page_url": null,
     *              "path": "http://test.manage.zhuishuyun.com/api/trade/getBookConsumerInfoByUserId",
     *              "per_page": 15,
     *              "prev_page_url": null,
     *              "to": 1,
     *             "total": 1
     *            },
     *          "total_info": {
     *              "total_get_amount": 1111,
     *             "total_consumer_amount": 1111
     *          }
     *        }
     *     }
     */
    function getBookConsumerInfoByUserId(Request $request)
    {
        $userId = $request->has('userId') ? $request->input('userId') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Y-m-d', strtotime($request->input('end_time'))) : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? date('Y-m-d', strtotime($request->input('start_time'))) : '';
        if (empty($userId)) {
            return response()->error('PARAM_EMPTY');
        } else {
            $bookOrderResult = BookOrderService::getRecordByUid($userId, $start_time, $end_time, false);
            $bookOrderResult->total_get_amount = $this->getUserTotalBalanceInfo($userId, $start_time, $end_time);
            $bookOrderResult->total_consume_amount = $this->getUserConsumeInfo($userId, $start_time, $end_time);
        }
        return response()->success(['list' => $bookOrderResult, 'total_info' => ['total_get_amount' => $bookOrderResult->total_get_amount, 'total_consume_amount' => $bookOrderResult->total_consume_amount]]);
    }

    /**
     * 获取一段时间内的用户的消费总额
     * @param $userId 用户id
     * @param $start_time 开始时间
     * @param $end_time  结束时间
     * @return mixed
     */
    function getUserConsumeInfo($userId, $start_time, $end_time)
    {
        $bookOrderFeeAmount = BookOrderService::getBookTotalConsumeByUserIdAndTime($userId, $start_time, $end_time);
        $chapterOrderFeeAmount = ChapterOrderService::getChapterTotalConsumeByUserIdAndTime($userId, $start_time, $end_time);
        return $bookOrderFeeAmount + $chapterOrderFeeAmount;
    }


    /**
     * 获取一段时间内的用户的累计获取书币
     * @param $userId 用户id
     * @param $start_time 开始时间
     * @param $end_time  结束时间
     * @return mixed
     */
    function getUserTotalBalanceInfo($userId, $start_time, $end_time)
    {
        $params = [];
        $params['uid'] = $userId;
        $params['status'] = 'PAID';
        $params['order_type'] = 'RECHARGE';
        $params['end_time'] = $end_time;
        $params['begin_time'] = $start_time;
        $givenAmount = 0;

        $orderResult = OrderService::search($params, true);
        foreach ($orderResult as $item) {
            $product_id = $item['product_id'];
            $result = Product::getProductGivenAmount($product_id);
            $amount = $result['price'] * 100 + $result['given'];
            $givenAmount += $amount;
        }
        return $givenAmount;
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} trade/getChapterConsumerInfoByUserId 获取用户的消费的章节信息
     * @apiGroup Trade
     * @apiName getChapterConsumerInfoByUserId
     * @apiParam  {Number}  [userId]  用户id(可不传)
     * @apiParam {String}  [start_time] 开始时间(可不传)
     * @apiParam {String}  [end_time] 结束时间(可不传)
     *
     * @apiSuccess {Number}  id 订购id.
     * @apiSuccess {Number}  distribution_channel_id 渠道id
     * @apiSuccess {Number}  bid 书本id
     * @apiSuccess {Number}  cid 章节id
     * @apiSuccess {String}  book_name 图书名称
     * @apiSuccess {String}  chapter_name 章节名称
     * @apiSuccess {Number}  uid 用户id
     * @apiSuccess {Number}  u u参数
     * @apiSuccess {Number}  fee 订购费用
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {Number}  send_order_id 派单id
     * @apiSuccess {Number}  charge_balance 充值币余额
     * @apiSuccess {Number}  reward_balance 奖励币余额
     * @apiSuccess {Number}  total_get_amount 累计获取书币
     * @apiSuccess {Number}  total_consume_amount 累计消费书币
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {
     *            "list": {
     *             "current_page": 1,
     *             "data": [
     *                        {
     *                          "id": 6,
     *                          "distribution_channel_id": 1,
     *                          "bid": 256,
     *                          "cid": 122,
     *                          "chapter_name": "谁谁谁"
     *                          "book_name": "金牌红娘",
     *                          "uid": 1,
     *                          "u": 123545,
     *                          "fee": "1.00",
     *                          "created_at": "2017-12-02 19:15:56",
     *                          "updated_at": "2017-12-01 15:26:50",
     *                          "send_order_id": 5,
     *                          "charge_balance": 44,
     *                          "reward_balance": 66
     *                        },
     *                       {
     *                           "id": 6,
     *                           "distribution_channel_id": 1,
     *                           "bid": 256,
     *                           "cid": 122,
     *                           "chapter_name": "谁谁谁"
     *                           "book_name": "金牌红娘",
     *                           "uid": 1,
     *                           "u": 123545,
     *                           "fee": "1.00",
     *                           "created_at": "2017-12-02 19:15:56",
     *                           "updated_at": "2017-12-01 15:26:50",
     *                           "send_order_id": 5,
     *                           "charge_balance": 44,
     *                           "reward_balance": 66
     *                       }
     *                    ],
     *                  "first_page_url": "http://test.manage.zhuishuyun.com/api/trade/getBookConsumerInfoByUserId?page=1",
     *                  "from": 1,
     *                  "last_page": 1,
     *                  "last_page_url": "http://test.manage.zhuishuyun.com/api/trade/getBookConsumerInfoByUserId?page=1",
     *                  "next_page_url": null,
     *                  "path": "http://test.manage.zhuishuyun.com/api/trade/getBookConsumerInfoByUserId",
     *                  "per_page": 15,
     *                  "prev_page_url": null,
     *                  "to": 1,
     *                  "total": 1
     *            },
     *            "total_info": {
     *                "total_get_amount": 1111,
     *                "total_consumer_amount": 1111
     *           }
     *        }
     *     }
     */
    function getChapterConsumerInfoByUserId(Request $request)
    {
        $userId = $request->has('userId') ? $request->input('userId') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Y-m-d', strtotime($request->input('end_time'))) : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? date('Y-m-d', strtotime($request->input('start_time'))) : '';
        if (empty($userId)) {
            return response()->error('PARAM_EMPTY');
        } else {
            $chapterOrderResult = ChapterOrderService::getRecordByUid($userId, $start_time, $end_time, false);
            $chapterOrderResult->total_get_amount = $this->getUserTotalBalanceInfo($userId, $start_time, $end_time);
            $chapterOrderResult->total_consume_amount = $this->getUserConsumeInfo($userId, $start_time, $end_time);
        }
        return response()->success(['list' => $chapterOrderResult, 'total_info' => ['total_get_amount' => $chapterOrderResult->total_get_amount, 'total_consume_amount' => $chapterOrderResult->total_consume_amount]]);
    }

    /**
     * 导出用户的按本订购的消费记录
     * @param Request $request
     * @return mixed
     */
    function exportUserBookConsumerInfo(Request $request)
    {
        $userId = $request->has('userId') ? $request->input('userId') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Y-m-d', strtotime($request->input('end_time'))) : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? date('Y-m-d', strtotime($request->input('start_time'))) : '';
        if (empty($userId)) {
            return response()->error('PARAM_EMPTY');
        } else {
            $bookOrderResult = BookOrderService::getRecordByUid($userId, $start_time, $end_time, true);
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:attachment;filename=" . "用户书本订购记录" . date("YmdHis") . ".csv");

            echo iconv("UTF-8", "GBK", "\"id单号\",\"渠道id\",\"书本id\",\"图书名称\",\"用户id\",\"u参数\",\"订购费用\",\"创建时间\",\"更新时间\",\"充值币余额\",\"奖励币余额\",\"派单id\"\r\n");
            if ($bookOrderResult) {
                foreach ($bookOrderResult as $item) {
                    echo("\"" . iconv("UTF-8", "GBK", '`' . $item->id) . "\",");
                    echo("\"" . $item->distribution_channel_id . "\",");
                    echo("\"" . $item->bid . "\",");
                    echo("\"" . iconv("UTF-8", "GBK", $item->book_name) . "\",");
                    echo("\"" . $item->uid . "\",");
                    echo("\"" . $item->u . "\",");
                    echo("\"" . $item->fee . "\",");
                    echo("\"" . iconv("UTF-8", "GBK", date('Y-m-d H:i:s', strtotime($item->created_at))) . "\",");
                    echo("\"" . iconv("UTF-8", "GBK", date('Y-m-d H:i:s', strtotime($item->updated_at))) . "\",");
                    echo("\"" . $item->charge_balance . "\",");
                    echo("\"" . $item->reward_balance . "\",");
                    echo("\"" . $item->send_order_id . "\"\r\n");
                }
            }
            exit();
        }
    }

    /**
     *
     * 导出用户的按章节订购的消费记录
     * @param Request $request
     * @return mixed
     */
    function exportUserChapterConsumerInfo(Request $request)
    {
        $userId = $request->has('userId') ? $request->input('userId') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Y-m-d', strtotime($request->input('end_time'))) : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? date('Y-m-d', strtotime($request->input('start_time'))) : '';
        if (empty($userId)) {
            return response()->error('PARAM_EMPTY');
        } else {
            $chapterOrderResult = ChapterOrderService::getRecordByUid($userId, $start_time, $end_time, true);
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:attachment;filename=" . "用户章节订购记录" . date("YmdHis") . ".csv");

            echo iconv("UTF-8", "GBK", "\"id单号\",\"渠道id\",\"书本id\",\"图书名称\",\"章节id\",\"章节名称\",\"用户id\",\"u参数\",\"订购费用\",\"创建时间\",\"更新时间\",\"充值币余额\",\"奖励币余额\",\"派单id\"\r\n");
            if ($chapterOrderResult) {
                foreach ($chapterOrderResult as $item) {
                    echo("\"" . iconv("UTF-8", "GBK", '`' . $item->id) . "\",");
                    echo("\"" . $item->distribution_channel_id . "\",");
                    echo("\"" . $item->bid . "\",");
                    echo("\"" . iconv("UTF-8", "GBK", $item->book_name) . "\",");
                    echo("\"" . $item->cid . "\",");
                    echo("\"" . iconv("UTF-8", "GBK", $item->chapter_name) . "\",");
                    echo("\"" . $item->uid . "\",");
                    echo("\"" . $item->u . "\",");
                    echo("\"" . $item->fee . "\",");
                    echo("\"" . iconv("UTF-8", "GBK", date('Y-m-d H:i:s', strtotime($item->created_at))) . "\",");
                    echo("\"" . iconv("UTF-8", "GBK", date('Y-m-d H:i:s', strtotime($item->updated_at))) . "\",");
                    echo("\"" . $item->charge_balance . "\",");
                    echo("\"" . $item->reward_balance . "\",");
                    echo("\"" . $item->send_order_id . "\"\r\n");
                }
            }
            exit();
        }
    }
}