<?php

namespace App\Admin\Extensions\ToolBar\Forms;

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

set_time_limit(1800);
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 10800);
ini_set('max_input_time', 10800);
class PharmacyDosageImportForm extends Form
{
    /**
     * 处理表单提交逻辑.
     */
    public function handle(array $input): JsonResponse
    {
        if (! Admin::user()->isRole('pharmacy') || ! Admin::user()->pharmacy_id) {
            admin_exit(Content::make()->withError(trans('admin.deny')));
        }
        $pharmacyId = Admin::user()->pharmacy_id;
        // 表单参数
        $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, $pharmacyId) {
                // 此处的数组下标依然是excel表中数据行的行号
                $rows = $collection->toArray();
                foreach ($rows as $row) {
                    $item = array_map(function ($value) {
                        return is_string($value) ? trim($value) : $value;
                    }, $row);
                    $dosageModel = null;
                    if (isset($item['用法用量']) && $item['用法用量']) {
                        $dosageModel = DosageModel::where('dosage_desc', $item['用法用量'])->where('pharmacy_id', $pharmacyId)->first();
                    }
                    if (! $dosageModel) {
                        $dosageModel = new DosageModel;
                    }
                    $dosageModel->pharmacy_id = $pharmacyId;
                    $dosageModel->dosage_desc = $item['用法用量'];
                    $dosageModel->dosage_show = $item['显示内容'] ?? '';

                    if ($dosageModel->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('xlsx,csv')
            ->maxSize(1024 * 30)
            ->autoUpload()
            ->uniqueName()
            ->required()
            ->help("导入要求：<br />
                   <span style='color:red;'>
                   1、支持xlsx、csv两种格式
                   </span>");
        $downloadUrl = admin_url('dosage-template');
        $this->html("<a target='_blank' href='{$downloadUrl}'>下载用法用量导入模板</a>");
    }
}
