<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Barryvdh\Snappy\Facades\SnappyPdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class PdfController extends Controller
{
    public function GetCheckPdf()
    {
        $OrderNoList = request('OrderNoList');//医嘱号列表（数组）
        if (!isset($OrderNoList) or empty($OrderNoList)) return \Yz::JsonReturn("OrderNoList,不能为空");
        if (!is_array($OrderNoList)) return \Yz::JsonReturn("OrderNoList,应为数组");
        $list = [];
        foreach ($OrderNoList as $orderNo) {
            $entrustInfo=DB::table('s_list as a')->where(['a.entrust_id'=>$orderNo,'a.list_status'=>1,'a.is_nullify'=>0])->first();
            $url="";
            if(!!$entrustInfo)  $url=env('APP_URL') .$entrustInfo->check_aply_pdf ;
            $list[] = [
                'OrderNo' => $orderNo,
                'PdfUrl' => $url,
            ];
        }
        return \Yz::JsonReturn(true, '查询完成', ['list' => $list]);
    }

    //创建检查申请单pdf文件
    public function CreateJianChaShenQingDanPdf()
    {
        $OrderNoList = request('OrderNoList');//医嘱号列表（数组）
        if (!isset($OrderNoList) or empty($OrderNoList)) return \Yz::JsonReturn("OrderNoList,不能为空");
        if (!is_array($OrderNoList)) return \Yz::JsonReturn("OrderNoList,应为数组");
        $config=DB::table('configs')->where(['label'=>'开启申请单pdf'])->first();
        if (!$config or $config->value<>1) return \Yz::JsonError("未开启申请单pdf");
        $generator = new \Picqer\Barcode\BarcodeGeneratorHTML();
        $successCount=0;
        foreach ($OrderNoList as $orderNo) {
            $entrustInfo=DB::table('s_list as a')->where(['a.entrust_id'=>$orderNo,'a.list_status'=>1,'a.is_nullify'=>0])
                ->select('a.*','c.period_begin_time','c.period_end_time')
                ->leftJoin('s_period as c','a.reservation_time','=','c.id')
                ->first();
            if(!$entrustInfo) continue;
            $tiaoma = $generator->getBarcode($entrustInfo->app_num, $generator::TYPE_CODE_128, 2, 40);

            $source=null;
            if(!empty($entrustInfo->reservation_sources)){
                $source=DB::table('s_department_resources')->where(['id'=>$entrustInfo->reservation_sources])->first();
            }
            $entrustInfo->department_resources=$source;
            $entrustInfo->user_sex_label='';
            if($entrustInfo->user_sex==1){
                $entrustInfo->user_sex_label='男';
            }
            if($entrustInfo->user_sex==2){
                $entrustInfo->user_sex_label='女';
            }
            $entrustInfo->age=\Tools::getAgeFromBirthday($entrustInfo->user_brithday);
            //患者类型
            $p_type=config('app.globals.患者类型');
            $entrustInfo->patient_type_label=$p_type[$entrustInfo->patient_type] ?? '';
            //星期
            $entrustInfo->weekday_label=\Tools::GetWeekName($entrustInfo->reservation_date);

            // 准备数据
            $data = [
                'printInfo' =>$entrustInfo,
                'barcode' => $tiaoma,
            ];

            $filePath = storage_path('app/public/CheckPdf/' . date('Ymd') . '/' . $orderNo . '.pdf');
// 检查文件是否存在，存在则删除
            if (File::exists($filePath)) {
                File::delete($filePath);
            }
// 生成并保存新文件
            $pdf = SnappyPdf::loadView('pdf.JianChaShenQingDan', $data)
                ->setOption('page-size', 'a5')
                // 设置方向（portrait 纵向 / landscape 横向）
                ->setOption('orientation', 'landscape');
            $pdf->save($filePath);
            $fileUrl = Storage::url('CheckPdf/' . date('Ymd') . '/' . $orderNo . '.pdf');
            DB::table('s_list')->where('entrust_id', $orderNo)->update(['check_aply_pdf' => $fileUrl]);
            $successCount++;
        }

        return \Yz::JsonReturn(true, '生成检查申请单pdf成功', ['success_count' => $successCount]);


    }

}
