<?php

namespace App\Admin\Extensions\ToolBar\Forms\Shop;

use App\Models\Shop\ShopDeliveryImport;
use App\Service\Shop\ShopService;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Widgets\Form;
use Dcat\EasyExcel\Excel;
use Exception;

class DeliveryImportForm 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->text('remark', '发货备注')->placeholder('方便自己区分');
        $this->file('import_file', '文件')
            ->disk('admin')
            ->accept('xls,xlsx,csv')
            ->autoUpload()
            ->uniqueName()
            ->required()
            ->help("导入要求：<br />
                   <span style='color:red;'>
                   1、支持xls、xlsx、csv三种格式！<br />
                   2、表头必须包含【订单号,快递公司,快递单号】这三列，列的顺序无所谓，多余列会自动过滤！<br />
                   3、“快递公司”填写发货模板第二个sheet中的“快递公司编码”<br />
                   4、发货信息必须在第一个sheet！
                   </span>");
        $downloadUrl = admin_url('shop-delivery-template-url');
        $this->html("<a target='_blank' href='{$downloadUrl}'>下载发货模板文件</a>");
    }
}
