<?php

namespace App\Imports;

use App\Http\Models\LinkTaskDetail;
use App\Http\Models\LinkTaskUrl;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;


class LinkHallWorker implements ToCollection
{
    use Importable;
    protected $taskId;

    public function __construct($taskId)
    {
        $this->taskId = $taskId;
    }

    const FIELD_MAP = [
        3 => 'username',
        4 => 'email',
        5 => 'password',
        6 => 'url',
        7 => 'show_url',
        8 => 'remark',
    ];

    public function collection(Collection $collections)
    {
        $results = [];
        foreach ($collections as $key => $collection) {

            if ($key < 1) {
                continue;
            }
            $temp = $this->fieldMap($collection);
            $results[] = $temp;
        }

        $details = LinkTaskDetail::query()->where(['task_id' => $this->taskId])->get();

        foreach ($details as $inx => $detail) {
            if (!empty($results[$inx])) {
                $detail->update([
                    'username' => $results[$inx]['username'],
                    'email' => $results[$inx]['email'],
                    'password' => $results[$inx]['password'],
                    'url' => $results[$inx]['url'],
                    'remark' => $results[$inx]['remark'],
                ]);

                $showUrls = $results[$inx]['show_url'] ?? [];

                $insetData = [];
                foreach ($showUrls as $url) {
                    $insetData[] = [
                        'link_tasks_detail_id' => $detail->id,
                        'url' => $url,
                        'status' => 1,//默认,
                        'valid_status' => 3,//待检测
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ];
                }
                LinkTaskUrl::query()->insert($insetData);
            }
        }
    }


    public function fieldMap($collect): array
    {
        foreach ($collect as $inx => $val) {
            if (empty(self::FIELD_MAP[$inx])) continue;
            if (self::FIELD_MAP[$inx] == 'show_url') {
                $result[self::FIELD_MAP[$inx]] = trim($val) ?
                    explode("\n", trim($val)) :
                    [];
            } else {
                $result[self::FIELD_MAP[$inx]] = trim($val);
            }
        }
        return $result ?? [];
    }

}