<?php

namespace App\Console\Commands;

use App\Models\PharmacyDrugModel;
use App\Models\PharmacyModel;
use Illuminate\Console\Command;

class InitPharmacyDrugCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'init:pharmacy_drug {pharmacy_id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '药店药品复制';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('开始药店药品复制...');
        // 以药店1的药品为模板复制到其他药店
        $pharmacy_id = $this->argument('pharmacy_id') ?? 0;
        if (intval($pharmacy_id) <= 1) {
            $this->info('请输入正确的药店id');

            return;
        }
        // 查找一下传入的药店id是否存在
        $pharmacy = PharmacyModel::where('id', $pharmacy_id)->first();
        if (empty($pharmacy)) {
            $this->info('药店不存在，请重新输入');

            return;
        }
        $pharmacyDrugList = PharmacyDrugModel::where('pharmacy_id', 1)->get();
        if ($pharmacyDrugList->count() <= 0) {
            $this->info('模板药店药品为空');

            return;
        }

        foreach ($pharmacyDrugList as $pharmacyDrug) {
            // 查找该药品在该药店是否存在，如果存在则跳过，如果不存在则复制
            $is_exists = PharmacyDrugModel::where('pharmacy_id', $pharmacy_id)->where('drug_id', $pharmacyDrug->drug_id)->first();
            if (! empty($is_exists)) {
                continue;
            }
            $newPharmacyDrug = new PharmacyDrugModel();
            $newPharmacyDrug->pharmacy_id = $pharmacy_id;
            $newPharmacyDrug->drug_id = $pharmacyDrug->drug_id;
            $newPharmacyDrug->unit = $pharmacyDrug->unit;
            $newPharmacyDrug->save();
        }

    }
}
