<?php

namespace App\Http\Controllers\Admin;


use App\Exports\WorkOrderExport;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\ServiceUser;
use App\Models\User;
use App\Models\WorkOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class WorkServerController extends Controller
{
    use ResponseJson;

    public function getWorkOrderList(Request $request)
    {
        try {
            $status = $request->get('status');
            $page_size = $request->get('page_size',15);
            $list = WorkOrder::when($status !== null, function ($query) use ($status) {
                $query->where('status', $status);
            })->orderByDesc('id')
                ->paginate($page_size);

            foreach ($list as $item){
                $item->images = json_decode($item->images,true);
                $item->deal_images = json_decode($item->deal_images,true);
                $user_info = ServiceUser::where('user_id',$item->user_id)->first();
                $item->user_name = $user_info->name??'';
                $item->user_mobile = $user_info->mobile??'';
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            Log::info('getWorkOrderList:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 导出工单数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function exportWorkOrder(Request $request){
        try {
            $status = $request->get('status');
            $list = WorkOrder::when($status !== null, function ($query) use ($status) {
                $query->where('status', $status);
            })->orderByDesc('id')->get();

            foreach ($list as $item){
                $user_info = ServiceUser::where('user_id',$item->user_id)->first();
                $item->user_name = $user_info->name??'';
                $item->user_mobile = $user_info->mobile??'';
            }
            return Excel::download(new WorkOrderExport($list), 'work_order.xlsx');
        }catch (\Exception $e){
            Log::info('exportWorkOrder:'.$e->getMessage());
            return $this->jsonResponse(1,$e->getMessage());
        }
    }
}
