<?php

namespace App\Api\Controllers;

use App\Common\Util;
use App\Http\Controllers\BaseApiController;
use App\Models\PatientModel;
use App\Models\PharmacyModel;
use App\Models\User;
use Illuminate\Http\Request;
use Jxlwqq\IdValidator\IdValidator;
use Milon\Barcode\DNS2D;

// 问诊人控制器
class PatientController extends BaseApiController
{
    public function test()
    {
        return $this->success(['a' => 1, 'b' => 2, 'c' => 3]);
    }

    // 获取问诊人列表
    public function patientList(Request $request)
    {
        $authInfo = auth('api')->user();
        $query = PatientModel::query();
        if ($authInfo->last_login_type == User::LOGIN_TYPE_USER) {  // 用户
            $query->where('user_id', $authInfo->id);
        } elseif ($authInfo->last_login_type == User::LOGIN_TYPE_PHARMACY) { // 药店
            $pharmacy = PharmacyModel::query()->where('user_id', $authInfo->id)->first();
            $query->where('pharmacy_id', $pharmacy->id);
        }
        $search_input = $request->input('search_input');
        if ($search_input) {
            $query->where(function ($q) use ($search_input) {
                $q->where('id_card', 'like', "%{$search_input}%")
                    ->orWhere('name', 'like', "%{$search_input}%");
            });
            // $query->where('id_card', 'like', "%{$search_input}%");
            // $query->orWhere('name', 'like', "%{$search_input}%");
            // ->orWhere('mobile', 'like', "%{$search_input}%");
        }
        // 分页
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 10);
        $data = $query->orderBy('id', 'desc')->paginate($perPage, ['*'], 'page', $page);
        // foreach ($data as $key => $value) {
        //     $data[$key]['age'] = getAgeByIdCard($value['id_card']);
        // }

        return $this->success($data);
    }

    // 添加问诊人
    public function add(Request $request)
    {
        $data = $request->all();
        $authInfo = auth('api')->user();
        $patient = new PatientModel;
        if ($authInfo->last_login_type == User::LOGIN_TYPE_USER) {  // 用户
            $patient->user_id = $authInfo->id;
        } elseif ($authInfo->last_login_type == User::LOGIN_TYPE_PHARMACY) { // 药店
            $pharmacy = PharmacyModel::query()->where('user_id', $authInfo->id)->first();
            $patient->pharmacy_id = $pharmacy->id;
        }
        // 验证身份证格式
        $idValidator = new IdValidator();
        // if (! $idValidator->isValid($data['id_card'])) {
        // if( !in_array(strlen($data['id_card']),[15,18])){
        if (strlen($data['id_card']) != 18) {  // 身份证非必填项
            // return $this->failed('身份证格式错误');
        }

        if (is_int($data['age']) || $data['age'] <= 0) {
            return $this->failed('年龄格式错误');
        }

        if (! array_key_exists($data['gender'], PatientModel::SEX_MAP)) {
            return $this->failed('性别错误');
        }

        $mobile = $data['mobile'];

        // $verificationCode = cache()->get("sms_verification_code_{$mobile}");
        // $code = $data['code'];
        // if ($verificationCode != $code) {
        //     return $this->failed('验证码错误');
        // }

        // $idCardInfo = Util::getIdCardInfo($data['id_card']);

        $patient->name = $data['name'];
        $patient->id_card = $data['id_card'];
        $patient->mobile = $mobile;
        $patient->gender = $data['gender'];
        $patient->age = $data['age'];
        $patient->is_default = 0;
        // $res = PatientModel::create($data);
        $res = $patient->save();
        if ($res) {
            return $this->success($res);
        } else {
            return $this->failed('添加失败');
        }
    }

    // 修改问诊人
    public function update(Request $request)
    {
        $id = $request->input('id');
        $id_card = $request->input('id_card');
        $gender = $request->input('gender');
        $age = $request->input('age');

        // 验证身份证格式
        $idValidator = new IdValidator();
        // if (! $idValidator->isValid($id_card)) {
        if (strlen($id_card) != 18) {
            // return $this->failed('身份证格式错误');
        }

        if (is_int($age) || $age <= 0) {
            return $this->failed('年龄格式错误');
        }

        if (! array_key_exists($gender, PatientModel::SEX_MAP)) {
            return $this->failed('性别错误');
        }

        // $idCardInfo = Util::getIdCardInfo($id_card);
        $data = PatientModel::find($id);
        if (! $data) {
            return $this->failed('该问诊人不存在');
        }
        $mobile = $request->input('mobile');
        // $verificationCode = cache()->get("sms_verification_code_{$mobile}");
        // $code = $request->input('code');
        // if ($verificationCode != $code) {
        //     return $this->failed('验证码错误');
        // }

        $data->name = $request->input('name');
        $data->id_card = $id_card;
        $data->gender = $gender;
        $data->age = $age;
        $data->mobile = $mobile;
        $data->save();

        return $this->success($data);
    }

    // 删除问诊人
    public function delete(Request $request)
    {
        $id = $request->input('id');
        $data = PatientModel::find($id);
        if (! $data) {
            return $this->failed('该问诊人不存在');
        }
        $data->delete();

        return $this->success($data);
    }

    // 设置默认问诊人
    public function setDefault(Request $request)
    {
        // 通过id找到是否存在默认问诊人，如果存在比对id是否相同，如果不同则修改默认问诊人状态
        // TODO 验证条件待调整
        $authInfo = auth('api')->user();
        // 把该账号下的默认问诊人状态改为0
        $query = PatientModel::where('is_default', 1);
        if ($authInfo->last_login_type == User::LOGIN_TYPE_USER) {
            $query = $query->where('user_id', $authInfo->id);
        } elseif ($authInfo->last_login_type == User::LOGIN_TYPE_PHARMACY) {
            $pharmacy = PharmacyModel::query()->where('user_id', $authInfo->id)->first();
            $query = $query->where('pharmacy_id', $pharmacy->id);
        }
        $defaultPatient = $query->first();
        if ($defaultPatient) {
            $defaultPatient->is_default = 0;
            $defaultPatient->save();
        }
        // 把当前问诊人设为默认
        $id = $request->input('id');
        $data = PatientModel::find($id);
        if (! $data) {
            return $this->failed('该问诊人不存在');
        }
        $data->is_default = 1;
        $data->save();

        return $this->success($data);
    }

    // 获取默认问诊人
    public function getDefault(Request $request)
    {
        $authInfo = auth('api')->user();
        $query = PatientModel::where('is_default', 1);
        $last_login_type = $authInfo->last_login_type;
        $user_id = $authInfo->id;
        if ($last_login_type == User::LOGIN_TYPE_USER) {
            $query = $query->where('user_id', $user_id);
        } elseif ($last_login_type == User::LOGIN_TYPE_PHARMACY) {
            $pharmacy = PharmacyModel::query()->where('user_id', $user_id)->first();
            $query = $query->where('pharmacy_id', $pharmacy->id);
        }
        $data = $query->first();
        if ($data) {
            return $this->success($data);
        } else {
            return $this->failed('暂无默认问诊人');
        }
    }

    // 获取二维码
    public function getQrCode(Request $request)
    {
        $scene = $request->input('scene');
        if (! $scene) {
            return $this->failed('请传入参数scene~');
        }
        $dns2d = new DNS2D();
        $base64Img = 'data:image/jpg;base64,'.$dns2d->getBarcodePNG($scene, 'QRCODE', 200, 200);

        // return "<img src={$base64Img} >";
        return $this->success($base64Img);
    }
}
