<?php

namespace App\Console\Commands;

use App\Models\Article;
use Illuminate\Console\Command;

class UpdateFieldArticle extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:article_field';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    private $path = "excel/article.xlsx";

    private $saiKyotoId = 2;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("Start update");

        $pathExcel = storage_path($this->path);

        $sheet = $this->readExcel($pathExcel, 0);
        $this->updateArticle($sheet, 317);

        $sheet = $this->readExcel($pathExcel, 1);
        $this->updateArticle($sheet);

        $this->info("End update");
    }

    private function updateArticle($sheet, $start = 2)
    {
        $this->info("Start update article");
        $highestRow = $sheet->getHighestRow();
        for ($i = $start; $i <= $highestRow; $i++) {
            $article = Article::where("building_id", $this->getData($sheet, "A{$i}"))->first();
            if ($article) {
                $dataUpdate = [
                    "company_manner" => $this->getCompanyManner($this->getData($sheet, "D{$i}")),
                    "place_area" => $this->getData($sheet, "G{$i}"),
                ];
                $article->update($dataUpdate);
                $this->updateCustomFieldHouse($article, $sheet, $i);
            }
            $this->info("# {$i}/{$highestRow} " . date("Y-m-d H:s:i"));
        }
        $this->info("Success update article");
    }

    private function getData($sheet, $index, $dateTime = false)
    {
        $cell = $sheet->getCell("{$index}");
        if ($dateTime && \PHPExcel_Shared_Date::isDateTime($cell)) {
            $dateTimeObject = \PHPExcel_Shared_Date::ExcelToPHPObject($cell->getValue());
            return $dateTimeObject->format('Y-m-d H:i:s');
        }

        return $cell->getValue() . "";
    }

    private function readExcel($path, $index = 0)
    {
        $excel = \PHPExcel_IOFactory::createReaderForFile($path);
        $excelObj = $excel->load($path);
        $ws = $excelObj->getSheet($index);
        return $ws;
    }

    private function updateCustomFieldHouse($article, $sheet, $i)
    {
        $data = [
            "type" => 1,
            "code" => 1,
            "contents" => "",
        ];

        $fields = [
            $this->getData($sheet, "B{$i}"),
            $this->getData($sheet, "C{$i}"),
            $this->getData($sheet, "E{$i}"),
            $this->getData($sheet, "F{$i}")
        ];

        foreach ($fields as $key => $field) {
            if (empty($field)) {
                continue;
            }

            $data["code"] = $key + 4;
            $data["contents"] = $field;
            $data["company_id"] = $this->saiKyotoId;
            $article->customs()->create($data);
        }
    }

    private function getCompanyManner($name)
    {
        $manager = [
            "仲介（一般媒介）" => 3,
            "売主" => 1,
            "仲介（専任媒介）" => 4,
            "仲介（専属専任）" => 5,
            "販売提携（代理）" => 6,
        ];

        return $manager[$name] ?? "";
    }
}
