<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\ProductCategory;
use App\Models\Showroom;
use App\Models\StatProduct;
use App\Models\StatProductDownload;
use App\Models\StatShowroom;
use Carbon\Carbon;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\Dashboard;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Card;
use Dcat\Admin\Widgets\Tab;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;

class DashBoardController extends Controller
{
    public function view(Content $content)
    {
        if(request()->isMethod('post')){
            $isProduct = request()->input('product', 1);
            if($isProduct){
                return $this->viewerProduct();
            }
            return $this->viewerShowroom();
        }
        $isProduct = \request('product',1);
        if ($isProduct) {
            $view = $this->viewerProduct();
        }else{
            $view = $this->viewerShowroom();
        }
        return $content->body($view);
    }


    public function download(Content $content)
    {
        $this->reload();
        if(request()->isMethod('post')){
            return $this->queryData('download');
        }

        $categories = ProductCategory::with(['products:id,name,cate_id'])->get();
        $data = [
            'categories' => $categories
        ];
        static::loadJS('download');
        return $content->body(view('admin.dashboard.download', $data));
    }

    private function viewerShowroom()
    {
        $this->reload();
        if(request()->isMethod('post')){
            return $this->queryData('showroom');
        }
        static::loadJS('showroom');
        $showrooms = Showroom::all();
        $data = [
            'showrooms' => $showrooms
        ];
        return view('admin.dashboard.showroom', $data);
    }

    private function viewerProduct()
    {
        $this->reload();
        if(request()->isMethod('post')){
            return $this->queryData('product');
        }
        static::loadJS('product');
        $categories = ProductCategory::with(['products:id,name,cate_id'])->get();
        $data = [
            'categories' => $categories,
        ];
        return view('admin.dashboard.product', $data);
    }

    private function queryData($type): JsonResponse
    {
        $startAt = \request()->input('startAt','');
        $endAt = \request()->input('endAt','');
        $productIds = \request()->input('productIds',[]);
        $name = \request()->input('name','');
        $dates = $this->getDays($startAt, $endAt);

        $userIds = $this->getUserIds();

        if(empty($productIds) || ($name && empty($userIds))){
            return Admin::json()->data(['dates' => $dates])->success('');
        }


        if($type == 'download' || $type == 'product'){
            $model = $type == 'download' ? app(StatProductDownload::class) :app(StatProduct::class);
            $model = $model->with([
                'product' => function($query) use ($productIds){
                    /* @var Builder $query*/
                    $query->when($productIds, function ($query) use ($productIds){
                        /* @var Builder $query*/
                        return $query->whereIn('id', $productIds);
                    });
                },
            ])->selectRaw(
                'product_id,DATE_FORMAT(created_at, "%Y-%m-%d") as date, count(*) as count'
            );
        }else{
            $model = StatShowroom::with([
                'showroom' => function($query) use ($productIds){
                    /* @var Builder $query*/
                    $query->when($productIds, function ($query) use ($productIds){
                        /* @var Builder $query*/
                        return $query->whereIn('id', $productIds);
                    });
                },
            ])->selectRaw(
                'showroom_id,showroom_id as product_id,DATE_FORMAT(created_at, "%Y-%m-%d") as date, count(*) as count'
            );
        }

        /* @var Model $model*/
        $lists = $model->when($startAt, function ($query) use ($startAt){
            return $query->where('created_at', '>=',$startAt);
        })->when($endAt, function ($query) use ($endAt){
            return $query->where('created_at', '<=',$endAt);
        })->when($userIds, function ($query) use ($userIds){
            return $query->whereIn('user_id', $userIds);
        })->groupBy(['product_id','date'])
            ->get();

        $statData = [];
        foreach ($lists as $list){
            $statData[$list->date][$list->product_id] = $list->toArray();
        }


        $analyzeData = [];
        foreach ($productIds as $id){
            foreach ($dates as $date){
                $analyzeData[$id][] = $statData[$date][$id]['count'] ?? 0;
            }
        }
        $data = [
            'dates' => $dates,
        ];
        foreach ($analyzeData as $key => $value){
            $data['analyze_'.$key] = $value;
        }

        return Admin::json()->data($data)->success('');

    }

    private function reload()
    {
        $pjax = request()->input('_pjax', 0);
        if($pjax){
            header('location:'.request()->url());
            exit;
        }
    }

    private static function getDays($startAt, $endAt): array
    {
        $startAt = $startAt ?: Carbon::today()->subDays(30)->toDateString();
        $endAt = $endAt ?: Carbon::today()->toDateString();
        $daysPeriod = Carbon::parse($startAt)->daysUntil($endAt);
        return iterator_to_array(
            $daysPeriod->map(function ($day){
                return Carbon::make($day)->toDateString();
            })
        );
    }

    private function getUserIds(): array
    {
        $name = \request()->input('name','');
        if(empty($name)) return [];
        $account = Account::with([
            'user:id,account_id'
        ])->where('user_name', 'Like', "%$name%")->get();
        return iterator_to_array(
            $account->map(function ($row){
                return $row->user->id;
            })
        );
    }

    private static function loadJS($type)
    {
        \Admin::css([
            'vendor/dcat-admin/dcat/plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css'
        ]);
        $analyzeJS = '/static/js/analyze.js';
        $analyzeJS = $analyzeJS.'?t='.fileatime(public_path($analyzeJS));

        \Admin::js([
            '/vendor/dcat-admin/dcat/plugins/moment/moment-with-locales.min.js',
            '/vendor/dcat-admin/dcat/plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js',
            '/static/js/echarts.common.min.js',
            $analyzeJS,
        ]);

        if(is_array($type)){
            foreach ($type as $item){
                $pageJS = "/static/js/analyze.{$item}.js";
                $pageJS = $pageJS.'?t='.fileatime(public_path($pageJS));
                \Admin::js($pageJS);
            }
        }else{
            $pageJS = "/static/js/analyze.{$type}.js";
            $pageJS = $pageJS.'?t='.fileatime(public_path($pageJS));
            \Admin::js($pageJS);
        }
    }
}
