<?php

namespace App\Modules\Order\Services;

use App\Modules\Order\Models\ChannelOrderStatistic;
use App\Modules\Order\Models\ChannelOrderStatisticDate;
use App\Modules\Order\Models\ChannelSendOrderStatistic;
use App\Modules\Order\Models\ChannelSendOrderStatisticDate;
use App\Modules\Trade\Models\Order;
use App\Modules\User\Models\User;
use DB;
use Illuminate\Support\Collection;

class OrderService
{
    /**
     * 增加派单统计金额
     */
    public function increaseSendOrderAmount(string $date, int $channel_id, int $send_order_id, float $amount, string $pay_time)
    {
        $date_statistic = ChannelSendOrderStatisticDate::where([
                                                                   'date'          => $date,
                                                                   'channel_id'    => $channel_id,
                                                                   'send_order_id' => $send_order_id,
                                                               ])->first();
        if ($date_statistic) {
            $date_statistic->amount += $amount;
            $date_statistic->save();
        } else {
            ChannelSendOrderStatisticDate::create([
                                                      'date'          => $date,
                                                      'channel_id'    => $channel_id,
                                                      'send_order_id' => $send_order_id,
                                                      'amount'        => $amount,
                                                  ]);
        }
        $statistic = ChannelSendOrderStatistic::where([
                                                          'channel_id'    => $channel_id,
                                                          'send_order_id' => $send_order_id,
                                                      ])->first();
        if ($statistic) {
            $statistic->amount += $amount;
            $statistic->save();
        } else {
            ChannelSendOrderStatistic::create([
                                                  'channel_id'     => $channel_id,
                                                  'send_order_id'  => $send_order_id,
                                                  'first_pay_time' => $pay_time,
                                                  'amount'         => $amount,
                                              ]);
        }
    }

    /**
     * 增加派单用户统计金额
     */
    public function increaseUserSendOrderAmount(string $date, int $channel_id, int $send_order_id, float $amount, string $pay_time)
    {
        $date_statistic = ChannelSendOrderStatisticDate::where([
                                                                   'date'          => $date,
                                                                   'channel_id'    => $channel_id,
                                                                   'send_order_id' => $send_order_id,
                                                               ])->first();
        if ($date_statistic) {
            $date_statistic->user_amount += $amount;
            $date_statistic->save();
        } else {
            ChannelSendOrderStatisticDate::create([
                                                      'date'          => $date,
                                                      'channel_id'    => $channel_id,
                                                      'send_order_id' => $send_order_id,
                                                      'user_amount'   => $amount,
                                                  ]);
        }
        $statistic = ChannelSendOrderStatistic::where([
                                                          'channel_id'    => $channel_id,
                                                          'send_order_id' => $send_order_id,
                                                      ])->first();
        if ($statistic) {
            $statistic->user_amount += $amount;
            $statistic->save();
        } else {
            ChannelSendOrderStatistic::create([
                                                  'channel_id'     => $channel_id,
                                                  'send_order_id'  => $send_order_id,
                                                  'first_pay_time' => $pay_time,
                                                  'user_amount'    => $amount,
                                              ]);
        }
    }

    /**
     * 增加站点统计金额
     */
    public function increaseChannelAmount(string $date, int $channel_id, float $amount)
    {
        $date_statistic = ChannelOrderStatisticDate::where([
                                                               'date'       => $date,
                                                               'channel_id' => $channel_id,
                                                           ])->first();
        if ($date_statistic) {
            $date_statistic->amount += $amount;
            $date_statistic->save();
        } else {
            ChannelOrderStatisticDate::create([
                                                  'date'       => $date,
                                                  'channel_id' => $channel_id,
                                                  'amount'     => $amount,
                                              ]);
        }
        $statistic = ChannelOrderStatistic::where('channel_id', $channel_id)->first();
        if ($statistic) {
            $statistic->amount += $amount;
            $statistic->save();
        } else {
            ChannelOrderStatistic::create([
                                              'channel_id' => $channel_id,
                                              'amount'     => $amount,
                                          ]);
        }
    }

    /**
     * 查找当日订单
     */
    private function findOrders(string $date)
    {
        return Order::where([
                                ['status', '=', 'PAID'],
                                ['created_at', '>=', $date],
                                ['created_at', '<=', $date . ' 23:59:59'],
                            ])
            ->select('send_order_id', 'distribution_channel_id', 'created_at', 'uid', 'price')
            ->get();
    }

    /**
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public function getSendOrdersByDate(string $startTime, string $endTime): array
    {
        $result = Order::where([
                                   ['created_at', '>=', $startTime],
                                   ['created_at', '<=', $endTime],
                                   ['send_order_id', '>', 0],
//            ['status', '=', 'PAID'],
                               ])->get();

        return $result ? $result->toArray() : [];
    }

    /**
     * 查找用户
     */
    private function findUsers(array $uids)
    {
        return User::whereIn('id', $uids)->select('id', 'send_order_id')->get();
    }

    /**
     * 重算站点充值金额
     */
    private function reCalcChannelOrderAmount(string $date, int $channel_id, float $amount)
    {
        ChannelOrderStatisticDate::updateOrCreate([
                                                      'date'       => $date,
                                                      'channel_id' => $channel_id,
                                                  ], [
                                                      'amount' => $amount,
                                                  ]);
        $amount = ChannelOrderStatisticDate::where('channel_id', $channel_id)->sum('amount');
        ChannelOrderStatistic::updateOrCreate([
                                                  'channel_id' => $channel_id,
                                              ], [
                                                  'amount' => $amount,
                                              ]);
    }

    /**
     * 重算派单用户充值金额
     */
    private function reCalcUserSendOrderAmount(string $date, int $channel_id, Collection $orders)
    {
        $uids             = $orders->pluck('uid')->all();
        $users            = $this->findUsers($uids);
        $send_order_users = $users->groupBy('send_order_id')->toArray();
        foreach ($send_order_users as $send_order_id => $item) {
            $uids   = collect($item)->pluck('id')->all();
            $amount = $orders->whereIn('uid', $uids)->sum('price');
            ChannelSendOrderStatisticDate::updateOrCreate([
                                                              'date'          => $date,
                                                              'channel_id'    => $channel_id,
                                                              'send_order_id' => $send_order_id,
                                                          ], [
                                                              'user_amount' => $amount,
                                                          ]);
            $amount = ChannelSendOrderStatisticDate::where('send_order_id', $send_order_id)->sum('user_amount');
            ChannelSendOrderStatistic::updateOrCreate([
                                                          'channel_id'    => $channel_id,
                                                          'send_order_id' => $send_order_id,
                                                      ], [
                                                          'user_amount' => $amount,
                                                      ]);
        }
    }

    /**
     * 重算派单充值金额
     */
    private function reCalcSendOrderAmount(string $date, int $channel_id, Collection $orders)
    {
        $send_order_users = $orders->groupBy('send_order_id')->toArray();
        foreach ($send_order_users as $send_order_id => $item) {
            $amount = collect($item)->sum('price');
            ChannelSendOrderStatisticDate::updateOrCreate([
                                                              'date'          => $date,
                                                              'channel_id'    => $channel_id,
                                                              'send_order_id' => $send_order_id,
                                                          ], [
                                                              'amount' => $amount,
                                                          ]);
            $amount         = ChannelSendOrderStatisticDate::where('send_order_id', $send_order_id)->sum('amount');
            $first_pay_time = Order::where(['send_order_id' => $send_order_id, 'status' => 'PAID'])->min('created_at');
            ChannelSendOrderStatistic::updateOrCreate([
                                                          'channel_id'    => $channel_id,
                                                          'send_order_id' => $send_order_id,
                                                      ], [
                                                          'amount'         => $amount,
                                                          'first_pay_time' => $first_pay_time,
                                                      ]);
        }
    }

    public function reCalcOrderStatisticAmount(string $date)
    {
        $orders         = $this->findOrders($date);
        $channel_orders = $orders->groupBy('distribution_channel_id')->toArray();
        foreach ($channel_orders as $channel_id => $channel_order) {
            $colllection = collect($channel_order);
            $amount      = $colllection->sum('price');
            $this->reCalcChannelOrderAmount($date, $channel_id, $amount);
            $this->reCalcSendOrderAmount($date, $channel_id, $colllection);
            $this->reCalcUserSendOrderAmount($date, $channel_id, $colllection);
        }
    }

    #region 派单按用户注册统计

    /**
     * 获取时间段内的派单号
     * @param $start
     * @param $end
     * @return array
     */
    public function getSendOrderIdByTime($start, $end): array
    {
        $order  = new Order();
        $result = $order->getSendOrderIdByTime($start, $end);
        return $result;
    }

    /**
     * 获取时间段内派单首充数,和首充金额
     * @param $start
     * @param $end
     * @return array
     */
    public function getSendOrderFirstPayCountAndPriceByTime($start, $end): array
    {
        $order  = new Order();
        $result = $order->getSendOrderFirstPayCountAndPriceByTime($start, $end);
        return $result;
    }

    /**
     * 根据派单ID获取截止时间点前派单首充数,和首充金额
     * @param $send_order_id
     * @param $end
     * @return array
     */
    public function getSendOrderFirstPayCountAndPriceByID($send_order_id, $end): array
    {
        $order  = new Order();
        $result = $order->getSendOrderFirstPayCountAndPriceByID($send_order_id, $end);
        return $result;
    }

    /**
     * 获取时间段内派单充值数和总金额
     * @param $start
     * @param $end
     * @return array
     */
    public function getSendOrderSuccessPayCountByTime($start, $end): array
    {
        $order  = new Order();
        $result = $order->getSendOrderSuccessPayCountByTime($start, $end);
        return $result;
    }

    /**
     * 根据派单ID获取时间段内派单充值数和总金额
     * @param $send_order_id
     * @param $end
     * @return array
     */
    public function getSendOrderSuccessPayCountByID($send_order_id, $end): array
    {
        $order  = new Order();
        $result = $order->getSendOrderSuccessPayCountByID($send_order_id, $end);
        return $result;
    }

    /**
     * 获取时间段内派单付费人数
     * @param $start
     * @param $end
     * @return array
     */
    public function getSendOrderSuccessPayUserCountByTime($start, $end): array
    {
        $order  = new Order();
        $result = $order->getSendOrderSuccessPayUserCountByTime($start, $end);
        return $result;
    }



    /**
     * 获取时间段内派单N小时充值金额
     * @param $start
     * @param $end
     * @param $hour
     * @return array
     */
    public function getSendOrderPayPriceByHour($start, $end, $hour): array
    {
        $order  = new Order();
        $result = $order->getSendOrderPayPriceByHour($start, $end, $hour);
        return $result;
    }

    /**
     * 获取时间段内派单N小时充值金额
     * @param $send_order_id
     * @param $end
     * @param $hour
     * @return array
     */
    public function getSendOrderPayPriceByIdAndHour($send_order_id, $end, $hour): array
    {
        $order  = new Order();
        $result = $order->getSendOrderPayPriceByIdAndHour($send_order_id, $end, $hour);
        return $result;
    }

    /**
     * 获取时间段内派单N小时(首充或非首充33)用户数
     * @param $start
     * @param $end
     * @param $hour
     * @param int $first_pay_type 首充类型 -1全部 0非首充  1首充
     * @return array
     */
    public function getSendOrderPayUserCountByHour($start, $end, $hour, $first_pay_type =-1): array
    {
        $order  = new Order();
        $result = $order->getSendOrderPayUserCountByHour($start, $end, $hour, $first_pay_type);
        return $result;
    }

    /**
     * 获取时间段内派单N小时(首充或非首充33)用户数
     * @param $send_order_id
     * @param $end
     * @param $hour
     * @param int $first_pay_type 首充类型 -1全部 0非首充  1首充
     * @return array
     */
    public function getSendOrderPayUserCountByIdAndHour($send_order_id, $end, $hour, $first_pay_type =-1): array
    {
        $order  = new Order();
        $result = $order->getSendOrderPayUserCountByIdAndHour($send_order_id, $end, $hour, $first_pay_type);
        return $result;
    }
    #endregion
}