<?php

namespace App\Api\Controllers;

use App\Http\Controllers\BaseApiController;
use App\Models\DrugModel;
use App\Models\PharmacyDrugModel;
use App\Models\PharmacyModel;
use App\Models\PrescriptionModel;
use App\Models\User;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

// 药品控制器
class DrugController extends BaseApiController
{
    public function test()
    {

        // $id_card = '342224198909070018';
        // if (! validateIdCard($id_card)) {
        //     return $this->failed('身份证格式错误');
        // }
        // $drug = DrugModel::query()->find(1);
        // $drug->limit_buy_7 = 4;
        // $drug->save();
        // $drug->limit_buy_7 = 5;
        // $drug->save();
        // $mobile = '18321861540';
        // $templateName = 'verification_code';
        // $templateData = ['code' => '1234'];
        // $smsService = new SmsService();
        // $response = $smsService->sendSms($mobile, $templateName, $templateData);

        // return response()->json($response);

        // return $this->success('ok');

        $search_input = '测试';
        $data = PharmacyDrugModel::where('pharmacy_id', 1)
            ->whereHas('drug', function ($query) use ($search_input) {
                $query->where('name', 'LIKE', "%{$search_input}%")
                    ->orWhere('code', 'LIKE', "%{$search_input}%"); // 这里的'%筛选条件%'是你想要匹配的药品名称
            })
            ->paginate(10);

        $data->map(function ($row) {
            return $row->drug;
        });

        return $this->success($data);
    }

    // 药品列表
    public function drugList(Request $request)
    {
        $authInfo = auth('api')->user();
        $pharmacy_id = 0;
        if ($authInfo->last_login_type == User::LOGIN_TYPE_USER) {
            $pharmacy_id = $request->input('pharmacy_id');
        } elseif ($authInfo->last_login_type == User::LOGIN_TYPE_PHARMACY) {
            $pharmacy = PharmacyModel::where('user_id', $authInfo->id)->first();
            $pharmacy_id = $pharmacy->id;
        }
        $search_input = $request->input('search_input');
        // $data = PharmacyDrugModel::where('pharmacy_id', $pharmacy_id)
        //     ->whereNotNull('dosage_id')
        //     ->whereHas('drug', function ($query) use ($search_input) {
        //         $query->where('is_rx', 1);
        //         if ($search_input) {
        //             $query->where('name', 'LIKE', "%{$search_input}%")
        //                 ->orWhere('code', 'LIKE', "%{$search_input}%"); // 这里的'%筛选条件%'是你想要匹配的药品名称
        //         }
        //     })
        //     ->paginate(10);
        $data = PharmacyDrugModel::where('pharmacy_id', $pharmacy_id)
            // ->whereNotNull('dosage_id')
            ->whereHas('drug', function ($query) use ($search_input) {
                $query->where('is_rx', DrugModel::RX_TRUE)
                    ->where(function ($subQuery) use ($search_input) {
                        if ($search_input) {
                            $subQuery->where('name', 'LIKE', "%{$search_input}%")
                                ->orWhere('code', 'LIKE', "%{$search_input}%");
                        }
                    });
            })
            ->paginate(10);
        // Log::info('drug list sql=>'.$data->toSql());
        $data->map(function ($row) {
            return $row->drug;
        });

        return $this->success($data);
    }

    // 药品7日内限购
    public function drugLimit(Request $request)
    {
        // 当前药品未设置则使用全局的7日内限购
        $site_config = DB::table('admin_settings')->where('slug', 'site_config')->value('value');
        $site_config = json_decode($site_config, true);
        $limit_num = intval($site_config['prescription_limit_buy_7']);
        $limit_type = intval($site_config['prescription_limit_buy_7']) > 0 ? 1 : 0; // 1为限购，0为不限购

        $drug_id = $request->input('drug_id');
        // 判断当前药品有没有设置7日内限购
        $drug = DrugModel::query()->find($drug_id);
        if ($drug && intval($drug->limit_buy_7) > 0) {
            $limit_num = $drug->limit_buy_7;
            $limit_type = 1;
        }
        $patient_id = $request->input('patient_id');
        $pharmacy_id = $request->input('pharmacy_id');

        $sevenDaysAgo = Carbon::now()->subDays(7);
        $prescriptions = PrescriptionModel::where('patient_id', $patient_id)
            ->where('status', PrescriptionModel::PRESCRIPTION_STATUS_SUCCESS)
            ->where('pharmacy_id', $pharmacy_id)
            ->where('created_at', '>=', $sevenDaysAgo)
            ->get();

        $drugCounts = [];
        // 判断搜索出来的处方不为空
        if ($prescriptions->count() > 0) {
            foreach ($prescriptions as $prescription) {
                // $drugs = json_decode($prescription->drug_info, true); // Parse JSON data
                $drugs = $prescription->drug_info;
                if (count($drugs) > 0) {
                    foreach ($drugs as $drug) {
                        $drugId = $drug['drug_id'];
                        $drugCounts[$drugId] = ($drugCounts[$drugId] ?? 0) + $drug['num'];
                    }
                }

            }
        }

        $purchaseCount = $drugCounts[$drug_id] ?? 0;

        // 计算获取剩余可买的次数
        $limit_num = $limit_num - $purchaseCount;
        Log::info(' drug_id'.$drug_id.' limit_num=>'.$limit_num.' limit_type'.$limit_type);

        return $this->success(['limit_num' => $limit_num, 'limit_type' => $limit_type]);

    }
}
