<?php

namespace App\Http\Controllers\API\Admin\YeWu;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class PingTaiPushController extends Controller
{
    public function GetList()
    {
        $searchInfo = request('searchInfo');
        $page =request('page');
        $pageSize =request('pageSize');
        if(!empty($searchInfo['dateRange'])){
            $searchInfo['dateRange']=[
                $searchInfo['dateRange'][0]." 00:00:00",
                $searchInfo['dateRange'][1]." 23:59:59"
            ];
        }
        $list = DB::table('health_certificate_push');
        if (isset($searchInfo['dateRange']) && count($searchInfo['dateRange'])==2) {
            $list = $list->whereBetween('created_at', $searchInfo['dateRange']);
        }
        if (isset($searchInfo['userinfo']) && !empty($searchInfo['userinfo'])) {
            $list = $list->where(function($query) use ($searchInfo) {
                $query->where('name', 'like', '%' . $searchInfo['userinfo'] . '%')
                    ->orWhere('tel', '=', $searchInfo['userinfo'])
                    ->orWhere('identifierValue', '=', $searchInfo['userinfo']);
            });
        }
        if (isset($searchInfo['orgname'])) {

            $list = $list->where('hospitalName', 'like', '%' . $searchInfo['orgname'] . '%');
        }
        if (isset($searchInfo['hospitalCode'])) {
            $list = $list->where('hospitalCode',  $searchInfo['hospitalCode']);
        }
        $count = $list->count();
        $list = $list->orderBy('created_at', 'desc')->skip(($page-1)*$pageSize)->take($pageSize)->get();
        foreach ($list as $k => $v) {
            $list[$k]->pdf_url=null;
            $pdf=DB::table('health_certificate_push_pdf')
                ->where([  'hospitalCode' => $v->hospitalCode,'healthExaminationId' => $v->healthExaminationId])
                ->orderBy('id', 'desc')
                ->first();
            if(!!$pdf){
                $list[$k]->pdf_url=$pdf->pdf_url;
            }

        }

        return \Yz::Return(true, "查询完成", ['list' => $list,'count'=>$count]);
    }
    public function GetPingTaiOrgList()
    {
        $list = DB::table('health_certificate_push')->select('hospitalCode','hospitalName')->groupBy('hospitalCode','hospitalName')->get();
        return \Yz::Return(true, "查询完成", ['list' => $list]);
    }

    public function GetDetail()
    {
        $id = request('id');

        // 获取原始信息
        $info = DB::table('health_certificate_push')->where('id', $id)->first();

        if (!$info) {
            return \Yz::Return(false, "未找到对应数据");
        }

        // 将对象转换为数组以便处理
        $infoArray = (array)$info;

        // 创建英文字段到中文字段的完整映射表
        $fieldMapping = [
            'hospitalCode' => '医疗机构编码',
            'hospitalName' => '医疗机构名称',
            'postTime' => '数据上传时间',
            'usci' => '统一社会信用代码',
            'healthExaminationId' => '体检登记号',
            'examTypeCode' => '从业人员健康检查类别代码',
            'examTypeName' => '从业人员健康检查类别名称',
            'examTypeText' => '从业人员健康检查类别显示文本',
            'examDate' => '体检日期',
            'healthCertificateId' => '唯一标识',
            'billingStatus' => '收费状态；0 免费，1 自费',
            'name' => '姓名',
            'photo' => '照片',
            'tel' => '电话',
            'gender' => '性别代码',
            'genderName' => '性别名称',
            'identifierTypeCode' => '身份证件类别代码',
            'identifierTypeName' => '身份证件类别名称',
            'identifierValue' => '身份证件号码',
            'hasBacterialDysentery' => '细菌性痢疾（1有 2无）',
            'bacterialDysenteryNote' => '细菌性痢疾-备注',
            'bacterialDysenteryPractitionerNumber' => '细菌性痢疾-检查医师执业证书编号',
            'bacterialDysenteryPractitionerLocalId' => '细菌性痢疾-检查医师机构内编码',
            'bacterialDysenteryPractitionerName' => '细菌性痢疾-检查医师',
            'bacterialDysenteryDate' => '细菌性痢疾-检查日期',
            'hasTyphoid' => '伤寒和副伤寒（1有 2无）',
            'typhoidNote' => '伤寒和副伤寒-备注',
            'typhoidPractitionerNumber' => '伤寒和副伤寒-检查医师执业证书编号',
            'typhoidPractitionerLocalId' => '伤寒和副伤寒-检查医师机构内编码',
            'typhoidPractitionerName' => '伤寒和副伤寒-检查医师',
            'typhoidDate' => '伤寒和副伤寒-检查日期',
            'hasViralHepatitis' => '病毒性肝炎（甲型、戊型）（1有 2无）',
            'viralHepatitisNote' => '病毒性肝炎-备注',
            'viralHepatitisPractitionerNumber' => '病毒性肝炎-检查医师执业证书编号',
            'viralHepatitisPractitionerLocalId' => '病毒性肝炎-检查医师机构内编码',
            'viralHepatitisPractitionerName' => '病毒性肝炎-检查医师',
            'viralHepatitisDate' => '病毒性肝炎-检查日期',
            'hasActiveTB' => '活动性肺结核（1有 2无）',
            'activeTBNote' => '活动性肺结核-备注',
            'activeTBPractitionerNumber' => '活动性肺结核-检查医师执业证书编号',
            'activeTBPractitionerLocalId' => '活动性肺结核-检查医师机构内编码',
            'activeTBPractitionerName' => '活动性肺结核-检查医师',
            'activeTBDate' => '活动性肺结核-检查日期',
            'hasSkinDiseases' => '化脓性或渗出性皮肤病（1有 2无）',
            'skinDiseasesNote' => '化脓性或渗出性皮肤病-备注',
            'skinDiseasesPractitionerNumber' => '化脓性或渗出性皮肤病-检查医师执业证书编号',
            'skinDiseasesPractitionerLocalId' => '化脓性或渗出性皮肤病-检查医师机构内编码',
            'skinDiseasesPractitionerName' => '化脓性或渗出性皮肤病-检查医师',
            'skinDiseasesDate' => '化脓性或渗出性皮肤病-检查日期',
            'hasHandFungal' => '手部真菌感染性疾病(如手癣、指甲癣等)（1有 2无 -1未检查）',
            'handFungalNote' => '手部真菌感染性疾病-备注',
            'handFungalPractitionerNumber' => '手部真菌感染性疾病-检查医师执业证书编号',
            'handFungalPractitionerLocalId' => '手部真菌感染性疾病-检查医师机构内编码',
            'handFungalPractitionerName' => '手部真菌感染性疾病-检查医师',
            'handFungalDate' => '手部真菌感染性疾病-检查日期',
            'hasCholera' => '霍乱（1有 2无 -1未检查）',
            'choleraNote' => '霍乱-备注',
            'choleraPractitionerNumber' => '霍乱-检查医师执业证书编号',
            'choleraPractitionerLocalId' => '霍乱-检查医师机构内编码',
            'choleraPractitionerName' => '霍乱-检查医师',
            'choleraTestDate' => '霍乱-检查日期',
            'hasAmebicDysentery' => '阿米巴性痢疾（1有 2无 -1未检查）',
            'amebicDysenteryNote' => '阿米巴性痢疾-备注',
            'amebicDysenteryPractitionerNumber' => '阿米巴性痢疾-检查医师执业证书编号',
            'amebicDysenteryPractitionerLocalId' => '阿米巴性痢疾-检查医师机构内编码',
            'amebicDysenteryPractitionerName' => '阿米巴性痢疾-检查医师',
            'amebicDysenteryDate' => '阿米巴性痢疾-检查日期',
            'hasHandEczema' => '手部湿疹（1有 2无 -1未检查）',
            'handEczemaNote' => '手部湿疹-备注',
            'handEczemaPractitionerNumber' => '手部湿疹-检查医师执业证书编号',
            'handEczemaPractitionerLocalId' => '手部湿疹-检查医师机构内编码',
            'handEczemaPractitionerName' => '手部湿疹-检查医师',
            'handEczemaDate' => '手部湿疹-检查日期',
            'hasHandPsoriasis' => '手部的银屑病或者鳞屑（1有 2无 -1未检查）',
            'handPsoriasisNote' => '手部的银屑病或者鳞屑-备注',
            'handPsoriasisPractitionerNumber' => '手部的银屑病或者鳞屑-检查医师执业证书编号',
            'handPsoriasisPractitionerLocalId' => '手部的银屑病或者鳞屑-检查医师机构内编码',
            'handPsoriasisPractitionerName' => '手部的银屑病或者鳞屑-检查医师',
            'handPsoriasisDate' => '手部的银屑病或者鳞屑-检查日期',
            'validityDate' => '健康证明生效日期',
            'expiryDate' => '健康证明有效截止日期',
            'effectiveTime' => '健康证明出具时间',
            'updateTime' => '健康证明更新时间',
            'healthCertificateUrl' => '从业人员健康证明非结构化文档地址（北京市地址）',
            'healthCertificateUrlPt' => '从业人员健康证明非结构化文档地址（区平台地址）',
            'isEffective' => '是否有效'
        ];

        // 构建中文键值对
        $translatedInfo = [];
        foreach ($fieldMapping as $key => $chineseKey) {
            if (isset($infoArray[$key])) {
                if($key=='photo' and !empty($infoArray[$key])) {
                    $relativePath = substr($infoArray[$key], strlen('/storage'));
                    $infoArray[$key]=Storage::disk('public')->url($relativePath);
                }
                $translatedInfo[$chineseKey] = $infoArray[$key];
            }
        }

        // 返回结果
        return \Yz::Return(true, "查询完成", ['info' => $translatedInfo]);
    }


    //按机构统计
    public function CountByOrg(Request $request)
    {
        $s_group = [1, 8];
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $searchInfo = request('searchInfo');
        if (!in_array($group, $s_group)) {
            return \Yz::echoError1("无权限查看此数据");
        }
        if(empty($searchInfo['dateRange'])){
            $searchInfo['dateRange']=[
              date('Y-m-d')." 00:00:00",
             date('Y-m-d')." 23:59:59"
            ];
        }
        $list = DB::table('health_certificate_push')
            ->select(
                'hospitalCode as org_code',
                'hospitalName as org_name',
                DB::raw('COUNT(DISTINCT healthCertificateId) as count')
            );
        if (isset($searchInfo['dateRange'])) {
            $list = $list->whereBetween('created_at', $searchInfo['dateRange']);
        } else {
            $list = $list->whereBetween('created_at', [date('Y-m-d'), date('Y-m-d')]);
        }
        $list = $list->groupBy('hospitalCode', 'hospitalName')
            ->get();
        return \Yz::Return(true,'查询成功',['list'=>$list,'dateRange'=>$searchInfo['dateRange']]);
    }

    //按月统计
    public function CountByMonth(Request $request)
    {
        $s_group = [1, 8];
        $userid = $request->get('userid');//中间件产生的参数
        $group = $request->get('role');//中间件产生的参数
        $searchInfo = request('searchInfo');
        if (!in_array($group, $s_group)) {
            return \Yz::echoError1("无权限查看此数据");
        }
        if(empty($searchInfo['dateRange'])){
            $searchInfo['dateRange']=[
                date('Y-m-d')." 00:00:00",
                date('Y-m-d')." 23:59:59"
            ];
        }
        $list = DB::table('health_certificate_push')
            ->select(
                DB::raw("DATE_FORMAT(created_at, '%Y-%m') as month"),
                DB::raw('COUNT(DISTINCT healthCertificateId) as count')
            );
        if (isset($searchInfo['dateRange'])) {
            $list = $list->whereBetween('created_at', $searchInfo['dateRange']);
        } else {
            $list = $list->whereBetween('created_at', [date('Y-m-d'), date('Y-m-d')]);
        };

        $list = $list->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m')"))
            ->orderBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m')"), 'asc')
            ->get();

        return \Yz::Return(true,'查询成功',['list'=>$list,'dateRange'=>$searchInfo['dateRange']]);
    }
}
