<?php

namespace App\Http\Controllers\Api;

use App\Servers\DrugReportInfoService;
use App\Models\DrugReportAss;
use App\Servers\Aliyun\Oss;
use Carbon\Carbon;
use ZipArchive;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class DrugReportInfoController extends Api
{
    /**
     * 查询医药报告选项
     */
    public function get_list(DrugReportAss $DrugReportAss)
    {
        $start_time                         = request('start_time', 0);
        $end_time                           = request('end_time', 0);
        $produce_ent_id                     = request('produce_ent_id', 0);
        $from_ref_ent_id                    = request('from_ref_ent_id', 0);
        $bill_code                          = request('bill_code', 0);
        $physic_name                        = request('physic_name', 0);
        $batch_no                           = request('batch_no', 0);
        $drug_report_sign_status            = request('drug_report_sign_status');
        $seal_status                        = request('seal_status');
        $limit						        = request('limit',10);
        $map                                = [];
        if ($start_time){
            $start_time                     = strtotime($start_time);
            $map[]                          = ['drug_report_ass.bill_time','>=', $start_time];
        }
        if ($end_time){
            $end_time                       = Carbon::parse($end_time)->endOfDay()->timestamp;
            $map[]                          = ['drug_report_ass.bill_time','<=', $end_time];
        }
        if ($produce_ent_id)        $map[] = ['drug_report_ass.produce_ent_id','=', $produce_ent_id];
        if ($from_ref_ent_id)       $map[] = ['drug_report_ass.from_ref_ent_id','=', $from_ref_ent_id];
        if ($bill_code)             $map[] = ['drug_report_ass.bill_code','=', $bill_code];
        if ($physic_name)           $map[] = ['drug_report_ass.physic_name','=', $physic_name];
        if ($batch_no)              $map[] = ['drug_report_ass.batch_no','=', $batch_no];
        if (!is_null($seal_status))              $map[] = ['drug_report_ass.seal_status','=', $seal_status];
        $countMap                   = $map;
        if (!is_null($drug_report_sign_status))              $map[] = ['drug_report_ass.drug_report_sign_status','=', $drug_report_sign_status];
        $Paginator                  =   $DrugReportAss->query()
            /*->leftJoin('drug_report_info', function ($join) {
                $join->on('drug_report_ass.batch_no', '=', 'drug_report_info.batch_no')
                    ->on('drug_report_ass.drug_id', '=', 'drug_report_info.drug_id');
            })*/
            ->where($map)
            ->select( ['drug_report_ass.id','drug_report_ass.bill_code','drug_report_ass.batch_no','drug_report_ass.drug_id','drug_report_ass.crt_date',
                'drug_report_ass.produce_ent_id','drug_report_ass.produce_ent_name','drug_report_ass.from_ref_ent_id',
                'drug_report_ass.from_ent_name','drug_report_ass.drug_report_sign_status','drug_report_ass.seal_status',
                'drug_report_ass.seal_report_url','drug_report_ass.report_name','drug_report_ass.physic_name','drug_report_ass.pkg_spec','drug_report_ass.prepn_spec','drug_report_ass.prepn_type_desc',
                DB::raw('(
                    SELECT drug_report_info.seal_report_url
                    FROM drug_report_info
                    WHERE drug_report_info.batch_no = drug_report_ass.batch_no
                    AND drug_report_info.drug_id = drug_report_ass.drug_id
                    ORDER BY drug_report_info.id DESC LIMIT 1
                ) as info_seal_report_url'),
                DB::raw('(
                    SELECT drug_report_info.is_seal
                    FROM drug_report_info
                    WHERE drug_report_info.batch_no = drug_report_ass.batch_no
                    AND drug_report_info.drug_id = drug_report_ass.drug_id
                    ORDER BY drug_report_info.id DESC LIMIT 1
                ) as is_seal')
            ])
            ->orderBy('id', 'desc')
            ->paginate($limit);
        foreach ($Paginator->items() as &$item){
            if (in_array($item['seal_status'],[5,6])){
                if ($item['info_seal_report_url']){
                    $item['seal_report_url'] = $item['info_seal_report_url'];
                }
            }
        }
        $countData                  = $DrugReportAss->query()
            ->where($countMap)
            ->select(['drug_report_sign_status',DB::raw('count(*) as count')])
            ->groupBy('drug_report_sign_status')
            ->get();
        $count                  = $DrugReportAss->query()
            ->where($countMap)
            ->count();
        $data['count']                   = $count;
        $data['pending_send_count']      = 0;
        $data['pending_signed_count']    = 0;
        $data['signed_count']            = 0;
        $data['refuse_count']            = 0;
        foreach ($countData as $value){
            switch ($value['drug_report_sign_status']){
                case 0:
                    $data['pending_send_count'] = $value['count'];
                    break;
                case 2:
                    $data['pending_signed_count'] = $value['count'];
                    break;
                case 3:
                    $data['signed_count'] = $value['count'];
                    break;
                case 4:
                    $data['refuse_count'] = $value['count'];
                    break;
            }

        }
        // 获取数据
        $data['total']				= $Paginator->total();
        $data['current_page']		= $Paginator->currentPage();
        $data['per_page']			= $Paginator->perPage();
        $data['last_page']			= $Paginator->lastPage();
        $data['data']				= $Paginator->items();
        return						json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);

    }
    /**
     * 下载包
     *
     * */
    public function down_excel(DrugReportAss $DrugReportAss)
    {
        $ids						        = request('ids','');
        $list                       =   $DrugReportAss->query();
        if($ids){
            $ids        = explode(',',$ids);
            $list       =   $list->whereIn('drug_report_ass.id',$ids);
        }
        $list           =   $list->orderBy('drug_report_ass.id', 'desc')
            ->select( ['drug_report_ass.seal_status','drug_report_ass.bill_code','drug_report_ass.batch_no','drug_report_ass.drug_id','drug_report_ass.physic_name','drug_report_ass.crt_date','drug_report_ass.seal_report_url','drug_report_ass.report_name',
                DB::raw('(
                    SELECT drug_report_info.seal_report_url
                    FROM drug_report_info
                    WHERE drug_report_info.batch_no = drug_report_ass.batch_no
                    AND drug_report_info.drug_id = drug_report_ass.drug_id
                    ORDER BY drug_report_info.id DESC LIMIT 1
                ) as info_seal_report_url')])
            ->get()
            ->toArray();
        if (!$list)     return json_send(['code'=>'error','msg'=>'没有数据']);
        $localUrl    = $this->down($list);
        $fileName = basename($localUrl);
        //上传oss
        $oss = new Oss();
        $url    = $oss->uploadFile($fileName,$localUrl,'','zip');
        unlink($localUrl);
        return json_send(['code'=>'success','msg'=>'下载成功','data'=>['url'=>$url]]);
    }
    /**
     * 下载文件到本地
     *
     * */
    public function down($list){
        // 创建临时目录
        $tempDir = public_path('/uploads/' . uniqid('drug_'));
        if (!file_exists($tempDir)) {
            mkdir($tempDir, 0755, true);
        }
        // 下载图片到临时目录
        foreach ($list as $item) {
            if (in_array($item['seal_status'],[5,6]) && $item['info_seal_report_url']){
                $item['seal_report_url']    = $item['info_seal_report_url'];
            }
            if (!$item['seal_report_url']) continue;
            try {
                $content               = file_get_contents($item['seal_report_url']);
                $localPath = $tempDir . '/' . $item['report_name'];
                file_put_contents($localPath, $content);
            } catch (\Exception $e) {
                return json_send(['code'=>'error','msg'=>'下载失败','data'=>$e->getMessage()]);
            }
        }
        // 创建 ZIP 文件
        $zipPath = public_path('/uploads/zip/' . uniqid('drug_')).'.zip';
        $zip = new ZipArchive();
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
            $files = scandir($tempDir);
            foreach ($files as $file) {
                if ($file != "." && $file != "..") {
                    $filePath = $tempDir . '/' . $file;
                    if (file_exists($filePath)) {
                        $zip->addFile($filePath, $file);
                    }
                }
            }
            $zip->close();
        }

        // 清理临时目录
        $this->deleteDir($tempDir);

        return $zipPath;
    }
    /**
     * 删除目录及其内容
     */
    private function deleteDir(string $dirPath): void
    {
        if (!is_dir($dirPath)) {
            return;
        }
        $files = scandir($dirPath);
        foreach ($files as $file) {
            if ($file != "." && $file != "..") {
                $filePath = $dirPath . '/' . $file;
                if (is_dir($filePath)) {
                    $this->deleteDir($filePath);
                } else {
                    unlink($filePath);
                }
            }
        }
        rmdir($dirPath);
    }

    /**
     * 查询医药报告选项
     */
    public function option( DrugReportInfoService $service)
    {
        try {

            $data = [
                'produce_ent' => $service->getProduceEntIdOption(),
                'from_ref_ent' => $service->getFromRefEntIdOption(),
            ];
            return						json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);
        } catch (\Exception $e) {
            return json_send(['code'=>'error','msg'=>'获取失败','data'=>$e->getMessage()]);
        }
    }
}
