<?php

namespace App\Http\Controllers\Wap\Book;

use App\Modules\Book\Models\DataAnalysisBookConfig;
use App\Modules\Book\Services\BookService;
use App\Modules\Book\Services\ChapterCommentsService;
use App\Modules\Book\Services\ChapterShareWechatConfigService;
use App\Modules\Statistic\Models\DataAnalysisSelectUser;
use App\Modules\Statistic\Services\AdVisitStatService;
use App\Modules\Statistic\Services\DataAnalysisChapterService;
use App\Modules\Statistic\Services\DataAnalysisSelectUserService;
use App\Modules\Statistic\Services\WapVisitStatService;
use App\Modules\Subscribe\Services\CrmChapterOrderDetailService;
use App\Modules\Subscribe\Services\CustomChapterOrderService;
use App\Modules\Subscribe\Services\OrderService;
use App\Modules\Subscribe\Models\Order;
use App\Modules\User\Services\CrmUserService;
use App\Modules\User\Services\ForceGuidePersonAccountService;
use App\Modules\User\Services\ForceSubscribeUserIService;
use App\Modules\User\Services\ReadRecordStatsService;
use App\Modules\User\Services\UserBindHkWelfareService;
use App\Modules\User\Services\UserService;
use App\Modules\YunQi\Services\BookUserService;
use Illuminate\Http\Request;
use App\Http\Controllers\Wap\BaseController;
use Cookie;
use Redis;
use App\Modules\Book\Services\ChapterService;
use App\Modules\User\Services\ReadRecordService;
use App\Http\Controllers\Wap\Book\Transformers\ChapterTransformer;
use App\Modules\Book\Services\BookConfigService;
use App\Http\Controllers\Wap\Book\Transformers\ChapterListTransformer;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\Subscribe\Services\ChapterOrderService;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\Subscribe\Services\ChapterReminderService;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use Hashids;
use GuzzleHttp\Client;
use Log;
use DB;
use App\Modules\User\Services\UserSignService;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\User\Services\UserDeepReadTagService;
use App\Modules\Book\Services\BookSubscribleChapterService;
use App\Modules\Channel\Services\ChannelSubscribeSettingService;

class ChapterController extends BaseController
{
    /**
     * @apiDefine Chapter 章节
     */

    //用户是否强关
    private $is_had_subscribe = false;

    //章节是否需要强关
    private $is_need_subscribe;

    //用户信息
    private $user;

    //图书信息
    private $book_info;

    //cid
    private $cid;

    //加密的bid
    private $en_bid;

    //章节信息
    private $chapter;

    private $is_first_book_order = 0;

    private $domain;

    private $crm_order = '';

    /**
     * @apiVersion 1.0.0
     * @apiDescription 章节列表不分页
     * @api {get} books/{bid}/allcatalog 章节列表不分页
     * @apiGroup Chapter
     * @apiName getCatalog
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Array}       data.list 分页结果集
     * @apiSuccess {Int}         data.list.bid   bid
     * @apiSuccess {Int}         data.list.chapter_id   章节id
     * @apiSuccess {String}      data.list.chapter_name   章节名称
     * @apiSuccess {Int}         data.list.chapter_sequence   序号
     * @apiSuccess {Int}         data.list.chapter_is_vip   是否vip
     * @apiSuccess {Int}         data.list.chapter_size   章节大小
     * @apiSuccess {Int}         data.list.prev_cid   上一章节id
     * @apiSuccess {Int}         data.list.next_cid   下一章节
     * @apiSuccess {String}      data.list.recent_update_at   更新时间
     * @apiSuccess {String}      data.list.is_need_subscirbe   是否强制关注
     * @apiSuccess {String}      data.list.is_show_price   是否显示价格
     * @apiSuccess {String}      data.list.price   价格
     * @apiSuccess {object}      data.meta   分页信息
     * @apiSuccess {Int}         data.meta.total  总条数
     * @apiSuccess {Int}         data.meta.per_page  每页条数
     * @apiSuccess {Int}         data.meta.current_page 当前页
     * @apiSuccess {Int}         data.meta.last_page  最后页
     * @apiSuccess {String}      data.meta.next_page_url  下一页
     * @apiSuccess {String}      data.meta.prev_page_url  上一页
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data:
     *            [
     *             {
     *               bid: 5,
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               is_need_subscirbe: 1,
     *            },
     *             {
     *               bid: 5,
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               is_need_subscirbe: 1,
     *            },
     *          ]
     *       }
     */
    public function getCatalog(Request $request, $t, $domain, $bid)
    {
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        $this->en_bid = $bid;
        $bid = Hashids::decode($bid)[0];
        $lists = ChapterService::getChapterLists($bid);
        $book_info = BookConfigService::getBookById($bid);
        if (!$book_info) {
            return response()->error('PARAM_ERROR');
        }
        $this->book_info = $book_info;
        $is_show_price = $this->showChapterPrice($bid, $book_info->charge_type);
        foreach ($lists as $v) {
            $v->is_show_price = $is_show_price;
            $v->price = '';
            if ($is_show_price) {
                $v->price = $this->getPrice($book_info, $v);
            }
        }
        return response()->collection(new ChapterListTransformer, $lists);
    }

    /**
     * @apiVersion 1.0.0
     * @apiDescription 章节列表分页
     * @api {get} books/{bid}/catalog 章节列表分页
     * @apiGroup Chapter
     * @apiName getCatalogPerPage
     * @apiParam   {Int}         page_size  分页大小(默认15)
     * @apiParam   {Int}         page  页码(默认1)
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Array}       data.list 分页结果集
     * @apiSuccess {Int}         data.list.bid   bid
     * @apiSuccess {Int}         data.list.chapter_id   章节id
     * @apiSuccess {String}      data.list.chapter_name   章节名称
     * @apiSuccess {Int}         data.list.chapter_sequence   序号
     * @apiSuccess {Int}         data.list.chapter_is_vip   是否vip
     * @apiSuccess {Int}         data.list.chapter_size   章节大小
     * @apiSuccess {Int}         data.list.prev_cid   上一章节id
     * @apiSuccess {Int}         data.list.next_cid   下一章节
     * @apiSuccess {String}      data.list.recent_update_at   更新时间
     * @apiSuccess {String}      data.list.is_need_subscirbe   是否强制关注
     * @apiSuccess {String}      data.list.is_show_price   是否显示价格
     * @apiSuccess {String}      data.list.price   价格
     * @apiSuccess {object}      data.meta   分页信息
     * @apiSuccess {Int}         data.meta.total  总条数
     * @apiSuccess {Int}         data.meta.per_page  每页条数
     * @apiSuccess {Int}         data.meta.current_page 当前页
     * @apiSuccess {Int}         data.meta.last_page  最后页
     * @apiSuccess {String}      data.meta.next_page_url  下一页
     * @apiSuccess {String}      data.meta.prev_page_url  上一页
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data:
     *            list:[
     *             {
     *               bid: 5,
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               is_need_subscirbe: 1,
     *            },
     *             {
     *               bid: 5,
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               is_need_subscirbe: 1,
     *            },
     *          ]
     *          meta:{
     *              total: 1253,
     *              per_page: 15,
     *              current_page: 1,
     *              last_page: 84,
     *              next_page_url: "http://myapi.cn/api/books/1/chapter?page=2",
     *              prev_page_url: ""
     *         }
     *       }
     */
    public function getCatalogPerPage(Request $request, $t, $domain, $bid)
    {
        if (!$this->checkUid()) {
            return response()->error('WAP_NOT_LOGIN');
        }
        $this->en_bid = $bid;

        $bid_array = Hashids::decode($bid);

        if (isset($bid_array[0])) {
            $bid = $bid_array[0];
        } else {
            return response()->error('PARAM_ERROR');
        }
        $book_info = BookConfigService::getBookById($bid);
        if (!$book_info) {
            return response()->error('PARAM_ERROR');
        }
        $this->book_info = $book_info;
        $page_size = $request->input('page_size', 15);
        if($page_size>=100) $page_size=100;
        $res = ChapterService::getChapterListsPage($bid, $page_size);
        $is_show_price = $this->showChapterPrice($bid, $book_info->charge_type);
        foreach ($res as $v) {
            $v->is_show_price = $is_show_price;
            $v->price = '';
            if ($is_show_price) {
                $v->price = $this->getPrice($book_info, $v);
            }
        }
        return response()->pagination(new ChapterListTransformer, $res);
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 章节内容
     * @api {get} books/{bid}/chapters/{chapter_id} 章节内容
     * @apiGroup Chapter
     * @apiName index
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         data.chapter_id   章节id
     * @apiSuccess {String}      data.chapter_name   章节名称
     * @apiSuccess {Int}         data.chapter_sequence   序号
     * @apiSuccess {Int}         data.chapter_is_vip   是否vip
     * @apiSuccess {Int}         data.chapter_size   章节大小
     * @apiSuccess {Int}         data.prev_cid   上一章节id
     * @apiSuccess {Int}         data.next_cid   下一章节
     * @apiSuccess {String}      data.recent_update_at   更新时间
     * @apiSuccess {String}      data.chapter_content  章节内容
     * @apiSuccess {Int}         data.is_need_subscirbe  是否强制关注(删除)
     * @apiSuccess {Int}         data.is_show_subscribe_link  是否显示底部强关链接
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               chapter_content: "叶妩被司行霈的阴阳怪气一吓,思路偏得太远了。 她张口结舌,忘记了自己要说什么。",
     *            }
     *       }
     */
    public function index(Request $request, $t, $domain, $bid, $cid)
    {
        $this->domain = $domain;
        $special_user_log = env('SPECIAL_USER_LOG');
        //注意:内部约定用  有此参数不需要强关
        Cookie::queue('force_show_qrcode', 1, -1);

        if (!$this->checkUid()) {
            myLog('special')->info('chapter index controller---$this->checkUid() fail-------');
            return response()->error('WAP_NOT_LOGIN');
        }

        $this->en_bid = $bid;

        $bid = explode(',',$bid)[0];
        $bid = Hashids::decode($bid)[0];
        //获取图书信息
        $book_info = BookConfigService::getBookById($bid);

        //是否开启全站按章模式
        $global_charge_by_chapter_channels = explode(',',env('GLOBAL_CHARGE_BY_CHAPTER_CHANNEL'));
        if(in_array($this->distribution_channel_id,$global_charge_by_chapter_channels))
        {
            $book_info->charge_type = 'CHAPTER';
        }

        if (empty($book_info)) return response()->error('WAP_SYS_ERROR');

        $this->book_info = $book_info;
        $this->cid = $cid;

        //下架图书不能看
        if ($this->isOffShelf()) {
            return response()->error('WAP_OFF_SHELF');
        }

        //获取章节信息
        $chapter = ChapterService::getChapterNameById($cid, $bid);
        $this->chapter = $chapter;

        //章节被删除
        if (($is_delete = $this->chapterNotExists())) {
            return response()->error('WAP_DOMAIN_NOT_MATCH', [
                'url' => $is_delete
            ]);
        }
        $user_info = $this->_user_info;
        $this->user = $user_info;
        //用户是否强关
        $this->is_had_subscribe = true;

        //需要强制关注 不是vip章节 已经关注了
        if ($chapter->is_vip == 0) {
            $this->getChapter();
            return response()->item(new ChapterTransformer, $this->chapter);
        }

        //已经付费
        if ($this->getOrderRecord($bid, $cid)) {
            $this->getChapter();
            if($special_user_log && $special_user_log == $this->uid){
                $my_log = myLog('special');
                $my_log->info('had order order record--------------------------');
            }
            return response()->item(new ChapterTransformer, $this->chapter);
        }
        //获取价格
        $fee = $this->getPrice($book_info, $chapter);
        //以上都是不用付费的情况******************************************************
        //未付费
        //返回的价格信息
        $data = [
            'book_id' => $this->en_bid,
            'book_name' => $book_info->book_name,
            'chapter_name' => $chapter->name,
            'chapter_id' => $cid,
            'pay_type' => $book_info->charge_type,
            'fee' => $fee,
            'user_balance' => $user_info->balance,
            'product_id' => $book_info->product_id,
            'uid' => $this->uid,
            'distribution_channel_id' => $this->distribution_channel_id,
            'is_discount' => 0,
            'discount_fee' => '',
            'discount' => '',
            'is_first_book_order'=>$this->is_first_book_order
        ];
        if($special_user_log && $special_user_log == $this->uid){
            $my_log = myLog('special');
            $my_log->info('data is:');
            $my_log->info($data);
        }
        //余额不足 弹窗提醒
        if ($user_info['balance'] < $fee) {
            //除了单本订购 其他的都不提醒,直接跳转到充值页面
            if ($book_info->charge_type == 'CHAPTER') {
                if($special_user_log && $special_user_log == $this->uid){
                    $my_log = myLog('special');
                    $my_log->info('chapter order balance lack');
                }
                return response()->error('WAP_CHAPTER_SECOND_BALANCE_PAY', $data);
            }
            //需要提箱
            if ($this->isOrderRemind($bid)) {
                return response()->error('WAP_BOOK_BALANCE_PAY', $data);
            } else {
                return response()->error('WAP_BOOK_SECOND_BALANCE_PAY', $data);
            }

        }

        //余额充足 单本弹窗提醒,章节直接扣费
        if ($this->isOrderRemind($bid) && $book_info->charge_type == 'BOOK') {
            return response()->error('WAP_BOOK_BUY', $data);
        }

        //付费 不提醒
        if ($this->balancePay($book_info, $chapter, 0)) {
            if($special_user_log && $special_user_log == $this->uid){
                $my_log = myLog('special');
                $my_log->info('balance pay ok-----');
            }
            $this->getChapter();
            return response()->item(new ChapterTransformer, $this->chapter);
        } else {
            if($special_user_log && $special_user_log == $this->uid){
                $my_log = myLog('special');
                $my_log->info('balance pay fails!!!!!!!!!!!!!!!!');
            }
            //付费 异常
            return response()->error('WAP_SYS_ERROR');
        }
    }


    /**
     * @apiVersion 1.0.0
     * @apiDescription 余额支付
     * @api {get} books/{bid}/balance/chapterOrders/{cid} 余额支付
     * @apiGroup Chapter
     * @apiName pay
     * @apiParam   (Int)         remind 提醒
     * @apiSuccess {int}         code 状态码
     * @apiSuccess {String}      msg  信息
     * @apiSuccess {object}      data 结果集
     * @apiSuccess {Int}         data.chapter_id   章节id
     * @apiSuccess {String}      data.chapter_name   章节名称
     * @apiSuccess {Int}         data.chapter_sequence   序号
     * @apiSuccess {Int}         data.chapter_is_vip   是否vip
     * @apiSuccess {Int}         data.chapter_size   章节大小
     * @apiSuccess {Int}         data.prev_cid   上一章节id
     * @apiSuccess {Int}         data.next_cid   下一章节
     * @apiSuccess {String}      data.recent_update_at   更新时间
     * @apiSuccess {String}      data.chapter_content  章节内容
     * @apiSuccess {Int}         data.is_need_subscirbe  是否强制关注(删除)
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *       code: 0,
     *       msg: "",
     *       data: {
     *               chapter_id: 5,
     *               chapter_name: "第1240章 不是我",
     *               chapter_sequence: 1239,
     *               chapter_is_vip: 1,
     *               chapter_size: 2422,
     *               prev_cid: 0,
     *               next_cid: 0,
     *               recent_update_at: 2017-11-20 15:01:56,
     *               chapter_content: "叶妩被司行霈的阴阳怪气一吓,思路偏得太远了。 她张口结舌,忘记了自己要说什么。",
     *            }
     *       }
     */
    public function pay(Request $request, $t, $domain, $bid, $cid)
    {
        if (!$this->checkUid()) {
            return response()->error('NOT_LOGIN');
        }
        $remind = (int)$request->input('remind');
        $this->en_bid = $bid;
        $oldbid = $bid;
        $bid = Hashids::decode($bid)[0];
        $book_info = BookConfigService::getBookById($bid);;
        if (empty($book_info)) response()->error('WAP_SYS_ERROR');

        //获取章节
        $chapter = ChapterService::getChapterNameById($cid, $bid);
        if (!$chapter) {
            return response()->error('WAP_SYS_ERROR');
        }
        $this->chapter = $chapter;
        $this->book_info = $book_info;
        $this->cid = $cid;
        if ($this->balancePay($book_info, $chapter, $remind)) {
            ReadRecordService::addReadRecord(['uid' => $this->uid, 'bid' => $bid, 'book_name' => $book_info->book_name,
                'cid' => $cid, 'chapter_name' => $chapter->name]);
            $this->getChapter();
            return response()->item(new ChapterTransformer, $this->chapter);
        } else {
            $fee = $this->getPrice($book_info, $chapter);
            $data = [
                'book_id' => $oldbid,
                'book_name' => $book_info->book_name,
                'chapter_name' => $chapter->name,
                'chapter_id' => $cid,
                'pay_type' => $book_info->charge_type,
                'fee' => $fee,
                'user_balance' => $this->_user_info['balance'],
                'product_id' => $book_info->product_id,
                'uid' => $this->uid,
                'distribution_channel_id' => $this->distribution_channel_id,
                'is_discount' => 0,
                'discount_fee' => '',
                'discount' => '',
                'is_first_book_order'=>$this->is_first_book_order
            ];

            //不需要提醒
            if ($book_info->charge_type == 'BOOK') {
                return response()->error('WAP_BOOK_SECOND_BALANCE_PAY', $data);
            } elseif ($book_info->charge_type == 'CHAPTER') {
                return response()->error('WAP_CHAPTER_SECOND_BALANCE_PAY', $data);
            } else {
                return response()->error('WAP_SYS_ERROR');
            }
        }
    }


    /**
     * 余额支付
     * @param $book_info
     * @param $chapter_id
     * @param $chapter_size
     * @return bool
     */
    protected function balancePay($book_info, $chapter, $is_remind)
    {
        $fee = $this->getPrice($book_info, $chapter);
        if ((int)$this->_user_info['balance'] >= $fee) {
            if ($this->bookOrderOrChapterOrder($book_info, $chapter->id, $fee, $chapter->name, $is_remind)) {
                $this->chapterOrderStats($fee);
                if($this->user){
                    $this->user->balance -= $fee;
                }
                $this->customChapterOrderStats($fee);
                return true;
            }
        }
        return false;
    }


    /**
     * 获取章节内容
     * @param $bid
     * @param $cid
     * @return bool|mixed
     */
    private function getChapter()
    {
        //初始化 默认字段
        $this->initChapterDefaultField();
        //章节内容
        $chapter_content = ChapterService::getChapter($this->book_info->bid, $this->cid);
        //$this->chapter->content = str_replace($chapter_content->name, '', $chapter_content->content);
        $this->chapter->content = $chapter_content->content;

        //阅读记录
        if($this->chapter->sequence >= 2){
            ReadRecordService::addReadRecord(['uid' => $this->uid, 'bid' => $this->book_info->bid, 'book_name' => $this->book_info->book_name,
                'cid' => $this->cid, 'chapter_name' => $this->chapter->name]);
        }
        //统计
        $this->chapterStats();
        //阅读器分享
        $this->share();
        //完整阅读纪录 阅读纪录
        $this->readRecordOther();
        //crm订阅
        $this->crmChapterStats();
    }

    /**
     * 章节阅读接口需要配置返回的字段
     */
    private function initChapterDefaultField()
    {
        if (!$this->chapter) {
            return;
        }
        //内容
        $this->chapter->content = '';
        //签到默认字段
        $this->chapter->sign_days = 1;
        $this->chapter->sign_status = 0;
        $this->chapter->sign_reard = 0;
        $this->chapter->sign_version = 'v1';
        $this->chapter->sign_items = [];//只有v2签到才会用到的字段
        //#短篇推送长篇需求#
        $this->chapter->next_jump = 0;
        $this->chapter->next_jump_url = '';
        $this->chapter->show_push_title = 0;
        $this->chapter->push_title_url = '';
        $this->chapter->push_title = [];
        //分享
        $this->chapter->is_show_share_button = 0;
        //6985的分享配置
        $this->chapter->share_config = '';
        //阅读底部强关图片 只有123有
        $this->chapter->is_had_subscribe = 0;
        //广告
        $this->chapter->is_show_ad = 0;//可不可点击
        $this->chapter->is_visiable_ad = 0;//可不可显示

    }



    private function share()
    {
        if ($this->is_had_subscribe && in_array($this->distribution_channel_id, [2, 14, 211,4025,4147,691,123]) && $this->user) {//,4147,691,123,4025
            $this->chapter->is_show_share_button = 1;
        }
    }



    //订阅统计
    private function chapterOrderStats($fee)
    {
        $day = date('Y--m-d');
        try {
            Redis::hincrby('wap:chapterandbookorder:bid:' . $this->book_info->bid, $day, $fee);
        } catch (\Exception $e) {

        }

        $this->smartPushTestBook($this->book_info->bid, $fee);
        $specialChannelIdStats = env('SPECIAL_CHANNEL_STATS', 211);
        if (in_array($this->distribution_channel_id, explode(',', $specialChannelIdStats))) {
            WapVisitStatService::specialChannelIdStatsSave($this->uid, $this->book_info->bid, $fee);
        }
    }

    /**
     * 添加订购记录
     * @param $book_info
     * @param $chapter_id
     * @param $fee
     * @return bool
     */
    protected function bookOrderOrChapterOrder($book_info, $chapter_id, $fee, $chapter_name, $is_remind)
    {

        if ($book_info['charge_type'] == 'BOOK') {
            $data = [
                'uid' => $this->uid,
                'fee' => $fee,
                'u' => Cookie::get('send_order_id'),
                'distribution_channel_id' => $this->distribution_channel_id,
                'bid' => $book_info->bid,
                'book_name' => $book_info->book_name,
                'send_order_id' => Cookie::get('send_order_id') ? Cookie::get('send_order_id') : 0,
            ];
            return BookOrderService::addOrderRecodeAndDecrUserBalance($data, $this->uid);
        } else {
            $data = [
                'uid' => $this->uid,
                'fee' => $fee,
                'cid' => $chapter_id,
                'bid' => $book_info->bid,
                'distribution_channel_id' => $this->distribution_channel_id,
                'book_name' => $book_info->book_name,
                'chapter_name' => $chapter_name,
                'send_order_id' => Cookie::get('send_order_id') ? Cookie::get('send_order_id') : 0,
                'is_remind' => $is_remind
            ];
            //print_r($data);
            if ($is_remind) {
                $this->addOrderRemind($book_info->bid);
            }
            return ChapterOrderService::addOrderAndDecrUserBalance($data, $this->uid);
        }
    }


    protected function addOrderRemind($bid)
    {
        if (ChapterReminderService::checkIsNoReminder($this->uid, $bid)) {
            return true;
        } else {
            ChapterReminderService::add($this->uid, $bid);
            return true;
        }
    }

    /**
     * 是否订购提醒
     * @param $chapter_id
     * @return bool
     */
    protected function isOrderRemind($bid)
    {
        $is_no_reminder = ChapterReminderService::checkIsNoReminder($this->uid, $bid) ? 1 : 0;
        return $is_no_reminder == 0;
    }


    /**
     * 获取订购记录
     * @param $book_info
     * @param $chapter_id
     * @return bool
     */
    private function getOrderRecord($bid, $chapter_id)
    {
        //包年记录
        $uid = $this->uid;
        $res = YearOrderService::getRecord($uid);
        if ($res) {
            $this->crm_order = 'YEAR_ORDER';
            return true;
        }
        $res = null;

        //单本订购记录
        $res = BookOrderService::getRecordByuidBid($uid, $bid);
        if ($res) {
            $this->crm_order = 'BOOK_ORDER';
            return true;
        }
        $res = null;

        //章节订购记录
        $chapterOrder = new ChapterOrderService();

        if ($chapterOrder->checkIsOrdered($uid, $bid, $chapter_id)) {
            return true;
        }
        $this->crm_order = 'CHAPTER_ORDER';
        return false;
    }


    /**
     * 计算价格
     * @param $book_info
     * @param $chapter_size
     * @return float
     */
    private function getPrice($book_info, $chapter)
    {
        if ($book_info->charge_type == 'BOOK') {
            if(BookOrderService::isHasBookOrder($this->uid)){
                $this->is_first_book_order = 0;
                return 1399;
            }else{
                $this->is_first_book_order = 1;
                return  899;
            }
        } else {
            $fee = BookService::getPrice($book_info,$this->distribution_channel_id,$chapter->size);
            return $fee;
        }
    }


    private function readRecordOther()
    {
        $bid = $this->book_info->bid;
        $cid = $this->cid;
        $distribution_channel_id = $this->distribution_channel_id;
        $send_order_id = $this->send_order_id;
        $from = $this->from_type;
        $sequence = $this->chapter->sequence;
        ReadRecordStatsService::record($this->uid,$bid,$cid,$distribution_channel_id,$send_order_id,$from,$sequence);
    }

    /**
     * 下架图书 true:下架不能阅读了,  false:可以正常阅读
     * @return bool
     */
    private function isOffShelf()
    {
        $book_info = $this->book_info;

        if ($book_info->is_on_shelf == 0 || $book_info->is_on_shelf == 3) {
            return true;
        }
        if ($book_info->is_on_shelf == 4) {
            //版权到期,有包年可以继续阅读
            $year_order = YearOrderService::getRecord($this->uid);
            if($year_order){
                return false;
            }
            //版权到期,有订购记录还可以继续阅读,订购
            $chapter_order = ChapterOrderService::checkBookIsOrdered($this->uid, $book_info->bid);
            if (!$chapter_order) return true;
        }
        return false;
    }

    //章节被删除的情况
    private function chapterNotExists()
    {
        $chapter = $this->chapter;
        $cid = $this->cid;
        if ($chapter) return false;

        //章节不存在的情况
        $no_check = ChapterService::getChapterNameByIdNoCheck($cid);
        $h5_scheme = 'https';
        if (!$no_check) {
            //章节真正不存在的情况
            $url = $h5_scheme . '://' . _domain() . '/catalog?id=' . $this->en_bid;
            return $url;
        }
        $url = $h5_scheme . '://' . _domain() . '/catalog?id=' . $this->en_bid;// . '&sequence=' . $no_check->sequence;
        return $url;
    }


    private function showChapterPrice($bid, $charge_type)
    {
        if ($charge_type == 'BOOK') {
            return false;
        }
        $show_chapter_price_bid = env('SHOW_CHAPTER_PRICE_BID', 'all');
        if ($show_chapter_price_bid != 'all') {
            $show_chapter_price_bid_array = explode(',', $show_chapter_price_bid);
            if (!in_array($bid, $show_chapter_price_bid_array)) {
                return false;
            }
        }
        $show_chapter_price_channel = env('SHOW_CHAPTER_PRICE_CHANNEL', '');
        if (!$show_chapter_price_channel) {
            return false;
        }

        if ($show_chapter_price_channel == 'all') {
            return true;
        }
        $show_chapter_price_channel_array = explode(',', $show_chapter_price_channel);
        if (in_array($this->distribution_channel_id, $show_chapter_price_channel_array)) {
            return true;
        }
        return false;
    }

    /**
     * 阅读统计
     */
    private function chapterStats()
    {
        $chapter = $this->chapter;
        $bid = $this->book_info->bid;
        //派单精确统计
        if ($chapter->sequence <= 30) {
            //$this->sendOrderChapterUv($bid, $chapter->sequence);
        }
        //智能推送 测书统计章节uv
        if ($chapter->sequence <= 60) {
            //测书数据 由30改到60 2018-11-26 18:00
            if($this->book_info->test_status == 1){
                $this->smartPushTestBookChapterUv($bid, $chapter->sequence); //2019-07-09 10:30 cancel
            }
        }
        //智能推送 测书统计第二章 uv
        if ($chapter->sequence == 2) {
            $this->smartPushTestBookSecondChapterUv($bid);
        }
        // 统计前5张uv 会放在book_five_chapter_uv表中,脚本在 \App\Console\Commands\BookTest::data1里面
        // 作用早忘记了
        $field = date('Y-m-d');

        //统计点击率
        $key = 'book_click_num_bid_' . $bid;
        try {
            Redis::HINCRBY($key, $field, 1);
        } catch (\Exception $e) {
        }

        //阅读页面pvuv
        $this->recordReaderUvAndPv();
    }

    private function smartPushTestBook($bid, $balance)
    {
        $smart_bid = ReadRecordService::getSmartPush($this->uid);
        if ($smart_bid && in_array($bid, $smart_bid)) {
            $field = sprintf('%s_amount', $bid);
            try {
                Redis::HINCRBY('smart_push_test_book', $field, $balance);
                Redis::sadd('smart_push_test_book_user_count' . $bid, $this->uid);
            } catch (\Exception $e) {
            }

        }
    }

    private function smartPushTestBookSecondChapterUv($bid)
    {
        $smart_bid = ReadRecordService::getSmartPush($this->uid);
        if ($smart_bid && in_array($bid, $smart_bid)) {
            try {
                Redis::sadd('smart_push_test_book_second_uv' . $bid, $this->uid);
            } catch (\Exception $e) {
            }
        }
    }

    private function smartPushTestBookChapterUv($bid, $sequence)
    {
        $smart_bid = ReadRecordService::getSmartPush($this->uid);
        if ($smart_bid && in_array($bid, $smart_bid)) {
            try {
                $key = 'smartPushTestBookChapterUv:bid:%s:seq:%s';
                Redis::sadd(sprintf($key, $bid, $sequence), $this->uid);
            } catch (\Exception $e) {

            }
        }
    }

    private function recordReaderUvAndPv()
    {
        WapVisitStatService::recordReaderUvAndPv($this->uid, $this->distribution_channel_id);
    }


    private function crmChapterStats(){
        $crm = Cookie::get('crm');
        if(!$crm)return ;
        if(!$this->crm_order) return ;
        $price_rate = env('DEFAULT_CHAPTER_PRICE', 0.015);
        $fee = ceil($this->chapter->size * $price_rate);
        if($fee <37) $fee = 37;
        if($fee >60) $fee = 60;
        try{
            CrmChapterOrderDetailService::create($this->uid,$fee,$this->book_info->bid,$crm,$this->cid,$this->crm_order);
        }catch (\Exception $e){}

    }
    private function customChapterOrderStats($fee)
    {
        //custom_290824
        Log::info('customChapterOrderStats start');
        Log::info($this->from_type);
        if(strpos($this->from_type,'custom') === false){
            return ;
        }

        $customer_id= str_ireplace('custom_','',$this->from_type);
        Log::info($customer_id);
        if(!$customer_id || !is_numeric($customer_id)) return ;
        $info = Redis::hget('latestcustomerinfo',$customer_id);
        if(!$info) return ;
        Log::info($info);
        $info_array = json_decode($info,1);
        Log::info($info_array);
        $customer_bid = isset($info_array['bid'])?$info_array['bid']:0;
        $customer_send_time = isset($info_array['send_time'])?$info_array['send_time']:0;
        if(!$customer_bid || !$customer_send_time) return ;
        CustomChapterOrderService::create([
            'distribution_channel_id'=>$this->distribution_channel_id,
            'bid'=>$this->book_info->bid,
            'cid'=>$this->cid,
            'book_name'=>$this->book_info->book_name,
            'chapter_name'=>$this->chapter->name,
            'uid'=>$this->uid,
            'send_order_id'=>$this->send_order_id,
            'fee'=>$fee,
            'charge_balance'=>0,
            'reward_balance'=>0,
            'custom_id'=>$customer_id,
            'flag'=>$customer_bid == $this->book_info->bid?1:0,
            'send_time'=>$customer_send_time
        ]);

    }


    public function getWechatJsConfig(Request $request)
    {
            $bid = $request->input('bid', '');
            $cid = $request->input('cid', '');
            $url = $request->input('url', '');
            $url = urldecode($url);

            \Log::info('url:' . ($this->uid) . $url);
            if (empty($bid) || empty($cid) || empty($url)) {
                return response()->error('PARAM_EMPTY');
            }
            $app_hash = array(
                4025=>['appid'=>'wx80b618c9dcc940f7','appsecret'=>'255a2de8db51e4084b5e9087d26d4ecb'],
                4147=>['appid'=>'wx2a99699cd9572812','appsecret'=>'0e0d57f94eeba50abb3af6883df05a5c'],
                691=>['appid'=>'wx5cefcd251dc40693','appsecret'=>'755f64c85173dad21f20870e38f59d8a'],
                123=>['appid'=>'wx983808610aa9dcc5','appsecret'=>'91002999590b79f3c7be35fd73c04049'],
                211=>['appid'=>'wx39338e374cc2055b','appsecret'=>'1a4c2039be271b3811182be5bb53eb34'],

            );
            $appId = $app_hash[$this->distribution_channel_id]['appid'];
            $appSecret = $app_hash[$this->distribution_channel_id]['appsecret'];
            $js_config = (new ChapterShareWechatConfigService($appId,$appSecret))->getSignPackage($url);

            $book = BookService::getBookById(Hashids::decode($bid)[0]);
            $first_cid = $book->first_cid;
            $share_url = 'https://site' . encodeDistributionChannelId($this->distribution_channel_id) . '.' . env('SHARE_DOMAIN') . '/reader?fromtype=readershare&bid=' . $bid . '&cid=' . ($first_cid) . '&fromflag=' . ($this->uid) . '&fromcid=' . $cid;
            if (in_array($this->distribution_channel_id, [2, 14])) {
                $js_config = ChapterShareWechatConfigService::getConfig($url);

            $share_url = 'https://site' . ($this->distribution_channel_id) . '.' . env('SHARE_DOMAIN') . '/reader?fromtype=readershare&bid=' . $bid . '&cid=' . ($first_cid) . '&fromflag=' . ($this->uid) . '&fromcid=' . $cid;
        }
        $js_config['share_url'] = $share_url;
        return response()->success($js_config);
    }
}