<?php

namespace App\Admin\Extensions\ToolBar\Forms;

use App\Models\DrugModel;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Widgets\Form;
use Dcat\EasyExcel\Excel;
use Dcat\EasyExcel\Support\SheetCollection;
use Exception;

class DrugImportForm extends Form
{
    /**
     * 处理表单提交逻辑.
     */
    public function handle(array $input): JsonResponse
    {
        // 表单参数
        $file = $input['import_file'];
        $filePath = storage_path('app/'.$file);
        try {
            // 每100行数据为一批数据进行读取
            $chunkSize = 10;
            $successNum = 0;
            $failNum = 0;
            Excel::import($filePath)->first()->chunk($chunkSize, function (SheetCollection $collection) use ($successNum) {
                // 此处的数组下标依然是excel表中数据行的行号
                $rows = $collection->toArray();
                foreach ($rows as $row) {
                    $item = array_map(function ($value) {
                        return is_string($value) ? trim($value) : $value;
                    }, $row);
                    $drugModel = DrugModel::where('product_id', $item['君元ID'])->first();
                    $drugModel->name = $item['药品名称'];
                    $drugModel->code = '';
                    $drugModel->standard_code = $item['本位码'];
                    $drugModel->unit = $item['单位'];
                    $drugModel->spec = $item['规格'];
                    $drugModel->dosage_form = $item['剂型'];
                    $drugModel->factory = $item['生产厂家'];
                    $drugModel->approval_no = $item['批准文号'];
                    $drugModel->is_rx = self::toBool($item['是否处方药']);
                    $drugModel->is_si = self::toBool($item['是否医保药品']);
                    $drugModel->product_id = $item['君元ID'] ?? 0;
                    if ($drugModel->save()) {
                        $successNum++;
                    }
                }
            });
            $return = $this->response()->success("导入成功{$successNum}条")->refresh();
            unlink($filePath);
        } catch (Exception $e) {
            $return = $this->response()->error("导入失败{$failNum}条：".$e->getMessage());
        }

        return $return;
    }

    /**
     * 构造表单.
     */
    public function form()
    {
        $this->file('import_file', '文件')
            ->disk('local')
            ->accept('xls,xlsx,csv')
            ->autoUpload()
            ->uniqueName()
            ->required()
            ->help("导入要求：<br />
                   <span style='color:red;'>
                   1、支持xls、xlsx、csv三种格式
                   </span>");
        $downloadUrl = admin_url('drug-template');
        $this->html("<a target='_blank' href='{$downloadUrl}'>下载药品导入模板</a>");
    }

    private static function toBool($value)
    {
        // 定义一个数组，包含所有需要转换的值及其对应的结果
        $mapping = [
            '是' => 1, 'Y' => 1, 'y' => 1, '1' => 1,
            '否' => 0, 'N' => 0, 'n' => 0, '0' => 0,
        ];

        // 将输入值转换为小写，以便不区分大小写
        $value = strtolower($value);

        // 检查值是否存在于映射数组中，如果存在则返回对应的值，否则返回null或自定义的默认值
        return isset($mapping[$value]) ? $mapping[$value] : 0;
    }
}
