<?php

namespace BYDAuto\Commands;

use BYDAuto\Models\Testdrive;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class BYDAutoNoticeCommand extends Command
{
    protected $signature = 'bydauto:notice {date?}';

    protected $description = '线索日报';

    public function handle()
    {
        $date = $this->argument('date') ?: Carbon::yesterday()->toDateString();
        $table = (new Testdrive())->getTable();

        $items = DB::table($table)
            ->selectRaw('source, COUNT(*) AS total')
            ->groupByRaw('source')
            ->whereDate('date_created', $date)
            ->get();
        $count = $items->sum('total');
        $sourceMap = [
            'alipromote:99800024' => '自建站99800024',
            'alipromote:100000006' => '自建站100000006',
            'alipromote:cluepackage' => '车生活推送',
            'alipromote:isaas' => '小程序',
        ];

        $users = config('chery-crm.daily_mail_users');
        $users = explode(',', $users);
        $html = \View::make('chery-crm::notice.salesleads-day', compact('items', 'date', 'sourceMap', 'count'))->render();
        Mail::html($html, function ($message) use ($date, $users) {
            $message->subject('线索日报 ' . $date)->to($users);
        });
    }

    public function sourceGroup()
    {
        $table = (new Testdrive())->getTable();

        $items = DB::table($table)
            ->selectRaw('DATE(date_created) AS day, source, COUNT(*) AS total')
            ->groupByRaw('DATE(date_created), source')
            ->orderByRaw('DATE(date_created), source')
            ->get();

        $sourceGroup = $items->groupBy('source');
        $html = \View::make('chery-crm::notice.salesleads', compact('sourceGroup'))->render();
        Mail::html($html, function ($message) {
            $message
                ->subject('销售线索每日通知')
                ->to('ifme.in@gmail.com');
        });
    }
}
