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

namespace App\Http\Controllers\Manage\SendOrder;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Manage\SendOrder\Transformers\SendOrderStatTransformer;
use App\Http\Controllers\Manage\SendOrder\Transformers\SendOrderTransformer;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\SendOrder\Services\SendOrderStatService;
use App\Modules\Statistic\Services\SendStatistics;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\Trade\Services\OrderService;
use App\Modules\User\Services\UserService;
use Illuminate\Http\Request;

/**
 * Class SendOrderController 派单
 * @package App\Http\Controllers\Manage\SendOrder
 */
class SendOrderController extends Controller
{

    /**
     * @apiDefine sendOrder 派单
     */

    /**
     * @apiVersion 1.0.0
     * @api {GET} sendOrder/getSendOrders 获取派单列表
     * @apiGroup sendOrder
     * @apiName getSendOrders
     * @apiParam  {Number}  [sendOrder_id]  派单id(可不传)
     * @apiParam {Number}  [channel_id]  渠道id(可不传)
     * @apiParam {String}  [bookName]  书本名称(可不传)
     * @apiParam {Number}  [order_status]  内外部派单(1： 内部派单， 2：外部派单)
     * @apiParam {String}  [name]  派单名称(可不传)
     * @apiParam {Number}  [book_id]  书本id(可不传)
     * @apiParam {Number}  [orderBy]  排序(1:12小时，2:7天，3：充值总额) 可不传，默然为创建时间排序
     * @apiParam {Number}  [orderByType]  排序类型(1:降序，2:升序) 可不传，默然为降序
     * @apiParam {String}  [start_time] 开始时间(可不传)
     * @apiParam {String}  [end_time] 结束时间(可不传)
     * @apiSuccess {Number}  id 派单id.
     * @apiSuccess {String}  distribution_channel_id 渠道id
     * @apiSuccess {String}  entrance 入口
     * @apiSuccess {String}  name 渠道名称
     * @apiSuccess {Number}  book_id 书本id
     * @apiSuccess {String}  channel_type 渠道类型
     * @apiSuccess {Number}  document_cover_id  文案封面id
     * @apiSuccess {Number}  headline_id  标题id
     * @apiSuccess {Number}  body_template_id ID. 内容模板id
     * @apiSuccess {Number}  original_guide_id  原文引导id
     * @apiSuccess {Number}  subscribe_chapter_id 关注章节ID
     * @apiSuccess {String}  book_name 图书名称
     * @apiSuccess {String}  chapter_name 章节名称
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  send_time 派单时间
     * @apiSuccess {String}  subscribe_chapter_name 关注章节名称
     * @apiSuccess {String}  subscribe_chapter_seq 关注章节序号
     * @apiSuccess {Number}  document_end_chapter_seq 结束章节序号
     * @apiSuccess {String}  sex_preference 性别偏好
     * @apiSuccess {Number}  remark 备注
     * @apiSuccess {Number}  continue_read_uv 继续阅读用户数
     * @apiSuccess {Number}  cost 成本
     * @apiSuccess {Number}  star_num 星星数
     * @apiSuccess {Number}  totalChargeAmount 充值总额数
     * @apiSuccess {Number}  registerNum 注册数
     * @apiSuccess {Number}  payUserNum 付费用户数
     * @apiSuccess {Number}  clickNum 点击数数
     * @apiSuccess {Number}  fansNum 粉丝数
     * @apiSuccess {Number}  toatlOrderCount 总订单数
     * @apiSuccess {Number}  vipOrderCount Vip用户订单数
     * @apiSuccess {Number}  normalOrderCount 普通用户订单数
     * @apiSuccess {Number}  vipPayUserNum Vip用户数
     * @apiSuccess {Number}  normalPayUserNum 普通用户数
     * @apiSuccess {Number}  promotion_page_id  推广页面id
     * @apiSuccess {String}  redirect_url 重定向url
     * @apiSuccess {Number}  consumeTotalFee 派单下的消费的币的总和
     * @apiSuccess {Number}  consumeChargeFee 派单下的消费的充值币
     * @apiSuccess {Number}  consumeRewardFee 派单下的消费的奖励币
     * @apiSuccess {Number}  firstChargeUserNum 首充用户数
     * @apiSuccess {Number}  repetitiousChargeUserNum 非首充用户数
     * @apiSuccess {String}  channel_name 渠道名称
     * @apiSuccess {String}  charge_type 书本收费方式
     * @apiSuccess {Number}  weekend_charge_amount 7天充值金额
     * @apiSuccess {Number}  half_day_charge_amount 12小时充值金额
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *           {
     *              "id": 5,
     *              "distribution_channel_id": null,
     *              "entrance": "书架",
     *              "name": "acai",
     *              "book_id": null,
     *              "channel_type": "AUTHENTICATED",
     *              "chapter_id": null,
     *              "document_cover_id": null,
     *               "headline_id": null,
     *               "body_template_id": null,
     *               "original_guide_id": null,
     *               "subscribe_chapter_id": null,
     *               "book_name": null,
     *               "chapter_name": null,
     *               "updated_at": "2017-11-22 14:40:46",
     *               "created_at": "2017-11-22 14:40:46",
     *               "send_time": "2017-11-22 14:40:46",
     *               "subscribe_chapter_name": null,
     *               "subscribe_chapter_seq": null,
     *               "document_end_chapter_seq"=12.
     *               "sex_preference": "男频",
     *               "remark": "0",
     *               "star_num": 0,
     *               "consumeTotalFee": 0,
     *               "consumeChargeFee": 0,
     *               "consumeRewardFee": 0,
     *               "fansNum": 0,
     *               "cost":111,
     *               "totalChargeAmount": 0,
     *               "registerNum": 0,
     *               "payUserNum": 0,
     *               "clickNum": 0,
     *               "vipPayUserNum":0,
     *               "toatlOrderCount":12,
     *               "vipOrderCount":12,
     *               "continue_read_uv": 11,
     *               "normalOrderCount":12,
     *               "normalPayUserNum":0,
     *               "firstChargeUserNum":0,
     *               "repetitiousChargeUserNum":0,
     *               "promotion_page_id": 1111,
     *               "redirect_url": "",
     *              "channel_name":"渠道名称1",
     *              "charge_type":"Book",
     *              "weekend_charge_amount": 71,
     *              "half_day_charge_amount": 105
     *            },
     *           {
     *              "id": 11,
     *             "distribution_channel_id": 123,
     *             "entrance": null,
     *             "name": "acai",
     *             "book_id": 111,
     *             "channel_type": "AUTHENTICATED",
     *             "chapter_id": 1111,
     *             "document_cover_id": 899,
     *             "headline_id": 12334,
     *             "body_template_id": 3455,
     *             "cost":111,
     *             "continue_read_uv": 11,
     *             "original_guide_id": 344,
     *             "subscribe_chapter_id": 11111,
     *             "book_name": "dpcq",
     *             "chapter_name": "ssss",
     *             "updated_at": "2017-11-22 14:40:46",
     *             "created_at": "2017-11-22 14:40:46",
     *             "send_time": "2017-11-22 14:40:46",
     *             "subscribe_chapter_name": null,
     *             "subscribe_chapter_seq": null,
     *             "remark": "0",
     *             "star_num": 0,
     *             "fansNum": 0,
     *             "vipPayUserNum":0,
     *             "normalPayUserNum":0,
     *             "totalChargeAmount": 0,
     *             "registerNum": 0,
     *             "payUserNum": 0,
     *             "consumeTotalFee": 0,
     *             "consumeChargeFee": 0,
     *             "consumeRewardFee": 0,
     *             "clickNum": 0,
     *             "toatlOrderCount":12,
     *             "vipOrderCount":12,
     *             "normalOrderCount":12,
     *             "firstChargeUserNum":0,
     *             "repetitiousChargeUserNum":0,
     *             "promotion_page_id": null,
     *             "redirect_url": "",
     *             "channel_name":"渠道名称1",
     *             "charge_type":"Book",
     *             "weekend_charge_amount": 71,
     *             "half_day_charge_amount": 105
     *            }
     *        ],
     *          "meta": {
     *                 total": 1,
     *                 per_page": 15,
     *                 current_page": 1,
     *                 last_page": 1,
     *                 next_page_url": "",
     *                 prev_page_url": ""
     *             }
     *     }
     */
    function getSendOrders(Request $request)
    {
        $name = $request->has('name') ? $request->input('name') : '';
        $bookId = $request->has('book_id') ? $request->input('book_id') : '';
        $orderBy = $request->has('orderBy') ? $request->input('orderBy') : '';
        $orderByType = $request->has('orderByType') ? $request->input('orderByType') : 1;
        $order_status = $request->has('order_status') ? $request->input('order_status') : 0;
        $orderByType = (0 == $orderByType) ? 1 : $orderByType;
        $bookName = $request->has('bookName') ? $request->input('bookName') : '';
        $channel_id = $request->has('channel_id') ? $request->input('channel_id') : '';
        $sendOrderId = $request->has('sendOrder_id') ? $request->input('sendOrder_id') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? $request->input('end_time') : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? $request->input('start_time') : '';
        $gender = $request->has('gender') && !empty($request->input('gender')) ? $request->input('gender') : '';

        $params = ['book_id' => $bookId, 'distribution_channel_id' => $channel_id, 'book_name' => $bookName, 'id' => $sendOrderId, 'orderBy' => $orderBy,
            'order_status' => $order_status, 'orderByType' => $orderByType, 'name' => $name, 'start_time' => $start_time, 'end_time' => $end_time, 'gender' => $gender];
        $data = SendOrderService::getManageSendOrders($params, false);
        foreach ($data as $item) {
            $sendOrderId = $item->id;
            $item->totalChargeAmount = (float)OrderService::getAmount(['send_order_id' => $sendOrderId]);
            $item->registerNum = UserService::getPromotionTotal($sendOrderId);;
            $item->clickNum = SendOrderService::getPv($sendOrderId);
            $item->clickNumUV = SendOrderService::getUv($sendOrderId);
            $item->continue_read_uv = SendOrderService::getContinueTotalReadUv($sendOrderId);
            $item->channel_name = ChannelService::getChannelNicknameById($item->distribution_channel_id);

            $item->fansNum = ForceSubscribeService::getFansNum($sendOrderId);
            $item->payUserNum = OrderService::getPayUserNum($sendOrderId);
            $item->vipPayUserNum = OrderService::getVipPayUserNum($sendOrderId);
            $item->normalPayUserNum = OrderService::getNormaPayUserNum($sendOrderId);

            $bookOrderInfo = BookOrderService::getSendorderTotal($sendOrderId, $start_time, $end_time);
            $chapterOrderInfo = ChapterOrderService::getSendorderTotal($sendOrderId, $start_time, $end_time);
            $item->consumeChargeFee = $bookOrderInfo['charge_balance'] + $chapterOrderInfo['charge_balance'];
            $item->consumeRewardFee = $bookOrderInfo['reward_balance'] + $chapterOrderInfo['reward_balance'];;
            $item->consumeTotalFee = $item->consumeChargeFee + $item->consumeRewardFee;

            $item->toatlOrderCount = OrderService::getOrderCount($sendOrderId);
            $item->vipOrderCount = OrderService::getVipOrderCount($sendOrderId);
            $item->normalOrderCount = OrderService::getNormalOrderCount($sendOrderId);

            $item->firstChargeUserNum = SendOrderService::getFirstChargeUserNum($sendOrderId);
            $item->repetitiousChargeUserNum = SendOrderService::getRepetitiousChargeUserNum($sendOrderId);
        }
        return response()->pagination(new SendOrderTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} sendOrder/exportSendOrders 导出派单列表
     * @apiGroup sendOrder
     * @apiName exportSendOrders
     * @apiParam   {Number}  [sendOrder_id]  派单id(可不传)
     * @apiParam   {Number}  [book_id]  书本id(可不传)
     * @apiParam   {String}  [name]  派单名称(可不传)
     * @apiParam {Number}  [order_status]  内外部派单(1： 内部派单， 2：外部派单)
     * @apiParam {Number}  [orderBy]  排序(1:12小时，2:7天) 可不传，默然为创建时间排序
     * @apiParam   {String}  [bookName]  书本名称(可不传)
     * @apiParam   {Number}  [channel_id]  渠道id(可不传)
     * @apiParam   {String}  [start_time] 开始时间(可不传)
     * @apiParam   {String}  [end_time] 结束时间(可不传)
     *
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {Number}  distribution_channel_id 渠道id
     * @apiSuccess {Number}  id 派单id.
     * @apiSuccess {Number}  cost 成本
     * @apiSuccess {Number}  book_id 书本id
     * @apiSuccess {String}  book_name 图书名称
     * @apiSuccess {Number}  clickNum 点击数数
     * @apiSuccess {Number}  registerNum 注册数
     * @apiSuccess {Number}  fansNum 粉丝数
     * @apiSuccess {Number}  document_end_chapter_seq 结束章节序号
     * @apiSuccess {String}  sex_preference 性别偏好
     * @apiSuccess {Number}  continue_read_uv 继续阅读用户数
     * @apiSuccess {Number}  payUserNum 付费用户数
     * @apiSuccess {Number}  vipPayUserNum VIP付费用户数
     * @apiSuccess {Number}  normalPayUserNum 普通付费用户数
     * @apiSuccess {Number}  totalChargeAmount 充值总额数
     * @apiSuccess {Number}  clickNumUV 独立用户数
     * @apiSuccess {Number}  toatlOrderCount 总订单数
     * @apiSuccess {Number}  vipOrderCount Vip用户订单数
     * @apiSuccess {Number}  normalOrderCount 普通用户订单数
     * @apiSuccess {String}  consumeTotalFee 派单下的消费的币的总和
     * @apiSuccess {String}  consumeChargeFee 派单下的消费的充值币
     * @apiSuccess {String}  consumeRewardFee 派单下的消费的奖励币
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *           {
     *             "created_at": "2017-11-22 14:40:46",
     *             "distribution_channel_id": 123,
     *             "id": 11,
     *             "book_id": 111,
     *             "book_name": "dpcq",
     *             "clickNum": 0,
     *             "registerNum": 0,
     *             "fansNum": 0,
     *             "cost":111,
     *             "continue_read_uv": 11,
     *             "payUserNum": 0,
     *             "vipPayUserNum":0,
     *             "normalPayUserNum":0,
     *             "totalChargeAmount": 0,
     *             "consumeTotalFee": 0,
     *             "consumeChargeFee": 0,
     *             "consumeRewardFee": 0,
     *             "clickNumUV":1.
     *             "toatlOrderCount":12,
     *             "vipOrderCount":12,
     *             "normalOrderCount":12,
     *            },
     *           {
     *             "created_at": "2017-11-22 14:40:46",
     *             "distribution_channel_id": 123,
     *             "id": 11,
     *             "book_id": 111,
     *             "book_name": "dpcq",
     *             "clickNum": 0,
     *             "registerNum": 0,
     *             "cost":111,
     *             "continue_read_uv": 11,
     *             "fansNum": 0,
     *             "consumeTotalFee": 0,
     *             "consumeChargeFee": 0,
     *             "consumeRewardFee": 0,
     *             "payUserNum": 0,
     *             "vipPayUserNum":0,
     *             "normalPayUserNum":0,
     *             "totalChargeAmount": 0,
     *             "clickNumUV":1.
     *             "toatlOrderCount":12,
     *             "vipOrderCount":12,
     *             "normalOrderCount":12,
     *            }
     *        ]
     *     }
     */
    function exportSendOrders(Request $request)
    {
        $name = $request->has('name') ? $request->input('name') : '';
        $bookId = $request->has('book_id') ? $request->input('book_id') : '';
        $orderBy = $request->has('orderBy') ? $request->input('orderBy') : '';
        $orderByType = $request->has('orderByType') ? $request->input('orderByType') : 1;
        $order_status = $request->has('order_status') ? $request->input('order_status') : 0;
        $orderByType = (0 == $orderByType) ? 1 : $orderByType;
        $bookName = $request->has('bookName') ? $request->input('bookName') : '';
        $channel_id = $request->has('channel_id') ? $request->input('channel_id') : '';
        $sendOrderId = $request->has('sendOrder_id') ? $request->input('sendOrder_id') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? $request->input('end_time') : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? $request->input('start_time') : '';
        $gender = $request->has('gender') && !empty($request->input('gender')) ? $request->input('gender') : '';

        $params = ['book_id' => $bookId, 'distribution_channel_id' => $channel_id, 'book_name' => $bookName, 'id' => $sendOrderId, 'orderBy' => $orderBy,
            'order_status' => $order_status, 'orderByType' => $orderByType, 'name' => $name, 'start_time' => $start_time, 'end_time' => $end_time, 'gender' => $gender];
        $data = SendOrderService::getManageSendOrders($params, true);
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . "派单明细" . date("YmdHis") . ".csv");

        echo iconv("UTF-8", "GBK", "\"创建时间\",\"派单时间\",\"渠道ID\",\"派单ID\",\"推广书籍ID\",\"推广书籍名称\",\"书籍类型\",\"消费币的总和\",\"消费的充值币\",\"消费的奖励币\",\"点击人数\",\"继续阅读用户数\",\"注册用户数\",\"关注人数\",\"付费用户数\",\"VIP付费用户数\",\"普通付费用户数\",\"充值金额\",\"7天充值金额\",\"12小时充值金额\",\"UV\",\"累计UV大于20的时间\",\"总订单数\",\"成本\",\"VIP用户订单数\",\"普通用户订单数\"\r\n");
        if ($data) {
            foreach ($data as $item) {

                $sendOrderId = $item->id;
                $item->totalChargeAmount = (float)OrderService::getAmount(['send_order_id' => $sendOrderId]);
                $item->registerNum = UserService::getPromotionTotal($sendOrderId);;
                $item->clickNum = SendOrderService::getPv($sendOrderId);
                $item->clickNumUV = SendOrderService::getUv($sendOrderId);

                $item->payUserNum = OrderService::getPayUserNum($sendOrderId);
                $item->fansNum = ForceSubscribeService::getFansNum($sendOrderId);
                $item->vipPayUserNum = OrderService::getVipPayUserNum($sendOrderId);
                $item->normalPayUserNum = OrderService::getNormaPayUserNum($sendOrderId);
                $item->continue_read_uv = SendOrderService::getContinueTotalReadUv($sendOrderId);

                $bookOrderInfo = BookOrderService::getSendorderTotal($sendOrderId, $start_time, $end_time);
                $chapterOrderInfo = ChapterOrderService::getSendorderTotal($sendOrderId, $start_time, $end_time);
                $item->consumeChargeFee = $bookOrderInfo['charge_balance'] + $chapterOrderInfo['charge_balance'];
                $item->consumeRewardFee = $bookOrderInfo['reward_balance'] + $chapterOrderInfo['reward_balance'];;
                $item->consumeTotalFee = $item->consumeChargeFee + $item->consumeRewardFee;

                $item->toatlOrderCount = OrderService::getOrderCount($sendOrderId);
                $item->vipOrderCount = OrderService::getVipOrderCount($sendOrderId);
                $item->normalOrderCount = OrderService::getNormalOrderCount($sendOrderId);

                echo("\"" . $item->created_at->toDateTimeString() . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->send_time ? $item->$item->send_time : "未填")) . "\",");
                echo("\"" . ($item->distribution_channel_id ? $item->distribution_channel_id : "-1") . "\",");
                echo("\"" . ($item->id ? $item->id : "-1") . "\",");
                echo("\"" . ($item->book_id ? $item->book_id : "-1") . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->book_name ? $item->book_name : "未填")) . "\",");
                echo("\"" . iconv("UTF-8", "GBK", ($item->channel_name ? $item->channel_name : "未填")) . "\",");
                echo("\"" . $item->consumeTotalFee . "\",");
                echo("\"" . $item->consumeChargeFee . "\",");
                echo("\"" . $item->consumeRewardFee . "\",");
                echo("\"" . $item->clickNum . "\",");
                echo("\"" . $item->continue_read_uv . "\",");
                echo("\"" . $item->registerNum . "\",");
                echo("\"" . $item->fansNum . "\",");
                echo("\"" . $item->payUserNum . "\",");
                echo("\"" . $item->vipPayUserNum . "\",");
                echo("\"" . $item->normalPayUserNum . "\",");
                echo("\"" . $item->totalChargeAmount . "\",");
                echo("\"" . ($item->weekend_charge_amount ? $item->weekend_charge_amount : 0) . "\",");
                echo("\"" . ($item->half_day_charge_amount ? $item->half_day_charge_amount : 0) . "\",");
                echo("\"" . $item->clickNumUV . "\",");

                $uv20Time = SendOrderService::getUv20Time($sendOrderId);
                echo("\"" . iconv("UTF-8", "GBK", ($uv20Time ? $uv20Time : "未到20")) . "\",");
                echo("\"" . $item->toatlOrderCount . "\",");
                echo("\"" . $item->cost . "\",");
                echo("\"" . $item->vipOrderCount . "\",");
                echo("\"" . $item->normalOrderCount . "\"\r\n");
            }
        }
        exit();
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} sendOrder/getHistorySendOrders 获取历史派单列表
     * @apiGroup sendOrder
     * @apiName getHistorySendOrders
     * @apiParam  {Number}  [sendOrder_id]  派单id(可不传)
     * @apiParam {Number}  [channel_id]  渠道id(可不传)
     * @apiParam {String}  [bookName]  书本名称(可不传)
     * @apiParam {String}  [name]  派单名称(可不传)
     * @apiParam {Number}  [book_id]  书本id(可不传)
     * @apiParam {Number}  [order_status]  内外部派单(1： 内部派单， 2：外部派单)
     * @apiParam {Number}  [orderBy]  排序(1:12小时，2:7天, 3：充值总额， 4：首充总额) 可不传，默然为创建时间排序   orderByType
     * @apiParam {Number}  [orderByType]  排序类型(1:降序，2:升序) 可不传，默然为降序
     * @apiParam {String}  [start_time] 开始时间(可不传)
     * @apiParam {String}  [end_time] 结束时间(可不传)
     *
     * @apiSuccess {Number}  id 派单id.
     * @apiSuccess {String}  name 派单名称
     * @apiSuccess {Number}  distribution_channel_id 渠道id
     * @apiSuccess {String}  book_name 图书名称
     * @apiSuccess {Number}  book_id 书本id
     * @apiSuccess {Number}  totalChargeAmount 充值总额
     * @apiSuccess {String}  distribution_channel_name, 渠道名称
     * @apiSuccess {String}  charge_type 书本收费方式
     * @apiSuccess {Number}  cost 成本
     * @apiSuccess {String}  send_time 派单时间
     * @apiSuccess {Number}  half_day_charge_amount 12小时充值金额
     * @apiSuccess {Number}  weekend_charge_amount 7天充值金额
     * @apiSuccess {Number}  firstChargeUserNum 首充用户数
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {Number}  fansNum 粉丝数
     * @apiSuccess {Number}  registerNum 注册数
     * @apiSuccess {Number}  payUserNum 付费用户数
     * @apiSuccess {Number}  paid_num 成功订单数
     * @apiSuccess {Number}  unpaid_num 失败订单数
     * @apiSuccess {Number}  first_recharge_amount 首充总额
     * @apiSuccess {Number}  vipPayUserNum VIP付费用户数
     * @apiSuccess {Number}  normalPayUserNum 普通付费用户数
     * @apiSuccess {Number}  vipOrderCount vip用户订单数
     * @apiSuccess {Number}  pv pv数
     * @apiSuccess {Number}  uv uv数
     * @apiSuccess {Number}  total_pv 总pv数
     * @apiSuccess {Number}  total_uv 总uv数
     * @apiSuccess {Number}  sum_fee 订阅总额
     * @apiSuccess {Number}  sum_charge_balance 充值总额
     * @apiSuccess {Number}  sum_reward_balance 奖励总额
     * @apiSuccess {Number}  date 日期
     *
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *           {
     *              "id": 5,
     *              "name": "acai",
     *              "distribution_channel_id": "1234",
     *              "book_name": 书名,
     *              "book_id": 123,
     *              "totalChargeAmount": 12,
     *              "distribution_channel_name":"渠道名称1",
     *              "charge_type":"Book",
     *              "cost":111,
     *              "send_time": "2017-11-22 14:40:46",
     *              "weekend_charge_amount": 71,
     *              "half_day_charge_amount": 105,
     *              "firstChargeUserNum":0,
     *              "updated_at": "2017-11-22 14:40:46",
     *              "created_at": "2017-11-22 14:40:46",
     *              "fansNum": 0,
     *              "registerNum": 0,
     *              "payUserNum": 0,
     *              "paid_num": 123,
     *              "unpaid_num": 123,
     *              "first_recharge_amount": 123,
     *              "vipPayUserNum": 123,
     *              "normalPayUserNum": 123,
     *              'vipOrderCount': 123,
     *              "pv": 0,
     *              "uv":0,
     *              "total_pv":12,
     *              "total_uv":12,
     *              "date":"2017-11-22 14:40:46"
     *            },
     *           {
     *              "id": 5,
     *              "name": "acai",
     *              "distribution_channel_id": "1234",
     *              "book_name": 书名,
     *              "book_id": 123,
     *              "totalChargeAmount": 12,
     *              "distribution_channel_name":"渠道名称1",
     *              "charge_type":"Book",
     *              "cost":111,
     *              "send_time": "2017-11-22 14:40:46",
     *              "weekend_charge_amount": 71,
     *              "half_day_charge_amount": 105,
     *              "firstChargeUserNum":0,
     *              "updated_at": "2017-11-22 14:40:46",
     *              "created_at": "2017-11-22 14:40:46",
     *              "fansNum": 0,
     *              "registerNum": 0,
     *              "payUserNum": 0,
     *              "paid_num": 123,
     *              "unpaid_num": 123,
     *              "first_recharge_amount": 123,
     *              "vipPayUserNum": 123,
     *              "normalPayUserNum": 123,
     *              'vipOrderCount': 123,
     *              "pv": 0,
     *              "uv":0,
     *              "total_pv":12,
     *              "total_uv":12,
     *              "date":"2017-11-22 14:40:46"
     *            },
     *        ],
     *          "meta": {
     *                 "total": 1,
     *                 "per_page": 15,
     *                 "current_page": 1,
     *                 "last_page": 1,
     *                 "next_page_url": "",
     *                 "prev_page_url": ""
     *             }
     *     }
     */
    function getHistorySendOrders(Request $request)
    {
        $name = $request->has('name') ? $request->input('name') : '';
        $bid = $request->has('book_id') ? $request->input('book_id') : '';

        $order_field = $request->has('orderBy') ? $request->input('orderBy') : '';
        $order_type = $request->has('orderByType') && $request->input('orderByType') == 2 ? 'asc' : 'desc';//排序类型

        $order_status = $request->has('order_status') ? $request->input('order_status') : 0;//内外部派单 1内部 2外部

        $book_name = $request->has('bookName') ? $request->input('bookName') : '';
        $distribution_channel_id = $request->has('channel_id') ? $request->input('channel_id') : '';
        $send_order_id = $request->has('sendOrder_id') ? $request->input('sendOrder_id') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Y-m-d H:i:s', strtotime($request->input('end_time')) + 86400 - 1) : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? $request->input('start_time') : '';
        $gender = $request->has('gender') && !empty($request->input('gender')) ? $request->input('gender') : '';

        $params = compact('name', 'bid', 'book_name', 'distribution_channel_id', 'send_order_id', 'start_time', 'end_time', 'order_status', 'order_type', 'order_field', 'gender');

        $data = SendOrderStatService::getList($params);
        //SendStatistics
        foreach ($data as &$v) {
            $v->beforevipuv = 0;
            $v->beforeforcesubuv = 0;
            $res = SendStatistics::getBeforeForceSubAndBeforeVipUv($v->bid, $v->send_order_id, date('Y-m-d', strtotime($v->create_time)), false);
            $v->beforevipuv = $res['before_vip'];
            $v->beforeforcesubuv = $res['before_forcesub'];
        }
        return response()->pagination(new SendOrderStatTransformer(), $data);
    }

    /**
     * @apiVersion 1.0.0
     * @api {GET} sendOrder/exportHistorySendOrders 导出历史派单列表
     * @apiGroup sendOrder
     * @apiName exportHistorySendOrders
     * @apiParam   {Number}  [sendOrder_id]  派单id(可不传)
     * @apiParam   {Number}  [book_id]  书本id(可不传)
     * @apiParam   {String}  [name]  派单名称(可不传)
     * @apiParam {Number}  [orderByType]  排序类型(1:降序，2:升序) 可不传，默然为降序
     * @apiParam {Number}  [order_status]  内外部派单(1： 内部派单， 2：外部派单)
     * @apiParam   {Number}  [orderBy]  排序(1:12小时，2:7天, 3：充值总额， 4：首充总额) 可不传，默然为创建时间排序   orderByType
     * @apiParam   {String}  [bookName]  书本名称(可不传)
     * @apiParam   {Number}  [channel_id]  渠道id(可不传)
     * @apiParam   {String}  [start_time] 开始时间(可不传)
     * @apiParam   {String}  [end_time] 结束时间(可不传)
     *
     * @apiSuccess {Number}  id 派单id.
     * @apiSuccess {String}  name 派单名称
     * @apiSuccess {Number}  distribution_channel_id 渠道id
     * @apiSuccess {String}  book_name 图书名称
     * @apiSuccess {Number}  book_id 书本id
     * @apiSuccess {Number}  totalChargeAmount 充值总额
     * @apiSuccess {String}  distribution_channel_name, 渠道名称
     * @apiSuccess {String}  charge_type 书本收费方式
     * @apiSuccess {Number}  cost 成本
     * @apiSuccess {String}  send_time 派单时间
     * @apiSuccess {Number}  half_day_charge_amount 12小时充值金额
     * @apiSuccess {Number}  weekend_charge_amount 7天充值金额
     * @apiSuccess {Number}  firstChargeUserNum 首充用户数
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {Number}  fansNum 粉丝数
     * @apiSuccess {Number}  registerNum 注册数
     * @apiSuccess {Number}  payUserNum 付费用户数
     * @apiSuccess {Number}  paid_num 成功订单数
     * @apiSuccess {Number}  unpaid_num 失败订单数
     * @apiSuccess {Number}  first_recharge_amount 首充总额
     * @apiSuccess {Number}  vipPayUserNum VIP付费用户数数
     * @apiSuccess {Number}  normalPayUserNum 普通付费用户数数
     * @apiSuccess {Number}  pv pv数
     * @apiSuccess {Number}  uv uv数
     * @apiSuccess {Number}  total_pv 总pv数
     * @apiSuccess {Number}  total_uv 总uv数
     * @apiSuccess {Number}  date 日期
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": [
     *           {
     *              "id": 5,
     *              "name": "acai",
     *              "distribution_channel_id": "1234",
     *              "book_name": "书名",
     *              "book_id": 123,
     *              "totalChargeAmount": 12,
     *              "distribution_channel_name":"渠道名称1",
     *              "charge_type":"Book",
     *              "cost":111,
     *              "send_time": "2017-11-22 14:40:46",
     *              "weekend_charge_amount": 71,
     *              "half_day_charge_amount": 105,
     *              "firstChargeUserNum":0,
     *              "updated_at": "2017-11-22 14:40:46",
     *              "created_at": "2017-11-22 14:40:46",
     *              "fansNum": 0,
     *              "registerNum": 0,
     *              "payUserNum": 0,
     *              "paid_num": 123,
     *              "unpaid_num": 123,
     *              "first_recharge_amount": 123,
     *              "vipPayUserNum": 123,
     *              "normalPayUserNum": 123,
     *              "pv": 0,
     *              "uv":0,
     *              "total_pv":12,
     *              "total_uv":12,
     *              "date":"2017-11-22 14:40:46"
     *            },
     *           {
     *              "id": 5,
     *              "name": "acai",
     *              "distribution_channel_id": "1234",
     *              "book_name": "书名",
     *              "book_id": 123,
     *              "totalChargeAmount": 12,
     *              "distribution_channel_name":"渠道名称1",
     *              "charge_type":"Book",
     *              "cost":111,
     *              "send_time": "2017-11-22 14:40:46",
     *              "weekend_charge_amount": 71,
     *              "half_day_charge_amount": 105,
     *              "firstChargeUserNum":0,
     *              "updated_at": "2017-11-22 14:40:46",
     *              "created_at": "2017-11-22 14:40:46",
     *              "fansNum": 0,
     *              "registerNum": 0,
     *              "payUserNum": 0,
     *              "paid_num": 123,
     *              "unpaid_num": 123,
     *              "first_recharge_amount": 123,
     *              "vipPayUserNum": 123,
     *              "normalPayUserNum": 123,
     *              "pv": 0,
     *              "uv":0,
     *              "total_pv":12,
     *              "total_uv":12,
     *              "date":"2017-11-22 14:40:46"
     *            },
     *        ],
     *     }
     */
    function exportHistorySendOrders(Request $request)
    {
        \Log::info($request->all());
        $name = $request->has('name') ? $request->input('name') : '';
        $bid = $request->has('book_id') ? $request->input('book_id') : '';
        $order_field = $request->has('orderBy') ? $request->input('orderBy') : '';
        $order_type = $request->has('orderByType') && $request->input('orderByType') == 2 ? 'asc' : 'desc';//排序类型
        $order_status = $request->has('order_status') ? $request->input('order_status') : 0;//内外部派单 1内部 2外部
        $book_name = $request->has('bookName') ? $request->input('bookName') : '';
        $distribution_channel_id = $request->has('channel_id') ? $request->input('channel_id') : '';
        $send_order_id = $request->has('sendOrder_id') ? $request->input('sendOrder_id') : '';
        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Y-m-d H:i:s', strtotime($request->input('end_time')) + 86400 - 1) : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? $request->input('start_time') : '';

        $params = compact('name', 'bid', 'book_name', 'distribution_channel_id', 'send_order_id', 'start_time', 'end_time', 'order_status', 'order_type', 'order_field');
        \Log::info('params is:');
        \Log::info($request->all());

        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . "派单历史数据" . date("YmdHis") . ".csv");

        echo iconv("UTF-8", "GBK", "\"创建时间\",\"派单实际发送时间\",\"派单ID\",\"派单名称\",\"渠道ID\",\"推广书籍名称\",\"推广书籍ID\",\"收费方式\",\"充值金额\",\"渠道名称\",\"成本\",\"派单实际发送时间\",\"12小时充值金额\",\"7天充值金额\",\"24小时充值金额\",\"3天充值金额\",\"首充用户数\",\"数据更新时间\",\"粉丝数\",\"注册用户数\",\"付费用户数\",\"成功订单数\",\"失败订单数\",\"首充总数\",\"VIP付费用户数\",\"普通付费用户数\",\"pv\",\"uv\",\"24小时uv\",\"24小时pv\",\"vip前一章uv\",\"强关前一章uv\"\r\n");

        $obj = SendOrderStatService::getObj($params);
        $obj->chunk(2000, function ($send_orders) {

            foreach ($send_orders as $item) {
                $res = SendStatistics::getBeforeForceSubAndBeforeVipUv($item->bid, $item->send_order_id, date('Y-m-d', strtotime($item->create_time)), false);

                echo("\"" . $item->create_time . "\",");
                echo("\"" . $item->send_time . "\",");
                echo("\"" . $item->send_order_id . "\",");
                echo("\"" . mb_convert_encoding(($item->name ? $item->name : "未填"), "GBK") . "\",");
                echo("\"" . $item->distribution_channel_id . "\",");
                echo("\"" . mb_convert_encoding(($item->book_name ? $item->book_name : "未填"), "GBK") . "\",");
                echo("\"" . $item->bid . "\",");
                echo("\"" . $item->charge_type . "\",");
                echo("\"" . $item->recharge_amount . "\",");
                echo("\"" . mb_convert_encoding(($item->distribution_channel_name ? $item->distribution_channel_name : "未填"), "GBK") . "\",");
                echo("\"" . $item->cost . "\",");
                echo("\"" . $item->send_time . "\",");
                echo("\"" . $item->recharge_amount_in_half_day . "\",");
                echo("\"" . $item->recharge_amount_in_two_weeks . "\",");
                echo("\"" . $item->recharge_amount_in_one_day . "\",");
                echo("\"" . $item->recharge_amount_in_three_days . "\",");
                echo("\"" . $item->first_recharge_user_num . "\",");
                echo("\"" . date("Y-m-d H:i:s", strtotime($item->updated_at)) . "\",");
                echo("\"" . $item->force_user_num . "\",");
                echo("\"" . $item->register_user_num . "\",");
                echo("\"" . $item->pay_user_num . "\",");
                echo("\"" . $item->paid_num . "\",");
                echo("\"" . $item->unpaid_num . "\",");
                echo("\"" . $item->first_recharge_amount . "\",");
                echo("\"" . $item->year_recharge_user_num . "\",");
                echo("\"" . $item->ticket_recharge_user_num . "\",");
                echo("\"" . $item->pv . "\",");
                echo("\"" . $item->uv . "\",");
                //24小时pv、uv
                $extra_stat = SendOrderService::getExtraStat($item->send_order_id);
                $uv_one_day = $extra_stat ? $extra_stat->uv_one_day : 0;
                $pv_one_day = $extra_stat ? $extra_stat->pv_one_day : 0;
                echo("\"" . $uv_one_day . "\",");
                echo("\"" . $pv_one_day . "\",");
                echo("\"" . $res['before_vip'] . "\",");
                echo("\"" . $res['before_forcesub'] . "\"\r\n");
            }
        });
        exit();
    }

    /**
     * 加密站点id
     * @param Request $request
     */
    function encodeSiteId(Request $request)
    {
        $siteId = $request->has('siteId') ? $request->input('siteId') : '';
        if (empty($siteId)) {
            return response()->error("PARAM_EMPTY");
        }

        if (!is_numeric($siteId)) {
            return response()->error("PARAM_ERROR");
        }
        $siteId = encodeDistributionChannelId($siteId);
        $url = "https://site" . $siteId . ".leyuee.com";
        return response()->success(['url' => $url]);
    }
}