<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\Device;
use App\Models\DeviceName;
use App\Models\Order;
use App\Models\OrderDevice;
use App\Models\OrderOverviewModel;
use App\Models\Project;
use App\Models\RentType;
use App\Models\Spec;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use phpDocumentor\Reflection\DocBlock;

class DataController extends BaseController
{
    protected $order;

    protected $order_device;

    protected $order_ids = [];

    protected $project_ids = [];

    protected $start_at;

    protected $end_at;

    public function __construct()
    {
        $this->order = new Order();
        $this->order_device = new OrderDevice();
    }

    public function getYearsAndMonths(Request $request)
    {
        $years = [];

        $this_year = Carbon::now()->year;
        for($i = 5; $i >= 0; $i--) {
            array_push($years, [
                'name' => $this_year - $i,
                'id' => $this_year - $i
            ]);
        }
        array_push($years, ['name' => '所有年', 'id' => '']);
        $months = [];
        for($i = 1; $i < 13; ++$i) {
            array_push($months, [
                'name' => $i . '月',
                'id' => $i
            ]);
        }
        $month = Carbon::now()->month;
        return $this->success(['data' => [
            'array' => [$years, $months],
            'index' => [count($years) - 2, $month - 1]
        ]]);
    }

    public function getDateInfo()
    {
        $max_date = Carbon::now()->toDateString();
//        $order = $this->order->orderBy('created_at', 'desc')->first();
//        $min_date = $order ? substr($order->created_at, 0, 10) : Carbon::now()->subYear()->toDateString();
        $min_date = Carbon::now()->subYears(10)->toDateString();
        $date = substr($max_date, 0, 7);
        $start_date = $max_date;
        $end_date = Carbon::now()->addMonth()->toDateString();
        $start_date = substr($start_date, 0, 7);
        $end_date = substr($end_date, 0, 7);
        return $this->success(['data' => compact('date', 'min_date', 'max_date', 'start_date', 'end_date')]);
    }

    public function getStartAt($date)
    {
        return strlen($date) <= 7 ? $date . '-01 00:00:00' : $date . ' 00:00:00';
    }

    public function getEndAt($date)
    {
        return strlen($date) <= 7 ? Carbon::createFromTimeString($date . '-01 00:00:00')->addMonth(1)->toDateTimeString() : Carbon::createFromTimeString($date . ' 00:00:00')->addDay(1)->toDateTimeString();
    }

    public function getOrders(Request $request)
    {
        $order_ids = $this->getOrderIds($request);

        $start_at = $this->getStartAt($request->input('start_date'));
        $end_at = $this->getEndAt($request->input('end_date'));
        return $this->order->whereIn('id', $order_ids)->where([
            ['type', '=', 1],
            ['created_at', '>=', $start_at],
            ['created_at', '<', $end_at]
        ])->get();
    }

    public function getOrderIds(Request $request)
    {
        $ids = $request->input('project_ids');
        if(!$ids || count($ids) < 0) return false;
        $this->project_ids = $ids;
        $order_devices = $this->order_device->whereIn('project_id', $ids);

        $in_items = ['device_ids', 'device_name_ids', 'spec_ids', 'rent_type_ids'];
        $key_items = ['device_id', 'device_name_id', 'spec_id', 'rent_type_id'];
        foreach ($in_items as $key => $item) {
            if($request->input($item)) {
                $item_ids = collect($request->input($item))->filter(function($id) {
                    return $id;
                });
                if($item_ids && $item_ids->count() > 0) {
                    $order_devices = $order_devices->whereIn($key_items[$key], $item_ids);
                }
            }
        }

        return $order_devices->pluck('order_id')->unique();
    }

    public function getStat(Request $request)
    {
        $info = [];
        $device_arr = $request->input('device_ids');
        $device_name_arr = $request->input('device_name_ids');
        $spec_arr = $request->input('spec_ids');
        if (array_sum($device_arr) != 0)
        {
            array_push($info,Device::whereIn('id',$device_arr)->pluck('name')->toArray()) ;
            array_push($info,DeviceName::whereIn('id',$device_name_arr)->pluck('name')->toArray()) ;
            array_push($info,Spec::whereIn('device_id',$device_arr)
                                            ->whereIn('device_name_id',$device_name_arr)
                                            ->whereIn('id',$spec_arr)
                                            ->pluck('name')->toArray());
            array_push($info,RentType::where('id',$request->input('rent_type_ids'))->value('name'));
        }
        if(!$request->input('project_ids')) return $this->error(['msg' => '']);
        if($request->input('chart_type') == 'pie') return $this->getPieData($request);
        else if($request->input('chart_type') == 'radar') return $this->getRadarData($request);
        $orders = $this->getOrders($request);
        if(!$orders) return $this->error(['msg' => '']);
        $names = [];
        $values = [];
        // year|month
        $type = $request->input('type') ? $request->input('type') : 'year';
        $cnt = 0;
        $projects = Project::whereIn('id', $this->project_ids)->where('id','!=',1)->get();
        if(empty($orders->toArray())){
            foreach ($projects as $p){
                $values[] = 0;
                $names[] = $p->name;
            }
        }
        foreach($orders as $item) {
            if($this->inDate($names, $item->created_at, $type)) {
                foreach ($projects as $key => $project) {
                    $values[$key][$cnt-1] = $project->id == $item->project_id ? $values[$key][$cnt-1] + ($item->money / 100) : $values[$key][$cnt-1];
                }

            } else {
                $names[$cnt] = $type == 'year' ? substr($item->created_at, 0, 7) : substr($item->created_at, 0, 10);
                foreach ($projects as $key => $project) {
                    $values[$key][$cnt] = $project->id == $item->project_id ? ($item->money / 100) : 0;
                }
                $cnt = $cnt + 1;
            }
        }
        $legends = $projects->pluck('name');
        return $this->success(['data' => compact('values', 'names', 'legends','info')]);
    }

    public function getRadarData(Request $request)
    {
        $orders = $this->getOrders($request);
        if(!$orders) return $this->error(['msg' => '']);

        $data = [];
        $projects = Project::whereIn('id', $request->input('project_ids'))->get();
        $indicator = [
            ['name' => '累计租赁花费', 'max' => 0],
            ['name' => '累计租赁数量', 'max' => 0],
            ['name' => '平均月消费', 'max' => 0],
            ['name' => '租赁次数', 'max' => 0],
            ['name' => '租赁天数', 'max' => 0]
        ];
        $legends = [];

        foreach($projects as $key => $project) {
            $tmp_orders = $orders->where('project_id', $project->id);
            $total_money = $tmp_orders->sum('money') / 100;
            $total_num = OrderDevice::whereIn('order_id', $orders->where('project_id', $project->id)->pluck('id'))->count();
            $months = $this->getMonths($tmp_orders);
            $mean_month = $total_money / $months;
            $rent_times = $tmp_orders->count();
            $rent_days = $this->getRentDays($tmp_orders);
            $indicator[0]['max'] = max($indicator[0]['max'], $total_money);
            $indicator[1]['max'] = max($indicator[1]['max'], $total_num);
            $indicator[2]['max'] = max($indicator[2]['max'], $mean_month);
            $indicator[3]['max'] = max($indicator[3]['max'], $rent_times);
            $indicator[4]['max'] = max($indicator[4]['max'], $rent_days);

            array_push($data, [
                'name' => $project->name,
                'value' => [$total_money, $total_num, $mean_month, $rent_times, $rent_days]
            ]);

            array_push($legends, $project->name);
        }

        return $this->success(['data' => compact('data', 'legends', 'indicator')]);
    }

    public function getMonths($orders)
    {
        $min_at = $orders->min('created_at');
        $max_at = $orders->max('updated_at');
        if($max_at && $max_at) $months = $min_at->diffInMonths($max_at);
        else $months = 1;
        return $months ? $months : 1;
    }

    public function getRentDays($orders)
    {
        $order_ids = $orders->pluck('id');
        $order_devices = OrderDevice::whereId('order_id', $order_ids)->get();
        $days = 0;
        foreach($order_devices as $order_device) {
            if($order_device->start_date && $order_device->end_date) {
                $days = $days + Carbon::createFromTimeString($order_device->start_date . ' 00:00:00')->diffInDays($order_device->end_date);
            }
        }
        return $days;
    }

    public function getPieData(Request $request)
    {
        $order_ids = $this->getOrderIds($request);
        if(!$order_ids) return $this->error(['msg' => '']);

        $total = OrderDevice::whereIn('order_id', $order_ids)->count();
        $devices = Device::all();
        $data = [];
        foreach($devices as $device) {
            $tmp = OrderDevice::whereIn('order_id', $order_ids)->where('device_id', $device->id)->count();
            $percent = $total > 0 ? round(($tmp / $total * 10000)) / 100 : '0';
            array_push($data, ['name' => $device->name, 'value' => $percent]);
        }

        $legends = $devices->pluck('name');
        return $this->success(['data' => compact('data', 'legends')]);
    }

    public function getDetailData(Request $request)
    {
//        $order_ids = $this->getOrderIds($request);
//        if(!$order_ids) return $this->error(['msg' => '']);
//        $order_devices = OrderDevice::whereIn('order_id', $order_ids)->orderBy('created_at')->get();
//        $devices = Device::all();
//
//        $dates = [];
//        // year|month
//        $type = $request->input('type') ? $request->input('type') : 'year';
//        $columns = [];
//        $date = '';
//        $values = [
//            ['date' => '日期', 'total' => '总金额', 'data' => $devices->pluck('name')]
//        ];
//        foreach($order_devices as $item) {
//            if($this->inDate($dates, $item->created_at, $type)) {
//                foreach($devices as $key => $device) {
//                    $money = $device->id == $item->device_id ? ($item->price * $item->quantity) / 100 : 0;
//                    $columns[$key] = $columns[$key] + $money;
//                }
//            } else {
//                $date = $type == 'year' ? substr($item->created_at, 0, 7) : substr($item->created_at, 0, 10);
//                array_push($dates, $date);
//                if(count($columns) > 0) {
//                    array_push($values, [
//                        'date' => $date,
//                        'total' => collect($columns)->sum() / 100,
//                        'data' => $columns
//                    ]);
//                }
//                $columns = [];
//                foreach($devices as $device) {
//                    $money = $device->id == $item->device_id ? ($item->price * $item->quantity) / 100 : 0;
//                    array_push($columns, $money);
//                }
//            }
//        }
//        if(count($columns) > 0) {
//            array_push($values, [
//                'date' => $date,
//                'total' => collect($columns)->sum(),
//                'data' => $columns
//            ]);
//        }
//        return $this->success(['data' => $values]);


        $date = $this->getStartAt($request->input('date'));
        $year = date('Y',strtotime($date));
        $project_id = $request->input('project_ids');
        $project_id = $project_id[0];
        $devices = Device::all();
        $data = [
            ['date' => '日期', 'total' => '总金额', 'data' => $devices->pluck('name')->toArray()]
        ];
        $items = OrderOverviewModel::whereYear('date',$year)->where('project_id',$project_id)->get()->toArray();
        foreach ($items as &$item)
        {
            $arr = [
                'data'=>[],
            ];
            $arr_data = $devices->pluck('id')->toArray();
            $arr['total'] = $item['total_price']/100;
            $arr['date'] = date('Y-m',strtotime($item['date']));
            //获取到月份的开始时间和结束时间
            $start_at = $item['date'];
            $end_at = $this->getEndAt(date('Y-m',strtotime($item['date'])));
            //获取到订单数组
            $order_arr = Order::where('project_id',$project_id)
                ->where('status',3)
                ->where('type',1)
                ->whereBetween('updated_at',[$start_at,$end_at])
                ->pluck('id')->toArray();
            $order_details = OrderDevice::whereIn('order_id',$order_arr)->get(['quantity','price','device_id'])->groupBy('device_id')->toArray();
            foreach ($order_details as  $key=>&$detail)
            {
                $total_nums = 0;
                foreach ($detail as $detail_value)
                {
                    $total_nums += ($detail_value['price']*$detail_value['quantity'])/100;
                }
                $device_data = $arr_data;
                //重置键值数组
                foreach ($device_data as $k=>&$device_datum)
                {
                    $device_datum = 0;
                }
                $device_data[$key-1] = $total_nums;
                $arr['data']=$device_data;
            }
            array_push($data,$arr);
        }
        return $this->success(['data' => $data]);
    }

    public function getTotalInfo(Request $request)
    {
        if (!$request->input('project_ids'))
        {
            return $this->error(['msg' => '暂未选择项目']);
        }
        $start_at = $this->getStartAt($request->input('date'));
        $end_at = $this->getEndAt($request->input('date'));
        $total_money = $this->order->whereIn('project_id', $request->input('project_ids'))->sum('money') / 100;
        $month_money = $this->order->whereIn('project_id', $request->input('project_ids'))->where([
            ['created_at', '>=', $start_at],
            ['created_at', '<', $end_at]
        ])->sum('money') / 100;
        return $this->success(['data' => compact('total_money', 'month_money')]);
    }

    public function inDate($dates, $created_at, $type)
    {
        $date = $type == 'year' ? substr($created_at, 0, 7) : substr($created_at, 0, 10);
        return in_array($date, $dates);
    }

    public function parseDate($date)
    {
        $now = Carbon::now();
        if(!$date) return ['year' => $now->year, 'month' => $now->month, 'day' => $now->day];
        $items = explode('-', $date);
        $year = $now->year;
        $month = $now->month;
        $day = $now->day;
        if(isset($items[0])) {
            $year = (int)$items[0];
            $year = $year > 2010 && $year < 2050 ? $year : $now->year;
        }
        if(isset($items[1])) {
            $month = (int)$items[1];
            $month = $month > 0 && $month < 13 ? $month : $now->month;
        }
        if(isset($item[2])) {
            $day = (int)$items[2];
            $day = $day > 0 && $day < 32 ? $date : 1;
        }
        return compact('year', 'month', 'day');
    }

    public function getYearAndMonthMoney(Request $request)
    {
        $date = $request->input('date');
        if(!$date) {
            $year_money = Order::where('type', 1)->sum('money') / 100;
            $month_money = $year_money;
        } else {
            $start_year = Carbon::createFromTimeString(substr($date, 0, 4) . '-01-01 00:00:00')->toDateTimeString();
            $end_year = Carbon::createFromTimeString(substr($date, 0, 4) . '-01-01 00:00:00')->addYear()->toDateTimeString();
            $start_month = Carbon::createFromTimeString($date . ' 00:00:00')->toDateTimeString();
            $end_month = Carbon::createFromTimeString($date . ' 00:00:00')->addMonth()->toDateTimeString();
            $year_money = Order::where([
                ['type', 1],
                ['created_at', '>=', $start_year],
                ['created_at', '<', $end_year]
            ])->sum('money') / 100;
            $month_money = Order::where([
                    ['type', 1],
                    ['created_at', '>=', $start_month],
                    ['created_at', '<', $end_month]
                ])->sum('money') / 100;
        }
        return $this->success(['data' => compact('year_money', 'month_money')]);
    }

    public function getSingleStat(Request $request)
    {
        $items = Order::where('type', 1);
        $date = $request->input('date');
        $project_id = $request->input('project_id') ? $request->input('project_id') : Project::where('id','>',1)->first()->id;
        $project = Project::find($project_id);
        $items = $items->where('project_id', $project->id);
        $sort_type = $request->input('sort_type') == 'year' ? 'year' : 'month';
        $date = $date ? $date : Carbon::now()->toDateString();
        $values = [];
        $names = [];
        $name = $sort_type == 'year' ? '每年租赁金额' : '每月租赁金额';
        if($sort_type == 'month') {
            $start_at = Carbon::createFromTimeString($date . ' 00:00:00')->toDateTimeString();
            $end_at = Carbon::createFromTimeString($date . ' 00:00:00')->addYear()->toDateTimeString();
            $items = $items->where([
                ['created_at', '>=', $start_at],
                ['created_at', '<', $end_at]
            ]);
            $items = $items->get();
            for($i = 1; $i < 13; ++$i) {
                $start_at = Carbon::createFromTimeString($date . ' 00:00:00')->addMonths($i - 1)->toDateTimeString();
                $end_at = Carbon::createFromTimeString($date . ' 00:00:00')->addMonths($i)->toDateTimeString();
                $value = $items->where('created_at', '>=', $start_at)->where('created_at', '<', $end_at)->sum('money') / 100;
                array_push($values, $value);
                array_push($names, $i . '月');
            }
        } else {
            $start_at = Carbon::createFromTimeString($date . ' 00:00:00')->toDateTimeString();
            $end_at = Carbon::now()->addYear(1)->toDateTimeString();
            $items = $items->where([
                ['created_at', '>=', $start_at],
                ['created_at', '<', $end_at]
            ]);
            $items = $items->get();
            $cnt = 1;
            $next_year = Carbon::now()->toDateTimeString();
            do {
                $start_at = Carbon::createFromTimeString($date . ' 00:00:00')->addYears($cnt - 1)->toDateTimeString();
                $end_at = Carbon::createFromTimeString($date . ' 00:00:00')->addYears($cnt)->toDateTimeString();
                $value = $items->where('created_at', '>=', $start_at)->where('created_at', '<', $end_at)->sum('money') / 100;
                array_push($values, $value);
                array_push($names, Carbon::createFromTimeString($date . ' 00:00:00')->addYear($cnt - 1)->year . '年');
                $cnt = $cnt + 1;
            } while($cnt < 10 && $end_at <= $next_year);

        }
        return $this->success(['data' => compact('values', 'names', 'project', 'name')]);
    }

    public function getMaxStat(Request $request)
    {
        $info = [];
        if ($request->input('devices')!=null)
        {
            array_push($info,Device::where('id',$request->input('device_ids'))->value('name')) ;
            array_push($info,DeviceName::where('id',$request->input('device_name_ids'))->value('name'))  ;
            array_push($info,Spec::where('device_id',$request->input('device_ids'))->where('device_name_id',$request->input('device_name_ids'))->where('id',$request->input('spec_ids'))->value('name'));
            array_push($info,RentType::where('id',$request->input('rent_type_ids'))->value('name'));
        }
        $date = $request->input('date');
        $date = $date ? $date : Carbon::now()->toDateString();
        $start_at = Carbon::createFromTimeString($date . ' 00:00:00')->toDateTimeString();
        $end_at = Carbon::now()->toDateTimeString();
        $items = OrderDevice::where([
            ['created_at', '>=', $start_at],
            ['created_at', '<', $end_at]
        ]);
        $in_items = ['device_ids', 'device_name_ids', 'spec_ids', 'rent_type_ids'];
        $key_items = ['device_id', 'device_name_id', 'spec_id', 'rent_type_id'];
        foreach ($in_items as $key => $item) {
            if($request->input($item)) {
                $item_ids = collect($request->input($item))->filter(function($id) {
                    return $id;
                });
                if($item_ids && $item_ids->count() > 0) {
                    $items = $items->whereIn($key_items[$key], $item_ids);
                }
            }
        }
        $items = $items->get();
        $projects = Project::where('id','!=',1)->get();
        foreach ($projects as $project) {
            $project->max_price = $items->where('project_id', $project->id)->max('price') / 100;
        }
        $orderBy = $request->input('orderBy');
        if($orderBy == 'asc') $projects = $projects->sortBy('max_price');
        else $projects = $projects->sortByDesc('max_price');
        if ($info == null)
        {
            $values = $projects->pluck('max_price')->toArray();
            foreach ($values as &$value)
            {
                $value = 0;
            }
            $values = 0;
        }else
        {
            $values = $projects->pluck('max_price');
        }
        $names = $projects->pluck('name');
        return $this->success(['data' => compact('values', 'names','info')]);
    }

    public function projectStat(Request $request)
    {
        if($request->input('chartIndex') == 0) {
            return $this->getSingleStat($request);
        } else if($request->input('chartIndex') == 2) {
            return $this->getMaxStat($request);
        }
        $items = Order::where('type', 1);
        $date = $request->input('date');
        if($date) {
            $start_month = Carbon::createFromTimeString($date . ' 00:00:00')->toDateTimeString();
            $end_month = Carbon::createFromTimeString($date . ' 00:00:00')->addMonth()->toDateTimeString();
            $items= $items->where([
                ['created_at', '>=', $start_month],
                ['created_at', '<', $end_month]
            ]);
        }
        $orderBy = $request->input('orderBy');
        $items = $items->groupBy('project_id')->selectRaw('sum(money) as sum, project_id')->pluck('sum', 'project_id');
        $projects = Project::where('id','!=',1)->get();
        foreach ($projects as $project) {
            $project->money = 0;
            foreach ($items as $key => $val) {
                if($key == $project->id) {
                    $project->money = $val / 100;
                    break;
                }
            }
        }
        if($orderBy == 'asc') $projects = $projects->sortBy('money');
        else $projects = $projects->sortByDesc('money');
        $values = $projects->pluck('money');
        $names = $projects->pluck('name');
        return $this->success(['data' => compact('values', 'names')]);
    }
}
