<?php

namespace App\Admin\Extensions\ToolBar\Forms;

use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Widgets\Form;
use Dcat\EasyExcel\Excel;
use Exception;

class DrugImportForm extends Form
{
    /**
     * 处理表单提交逻辑.
     */
    public function handle(array $input): JsonResponse
    {
        // 表单参数
        // $file = $input['import_file'];
        // $remark = $input['remark'] ?? '';
        // $filePath = storage_path('uploads/'.$file);

        // try {
        //     $rows = Excel::import($filePath)->first()->toArray();
        //     $context = '';
        //     foreach ($rows as $row) {
        //         $orderId = $row['订单号'] ?? '';
        //         $deliveryCode = $row['快递公司'] ?? '';
        //         $deliveryNo = $row['快递单号'] ?? '';
        //         if (! $orderId || ! $deliveryCode || ! $deliveryNo) {
        //             continue;
        //         }
        //         $rowData = trim($orderId).','.trim($deliveryNo).','.trim($deliveryCode);
        //         $context .= $rowData."\n"; // 拼接数据并加上换行符
        //     }
        //     $context = rtrim($context, "\n");
        //     $deliveryImport = new ShopDeliveryImport();
        //     $deliveryImport->context = $context;
        //     $deliveryImport->remark = $remark;
        //     if ($deliveryImport->save()) {
        //         $id = $deliveryImport->id;
        //         ShopService::deliveryImportNotice($id);
        //     }
        //     $return = $this->response()->success('导入成功')->refresh();
        // } catch (Exception $e) {
        //     $return = $this->response()->error('导入失败：'.$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>");
    }
}
