<?php

namespace App\Admin\Extensions\ToolBar\Forms;

use App\Admin\Renderable\DrugTable;
use App\Models\DrugModel;
use App\Models\PharmacyDrugModel;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class AddPharmacyDrugForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $this->multipleSelectTable('ids', '选择药品')
            ->title('选择药品')
            ->dialogWidth('70%') // 弹窗宽度，默认 800px
            ->from(DrugTable::make()) // 设置渲染类实例，并传递自定义参数
            ->model(DrugModel::class, 'id', 'name')->required()->width(6);
    }

    public function handle(array $input)
    {
        $ids = $input['ids'];

        if (! $ids) {
            return $this->response()->error('请选择药品')->refresh();
        }
        foreach ($ids as $id) {
            // $drug = DrugModel::find($id);
            $where = ['drug_id' => $id];
            $data = [
                'pharmacy_id' => $id,
                'drug_id' => $id,
                'dosage_id' => 0,
            ];
            PharmacyDrugModel::updateOrCreate($where, $data);
        }

        return $this->response()->alert(true)->success('导入药品成功。')->detail('')->refresh();

    }
}
