<?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;

// 药品控制器
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) {
                if ($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);
    }

    // 药品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 = $site_config['prescription_limit_buy_7'];

        $drug_id = $request->input('drug_id');
        // 判断当前药品有没有设置7日内限购
        $drug = DrugModel::query()->find($drug_id);
        if ($drug && $drug->limit_buy_7 > 0) {
            $limit_num = $drug->limit_buy_7;
        }
        $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('pharmacy_id', $pharmacy_id)
            ->where('created_at', '>=', $sevenDaysAgo)
            ->get();

        $drugCounts = [];
        foreach ($prescriptions as $prescription) {
            $drugs = json_decode($prescription->drugs, true); // Parse JSON data
            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;

        return $this->success($limit_num);

    }
}
