<?php

namespace App\Http\Controllers\API\Internal;

use App\Http\Controllers\Controller;
use App\Services\Admin\YeWu\HealthCheckupService;
use App\Services\OrgService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class CheckUpController extends Controller
{
    //给第三的接口，创建体检记录
    public function CreateCheckupRecord(Request $request)
    {
        // 验证请求数据
        $encrypted_data = request('encrypted_data');
        $iv = request('iv');
        $encrypt_iv = bin2hex(random_bytes(16 / 2));
        if (!isset($iv)) return \Yz::echoError1('加密时使用的iv不能为空');
        $encrypted_data = \App\Lib\Tools::AESDecrypt($encrypted_data, config('app.globals.AES_KEY'), $iv);
        if (!$encrypted_data) return \Yz::echoError1('encrypted_data解密失败');
        $encrypted_data = json_decode($encrypted_data, true);

        $validator = Validator::make($encrypted_data, [
            'checkup_info.type' => 'required|integer',
            'checkup_info.free_type' => 'required|integer',
            'checkup_info.name' => 'required|string',
            'checkup_info.sex' => 'required|integer',
            'checkup_info.tel' => 'required|string',
            'checkup_info.id_card_num' => 'required|string',
            'checkup_info.doc_type_id' => 'required|integer',
            'checkup_info.doc_type_name' => 'required|string',
            'checkup_info.org_sn' => 'required|string',
            'checkup_info.tijian_num' => 'required|string',
            'checkup_info.tijian_time' => 'required|date',
            'checkup_info.report_content' => 'required|array',
            'checkup_info.report_content.*.item_name' => 'required|string',
            'checkup_info.report_content.*.item_result' => 'required|string',
            'checkup_info.report_content.*.item_range' => 'required|array',
            'checkup_info.report_content.*.flag' => 'required|string',
            'checkup_info.report_content.*.item_unit' => 'required|string',
            'checkup_info.report_content.*.check_time' => 'required|date',
            'checkup_info.result_status' => 'required|integer',
            'checkup_info.shenhe_time' => 'required|date',
            'checkup_info.result_content' => 'required|string',
        ]);

        if ($validator->fails()) {
            return \Yz::echoError1($validator->errors());
        }
        $checkupInfo = $encrypted_data['checkup_info'];
        $checkupInfo['institution_sn'] = $checkupInfo['org_sn'];
        $checkupInfo['industry_type'] = $checkupInfo['doc_type_name'];
        $checkupInfo['register_time'] = $checkupInfo['tijian_time'];
        $checkupInfo['issue_time'] = null;
        $checkupInfo['expire_time'] = null;
        $checkupInfo['is_sanfang'] = 1;
        $s = app()->make(HealthCheckupService::class);
        $res = $s->CreateRecord($checkupInfo);

        if ($res['status'] !== true) {
            return \Yz::echoError1($res['msg']);
        } else {
            $msg = "记录完成";
            if ($checkupInfo['type'] == 1 and $checkupInfo['free_type'] == 0) {
                $msg = $msg . ",免费用户请调用上传资料接口上传相关证明文件，否则无效。";
            }
            $send_data = ["tijian_num" => $checkupInfo['tijian_num']];
            $send_data = json_encode($send_data, JSON_UNESCAPED_UNICODE);
            return \Yz::Return(true, $msg, ['info' => $this->AESEncrypt($send_data, $encrypt_iv), 'iv' => $encrypt_iv]);
        }

    }

    //给第三的接口，上传体检结果pdf文档
    public function UploadPdf(Request $request)
    {
        $encrypted_data = request('encrypted_data');
        $iv = request('iv');
        $encrypt_iv = bin2hex(random_bytes(16 / 2));
        if (!isset($iv)) return \Yz::echoError1('加密时使用的iv不能为空');
        $encrypted_data = \App\Lib\Tools::AESDecrypt($encrypted_data, config('app.globals.AES_KEY'), $iv);
        if (!$encrypted_data) return \Yz::echoError1('encrypted_data解密失败');
        $decrypted_data = json_decode($encrypted_data, true);
        //dd($decrypted_data);
        // 验证请求数据
        $validator = Validator::make($decrypted_data, [
            'type' => 'required|integer',  //1证明材料2报告材料pdf
            'tijian_num' => 'required|string',
            'org_sn' => 'required|string',
            'files' => 'required|array',
            // 'files.*' => 'required|file|mimes:pdf,jpg,png,webp|max:2048',// 每个文件必须是PDF格式，且大小不超过2MB
        ]);

        if ($validator->fails()) {
            return \Yz::echoError1($validator->errors());
        }
        $type = $decrypted_data['type'];
        //查询体检号是否存在
        $service = new OrgService();
        $res = $service->GetOrgInfo($decrypted_data['org_sn']);
        if ($res['status'] !== true) {
            return \Yz::echoError1($res['msg']);
        }
        //查询体检号是否存在
        $checkupInfo = DB::table('examination_records')
            ->where([
                'tijian_num' => $decrypted_data['tijian_num'],
                'institution_id' => $res['data']->id,
                'is_del' => 0,
            ])->orderBy('id', 'desc')->first();
        if (!$checkupInfo) {
            return \Yz::echoError1("体检号不存在");
        }
        // if ($request->hasFile('files') && $request->file('files')) {
        if (count($decrypted_data['files']) > 0) {
            $filesUrls = [];
            if ($type == 1) {
                $path = 'uploads/sanfang_img/' . date('Ymd'); // 根据当前日期创建子目录
            }
            if ($type == 2) {
                $path = 'uploads/pdfs/' . date('Ymd'); // 根据当前日期创建子目录
            }
            $mimeTypeToExtension = [
                'image/png' => 'png',
                'image/jpeg' => 'jpg',
                'application/pdf' => 'pdf',
            ];
            foreach ($decrypted_data['files'] as $file) {
                // 保存文件到磁盘
                $fullPath = public_path($path);
                if (!is_dir($fullPath)) {
                    mkdir($fullPath, 0777, true); // 创建目录，包括必要的父目录
                }
                $file_data = \App\Lib\Tools::AESDecrypt($file, config('app.globals.AES_KEY'), $iv);
                // 检查文件大小是否超过2MB
                $fileSize = strlen($file_data); // 获取文件数据的长度（字节数）
                if ($fileSize > 2 * 1024 * 1024) { // 如果文件大小超过2MB
                    return \Yz::echoError1("文件大小超过2MB，上传被拒绝。");
                }
                $finfo = finfo_open();
                // 根据文件内容获取其MIME类型
                $mimeType = finfo_buffer($finfo, $file_data, FILEINFO_MIME_TYPE);
                // 关闭finfo资源
                finfo_close($finfo);
                //     dd($mimeType);
                if (array_key_exists($mimeType, $mimeTypeToExtension)) {
                    $file_extension = $mimeTypeToExtension[$mimeType];
                } else {
                    return \Yz::echoError1("获取文件格式失败");
                }
                $filename = uniqid() . '_' . mt_rand(0, 999999) . '.' . $file_extension;
                // 定义存储路径
                file_put_contents($fullPath . '/' . $filename, $file_data);


                // $file->storeAs($path, $filename, 'public'); // 使用 'public' 磁盘
                $filesUrls[] =  '/storage/' . $path . '/' . $filename;

            }
            if ($type == 1) {
                foreach ($filesUrls as $fileUrl) {
                    $insert_img = DB::table('appointment_img')->insert([
                        'type' => 9,//通用证明材料
                        'imgurl' => $fileUrl,
                        'examination_records_id' => $checkupInfo->id,
                    ]);
                }
                if ($insert_img) {
                    $u = DB::table('examination_records')->where('id', $checkupInfo->id)->update(['is_has_file' => 1, 'updated_at' => date('Y-m-d H:i:s')]);
                }
            }
            if ($type == 2) {
                $u = DB::table('examination_records')->where('id', $checkupInfo->id)->update(['pdfs' => json_encode($filesUrls, JSON_UNESCAPED_UNICODE), 'updated_at' => date('Y-m-d H:i:s')]);
            }
            if (!$u) {
                return \Yz::echoError1("上传文件失败");
            }
            $send_data = ["tijian_num" => $checkupInfo->tijian_num];
            $send_data = json_encode($send_data, JSON_UNESCAPED_UNICODE);
            return \Yz::Return(true, '上传成功', ['info' => $this->AESEncrypt($send_data, $encrypt_iv), 'iv' => $encrypt_iv]);
        }

        return \Yz::echoError1("上传文件失败");
    }

    function AESEncrypt($data, $encrypt_iv)
    {
        // return $data;
        return \App\Lib\Tools::AESEncrypt($data, config('app.globals.AES_KEY'), $encrypt_iv);
    }
}
