<?php

namespace App\Admin\Actions;

use App\Models\User;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;

class UserImport extends Action
{

    public    $name     = '批量导入';

    protected $vote;

    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        $file = $request->file('file');
        //        if ($file->extension() != 'csv') {
        //            return $this->response()->error('必须使用csv文件' . $file->extension());
        //        }
        $handle = fopen($file, 'r');
        if (!$handle) {
            exit('读取文件失败');
        }
        $failed  = 0;
        $success = 0;
        while (($data = fgetcsv($handle)) !== false) {
            if (empty($data[0])) {
                continue;
            }

            if (strlen($data[0]) != 11) {
                $failed++;
                continue;
            }
            if ($this->preg_is_utf8($data[1])) {
                $name = $data[1];
            } else {
                $name = iconv('gbk', 'utf-8', $data[1]);
            }
            try {
                User::create([
                    'parent_id' => $request->parent_id ?: 1,
                    'mobile'    => $data[0],
                    'name'      => $name,
                ]);
                $success++;
            } catch (\Exception $exception) {
                $failed++;
            }
        }
        fclose($handle);

        return $this->response()->success('批量处理成功' . $success . '条，失败' . $failed . '条')->refresh();
    }

    function preg_is_utf8($string)
    {
        return preg_match('/^.*$/u', $string) > 0;//preg_match('/^./u', $string)
    }

    public function form()
    {
        $parents = User::select()->where('type', 1)->pluck('name', 'id');
        $this->select('parent_id')->options($parents);
        $this->file('file', '请选择文件')->help('CSV - 手机号-姓名');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-info import-post"><i class="fa fa-upload"></i> 批量导入</a>
HTML;
    }

}
