<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/20
 * Time: 下午5:26
 */

namespace App\Console\Commands;

use App\Modules\Book\Models\Book;
use App\Modules\Subscribe\Services\BookOrderService;
use App\Modules\User\Services\ReadRecordService;
use DB;
use Illuminate\Console\Command;
use Log;

class WholeBookOrderData extends Command
{
    /**
     * 执行命令 检查图书封面
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wholeBookOrderData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '整本书订购的统计';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Log::info('wholeBookOrderData start command');
        $this->loadWholeBookOrderInfo();
        Log::info('wholeBookOrderData end command');
    }

    function loadWholeBookOrderInfo()
    {
        $bookArray = [];
        $lastCidArray = [];
        $pageSize = 10000;
        $totalCount = BookOrderService::getCount();
        $totalPageCount = Ceil($totalCount / $pageSize); ////总页数

        for ($pageIndex = 0; $pageIndex < $totalPageCount; $pageIndex++) {
            $startIndex = $pageIndex * $pageSize;
            $orderInfo = BookOrderService::getOrderInfos($startIndex, $startIndex + $pageSize);
            foreach ($orderInfo as $orderItem) {
                $bid = $orderItem->bid;
                $readRecod = ReadRecordService::getRecordByUidBid($orderItem->uid, $bid);
                if ($readRecod) {
                    $read_cid = explode($readRecod, '_')[0];

                    if (isset($lastCidArray[$bid])) {
                        $last_cid = $lastCidArray[$bid];
                    } else {
                        $cidInfo = Book::where('id', $bid)->select('last_cid')->first();
                        $last_cid = $cidInfo->last_cid;
                        $lastCidArray[$bid] = $last_cid;
                    }

                    if ($read_cid == $last_cid) {
                        $bookArray[$bid] = isset($bookArray[$bid]) ? ($bookArray[$bid] + 1) : 1;
                    }
                }
            }
        }

        foreach ($bookArray as $bid => $count) {
            DB::table('temp_book_order_stats')->where('bid', $bid)->update(['read_end_sub_user_num' => $count]);
        }
    }
}