<?php

namespace App\Http\Controllers\Service;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserInfoResource;
use App\Http\Response\ResponseJson;
use App\Models\MedicalReport;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Models\User;
use App\Models\UserInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    use ResponseJson;

    public function userInfo(Request $request, User $user)
    {
        $user_info = UserInfoResource::make($user->userInfo);
        return $this->success('ok', $user_info);
    }

    public function medicalReports(Request $request, User $user)
    {
        $user_id = $user->id;
        $user_info = UserInfo::firstOrCreate(['user_id' => $user_id]);
        $user_info = UserInfoResource::make($user_info)->toArray($request);
        $reports = MedicalReport::where('user_id', $user_id)->orderBYDesc('id')->get();
        foreach ($reports as $report) {
            $report->content = json_decode($report->content);
        }

        $data = [
            'medical_report' => $reports,
            'anomaly' => $user_info['anomaly'],
        ];
        return $this->success('ok', $data);
    }

    public function showServiceUser(Request $request,  ServiceUser $service_user)
    {
        $service_user->card_num = '';
        $service_user->protocol = [];
        return $this->success('ok', $service_user);
    }

    public function bindServiceUser(Request $request, ServiceUser $service_user)
    {
        $user_id = auth()->id();
        if ($service_user->user_id && $service_user->user_id == $user_id) return $this->success('ok',['is_servicer'=>1]);
        if ($service_user->user_id && $service_user->user_id != $user_id) return $this->failure('服务人员已绑定微信');
        $is_exists = ServiceUser::where('user_id', $user_id)->exists();
        if ($is_exists) return $this->failure('账号已存在服务人员信息');
        DB::beginTransaction();
        ServiceUser::where('id', $service_user->id)->update(['user_id'=>$user_id]);
        ServiceRoleUser::where('s_user_id', $service_user->id)->update(['user_id'=>$user_id]);
        DB::commit();
        return $this->success('ok', ['is_servicer'=>1]);
    }
}
