<?php
namespace App\Domains\Stats\Http\Controllers;

use Carbon\Carbon;
use App\Models\Card\Card;
use Illuminate\Http\Request;
use App\Models\Virtual\OrderCard;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

/**
 * 销售激活统计
 */
class SoldActivatedController extends Controller
{
    protected $request;

    /**
     * 构造函数，自动注入.
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 列表.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $conditions = $this->request->all();

        Validator::validate($conditions, [
            'starttime' => ['required', 'date'],
            'endtime' => ['required', 'date', 'after_or_equal:starttime'],
        ], [
            'starttime.required' => '开始时间不能为空',
            'endtime.required' => '结束时间不能为空',
            'endtime.after_or_equal' => '结束时间必须大于等于开始时间',
        ]);

        $starttime = Carbon::parse($conditions['starttime'])->startOfMonth();
        $endtime = Carbon::parse($conditions['endtime'])->endOfMonth();

        $query = OrderCard::leftJoin('cards', 'cards.sim', '=', 'virtual_order_cards.sim')
        ->select([
            'company_id',
            DB::raw('count(*) as sells'),
            DB::raw('count(CASE WHEN virtual_activated_at IS NOT NULL THEN 1 END) as activates'),
            DB::raw("to_char(virtual_activated_at, 'YYYY-MM')  as activated_month"),
            DB::raw("to_char(virtual_order_cards.created_at, 'YYYY-MM') as order_month"),
        ])->groupBy([
            'company_id',
            DB::raw("to_char(virtual_activated_at, 'YYYY-MM')"),
            DB::raw("to_char(virtual_order_cards.created_at, 'YYYY-MM')")
        ]);

        $query = $query->where('virtual_order_cards.created_at', '>=', $starttime)->where('virtual_order_cards.created_at', '<=', $endtime);

        if (isset($conditions['company_id'])) {
            $query = $query->where('company_id', $conditions['company_id']);
        }

        $list = $query->get();

        if (!$list->isEmpty()) {
            $maxMonth = max($list->pluck('activated_month')->toArray());
            $maxMonth = Carbon::parse($maxMonth);
        }

        $list = $list->groupBy('company_id');

        $res = [];

        foreach ($list as $company_id => $companyList) {
            $companyList = $companyList->groupBy('order_month');

            for ($i=0; $i <= $endtime->diffInMonths($starttime); $i++) {
                $month = $starttime->copy()->addMonths($i)->format('Y-m');

                $monthList =  $companyList[$month] ?? collect();

                $monthList =  $monthList->keyBy('activated_month');

                $res[$company_id][$month]['order_month'] = $month;
                $res[$company_id][$month]['sells'] = 0;

                for ($j=0; $j <= $maxMonth->diffInMonths($starttime); $j++) {
                    $m = $starttime->copy()->addMonths($j)->format('Y-m');

                    $item = $monthList[$m] ?? [];

                    $res[$company_id][$month]['sells'] += $item['sells'] ?? 0;
                    $res[$company_id][$month][$m] = $item['activates'] ?? 0;
                }
            }

            $res[$company_id] = array_values($res[$company_id]);
        }

        return res($res, '销售激活统计', 201);
    }
}
