<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2017/11/22
 * Time: 11:36
 */

namespace App\Http\Controllers\Channel\SendOrder;

use App\Http\Controllers\Channel\BaseController;
use App\Http\Controllers\Channel\SendOrder\Transformers\SendOrderTransformer;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\Book\Services\ChapterService;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\Promotion\Services\PromotionService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Statistic\Services\WapVisitStatService;
use App\Modules\Trade\Services\OrderService;
use App\Modules\User\Services\UserService;
use DB;
use  Hashids;

use Illuminate\Http\Request;

class SendOrderController extends BaseController
{
    /**
     * @apiDefine sendOrder 派单
     */

    /**
     * @apiVersion 1.0.0
     * @api {GET} sendOrder/getSendOrders 获取派单列表
     * @apiGroup sendOrder
     * @apiName getSendOrders
     * @apiParam{Number}  [sendOrder_id]  派单id(可不传)
     * @apiParam{Number}  [book_id]  书本id(可不传)
     * @apiParam{String}  [name]  派单名称(可不传)
     * @apiParam{String}  [book_name] 书名(可不传)
     * @apiParam{String}  [start_time] 开始时间(可不传)
     * @apiParam{String}  [end_time] 结束时间(可不传)
     * @apiParam{String}  [pre_send_date_start] 预计发布时间开始(可不传)
     * @apiParam{String}  [pre_send_date_end] 预计发布时间结束(可不传)
     * @apiParam{String}  [promotion_point] 派单源 微信(默认)or浏览器(微信:1,浏览器:2)
     * @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}  qr_code_id  二维码
     * @apiSuccess {Number}  subscribe_chapter_id 关注章节ID
     * @apiSuccess {Number}  document_end_chapter_seq 结束章节序号
     * @apiSuccess {String}  book_name 图书名称
     * @apiSuccess {String}  chapter_name 章节名称
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  pre_send_date 预计发布时间
     * @apiSuccess {String}  sex_preference 性别偏好
     * @apiSuccess {String}  subscribe_chapter_name 关注章节名称
     * @apiSuccess {String}  subscribe_chapter_seq 关注章节序号
     * @apiSuccess {Number}  remark 备注
     * @apiSuccess {Number}  star_num 星星数
     * @apiSuccess {Number}  cost 成本
     * @apiSuccess {Number}  totalChargeAmount 充值总额数
     * @apiSuccess {Number}  registerNum 注册数
     * @apiSuccess {Number}  payUserNum 付费用户数
     * @apiSuccess {Number}  clickNum 点击数数
     * @apiSuccess {Number}  browserClickNum 浏览器端pv
     * @apiSuccess {Number}  browserClickNumUV 浏览器端uv
     * @apiSuccess {Number}  fansNum 粉丝数
     * @apiSuccess {Number}  promotion_page_id  推广页面id
     * @apiSuccess {String}  redirect_url 重定向url
     * @apiSuccess {String}  qrcode 二维码
     * @apiSuccess {String}  domain 域名
     * @apiSuccess {String}  consumeTotalFee 派单下的消费的币的总和
     * @apiSuccess {String}  consumeChargeFee 派单下的消费的充值币
     * @apiSuccess {String}  consumeRewardFee 派单下的消费的奖励币
     * @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,
     *               "document_end_chapter_seq"=12.
     *               "sex_preference": "男频",
     *               "chapter_name": null,
     *               "updated_at": "2017-11-22 14:40:46",
     *               "created_at": "2017-11-22 14:40:46",
     *               "pre_send_date": "2018/11/12"
     *               "subscribe_chapter_name": null,
     *               "subscribe_chapter_seq": null,
     *               "remark": "0",
     *              "star_num": 0,
     *              "fansNum": 0,
     *              "cost":1111
     *              "totalChargeAmount": 0,
     *              "registerNum": 0,
     *              "payUserNum": 0,
     *              "clickNum": 0,
     *              "promotion_page_id": 1111,
     *              "redirect_url": ""
     *              "qrcode": ""
     *              "domain":"leque"
     *             "toatlOrderCount":12,
     *             "vipOrderCount":12,
     *             "normalOrderCount":12,
     *            },
     *           {
     *              "id": 11,
     *             "distribution_channel_id": 123,
     *             "entrance": null,
     *             "name": "acai",
     *             "book_id": 111,
     *             "cost":1111
     *             "channel_type": "AUTHENTICATED",
     *             "chapter_id": 1111,
     *             "document_cover_id": 899,
     *             "headline_id": 12334,
     *             "body_template_id": 3455,
     *             "document_end_chapter_seq"=12.
     *             "original_guide_id": 344,
     *             "subscribe_chapter_id": 11111,
     *             "book_name": "dpcq",
     *             "sex_preference": "男频",
     *             "chapter_name": "ssss",
     *              "domain":"leque"
     *             "updated_at": "2017-11-22 14:40:46",
     *             "created_at": "2017-11-22 14:40:46",
     *             "subscribe_chapter_name": null,
     *             "subscribe_chapter_seq": null,
     *             "remark": "0",
     *             "star_num": 0,
     *             "fansNum": 0,
     *             "totalChargeAmount": 0,
     *             "addUserNum": 0,
     *             "payUserNum": 0,
     *             "clickNum": 0,
     *             "toatlOrderCount":12,
     *             "vipOrderCount":12,
     *             "normalOrderCount":12,
     *             "promotion_page_id": null,
     *             "redirect_url": ""
     *             "qrcode": ""
     *            }
     *        ],
     *          "meta": {
     *                 "total": 1,
     *                 "per_page": 15,
     *                 "current_page": 1,
     *                 "last_page": 1,
     *                 "next_page_url": "",
     *                 "prev_page_url": ""
     *             }
     *     }
     */
    function getSendOrders(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $name = $request->has('name') ? $request->input('name') : '';
        $book_id = $request->has('book_id') ? $request->input('book_id') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $id = $sendOrderId = $request->has('sendOrder_id') ? $request->input('sendOrder_id') : '';
        $promotion_type = $request->has('promotion_type') ? $request->input('promotion_type') : '';
        $import_company_name = $request->has('company_name') ? $request->input('company_name') : '';
        $pre_send_date_end = $request->has('pre_send_date_end') ? $request->input('pre_send_date_end') : '';
        $pre_send_date_start = $request->has('pre_send_date_start') ? $request->input('pre_send_date_start') : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? $request->input('start_time') : '';
        $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) : '';
        $promotion_point = $request->has('promotion_point') ? $request->input('promotion_point') : 1;
        //$data = SendOrderService::getSendOrders($bookId, $distribution_channel_id, $name, $bookName, $sendOrderId, $start_time, $end_time, false);
        $data = SendOrderService::search(compact(
            'book_id',
            'distribution_channel_id',
            'name',
            'pre_send_date_end',
            'import_company_name',
            'pre_send_date_start',
            'promotion_type',
            'pre_send_date',
            'book_name',
            'start_time',
            'end_time',
            'id',
            'promotion_point'
        ));

        $send_order_export_special_channel = env('SEND_ORDER_EXPORT_SPECIAL_CHANNEL');
        $isExistSpecialChannel = in_array($distribution_channel_id, explode(',', $send_order_export_special_channel));

        foreach ($data as $item) {
            $itemName = $item->name;
            if ($isExistSpecialChannel) {
                if (strpos($itemName, "-")) {
                    $strs = explode('-', $itemName);
                    if (count($strs) == 4) {
                        $date = $this->getFormatDate($strs[2], $item->created_at);
                        $strs[2] = date('Y/m/d', strtotime($date));
                        $itemName = implode('-', $strs);
                        if (!$item->pre_send_date) {
                            $item->pre_send_date = $date;
                        }
                    } elseif (count($strs) == 6) {
                        $date = $this->getFullDate($strs[2], $strs[3], $strs[4], $item->created_at);
                        if (!$item->pre_send_date) {
                            $item->pre_send_date = $date;
                        }
                        $itemName = $strs[0] . '-' . $strs[1] . '-' . $date . '-' . $strs[5];
                    }
                }
            }

            $sendOrderId = $item->id;
            $item->name = $itemName;
            $browser_visit_info = SendOrderService::getBrowserUvAndPv($sendOrderId);
            $item->browserClickNum = $browser_visit_info['pv'];
            $item->browserClickNumUV = $browser_visit_info['uv'];
            $item->clickNum = SendOrderService::getPv($sendOrderId);
            $item->clickNumUV = SendOrderService::getUv($sendOrderId);//uv
            $item->payUserNum = OrderService::getPayUserNum($sendOrderId);
            $item->registerNum = UserService::getPromotionTotal($sendOrderId);
            $item->fansNum = ForceSubscribeService::getNewFansNum($sendOrderId);
            $item->continue_read_uv = SendOrderService::getContinueTotalReadUv($item->id);

            if ($promotion_point == 2) {
                $item->promotion_url = 'https://bsite' . encodeDistributionChannelId($distribution_channel_id) . '.leyuee.com/yun/' . $item->id;
            } else {
                $item->promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . $this->getDomainByBid($item->book_id) . '/yun/' . $item->id;
            }
            $item->totalChargeAmount = (float)OrderService::getAmount(['send_order_id' => $sendOrderId]);
//            $item->totalChargeAmount = OrderService::getPromotionRegUserRechargeAmount(['send_order_id' => $item->id]);
            $item->qrcode = "";//"data:image/png;base64," . base64_encode(QrCode::format('png')->size(200)->generate($promotion_url));

//            $bookOrderInfo = BookOrderService::getSendorderTotal($sendOrderId, $start_time, $end_time);
//            $chapterOrderInfo = ChapterOrderService::getSendorderTotal($sendOrderId, $start_time, $end_time);
            $item->consumeChargeFee = 0;//$bookOrderInfo['charge_balance'] + $chapterOrderInfo['charge_balance'];
            $item->consumeRewardFee = 0;//$bookOrderInfo['reward_balance'] + $chapterOrderInfo['reward_balance'];;
            $item->consumeTotalFee = 0;//$item->consumeChargeFee + $item->consumeRewardFee;
        }
        return response()->pagination(new SendOrderTransformer, $data);
    }

    function getFullDate($year, $month, $day, $created_at = '')
    {
        if (strlen($year) != 4) {
            if ($created_at) {
                $year = date('Y', strtotime($created_at));
            } else {
                $year = date('Y');
            }
        }

        if (strlen($month) == 1) {
            $month = '0' . $month;
        }

        if (strlen($day) == 1) {
            $day = '0' . $day;
        }

        $date = $year . $month . $day;
        $date = date('Y/m/d', strtotime($date));
        return $date;
    }

    function getFormatDate($date, $created_at = '')
    {
        $count = strlen($date);
        if ($created_at) {
            $year = date('Y', strtotime($created_at));
        } else {
            $year = date('Y');
        }

        if (2 == $count) {
            $date = $year . '0' . $date[0] . '0' . $date[1];
        } elseif (3 == $count) {
            if (0 === strpos($date, '0')) {
                $date = $year . substr($date, 0, 2) . '0' . $date[2];
            } else {
                $date = $year . '0' . $date;
            }
        } elseif (4 == $count) {
            $date = $year . $date;
        }
        return $date;
    }

    /**
     * 根据图书id获取域名
     * @param $bid
     */
    function getDomainByBid($bid = '')
    {
        $domain = 'leyuee.com';
        //如果图书id为空，则返回默认的域名
        if (!empty($bid)) {
            $bookConfig = BookConfigService::getBookById($bid);
            if ($bookConfig) {
                $domain = $bookConfig->promotion_domain;
            }
        }
        return $domain;
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 派单列表导出
     * @api {GET} sendOrder/exportSendOrders 派单列表导出
     * @apiGroup sendOrder
     * @apiName exportSendOrders
     * @apiParam{Number}  [sendOrder_id]  派单id(可不传)
     * @apiParam{Number}  [book_id]  书本id(可不传)
     * @apiParam{String}  [book_name] 书名(可不传)
     * @apiParam{String}  [name]  派单名称(可不传)
     * @apiParam{String}  [pre_send_date_start] 预计发布时间开始(可不传)
     * @apiParam{String}  [pre_send_date_end] 预计发布时间结束(可不传)
     * @apiParam{String}  [start_time] 开始时间(可不传)
     * @apiParam{String}  [end_time] 结束时间(可不传)
     * @apiParam{String}  [promotion_point] 派单源 微信(默认)or浏览器(微信:1,浏览器:2)
     * @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 {Number}  cost 成本
     * @apiSuccess {String}  updated_at 更新时间
     * @apiSuccess {String}  created_at 创建时间
     * @apiSuccess {String}  subscribe_chapter_name 关注章节名称
     * @apiSuccess {String}  subscribe_chapter_seq 关注章节序号
     * @apiSuccess {Number}  remark 备注
     * @apiSuccess {Number}  star_num 星星数
     * @apiSuccess {Number}  totalChargeAmount 充值总额数
     * @apiSuccess {Number}  registerNum 注册数
     * @apiSuccess {Number}  payUserNum 付费用户数
     * @apiSuccess {Number}  clickNum 点击数数
     * @apiSuccess {Number}  fansNum 粉丝数
     * @apiSuccess {Number}  promotion_page_id  推广页面id
     * @apiSuccess {String}  redirect_url 重定向url
     * @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",
     *                "subscribe_chapter_name": null,
     *                "subscribe_chapter_seq": null,
     *                "remark": "0",
     *                "star_num": 0,
     *                "fansNum": 0,
     *               "cost":111,
     *              "totalChargeAmount": 0,
     *              "registerNum": 0,
     *              "payUserNum": 0,
     *              "clickNum": 0,
     *                "promotion_page_id": 1111,
     *               "redirect_url": ""
     *            },
     *           {
     *              "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,
     *             "original_guide_id": 344,
     *             "subscribe_chapter_id": 11111,
     *             "book_name": "dpcq",
     *             "cost":1111
     *             "chapter_name": "ssss",
     *             "updated_at": "2017-11-22 14:40:46",
     *             "created_at": "2017-11-22 14:40:46",
     *             "subscribe_chapter_name": null,
     *             "subscribe_chapter_seq": null,
     *             "remark": "0",
     *             "star_num": 0,
     *              "fansNum": 0,
     *              "totalChargeAmount": 0,
     *              "addUserNum": 0,
     *              "payUserNum": 0,
     *              "clickNum": 0,
     *             "promotion_page_id": null,
     *             "redirect_url": ""
     *            }
     *        ],
     *          "meta": {
     *                 "total": 1,
     *                 "per_page": 15,
     *                 "current_page": 1,
     *                 "last_page": 1,
     *                 "next_page_url": "",
     *                 "prev_page_url": ""
     *             }
     *     }
     */
    function exportSendOrders(Request $request)
    {
        set_time_limit(0);
        $distribution_channel_id = $this->getChannelId();
        $name = $request->has('name') ? $request->input('name') : '';
        $book_id = $request->has('book_id') ? $request->input('book_id') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $id = $request->has('sendOrder_id') ? $request->input('sendOrder_id') : '';
        $promotion_type = $request->has('promotion_type') ? $request->input('promotion_type') : '';
        $pre_send_date_end = $request->has('pre_send_date_end') ? $request->input('pre_send_date_end') : '';
        $import_company_name = $request->has('company_name') ? $request->input('company_name') : '';
        $pre_send_date_start = $request->has('pre_send_date_start') ? $request->input('pre_send_date_start') : '';
        $start_time = $request->has('start_time') && !empty($request->input('start_time')) ? $request->input('start_time') : '';
        $promotion_point = $request->has('promotion_point') ? $request->input('promotion_point') : 1;

        $send_order_export_special_channel = env('SEND_ORDER_EXPORT_SPECIAL_CHANNEL');
        $isExistSpecialChannel = in_array($distribution_channel_id, explode(',', $send_order_export_special_channel));

        $end_time = $request->has('end_time') && !empty($request->input('end_time')) ? date('Y-m-d H:i:s', strtotime(trim($request->input('end_time'))) + 86400 - 1) : '';
        //$data = SendOrderService::getSendOrders($bookId, $distribution_channel_id, $name, $bookName, $sendOrderId, $start_time, $end_time, true);
        $data = SendOrderService::search(compact('book_id', 'distribution_channel_id', 'name', 'import_company_name', 'pre_send_date_end', 'pre_send_date_start', 'promotion_type', 'book_name', 'start_time', 'end_time', 'id', 'promotion_point'), true);
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . "派单列表" . date("YmdHis") . ".csv");
        $specialChannelIdStats = env('SPECIAL_CHANNEL_STATS', 211);
        if ($isExistSpecialChannel) {
            if (in_array($distribution_channel_id, explode(',', $specialChannelIdStats))) {
                echo mb_convert_encoding("\"推广名称\",\"预计发送时间\",\"推广员\",\"书名\",\"点击数\",\"新增用户\",\"注册用户数\",\"新增关注\",\"新增关注率\",\"新关成本\",\"付费用户\",\"首充用户数\",\"成本\",\"累计充值\",\"累计充值成本率\",\"72小时累计充值总额\",\"72小时累计充值回本率\",\"7日充值总额\",\"公司名称\",\"总粉丝数\",\"累计UV大于20的时间\",\"推广位置\",\"小说来源\",\"推广链接\",\"章节名称\",\"充值总额\",\"充值成本率\",\"30日充值总额\",\"30日回本率\",\"24小时充值总额\",\"24小时回本率\",\"72小时充值总额\",\"72小时回本率\",\"30日累计充值总额\",\"30日累计充值回本率\",\"60日累计充值总额\",\"创建时间\",\"首日累计订阅人数\",\"首日累计订阅总额\",\"三日累计订阅人数\",\"三日累计订阅总额\",\"累计订阅人数\",\"累计订阅总额\"\r\n", 'GBK', 'UTF-8');
            } else {
                echo mb_convert_encoding("\"推广名称\",\"预计发送时间\",\"推广员\",\"书名\",\"点击数\",\"新增用户\",\"注册用户数\",\"新增关注\",\"新增关注率\",\"新关成本\",\"付费用户\",\"首充用户数\",\"成本\",\"累计充值\",\"累计充值成本率\",\"72小时累计充值总额\",\"72小时累计充值回本率\",\"7日充值总额\",\"公司名称\",\"总粉丝数\",\"累计UV大于20的时间\",\"推广位置\",\"小说来源\",\"推广链接\",\"章节名称\",\"充值总额\",\"充值成本率\",\"30日充值总额\",\"30日回本率\",\"24小时充值总额\",\"24小时回本率\",\"72小时充值总额\",\"72小时回本率\",\"30日累计充值总额\",\"30日累计充值回本率\",\"60日累计充值总额\",\"创建时间\"\r\n", 'GBK', 'UTF-8');
            }
        } else {
            echo mb_convert_encoding("\"推广名称\",\"推广链接\",\"书名\",\"章节名称\",\"点击数\",\"新增用户\",\"注册用户数\",\"新增关注\",\"新增关注率\",\"付费用户\",\"首充用户数\",\"充值总额\",\"成本\",\"充值成本率\",\"24小时充值总额\",\"24小时回本率\",\"72小时充值总额\",\"72小时回本率\",\"30日累计充值总额\",\"60日累计充值总额\",\"创建时间\"\r\n", 'GBK', 'UTF-8');
        }

        if ($data) {
            foreach ($data as $item) {

                $item->clickNum = SendOrderService::getPv($item->id);
                $item->clickNumUV = SendOrderService::getUv($item->id);//uv
                $item->payUserNum = OrderService::getPayUserNum($item->id);
                $item->fansNum = ForceSubscribeService::getNewFansNum($item->id);
                $item->registerNum = UserService::getPromotionTotal($item->id);
                $item->totalChargeAmount = (float)OrderService::getAmount(['send_order_id' => $item->id]);
//                $item->totalChargeAmount = OrderService::getPromotionRegUserRechargeAmount(['send_order_id' => $item->id]);

                $itemName = $item->name;
                $promotionUrl = "https://site" . $distribution_channel_id . "." . ($this->getDomainByBid($item->book_id ? $item->book_id : '')) . "/yun/" . $item->id;

                /*$stats_obj = SendOrderStat::where('send_order_id',$item->id)->first();
                $item->one_day_recharge = $stats_obj->recharge_amount_in_one_day;
                $item->three_days_recharge = $stats_obj->recharge_amount_in_three_days;*/

                //计算123 渠道号的 24小时 、72小时、7天,30日充值成本和回本
                $oneDayChargeAmount = 'NAV';
                $threeDayChargeAmount = 'NAV';
                $sevenDayChargeAmount = 'NAV';
                $thirtyDayChargeAmount = 'NAV';
                $promotionRegUserRecharge = 0;  //累计充值
                $promotionRegUserRechargeAmountInOneMonth = 0; //30天累计充值
                $promotionRegUserRechargeAmountInTwoMonth = 0; //60天累计充值
                $promotionRegUserRechargeAmountInThreeDays = 0; //72小时累计充值

                $firstChargeUserNum = SendOrderService::getFirstChargeUserNum($item->id);

                $uv20Time = $item->send_time;//SendOrderService::getUv20Time($item->id);
                if ($uv20Time) {
                    $send_time_24h_later = strtotime($uv20Time) + 86400;
                    $send_time_72h_later = strtotime($uv20Time) + 3 * 86400;
                    $send_time_7d_later = strtotime($uv20Time) + 7 * 86400;
                    $send_time_30d_later = strtotime($uv20Time) + 30 * 86400;
                    $promotionRegUserRecharge = OrderService::getPromotionRegUserRechargeAmount(['send_order_id' => $item->id]);
                    $promotionRegUserRechargeAmountInOneMonth = OrderService::getPromotionRegUserRechargeAmount(['send_order_id' => $item->id, 'end_time' => date("Y-m-d H:i:s", strtotime($uv20Time) + 30 * 86400)]);
                    $promotionRegUserRechargeAmountInThreeDays = OrderService::getPromotionRegUserRechargeAmount(['send_order_id' => $item->id, 'end_time' => date("Y-m-d H:i:s", strtotime($uv20Time) + 3 * 86400)]);
                    $promotionRegUserRechargeAmountInTwoMonth = OrderService::getPromotionRegUserRechargeAmount(['send_order_id' => $item->id, 'end_time' => date("Y-m-d H:i:s", strtotime($uv20Time) + 60 * 86400)]);

                    //计算24小时内的充值
                    if ($send_time_24h_later < time()) {
                        $selctEndTime = date('Y-m-d H:i:s', $send_time_24h_later);
                        $oneDayChargeAmount = OrderService::getAmount(['send_order_id' => $item->id, 'begin_time' => $uv20Time, 'end_time' => $selctEndTime]);
                    }

                    //计算72小时内的充值
                    if ($send_time_72h_later < time()) {
                        $selctEndTime = date('Y-m-d H:i:s', $send_time_72h_later);
                        $threeDayChargeAmount = OrderService::getAmount(['send_order_id' => $item->id, 'begin_time' => $uv20Time, 'end_time' => $selctEndTime]);
                    }

                    //计算7日内的充值
                    if ($send_time_7d_later < time()) {
                        $selctEndTime = date('Y-m-d H:i:s', $send_time_7d_later);
                        $sevenDayChargeAmount = OrderService::getAmount(['send_order_id' => $item->id, 'begin_time' => $uv20Time, 'end_time' => $selctEndTime]);
                    }

                    //计算30日内的充值
                    if ($send_time_30d_later < time()) {
                        $selctEndTime = date('Y-m-d H:i:s', $send_time_30d_later);
                        $thirtyDayChargeAmount = OrderService::getAmount(['send_order_id' => $item->id, 'begin_time' => $uv20Time, 'end_time' => $selctEndTime]);
                    }
                }

                if ($isExistSpecialChannel) {
                    $promotionSource = '-';

                    if (strpos($itemName, "-")) {
                        $strs = explode('-', $itemName);
                        if (count($strs) == 4) {
                            $date = $this->getFormatDate($strs[2], $item->created_at);
                            $date = date('Y/m/d', strtotime($date));
                            $promotionSource = $strs[1];
                            echo("\"" . mb_convert_encoding($strs[0], "GBK", "UTF-8") . "\",");
                            echo("\"" . $date . "\",");
                            echo("\"" . mb_convert_encoding($strs[3], "GBK", "UTF-8") . "\",");
                        } elseif (count($strs) == 6) {
                            $promotionSource = $strs[1];
                            $date = $this->getFullDate($strs[2], $strs[3], $strs[4], $item->created_at);
                            echo("\"" . mb_convert_encoding($strs[0], "GBK", "UTF-8") . "\",");
                            echo("\"" . $date . "\",");
                            echo("\"" . mb_convert_encoding($strs[5], "GBK", "UTF-8") . "\",");
                        } else {
                            echo("\"" . mb_convert_encoding($itemName, "GBK", "UTF-8") . "\",");
                            echo("\"" . mb_convert_encoding('-', "GBK", "UTF-8") . "\",");
                            echo("\"" . mb_convert_encoding('-', "GBK", "UTF-8") . "\",");
                        }
                    } else {
                        echo("\"" . mb_convert_encoding($itemName, "GBK", "UTF-8") . "\",");
                        echo("\"" . mb_convert_encoding('-', "GBK", "UTF-8") . "\",");
                        echo("\"" . mb_convert_encoding('-', "GBK", "UTF-8") . "\",");
                    }

                    echo("\"" . mb_convert_encoding($item->book_name ? $item->book_name : '书名为空', "GBK", "UTF-8") . "\",");
                    echo("\"" . $item->clickNum . "\",");
                    echo("\"" . $item->clickNumUV . "\",");
                    echo("\"" . $item->registerNum . "\",");
                    echo("\"" . $item->fansNum . "\",");
                    echo("\"" . ($this->getPersentAmount($item->fansNum, $item->registerNum)) . "\",");
                    echo("\"" . ((int)$item->fansNum != 0 ? round($item->cost / $item->fansNum, 2) : 0) . "\",");
                    echo("\"" . $item->payUserNum . "\",");
                    echo("\"" . $firstChargeUserNum . "\",");
                    echo("\"" . $item->cost . "\",");
                    echo("\"" . $promotionRegUserRecharge . "\",");
                    echo("\"" . ($this->getPersentAmount($promotionRegUserRecharge, $item->cost)) . "\",");
                    echo("\"" . mb_convert_encoding($promotionRegUserRechargeAmountInThreeDays, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($this->getPersentAmount($promotionRegUserRechargeAmountInThreeDays, $item->cost), "GBK", "UTF-8") . "\",");

                    echo("\"" . $sevenDayChargeAmount . "\",");
                    echo("\"" . mb_convert_encoding($item->import_company_name ? $item->import_company_name : '未填', "GBK", "UTF-8") . "\",");
                    echo("\"" . $item->fansNum . "\",");
                    echo("\"" . mb_convert_encoding($uv20Time ? $uv20Time : '未到20', "GBK", "UTF-8") . "\",");
                    echo("\"" . $promotionSource . "\",");
                    $cpSource = '未知';
                    if ($item->book_id) {
                        $bookConfig = BookConfigService::getBookById($item->book_id);
                        if ($bookConfig) {
                            $cpSource = $bookConfig->cp_source;
                        }
                    }

                    echo("\"" . mb_convert_encoding($cpSource, "GBK", "UTF-8") . "\",");
                    echo("\"" . $promotionUrl . "\",");
                    echo("\"" . mb_convert_encoding($item->chapter_name ? $item->chapter_name : '章节名称为空', "GBK", "UTF-8") . "\",");
                    echo("\"" . $item->totalChargeAmount . "\",");
                    echo("\"" . ($this->getPersentAmount($item->totalChargeAmount, $item->cost)) . "\",");
                    echo("\"" . mb_convert_encoding($thirtyDayChargeAmount, "GBK", "UTF-8") . "\",");
                    echo("\"" . ($this->getPersentAmount($thirtyDayChargeAmount, $item->cost)) . "\",");
                    echo("\"" . mb_convert_encoding($oneDayChargeAmount, "GBK", "UTF-8") . "\",");
                    echo("\"" . ($this->getPersentAmount($oneDayChargeAmount, $item->cost)) . "\",");
                    echo("\"" . mb_convert_encoding($threeDayChargeAmount, "GBK", "UTF-8") . "\",");
                    echo("\"" . ($this->getPersentAmount($threeDayChargeAmount, $item->cost)) . "\",");
                    echo("\"" . $promotionRegUserRechargeAmountInOneMonth . "\",");
                    //30日累计充值回本率
                    echo("\"" . mb_convert_encoding($this->getPersentAmount($promotionRegUserRechargeAmountInOneMonth, $item->cost), "GBK", "UTF-8") . "\",");
                    echo("\"" . $promotionRegUserRechargeAmountInTwoMonth . "\",");
                    //echo("\"" . $item->created_at->toDateTimeString() . "\"\r\n");

                    if (in_array($distribution_channel_id, explode(',', $specialChannelIdStats))) {
                        echo("\"" . $item->created_at->toDateTimeString() . "\",");
                        if ($item->send_time) {
                            $special_stats_date = date('Y-m-d', strtotime($item->send_time));
                        } else {
                            $special_stats_date = '';
                        }
                        $special_stats = WapVisitStatService::getSpecialChannelIdStats($item->id, $special_stats_date);
                        echo("\"" . $special_stats['first_day_subscribe_num'] . "\",");
                        echo("\"" . $special_stats['first_day_subscribe_amount'] . "\",");
                        echo("\"" . $special_stats['three_day_subscribe_num'] . "\",");
                        echo("\"" . $special_stats['three_day_subscribe_amount'] . "\",");
                        echo("\"" . $special_stats['total_subscribe_num'] . "\",");
                        echo("\"" . $special_stats['total_subscribe_amount'] . "\"\r\n");
                    } else {
                        echo("\"" . $item->created_at->toDateTimeString() . "\"\r\n");
                    }
                } else {
                    echo("\"" . mb_convert_encoding($itemName, "GBK", "UTF-8") . "\",");
                    echo("\"" . $promotionUrl . "\",");
                    echo("\"" . mb_convert_encoding($item->book_name ? $item->book_name : '书名为空', "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($item->chapter_name ? $item->chapter_name : '章节名称为空', "GBK", "UTF-8") . "\",");
                    echo("\"" . $item->clickNum . "\",");
                    echo("\"" . $item->clickNumUV . "\",");
                    echo("\"" . $item->registerNum . "\",");
                    echo("\"" . $item->fansNum . "\",");
                    echo("\"" . ($this->getPersentAmount($item->fansNum, $item->registerNum)) . "\",");
                    echo("\"" . $item->payUserNum . "\",");
                    echo("\"" . $firstChargeUserNum . "\",");
                    echo("\"" . $item->totalChargeAmount . "\",");
                    echo("\"" . $item->cost . "\",");
                    echo("\"" . ($this->getPersentAmount($item->totalChargeAmount, $item->cost)) . "\",");
                    echo("\"" . mb_convert_encoding($oneDayChargeAmount, "GBK", "UTF-8") . "\",");
                    echo("\"" . ($this->getPersentAmount($oneDayChargeAmount, $item->cost)) . "\",");
                    echo("\"" . mb_convert_encoding($threeDayChargeAmount, "GBK", "UTF-8") . "\",");
                    echo("\"" . ($this->getPersentAmount($threeDayChargeAmount, $item->cost)) . "\",");
                    echo("\"" . $promotionRegUserRechargeAmountInOneMonth . "\",");
                    echo("\"" . $promotionRegUserRechargeAmountInTwoMonth . "\",");
                    echo("\"" . $item->created_at->toDateTimeString() . "\"\r\n");
                }
            }
        }
        exit();
    }

    /**
     * 计算成本率
     * @param $amount 充值金额
     * @param $cost 成本
     * @return int|string
     */
    function getPersentAmount($amount, $cost)
    {
        if (is_numeric($amount)) {
            if (abs($cost) < 0.01) {
                $persentResult = '100%';
            } else {
                $persentResult = round(($amount / $cost) * 100, 2) . '%';
            }
        } else {
            $persentResult = '0%';
        }
        return $persentResult;
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 更新派单星级数和备注
     * @api {POST} sendOrder/updateStarNumAndRemark 更新派单星级数和备注
     * @apiGroup sendOrder
     * @apiName updateStarNumAndRemark
     * @apiParam{Number} id 派单id.
     * @apiParam{Number} distribution_channel_id 渠道id.
     * @apiParam{Number} star_num 派单星级数
     * @apiParam{String} remark 派单备注
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":[]
     *     }
     */
    function updateStarNumAndRemark(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $id = $request->has('id') ? $request->input('id') : '';
        $remark = $request->has('remark') ? $request->input('remark') : '';
        $starNum = $request->has('star_num') ? $request->input('star_num') : '';
        if (empty($id) || empty($distribution_channel_id) || empty($starNum)) {
            return response()->error("PARAM_EMPTY");
        }

        if (!is_numeric($starNum)) {
            return response()->error("PARAM_ERROR");
        }

        $data = SendOrderService::updateStarNumAndRemark($id, $distribution_channel_id, $starNum, $remark);
        if ($data) {
            return response()->success();
        }
        return response()->error("HANDLE_FAILED");
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 生成一个章节内容的派单
     * @api {POST} sendOrder/createFromChapter 生成一个章节内容的派单
     * @apiGroup sendOrder
     * @apiName createFromChapter
     * @apiParam   {String}  name 派单渠道名称.
     * @apiParam{Number} cost 成本.
     * @apiParam   {String}  distribution_channel_id 渠道id
     * @apiParam   {String}  channel_type 派单渠道类型.(允许值: AUTHENTICATED, UNAUTHENTICATED)
     * @apiParam   {String}  book_id  书本id
     * @apiParam   {String} promotion_type 推广类型[INTERVAL、EXTERVAL]. 内部、外部
     * @apiParam   {String}  book_name  书本名称
     * @apiParam   {String}  chapter_id  章节id
     * @apiParam   {String}  qr_code_id 二维码id.
     * @apiParam   {String}  chapter_name  章节名称
     * @apiParam   {String}  headline_id  推广标题id
     * @apiParam   {String}  body_template_id 内容模板id
     * @apiParam   {String}  document_cover_id  文案封面id
     * @apiParam   {String}  original_guide_id  原文引导ID.
     * @apiParam   {String}  subscribe_chapter_id  强制订阅章节id
     * @apiParam   {String}  subscribe_chapter_name  强制订阅章节名称
     * @apiParam   {String}  subscribe_chapter_seq 强制订阅章节序号
     * @apiParam   {String}  document_end_chapter_seq 最后章节序号
     * @apiParam   {String}  sex_preference 性别偏向
     * @apiParam{String}  [promotion_point] 派单源 微信(默认)or浏览器(微信:1,浏览器:2)
     * @apiSuccess {Number}  id 派单id
     * @apiSuccess {String}  promotion_url  推广链接
     * @apiSuccess {String}  name 派单名称
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{"id":5,"promotion_url":"http:\/\/www . xs . com\/promotion\/index\/123456"，"name":"派单名称"}
     *     }
     */
    function createFromChapter(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $name = $request->has('name') ? $request->input('name') : '';
        $promotion_type = $request->has('promotion_type') ? $request->input('promotion_type') : '';
        $cost = $request->has('cost') ? $request->input('cost') : 0;
        $book_id = $request->has('book_id') ? $request->input('book_id') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $chapter_id = $request->has('chapter_id') ? $request->input('chapter_id') : '';
        $qr_code_id = $request->has('qr_code_id') ? $request->input('qr_code_id') : '';
        $headline_id = $request->has('headline_id') ? $request->input('headline_id') : '';
        $chapter_name = $request->has('chapter_name') ? $request->input('chapter_name') : '';
        $channel_type = $request->has('channel_type') ? $request->input('channel_type') : '';
        $sex_preference = $request->has('sex_preference') ? $request->input('sex_preference') : '';
        $body_template_id = $request->has('body_template_id') ? $request->input('body_template_id') : '';
        $document_cover_id = $request->has('document_cover_id') ? $request->input('document_cover_id') : '';
        $original_guide_id = $request->has('original_guide_id') ? $request->input('original_guide_id') : '';
        $subscribe_chapter_id = $request->has('subscribe_chapter_id') ? $request->input('subscribe_chapter_id') : '';
        $subscribe_chapter_seq = $request->has('subscribe_chapter_seq') ? $request->input('subscribe_chapter_seq') : '';
        $subscribe_chapter_name = $request->has('subscribe_chapter_name') ? $request->input('subscribe_chapter_name') : '';
        $document_end_chapter_seq = $request->has('document_end_chapter_seq') ? $request->input('document_end_chapter_seq') : '';

        if (!$name || !$channel_type || !$promotion_type || !$book_id || !$book_name || !$sex_preference || !$document_end_chapter_seq || !$chapter_id || !$chapter_name || !$original_guide_id || !$headline_id || !$body_template_id || !$document_cover_id || !$document_cover_id || !$subscribe_chapter_id || !$subscribe_chapter_name || !$subscribe_chapter_seq) return response()->error('PARAM_EMPTY');

        if (empty($qr_code_id)) {
            $qr_code_id = 0;
        }

        $promotion_point = $request->has('promotion_point') ? $request->input('promotion_point') : 1;
        if (!in_array($promotion_point, [1, 2])) {
            $promotion_point = 1;
        }

        $redirect_url = "/reader?bid={$book_id}&cid={$chapter_id}";
        $book_id = Hashids::decode($book_id)[0];
        if ($book_id == 2423 && time() >= strtotime('2018-10-10 00:00:00') && time() <= strtotime('2018-10-15 00:00:00')) {
            return response()->error('CONTENT_MAINTAIN');
        }
        if ($promotion_point == 2) {
            $domain = 'leyuee.com';
        } else {
            $domain = $this->getDomainByBid($book_id);
        }
        $charge_type = $this->getBookChargeTypeByBid($book_id);
        $sendOrder = SendOrderService::createFromChapter(compact('name', 'channel_type', 'promotion_type', 'charge_type', 'cost', 'qr_code_id', 'domain', 'sex_preference', 'book_id', 'book_name', 'chapter_id', 'chapter_name', 'document_end_chapter_seq', 'original_guide_id', 'headline_id', 'body_template_id', 'document_cover_id', 'subscribe_chapter_id', 'subscribe_chapter_name', 'subscribe_chapter_seq', 'distribution_channel_id', 'redirect_url', 'promotion_point'));


        if ($promotion_point == 2) {
            $promotion_url = 'https://bsite' . encodeDistributionChannelId($distribution_channel_id) . '.leyuee.com/yun/' . $sendOrder->id;
        } else {
            $promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . $this->getDomainByBid($book_id) . '/yun/' . $sendOrder->id;
        }
        return response()->success(['id' => $sendOrder->id, 'promotion_url' => $promotion_url, 'name' => $name]);
    }

    /**
     * 通过推广模板图片生成
     * @param Request $request
     * @return mixed
     */
    function createFromPromotionImageTemplate(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $book_id = $request->has('book_id') ? $request->input('book_id') : '';


        $cost = $request->has('cost') ? $request->input('cost') : '';
        $name = $request->has('name') ? $request->input('name') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $promotion_point = $request->has('promotion_point') ? $request->input('promotion_point') : '';
        $promotion_type = $request->has('promotion_type') ? $request->input('promotion_type') : '';
        $channel_type = $request->has('channel_type') ? $request->input('channel_type') : '';
        $chapter_name = $request->has('chapter_name') ? $request->input('chapter_name') : '';
        $chapter_id = $request->has('chapter_id') ? $request->input('chapter_id') : '';
        $headline_id = $request->has('headline_id') ? $request->input('headline_id') : ''; //标题
        $image_id = $request->has('template_image_id') ? $request->input('template_image_id') : ''; //模板图片id
        $original_guide_id = $request->has('original_guide_id') ? $request->input('original_guide_id') : ''; //原文引导
        $subscribe_chapter_seq = $request->has('subscribe_chapter_seq') ? $request->input('subscribe_chapter_seq') : '';
        $subscribe_chapter_name = $request->has('subscribe_chapter_name') ? $request->input('subscribe_chapter_name') : '';
        $subscribe_chapter_id = $request->has('subscribe_chapter_id') ? $request->input('subscribe_chapter_id') : '';
        // 文案标题，推广图模板，原文引导，推广图模式

        $redirect_url = "/reader?bid={$book_id}&cid={$chapter_id}";
        $book_id = Hashids::decode($book_id)[0];
        $domain = $this->getDomainByBid($book_id);
        $charge_type = $this->getBookChargeTypeByBid($book_id);

        if ($book_id == 2423 && time() >= strtotime('2018-10-10 00:00:00') && time() <= strtotime('2018-10-15 00:00:00')) {
            return response()->error('CONTENT_MAINTAIN');
        }

        if (!$headline_id || !$original_guide_id || !$image_id || !$chapter_name || !$book_id || !$subscribe_chapter_id || !$subscribe_chapter_name || !$subscribe_chapter_seq || !$chapter_id || !$channel_type || !$promotion_type || !$name || !$promotion_point || !$book_name) {
            return response()->error('PARAM_EMPTY');
        } else {
            $sendOrder = SendOrderService::createFromChapter(compact('book_id', 'book_name', 'subscribe_chapter_seq', 'subscribe_chapter_name', 'subscribe_chapter_id', 'chapter_name', 'promotion_type', 'promotion_point', 'name', 'cost', 'channel_type', 'headline_id', 'original_guide_id', 'chapter_id', 'charge_type', 'domain', 'distribution_channel_id', 'redirect_url'));
            $promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . $this->getDomainByBid($book_id) . '/yun/' . $sendOrder->id;
            return response()->success(['id' => $sendOrder->id, 'promotion_url' => $promotion_url]);
        }
    }

    /**
     * 根据图书id获取图书的收费类型
     * @param string $bid
     */
    function getBookChargeTypeByBid($bid = '')
    {
        $charge_type = '';
        $bookConfig = BookConfigService::getBookById($bid);
        if ($bookConfig) {
            $charge_type = $bookConfig->charge_type;
        }
        return $charge_type;
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 生成目录中的章节的派单
     * @api {POST} sendOrder/createFromDirectory 生成一个目录的派单
     * @apiGroup sendOrder
     * @apiName createFromDirectory
     * @apiParam {String} name 派单渠道名称.
     * @apiParam{Number} cost 成本.
     * @apiParam {String} channel_type 派单渠道类型.(允许值: AUTHENTICATED, UNAUTHENTICATED)
     * @apiParam {String} book_id  书本id
     * @apiParam {String} promotion_type 推广类型[INTERVAL、EXTERVAL]. 内部、外部
     * @apiParam {String} qr_code_id 二维码id.
     * @apiParam {String} book_name  书本名称
     * @apiParam {String} chapter_id  章节id
     * @apiParam {String} chapter_name  章节名称
     * @apiParam {String}  subscribe_chapter_id  强制订阅章节id
     * @apiParam {String}  subscribe_chapter_name  强制订阅章节名称
     * @apiParam {String}  subscribe_chapter_seq 强制订阅章节序号
     * @apiParam{String}  [promotion_point] 派单源 微信(默认)or浏览器(微信:1,浏览器:2)
     * @apiSuccess {Number}  id 派单id
     * @apiSuccess {String}  promotion_url  推广链接
     * @apiSuccess {String}  name 派单名称
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{"id":5,"promotion_url":"http:\/\/www . xs . com\/promotion\/index\/123456"，"name":"派单名称"}
     *     }
     */
    function createFromDirectory(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $name = $request->has('name') ? $request->input('name') : '';
        $cost = $request->has('cost') ? $request->input('cost') : 0;
        $book_id = $request->has('book_id') ? $request->input('book_id') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $chapter_id = $request->has('chapter_id') ? $request->input('chapter_id') : '';
        $qr_code_id = $request->has('qr_code_id') ? $request->input('qr_code_id') : '';
        $chapter_name = $request->has('chapter_name') ? $request->input('chapter_name') : '';
        $channel_type = $request->has('channel_type') ? $request->input('channel_type') : '';
        $promotion_type = $request->has('promotion_type') ? $request->input('promotion_type') : '';
        $subscribe_chapter_id = $request->has('subscribe_chapter_id') ? $request->input('subscribe_chapter_id') : '';
        $subscribe_chapter_seq = $request->has('subscribe_chapter_seq') ? $request->input('subscribe_chapter_seq') : '';
        $subscribe_chapter_name = $request->has('subscribe_chapter_name') ? $request->input('subscribe_chapter_name') : '';
        $promotion_point = $request->has('promotion_point') ? $request->input('promotion_point') : 1;
        if (!in_array($promotion_point, [1, 2])) {
            $promotion_point = 1;
        }

        if (!$name || !$channel_type || !$promotion_type || !$book_id || !$book_name || !$chapter_id || !$chapter_name || !$subscribe_chapter_id || !$subscribe_chapter_seq || !$subscribe_chapter_name) return response()->error('PARAM_EMPTY');

        if (empty($qr_code_id)) {
            $qr_code_id = 0;
        }
        $redirect_url = "/reader?bid={$book_id}&cid={$chapter_id}";
        $book_id = Hashids::decode($book_id)[0];
        if ($book_id == 2423 && time() >= strtotime('2018-10-10 00:00:00') && time() <= strtotime('2018-10-15 00:00:00')) {
            return response()->error('CONTENT_MAINTAIN');
        }
        if ($promotion_point == 2) {
            $domain = 'leyuee.com';
        } else {
            $domain = $this->getDomainByBid($book_id);
        }
        $charge_type = $this->getBookChargeTypeByBid($book_id);
        $sendOrder = SendOrderService::createFromDirectory(compact(
            'name',
            'channel_type',
            'promotion_type',
            'charge_type',
            'cost',
            'domain',
            'book_id',
            'qr_code_id',
            'book_name',
            'chapter_id',
            'subscribe_chapter_id',
            'subscribe_chapter_name',
            'subscribe_chapter_seq',
            'chapter_name',
            'distribution_channel_id',
            'redirect_url',
            'promotion_point'
        ));

//        $promotion_url = '/yun/' . $sendOrder->id;
        if ($promotion_point == 2) {
            $promotion_url = 'https://bsite' . encodeDistributionChannelId($distribution_channel_id) . '.leyuee.com/yun/' . $sendOrder->id;
        } else {
            $promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . $this->getDomainByBid($book_id) . '/yun/' . $sendOrder->id;
        }
        return response()->success(['id' => $sendOrder->id, 'promotion_url' => $promotion_url, 'name' => $name]);
    }


    function uploadSendOrders(Request $request)
    {
        if (!$request->hasFile('sendOrderFile')) {
            return response()->error('PARAM_EMPTY');
        }
        $qr_code_id = 0;
        $channel_type = 'AUTHENTICATED';
        $distribution_channel_id = $this->getChannelId();
        $file_name = date('YmdHis') . '.csv';
        $file = $request->file('sendOrderFile');
        if (null != $file) {
            $path = $request->sendOrderFile->storeAs('sendorder', $file_name);
            $path = storage_path('app/' . $path);
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:attachment;filename=" . "派单信息" . date("YmdHis") . ".csv");
            echo mb_convert_encoding("\"派单id\",\"渠道名称\",\"成本\",\"预计发送时间\",\"粉丝数\",\"图书名称\",\"图书id\",\"原文链接章节\",\"内外部\",\"公司名称\",\"代理商名称\",\"代理商介绍\",\"原文链接\"\r\n", 'GBK', 'UTF-8');

            $file = fopen($path, "r");
            //遍历读取每一行数据
            $currentIndex = 0;
            while ($data = fgetcsv($file)) {
                \Log::info($data);
                if (!$data[6]) continue;
                if ($currentIndex > 0) {
                    $date = $this->getFormatDate($data[2]);
                    $date = date('Y-m-d', strtotime($date));
                    $data[2] = $date;

                    $name = mb_convert_encoding(trim($data[0]), "UTF-8", "GBK") . '-' . +trim($data[1]) . '-' . trim($data[2]) . '-' . mb_convert_encoding(trim($data[3]), "UTF-8", "GBK");
                    $cost = $data[4];
                    $fan_num = (int)(trim($data[5]) * 10000);
                    \Log::info($fan_num);
                    $book_name = mb_convert_encoding(trim($data[6]), "UTF-8", "GBK");
                    $book_id = trim($data[7]);
                    $chapter_sqp = trim($data[8]);
                    $reciver_promotion_type = mb_convert_encoding(trim($data[9]), "UTF-8", "GBK");
                    $import_company_name = mb_convert_encoding(trim($data[10]), "UTF-8", "GBK");

                    $agent_name = mb_convert_encoding(trim($data[11]), "UTF-8", "GBK");
                    $agent_intro = mb_convert_encoding(trim($data[12]), "UTF-8", "GBK");

                    $chapter = ChapterService::getChapterInfoByBidAndSeq($book_id, $chapter_sqp);
                    $chapter_id = $chapter->id;
                    $chapter_name = $chapter->name;
                    $promotion_type = ($reciver_promotion_type == '内部') ? 'INTERNAL' : 'EXTERNAL';

                    $domain = $this->getDomainByBid($book_id);
                    $charge_type = $this->getBookChargeTypeByBid($book_id);
                    $book_id = Hashids::encode($book_id);
                    $redirect_url = "/reader?bid=$book_id&cid=$chapter_id";
                    $book_id = Hashids::decode($book_id)[0];

                    if (!$name || !$channel_type || !$promotion_type || !$book_id || !$book_name || !$chapter_id || !$chapter_name || !$import_company_name || !$fan_num) {
                        return response()->error('PARAM_EMPTY');
                    }

                    $pre_send_date = $date;
                    $sendOrder = SendOrderService::createFromDirectory(compact('name', 'channel_type', 'promotion_type', 'pre_send_date', 'import_company_name', 'fan_num', 'charge_type', 'cost', 'domain', 'book_id', 'qr_code_id', 'book_name', 'chapter_id', 'chapter_name', 'distribution_channel_id', 'redirect_url'));
                    $promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . $this->getDomainByBid($book_id) . '/yun/' . $sendOrder->id;

                    $send_order_id = $sendOrder->id;

                    if ($agent_name && $agent_intro) {
                        $created_at = date("Y-m-d H:i:s");
                        $updated_at = date("Y-m-d H:i:s");
                        $params = compact('send_order_id', 'agent_name', 'agent_intro', 'created_at', 'updated_at');
                        DB::table('agent_info')->insert($params);
                    }

                    echo("\"" . $sendOrder->id . "\",");
                    echo("\"" . mb_convert_encoding($name, "GBK", "UTF-8") . "\",");
                    echo("\"" . $cost . "\",");
                    echo("\"" . date('Y/m/d', strtotime($date)) . "\",");
                    echo("\"" . $fan_num . "\",");
                    echo("\"" . mb_convert_encoding($book_name, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($book_id, "GBK", "UTF-8") . "\",");
                    echo("\"" . $chapter_id . "\",");
                    echo("\"" . mb_convert_encoding($reciver_promotion_type, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($import_company_name, "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($agent_name ? $agent_name : "未知", "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($agent_intro ? $agent_intro : "未知", "GBK", "UTF-8") . "\",");
                    echo("\"" . $promotion_url . "\"\r\n");
                }
                $currentIndex++;
            }
        }
        exit();
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 生成一个页面推广的派单
     * @api {POST} sendOrder/createFromPage 生成一个页面推广的派单
     * @apiGroup sendOrder
     * @apiName createFromPage
     * @apiParam{Number} cost 成本.
     * @apiParam{String} name 派单渠道名称.
     * @apiParam{String} promotion_type 推广类型[INTERVAL、EXTERVAL]. 内部、外部
     * @apiParam{String} qr_code_id 二维码id.
     * @apiParam{String} channel_type 派单渠道类型.(允许值: AUTHENTICATED, UNAUTHENTICATED)
     * @apiParam{String} page_id  页面ID
     * @apiParam{String}  [promotion_point] 派单源 微信(默认)or浏览器(微信:1,浏览器:2)
     * @apiSuccess {Number}  id 派单id
     * @apiSuccess {String}  promotion_url  推广链接
     * @apiSuccess {String}  name 派单名称
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":{"id":5,"promotion_url":"http:\/\/www . xs . com\/promotion\/index\/123456"，"name":"派单名称"}
     *     }
     */
    function createFromPage(Request $request)
    {
        $name = $request->has('name') ? $request->input('name') : '';
        $cost = $request->has('cost') ? $request->input('cost') : 0;
        $promotion_type = $request->has('promotion_type') ? $request->input('promotion_type') : '';
        $page_id = $request->has('page_id') ? $request->input('page_id') : '';
        $qr_code_id = $request->has('qr_code_id') ? $request->input('qr_code_id') : '';
        $channel_type = $request->has('channel_type') ? $request->input('channel_type') : '';
        $page = PromotionService::getById($page_id);

        if (!$name || !$channel_type || !$page_id || !$page) return response()->error('PARAM_EMPTY');
        if (empty($qr_code_id)) {
            $qr_code_id = 0;
        }

        $promotion_point = $request->has('promotion_point') ? $request->input('promotion_point') : 1;
        if (in_array($promotion_point, [1, 2])) {
            $promotion_point = 1;
        }

        $entrance = $page->title;
        $redirect_url = $page->link;
        $distribution_channel_id = $this->getChannelId();
        $domain = $this->getDomainByBid();
        $sendOrder = SendOrderService::createFromPage(compact('name', 'channel_type', 'promotion_type', 'cost', 'qr_code_id', 'domain', 'page_id', 'entrance', 'distribution_channel_id', 'redirect_url', 'promotion_point'));
//        $promotion_url = '/yun/' . $sendOrder->id;
        if ($promotion_point == 2) {
            $promotion_url = 'https://bsite' . encodeDistributionChannelId($distribution_channel_id) . '.leyuee.com/yun/' . $sendOrder->id;
        } else {
            $promotion_url = 'https://site' . encodeDistributionChannelId($distribution_channel_id) . '.leyuee.com/yun/' . $sendOrder->id;
        }
        //$promotion_url = 'https://'.$site . encodeDistributionChannelId($distribution_channel_id) . '.' . $this->getDomainByBid('') . '/yun/' . $sendOrder->id;
        return response()->success(['id' => $sendOrder->id, 'promotion_url' => $promotion_url, 'name' => $name]);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 更新派单
     * @api {POST} sendOrder/updateSendOrderInfo 更新派单
     * @apiGroup sendOrder
     * @apiName updateSendOrderInfo
     * @apiParam {Number} id 派单id.
     * @apiParam {String} name 派单名称
     * @apiParam {Number} cost 派单成本
     * @apiParam {String} channel_type 派单渠道类型.(允许值: AUTHENTICATED, UNAUTHENTICATED)
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":[]
     *     }
     */
    function updateSendOrderInfo(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $id = $request->has('id') ? $request->input('id') : '';
        $name = $request->has('name') ? $request->input('name') : '';
        $cost = $request->has('cost') ? $request->input('cost') : '';
        $channel_type = $request->has('channel_type') ? $request->input('channel_type') : '';
        $promotion_type = $request->has('promotion_type') ? $request->input('promotion_type') : '';
        $subscribe_chapter_seq = $request->input('subscribe_chapter_seq', '');
        if (empty($name) && empty($channel_type) && empty($cost) && empty($promotion_type)) {
            return response()->error("PARAM_EMPTY");
        }
        $subscribe_chapter = [];
        if ($subscribe_chapter_seq) {
            $send_orders = SendOrderService::getById($id);
            $bid = $send_orders->book_id;
            $chapter_info = ChapterService::getChapterInfoByBidAndSeq($bid, $subscribe_chapter_seq);
            if (!$chapter_info) {
                return response()->error('PARAM_ERROR');
            }
            $subscribe_chapter_id = $chapter_info->id;
            $subscribe_chapter['subscribe_chapter_id'] = $subscribe_chapter_id;
            $subscribe_chapter['subscribe_chapter_seq'] = $subscribe_chapter_seq;
            $subscribe_chapter['subscribe_chapter_name'] = $chapter_info->name;

        }

        $pre_send_date = null;
        $send_order_export_special_channel = env('SEND_ORDER_EXPORT_SPECIAL_CHANNEL');
        $isExistSpecialChannel = in_array($distribution_channel_id, explode(',', $send_order_export_special_channel));
        if ($isExistSpecialChannel && $name && strpos($name, "-")) {
            $strs = explode('-', $name);
            if (count($strs) == 4) {
                $date = $this->getFormatDate($strs[2]);
                $date = date('Y-m-d', strtotime($date));
                $pre_send_date = $date;
            }
        }

        $data = SendOrderService::updateSendOrderInfo($id, $distribution_channel_id, $name, $pre_send_date, $channel_type, $cost, $promotion_type, $subscribe_chapter);
        if ($data) {
            return response()->success();
        } else {
            return response()->error("HANDLE_FAILED");
        }
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 删除派单
     * @api {POST} sendOrder/removeSendOrder 删除派单
     * @apiGroup sendOrder
     * @apiName removeSendOrder
     * @apiParam {Number}  id 派单id.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":[]
     *     }
     */
    function removeSendOrder(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $id = $request->has('id') ? $request->input('id') : '';
        $data = SendOrderService::removeSendOrder($id, $distribution_channel_id);
        if ($data) {
            return response()->success();
        } else {
            return response()->error("HANDLE_FAILED");
        }
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 设置成本
     * @api {POST} sendOrder/setCost 设置成本
     * @apiGroup sendOrder
     * @apiName setCost
     * @apiParam{Number}id 派单id.
     * @apiParam{Number}cost 成本.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":[]
     *     }
     */
    function setCost(Request $request)
    {
        $distribution_channel_id = $this->getChannelId();
        $id = $request->has('id') ? $request->input('id') : '';
        $cost = $request->has('cost') ? $request->input('cost') : '';
        if (empty($id) || empty($cost)) {
            return response()->error("PARAM_EMPTY");
        }

        if (!is_numeric($cost)) {
            return response()->error("PARAM_ERROR");
        }
        $data = SendOrderService::setSendOrderCost($id, $distribution_channel_id, $cost);
        if ($data) {
            return response()->success(compact('cost'));
        } else {
            return response()->error("HANDLE_FAILED");
        }
    }

    /**
     * 匹配原文链接
     * @param Request $request
     */
    static function checkOriginUrl(Request $request)
    {
        if (!$request->hasFile('orginUrlFile')) {
            return response()->error('PARAM_EMPTY');
        }
        $file_name = date('YmdHis') . '.csv';
        $file = $request->file('orginUrlFile');
        if (null != $file) {
            $path = $request->orginUrlFile->storeAs('orginUrl', $file_name);
            $path = storage_path('app/' . $path);
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:attachment;filename=" . "原文链接" . date("YmdHis") . ".csv");
            echo mb_convert_encoding("\"公众号\",\"正确原文链接\",\"预览图文链接\",\"链接中解析到的url\",\"是否匹配\"\r\n", 'GBK', 'UTF-8');

            $file = fopen($path, "r");
            //遍历读取每一行数据
            $currentIndex = 0;
            while ($data = fgetcsv($file)) {
                \Log::info('data---1：' . json_encode($data));
                if (!$data[0] || !$data[1] || !$data[2]) continue;
                if ($currentIndex > 0) {
                    \Log::info('data---2：' . $data[2]);
                    $data[2] = str_replace('https', 'http', $data[2]);
                    $data[2] = str_replace('http', 'https', $data[2]);
                    $content = ChannelService::getContentByUrl($data[2]);
                    \Log::info($content);
                    $searchUrl = '';
                    $findStrEnd = ';';
                    $findStrBegin = 'msg_source_url =';

                    //解析页面中的msg_source_url的内容
                    $startIndex = strpos($content, $findStrBegin);
                    if ($startIndex > 0) {
                        \Log::info('开始进入了');
                        $endIndex = strpos($content, $findStrEnd, $startIndex);
                        if ($endIndex > $startIndex) {
                            $startIndex = $startIndex + strlen($findStrBegin) + 2;
                            $searchUrl = substr($content, $startIndex, $endIndex - $startIndex - 1);
                        }
                        //判断解析到的msg_source_url是否加密
                        \Log::info($searchUrl);
                        $url_items = parse_url($searchUrl);
                        \Log::info($url_items);
                        $distribution_channel_id = str_replace('site', '', explode('.', $url_items['host'])[0]);
                        if (!is_numeric($distribution_channel_id)) {
                            $deal_distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
                            //需要解密
                            $searchUrl = str_replace('site' . $distribution_channel_id, 'site' . $deal_distribution_channel_id, $searchUrl);
                        }
                    }

                    //判断上传的url是否加密
                    $deal_url = $data[1];
                    $url_items = parse_url($deal_url);
                    $distribution_channel_id = str_replace('site', '', explode('.', $url_items['host'])[0]);
                    //需要解密
                    if (!is_numeric($distribution_channel_id)) {
                        $deal_distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
                        $deal_url = str_replace('site' . $distribution_channel_id, 'site' . $deal_distribution_channel_id, $deal_url);
                    }

                    $isMatch = ($searchUrl == $deal_url) ? '匹配' : '不匹配';
                    $data[0] = mb_convert_encoding(trim($data[0]), "UTF-8", "GBK");
                    echo("\"" . mb_convert_encoding($data[0], "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($data[1], "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($data[2], "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($searchUrl ? $searchUrl : '未找到', "GBK", "UTF-8") . "\",");
                    echo("\"" . mb_convert_encoding($isMatch, "GBK", "UTF-8") . "\"\r\n");
                }
                $currentIndex++;
            }
        }
        exit();
    }

    /**
     * 加密、解密原文链接
     * @param Request $request
     */
    function decryptOrEncrptOriginUrl(Request $request)
    {
        $originUrl = $request->has('origin_url') ? $request->input('origin_url') : '';
        if (empty($originUrl)) {
            return response()->error("PARAM_EMPTY");
        }

        $url_items = parse_url($originUrl);
        $distribution_channel_id = str_replace('site', '', explode('.', $url_items['host'])[0]);
        //需要加密
        if (is_numeric($distribution_channel_id)) {
            $deal_distribution_channel_id = encodeDistributionChannelId($distribution_channel_id);
            //需要解密
        } else {
            $deal_distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
        }

        $originUrl = str_replace('site' . $distribution_channel_id, 'site' . $deal_distribution_channel_id, $originUrl);
        return response()->success(['originUrl' => $originUrl]);
    }
}
