<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\Notification;
use App\Models\Order;
use App\Models\Part;
use App\Models\Spec;
use App\Models\UseRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new Notification();
    }

    public function getStat(Request $request)
    {
        $user = Auth::guard('mini')->user();
        $not_read = $this->model->where('user_id', $user->id)->where('is_read', 2)->count();
        $is_read = $this->model->where('user_id', $user->id)->where('is_read', 1)->count();
        return $this->success(['data' => [$not_read, $is_read]]);
    }

    public function get(Request $request)
    {
        $user = Auth::guard('mini')->user();
        $is_read = $request->input('is_read');
        $items = $this->model->where('user_id', $user->id)->where('is_read', $is_read)->orderBy('created_at', 'desc');
        $items = $items->paginate();
        foreach ($items as $item) {
            $data = $item->getNameContent();
            $item->name = $data['name'];
            $item->content = $data['content'];
        }
        return $this->success(['data' => $items->items()]);
    }

    public function notReadCount(Request $request)
    {
        $user = Auth::guard('mini')->user();
        $count = $this->model->where('user_id', $user->id)->where('is_read', 2)->count();
        return $this->success(['data' => $count]);
    }

    public function change(Request $request)
    {
        $user = Auth::guard('mini')->user();
        if($request->input('type') == 'has_read') {
            $this->model->where('user_id', $user->id)->update(['is_read' => 1]);
        } else if($request->input('type') == 'empty') {
            $this->model->where('user_id', $user->id)->where('is_read', 1)->delete();
        } else if($request->input('type') == 'read_one') {
            $this->model->where('id', $request->input('id'))->update(['is_read' => 1]);
        }
        return $this->success();
    }

    public function detail(Request $request)
    {
        $item = $this->model->find($request->input('id'));
        if(!$item) return $this->error(['msg' => '通知不存在']);
        $item->update(['is_read' => 1]);
        $order = Order::find($item->order_id);
        if($order) {
            $order->formatOrder($order);
            $item->order = $order;
            $data = $item->getNameContent();
            $item->name = $data['name'];
            $item->content = $data['content'];
        }
        return $this->success(['data' => $item]);
    }
}
