<?php

namespace App\Http\Controllers\API\Internal;

use App\Http\Controllers\Controller;
use App\Http\Middleware\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class HealthCertificateController extends Controller
{
    public function CreatInfo(Request $request)
    {
        date_default_timezone_set('PRC');
        // 获取所有输入数据
        $input = $request->all();
        $key = $request->input('key');
        if (!isset($key) or empty($key) or $key <> '5Kj9P1pL0f8e7Vw3I2qX4mT6zJ1OxWcQ') {
            return response()->json([
                'status' => 400,
                'msg' => 'key验证失败',
                'transactionSerialNumber' => null,
                'platReceiveTime' => null
            ], 400);
        }

        // 验证规则
        $rules = [
            'hospitalCode' => 'required|string|max:20',
            'hospitalName' => 'required|string|max:70',
            'postTime' => 'required|date_format:Y-m-d H:i:s.u',
            'usci' => 'required|string|max:20',
            'healthExaminationId' => 'required|string|max:26',
            'examTypeCode' => 'required|string|max:2',
            'examTypeName' => 'required|string|max:50',
            'examTypeText' => 'required|string|max:50',
            'examDate' => 'required|date',
            'healthCertificateId' => 'required|string|max:26',
            'billingStatus' => 'required|string|max:1|in:0,1',
            'name' => 'required|string|max:70',
            'photo' => 'required|string',  // base64 string
            'tel' => 'required|string|max:20',
            'gender' => 'required|string|max:1',
            'genderName' => 'required|string|max:20',
            'identifierTypeCode' => 'required|string|max:2',
            'identifierTypeName' => 'required|string|max:50',
            'identifierValue' => 'required|string|max:18',
            'hasBacterialDysentery' => 'required|string|max:1',
            'bacterialDysenteryPractitionerName' => 'required|string|max:70',
            'bacterialDysenteryDate' => 'required|date',
            'hasTyphoid' => 'required|string|max:1',
            'typhoidPractitionerName' => 'required|string|max:70',
            'typhoidDate' => 'required|date',
            'hasViralHepatitis' => 'required|string|max:1',
            'viralHepatitisPractitionerName' => 'required|string|max:70',
            'viralHepatitisDate' => 'required|date',
            'hasActiveTB' => 'required|string|max:1',
            'activeTBPractitionerName' => 'required|string|max:70',
            'activeTBDate' => 'required|date',
            'hasSkinDiseases' => 'required|string|max:1',
            'skinDiseasesPractitionerName' => 'required|string|max:70',
            'skinDiseasesDate' => 'required|date',
            'hasHandFungal' => 'required|string|max:2',
            'handFungalPractitionerName' => 'nullable|string|max:70',
            'handFungalDate' => 'nullable|date',
            'hasCholera' => 'required|string|max:2',
            'choleraPractitionerName' => 'nullable|string|max:70',
            'choleraTestDate' => 'nullable|date',
            'hasAmebicDysentery' => 'required|string|max:2',
            'amebicDysenteryPractitionerName' => 'nullable|string|max:70',
            'amebicDysenteryDate' => 'nullable|date',
            'hasHandEczema' => 'required|string|max:2',
            'handEczemaPractitionerName' => 'nullable|string|max:70',
            'handEczemaDate' => 'nullable|date',
            'hasHandPsoriasis' => 'required|string|max:2',
            'handPsoriasisPractitionerName' => 'nullable|string|max:70',
            'handPsoriasisDate' => 'nullable|date',
            'validityDate' => 'required|date',
            'expiryDate' => 'required|date',
            'effectiveTime' => 'required|date_format:Y-m-d H:i:s',
            'updateTime' => 'required|date_format:Y-m-d H:i:s',
            'healthCertificateUrl' => 'required|string|max:200',
            'isEffective' => 'required|string|max:1|in:0,1',
        ];

        // 可选字段列表（这些字段存在时才验证）
        $optionalFields = [
            'bacterialDysenteryNote',
            'bacterialDysenteryPractitionerNumber',
            'bacterialDysenteryPractitionerLocalId',
            'typhoidNote',
            'typhoidPractitionerNumber',
            'typhoidPractitionerLocalId',
            'viralHepatitisNote',
            'viralHepatitisPractitionerNumber',
            'viralHepatitisPractitionerLocalId',
            'activeTBNote',
            'activeTBPractitionerNumber',
            'activeTBPractitionerLocalId',
            'skinDiseasesNote',
            'skinDiseasesPractitionerNumber',
            'skinDiseasesPractitionerLocalId',
            'handFungalNote',
            'handFungalPractitionerNumber',
            'handFungalPractitionerLocalId',
            'choleraNote',
            'choleraPractitionerNumber',
            'choleraPractitionerLocalId',
            'amebicDysenteryNote',
            'amebicDysenteryPractitionerNumber',
            'amebicDysenteryPractitionerLocalId',
            'handEczemaNote',
            'handEczemaPractitionerNumber',
            'handEczemaPractitionerLocalId',
            'handPsoriasisNote',
            'handPsoriasisPractitionerNumber',
            'handPsoriasisPractitionerLocalId',
            'CompanyName',
        ];

        foreach ($optionalFields as $field) {
            if (isset($input[$field])) {
                $rules[$field] = 'string';
            }
        }

        // 开始验证
        $validator = Validator::make($input, $rules);

        if ($validator->fails()) {
            return response()->json([
                'status' => 400,
                'msg' => '验证失败:' . json_encode($validator->errors(), JSON_UNESCAPED_UNICODE),
                'transactionSerialNumber' => null,
                'platReceiveTime' => null
            ], 400);
        }

        // 处理 base64 图片上传
        $base64Image = $request->input('photo');
       // Log::info($base64Image);
        preg_match("/data:image\/(.*?);base64,/", $base64Image, $matches);
        $imageType = isset($matches[1]) ? $matches[1] : 'jpg';

        // 检查是否是合法的 base64 图片格式
        if (!isset($matches[0])) {
            return response()->json([
                'status' => 400,
                'msg' => '图片格式不正确',
                'transactionSerialNumber' => null,
                'platReceiveTime' => null
            ], 400);
        }

        // 截取 base64 图片内容
        $imageData = substr($base64Image, strpos($base64Image, ',') + 1);
        $imageData = base64_decode($imageData);

        // 生成唯一文件名
        $fileName = Str::random(40) . '.' . $imageType;

        // 存储路径（public 目录下）
        $filePath = 'health_certificate/photo/' . date('Ymd') . '/' . $fileName;

        // 使用本地磁盘写入文件
      //  Storage::disk('public')->put($filePath, $imageData);

        // 构建访问 URL 或者直接存相对路径
     //   $photoPath = '/storage/' . $filePath;

        $upUrl= Storage::disk('network_drive')->put('/phpUpload/'.$filePath, $imageData);
        $photoPath=Storage::disk('network_drive')->url('/phpUpload/'.$filePath);
        // 获取所有数据
        $data = $request->except(['photo']);

        // 替换 photo 字段为路径
        $data['photo'] = $photoPath;
        unset($data['key']);

        // 获取数据库字段白名单
        $schema = Schema::getColumnListing('health_certificate_push');
// 过滤掉数据库中不存在的字段
        $data = array_filter($data, function ($key) use ($schema) {
            return in_array($key, $schema);
        }, ARRAY_FILTER_USE_KEY);

        // 插入数据库
        try {
            $id = DB::table('health_certificate_push')->insertGetId($data);

            return response()->json([
                'status' => 0,
                'msg' => '健康证明信息已成功插入',
                'transactionSerialNumber' => $id,
                'platReceiveTime' => date('Y-m-d H:i:s'),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'msg' => '插入失败：' . $e->getMessage(),
                'transactionSerialNumber' => null,
                'platReceiveTime' => null

            ], 500);
        }
    }

    public function uploadPdf(Request $request)
    {
        date_default_timezone_set('PRC');

        $key = $request->input('key');
        $hospitalCode = $request->input('hospitalCode');
        $hospitalName = $request->input('hospitalName');
        $healthExaminationId = $request->input('healthExaminationId');
        $reportId = $request->input('reportId');

        if(!isset($hospitalCode)){
            return response()->json([
                'status' => 400,
                'msg' => '医院code不能为空'
            ], 400);
        }
        if(!isset($healthExaminationId)){
            return response()->json([
                'status' => 400,
                'msg' => '体检号不能为空'
            ], 400);
        }



        $file = $request->file('file');
     //   Storage::disk('network_drive')->put('', $file);

        if (!$key || $key !== '5Kj9P1pL0f8e7Vw3I2qX4mT6zJ1OxWcQ') {
            return response()->json([
                'status' => 400,
                'msg' => 'key验证失败'
            ], 400);
        }

        if (!$file) {
            return response()->json([
                'status' => 400,
                'msg' => 'pdf文件不能为空'
            ], 400);
        }

        $path = 'health_certificate/pdf/' . date('Ymd');
        $fullPath = public_path($path);

        if (!is_dir($fullPath)) {
            mkdir($fullPath, 0777, true);
        }

        // 获取 MIME 类型（推荐使用 getMimeType）
        $mimeType = $file->getMimeType();
        // 也可以手动读取真实内容判断 MIME（可选）
        // $content = file_get_contents($file->getRealPath());
        // $finfo = finfo_open(FILEINFO_MIME_TYPE);
        // $mimeType = finfo_buffer($finfo, $content);
        // finfo_close($finfo);

        $mimeTypeToExtension = [
            'image/png' => 'png',
            'image/jpeg' => 'jpg',
            'application/pdf' => 'pdf',
        ];

        if (!isset($mimeTypeToExtension[$mimeType])) {
            return response()->json([
                'status' => 400,
                'msg' => '不支持的文件格式'
            ], 400);
        }

        $file_extension = $mimeTypeToExtension[$mimeType];

        // 验证大小：2MB以内
        if ($file->getSize() > 10 * 1024 * 1024) {
            return response()->json([
                'status' => 400,
                'msg' => '文件大小不能超过2M'
            ], 400);
        }

        $filename = uniqid() . '_' . mt_rand(0, 999999) . '.' . $file_extension;

       // $path = $file->store($path, 'public');
       // $url = '/storage/' . $path ;
      //  dd('/phpUpload/'.$path.'/'.$filename);
       $upUrl= Storage::disk('network_drive')->put('/phpUpload/'.$path, $file);
       $url=Storage::disk('network_drive')->url($upUrl);
       $data=[
           'hospitalCode' => $hospitalCode,
           'hospitalName' => $hospitalName,
           'healthExaminationId' => $healthExaminationId,
           'reportId' => $reportId,
           'pdf_url' => $url,
       ];
        $record=DB::table('health_certificate_push_pdf')->insertGetId($data);
        if($record){
            return response()->json([
                'status' => 0,
                'msg' => '上传成功',
                'data'=>[
                    'url' => $url,
                    'reportId'=>$reportId
                ]

            ]);
        }else{
            return response()->json([
                'status' => 400,
                'msg' => '提交pdf失败'
            ], 400);
        }

    }
}
