<?php

namespace App\Admin\Extensions\ToolBar\Forms;

use App\Models\PharmacyModel;
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 PharmacyImportForm 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);
                    $pharmacyModel = null;
                    if (isset($item['药店管理员手机号']) && $item['药店管理员手机号']) {
                        $pharmacyModel = PharmacyModel::where('mobile', $item['药店管理员手机号'])->first();
                    }
                    if (! $pharmacyModel) {
                        $pharmacyModel = new PharmacyModel;
                    }
                    $pharmacyModel->name = $item['药店名称'] ?? 0;
                    $pharmacyModel->area = $item['地区'];
                    $pharmacyModel->address = $item['详细地址'];
                    $pharmacyModel->mobile = $item['药店管理员手机号'];
                    $pharmacyModel->business_start = $item['营业开始时间'];
                    $pharmacyModel->business_end = $item['营业结束时间'];
                    if ($pharmacyModel->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两种格式<br \>
                   </span>");
        $downloadUrl = admin_url('pharmacy-template');
        $this->html("<a target='_blank' href='{$downloadUrl}'>下载药店导入模板</a>");
    }
}
