<?php

namespace App\Http\Controllers\API\WeiHu;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TiJianListController
{
    public function GetList(Request $request)
    {
        $group = $request->get('role');//中间件产生的参数
        if ($group != 1) {
            return \Yz::echoError1('权限不足');
        }
        $info = request('info');
        $sfz_encode = '';
        // 如果输入长度 >=15，认为是身份证号，进行HSM加密
        if (!empty($info) && strlen($info) >= 15) {
            if (env('APP_ENV') !== 'bendi') {
                $HSM_sfz = \App\Lib\HSM::HsmEncrypt($info);
                if ($HSM_sfz['status'] !== true) {
                    return \Yz::echoError1('调用HSM加密失败');
                }
                $sfz_encode = $HSM_sfz['data'];
            } else {
                $sfz_encode = $info;
            }

        }

        // 构造搜索条件闭包，避免 where/orWhere 逻辑混乱
        $searchCondition = function ($query) use ($info, $sfz_encode) {
            if (!empty($info)) {
                $query->where('name', 'like', '%' . $info . '%');
            }
            if (!empty($sfz_encode)) {
                $query->orWhere('id_card_num', $sfz_encode);
            }
        };

        // 预约记录查询
        $yuyue_list = DB::table('appointment_record as a')
            ->leftJoin('medical_institution as b', 'a.org_code', '=', 'b.sn')
            ->select('a.id', 'a.type', 'a.name', 'a.id_card_num', 'b.org_name', 'a.created_at')
            ->where($searchCondition)
            ->where('a.is_del', 0)
            ->orderBy('a.id', 'desc')
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })->toArray();


        foreach ($yuyue_list as $k => $v) {
            $yuyue_list[$k]['leixing']='预约';
            if (env('APP_ENV') !== 'bendi') {
                $sfz = \App\Lib\HSM::HsmDecrypt($v['id_card_num']);
                if ($sfz['status'] != true) {
                    return \Yz::echoError1('调用HSM解密失败');
                }
                $yuyue_list[$k]['id_card_num'] = $sfz['data'];
            }
        }



        // 体检记录查询
        $tijian_list = DB::table('examination_records as a')
            ->leftJoin('medical_institution as b', 'a.institution_id', '=', 'b.id')
            ->select('a.id', 'a.type', 'a.name', 'a.id_card_num', 'b.org_name', 'a.created_at')
            ->where($searchCondition)
            ->where('a.is_del', 0)  // 注意表别名 a
            ->orderBy('a.id', 'desc')
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })->toArray();

        foreach ($tijian_list as $k => $v) {
            $tijian_list[$k]['leixing']='体检';
            if (env('APP_ENV') !== 'bendi') {
                $sfz = \App\Lib\HSM::HsmDecrypt($v['id_card_num']);
                if ($sfz['status'] != true) {
                    return \Yz::echoError1('调用HSM解密失败');
                }
                $tijian_list[$k]['id_card_num'] = $sfz['data'];
            }
        }

        $all_list = [];
        $all_list = array_merge($yuyue_list, $tijian_list);

        return \Yz::Return(true, '查询完成', [
            'all_list' => $all_list,

        ]);
    }

    public function Del(Request $request)
    {
        $group = $request->get('role');
        $userid = $request->get('userid');
        if ($group != 1) {
            return \Yz::echoError1('权限不足');
        }
        $id = request('id');
        $leixing = request('leixing');
        $reason = request('reason');
        $screenshot = request('screenshot') ?: '';
        $tablename = 'appointment_record';
        if ($leixing == '预约') {
            $tablename = 'appointment_record';
        }
        if ($leixing == '体检') {
            $tablename = 'examination_records';
        }
        $record = DB::table($tablename)->where('id', $id)->first();
        if (!$record) {
            return \Yz::echoError1('未找到记录');
        }
        $operatorName = '';
        $user = DB::table('users')->where('id', $userid)->first();
        if ($user) $operatorName = $user->cn_name;
        $deleteLogService = app()->make(\App\Services\DeleteLogService::class);
        $deleteLogService->logDeletion(
            $tablename,
            $id,
            $record->name,
            $record->id_card_num,
            $userid,
            $operatorName,
            $reason,
            $record->org_name ?? '',
            $record->type ?? '',
            $screenshot
        );
        $update = DB::table($tablename)->where('id', $id)->update(['is_del' => 1]);
        if ($update) {
            return \Yz::Return(true, '标记删除完成', ['id' => $id, 'tablename' => $tablename, 'userid' => $userid]);
        } else {
            return \Yz::echoError1('操作失败');
        }

    }
}
