<?php

namespace App\Admin\Extensions\ToolBar\Forms;

use App\Admin\Renderable\DrugTable;
use App\Models\DrugModel;
use App\Models\PharmacyDrugModel;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Layout\Content;
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)
    {
        if (! Admin::user()->isRole('pharmacy') || ! Admin::user()->pharmacy_id) {
            admin_exit(Content::make()->withError(trans('admin.deny')));
        }
        $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' => Admin::user()->pharmacy_id,
                'drug_id' => $id,
            ];
            PharmacyDrugModel::updateOrCreate($where, $data);
        }

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

    }
}
