<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Lib\HSM;

class RecordQueryController extends Controller
{
    private function buildQuery(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $recordType = $request->input('record_type');
        $examType = $request->input('exam_type');

        if (!$startDate || !$endDate || !$recordType) {
            return null;
        }

        if ($recordType == 1) {
            $query = DB::table('appointment_record')
                ->select('name', 'id_card_num', 'created_at', DB::raw('(select org_name from medical_institution where sn = org_code) as org_name'))
                ->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59'])
                ->where('is_del', 0);
        } else {
            $query = DB::table('examination_records')
                ->select('name', 'id_card_num', 'created_at', 'industry_type', DB::raw('(select org_name from medical_institution where id = institution_id) as org_name'))
                ->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59'])
                ->where('is_del', 0);
        }

        if ($examType) {
            $query->where('type', $examType);
        }

        $query->orderBy('id');

        return $query;
    }

    private function decryptRecord($record)
    {
        try {
            if ($record->id_card_num) {
                $decryptIdCard = HSM::HsmDecrypt($record->id_card_num);
                $record->id_card_num = (!empty($decryptIdCard) && ($decryptIdCard['status'] ?? false)) ? $decryptIdCard['data'] : '解密失败';
            }
        } catch (\Throwable $e) {
            $record->id_card_num = '解密失败';
        }
        return $record;
    }

    public function index()
    {
        return view('record_query', [
            'startDate' => '',
            'endDate' => '',
            'recordType' => '',
            'examType' => '',
            'records' => null
        ]);
    }

    public function query(Request $request)
    {
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $recordType = $request->input('record_type');
        $examType = $request->input('exam_type');

        if (!$startDate || !$endDate || !$recordType) {
            return redirect()->back()->with('error', '请填写完整查询条件');
        }

        $query = $this->buildQuery($request);
        if (!$query) {
            return redirect()->back()->with('error', '请填写完整查询条件');
        }

        $records = $query->paginate(50)->through(function ($record) {
            return $this->decryptRecord($record);
        });

        $records->appends([
            'start_date' => $startDate,
            'end_date' => $endDate,
            'record_type' => $recordType,
            'exam_type' => $examType,
        ]);

        return view('record_query', compact('records', 'startDate', 'endDate', 'recordType', 'examType'));
    }

    public function export(Request $request)
    {
        set_time_limit(0);
        ini_set('memory_limit', '512M');

        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $recordType = $request->input('record_type');
        $examType = $request->input('exam_type');

        if (!$startDate || !$endDate || !$recordType) {
            return redirect()->back()->with('error', '请填写完整查询条件');
        }

        $query = $this->buildQuery($request);
        if (!$query) {
            return redirect()->back()->with('error', '请填写完整查询条件');
        }

        $recordType = (int) $recordType;
        $fileName = 'records_' . date('YmdHis') . '.csv';

        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
        ];

        $callback = function () use ($query, $recordType) {
            $handle = fopen('php://output', 'w');
            fwrite($handle, chr(0xEF) . chr(0xBB) . chr(0xBF));

            if ($recordType == 2) {
                fputcsv($handle, ['姓名', '身份证号', '体检日期', '机构名称', '行业类型'], ',');
            } else {
                fputcsv($handle, ['姓名', '身份证号', '体检日期', '机构名称'], ',');
            }

            $query->chunk(500, function ($records) use ($handle, $recordType) {
                foreach ($records as $record) {
                    $record = $this->decryptRecord($record);

                    $row = [
                        $record->name ?? '',
                        $record->id_card_num ?? '',
                        $record->created_at ?? '',
                        $record->org_name ?? '',
                    ];

                    if ($recordType == 2) {
                        $row[] = $record->industry_type ?? '';
                    }

                    fputcsv($handle, $row, ',');
                }
            });

            fclose($handle);
        };

        return response()->stream($callback, 200, $headers);
    }
}
