<?php

namespace App\Modules\Subscribe\Services;

use DB;
use App\Modules\User\Services\UserService;
use App\Modules\Subscribe\Models\ChapterOrder;

class ChapterOrderService
{


    //判断是否订购
    public function checkIsOrdered($uid, $bid, $cid)
    {
        $chapter_model = new ChapterOrder();
        $chapter_model->setCurrentTable($uid);
        return $chapter_model->where('uid', $uid)
            ->where('bid', $bid)
            ->where('cid', $cid)
            ->count();
    }

    //判断本书是否订购过
    public static function checkBookIsOrdered($uid, $bid){
        $chapter_model = new ChapterOrder();
        $chapter_model->setCurrentTable($uid);
        return $chapter_model->where('uid', $uid)
            ->where('bid', $bid)
            ->count();
    }

    /**
     * 根据uid章节订购信息
     * @return
     */
    public function getByUid($uid, $page_size)
    {
        $chapter_model = new ChapterOrder();
        $chapter_model->setCurrentTable($uid);
        return $chapter_model->where('uid', $uid)->orderBy('created_at', 'desc')->paginate($page_size);
    }


    /**
     * 根据用户id获取用户的订购记录
     * @param $uid  用户id
     * @param string $startTime 开始时间
     * @param string $endTime 结束时间
     * @param bool $isAll 获取所有
     * @return mixed
     */
    public static function getRecordByUid($uid, $startTime = "", $endTime = "", $isAll = false)
    {
        $chapter_model = new ChapterOrder();
        $chapter_model->setCurrentTable($uid);

        $chapter = $chapter_model->where('uid', $uid)->orderBy('updated_at', 'desc');
        if ($startTime) {
            $chapter->where('updated_at', '>=', $startTime);
        }
        if ($endTime) {
            $chapter->where('updated_at', '<=', $endTime . ' 23:59:59');
        }

        if ($isAll) {
            return $chapter->get();
        } else {
            return $chapter->paginate();
        }
    }


    /**
     * 获取章节消费总额
     * @param $uid
     * @return mixed
     */
    public static function getChapterTotalConsume($uid)
    {
        $chapter_model = new ChapterOrder();
        $chapter_model->setCurrentTable($uid);
        return $chapter_model->where('uid', $uid)->sum('fee');
    }


    /**
     * 获取章节消费总额
     * @param $uid
     * @return mixed
     */
    public static function getChapterTotalConsumeByUserIdAndTime($uid, $startTime = "", $endTime = "")
    {
        $chapter_model = new ChapterOrder();
        $chapter_model->setCurrentTable($uid);

        $chapter = $chapter_model->where('uid', $uid);
        if ($startTime) {
            $chapter->where('updated_at', '>=', $startTime);
        }
        if ($endTime) {
            $chapter->where('updated_at', '<=', $endTime . ' 23:59:59');
        }
        return $chapter->sum('fee');
    }


    /**
     * 获取订购章节数
     * @param $uid
     * @return mixed
     */
    public static function getUserRecordCount($uid)
    {
        $chapter_model = new ChapterOrder();
        $chapter_model->setCurrentTable($uid);
        return $chapter_model->where('uid', $uid)->count();
    }

    /**
     * 根据uid章节订购信息
     * @return
     */
    public static function addOrderAndDecrUserBalance($data, $uid)
    {
        $chapterOrder = new ChapterOrder();
        $chapterOrder->setCurrentTable($uid);
        $chapterOrder->uid = $uid;
        $chapterOrder->bid = $data['bid'];
        $chapterOrder->cid = $data['cid'];
        $chapterOrder->fee = $data['fee'];
        $chapterOrder->chapter_name = $data['chapter_name'];
        $chapterOrder->book_name = $data['book_name'];
        $chapterOrder->send_order_id = $data['send_order_id'];
        $chapterOrder->distribution_channel_id = $data['distribution_channel_id'];
        $user = UserService::getById($uid);
        DB::beginTransaction();
        $res = $result1 = $result2 = $result = null;
        try {
            if ($user->charge_balance >= $data['fee']) {
                $chapterOrder->charge_balance = $data['fee'];
                $chapterOrder->reward_balance = 0;
                $res = $chapterOrder->save();
                //$result1 = $user->decrement('balance', $data['fee']);
                //$result2 = $user->decrement('charge_balance', $data['fee']);
                $user->balance -= $data['fee'];
                $user->charge_balance -= $data['fee'];
            } elseif ($user->charge_balance > 0) {
                $chapterOrder->charge_balance = $user->charge_balance;
                $chapterOrder->reward_balance = $data['fee'] - $user->charge_balance;
                $reward = $data['fee'] - $user->charge_balance;
                $res = $chapterOrder->save();
                //$result1 = $user->decrement('balance', $data['fee']);
                //$result2 = $user->decrement('charge_balance', $user->charge_balance);
                //$result3 = $user->decrement('reward_balance', $reward);

                $user->balance -= $data['fee'];
                $user->charge_balance = 0;
                $user->reward_balance -= $reward;
            } else {
                $chapterOrder->charge_balance = 0;
                $chapterOrder->reward_balance = $data['fee'];
                $res = $chapterOrder->save();
                //$result1 = $user->decrement('balance', $data['fee']);
                //$result2 = $user->decrement('reward_balance', $data['fee']);
                $user->balance -= $data['fee'];
                $user->reward_balance -=  $data['fee'];
            }
            if ($user->is_new == 1) {
                $user->is_new = 0;
            }
            $result = $user->save();
        } catch (\Exception $e) {
            //\Log::info($e);
        }

        if ($res && $result) {
            DB::commit();
            return true;
        }
        DB::rollback();
        return false;
    }

    /**
     * @param $send_order_id
     * @param $start_time
     * @param $end_time
     * @return array ['total'=>133,'charge_balance'=>45,'reward_balance'=>$reward_balance]
     */
    public static function getSendorderTotal($send_order_id, $start_time, $end_time)
    {
        $chapter_model = new ChapterOrder();
        $charge_balance = 0;
        $reward_balance = 0;
        $fee = 0;
        /*
        for ($i = 0;$i<512;$i++){
            $chapter_model->setCurrentTable($i);
            $charge_balance += $chapter_model->where('send_order_id',$send_order_id)->whereBetween('created_at',[$start_time,$end_time])->sum('charge_balance');
            $reward_balance += $chapter_model->where('send_order_id',$send_order_id)->whereBetween('created_at',[$start_time,$end_time])->sum('reward_balance');
            $fee            += $chapter_model->where('send_order_id',$send_order_id)->whereBetween('created_at',[$start_time,$end_time])->sum('fee');
        }*/
        $chapter_model = null;
        return ['total' => $fee, 'charge_balance' => $charge_balance, 'reward_balance' => $reward_balance];

    }

}