<?php

namespace App\Console\Commands;

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

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

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

    private $filename = "excel/data_new_15_04_20.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 import file");

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

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

        $this->info("Success import house");

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

        $this->info("Success import room");

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

        $this->info("Success import land");

        $this->info("End import file");
    }

    private function updateArticle($sheet, $index)
    {
        $this->info("Start update article");

        $isHouse = $index == 0;
        $isRoom = $index == 1;
        $isLand = $index == 2;

        $highestRow = $sheet->getHighestRow();

        for ($i = 2; $i <= $highestRow; $i++) {
            $buildingId = $this->getData($sheet, "A{$i}");
            $article = Article::where("building_id", $buildingId)
                ->where("company_id", $this->saiKyotoId)
                ->first();

            if ($article) {
                $articleData = $this->updateData($sheet, $i, $index);
                $article->update($articleData);

                $relationVendor = $article->relationVendors()->first();
                if ($relationVendor) {
                    $articleConfDay = $this->getData($sheet, "B{$i}", true);
                    $relationVendor->update([
                        "article_conf_day" => $articleConfDay
                    ]);
                }
                $this->createOrUpdateCustomField($article, 3, $this->getData($sheet, "Q{$i}"));

                $manner = "";
                if ($isHouse) {
                    $manner = $this->getData($sheet, "T{$i}");
                } else if ($isRoom) {
                    $manner = $this->getData($sheet, "R{$i}");
                } else if ($isLand) {
                    $manner = $this->getData($sheet, "S{$i}");
                }
                $this->updateVendor($article, $manner);
                $this->info("# {$i}/{$highestRow} " . date("Y-m-d H:i:s") . ": {$article->name}");
            }
        }

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

    private function updateData($sheet, $i, $index)
    {
        $line3Name = $this->getData($sheet, "C{$i}");
        $station3Name = $this->getData($sheet, "D{$i}");
        $line3Data = MstLine::where("name", $line3Name)->first();
        $station3Data = MstLine::where("name", $line3Name)->first();
        $traffic3Time = $this->getData($sheet, "E{$i}");
        $trafficBus3Time = $this->getData($sheet, "F{$i}");

        $line4Name = $this->getData($sheet, "I{$i}");
        $station4Name = $this->getData($sheet, "J{$i}");
        $line4Data = MstLine::where("name", $line4Name)->first();
        $station4Data = MstLine::where("name", $station4Name)->first();
        $traffic4Time = $this->getData($sheet, "K{$i}");
        $trafficBus4Time = $this->getData($sheet, "L{$i}");

        $memo1 = $this->getData($sheet, "O{$i}");
        $memo2 = $this->getData($sheet, "P{$i}");

        $isHouse = $index == 0;
        $isRoom = $index == 1;
        $isLand = $index == 2;

        if ($isHouse) {
            $buildNote = $this->getData($sheet, "S{$i}");
            $landNote = $this->getData($sheet, "R{$i}");
        }

        if ($isRoom) {
            $buildNote = "";
            $landNote = "";
        }

        if ($isLand) {
            $landNote = $this->getData($sheet, "R{$i}");
            $buildNote = "";
        }

        return [
            "sub_traffic3_line" => $line3Name,
            "sub_traffic3_station" => $station3Name,
            "sub_traffic3_line_id" => optional($line3Data)->id,
            "sub_traffic3_station_id" => optional($station3Data)->id,
            "sub_traffic3_time" => $traffic3Time,
            "sub_traffic3_bus_time" => $trafficBus3Time,
            "sub_traffic4_line" => $line4Name,
            "sub_traffic4_station" => $station4Name,
            "sub_traffic4_line_id" => optional($line4Data)->id,
            "sub_traffic4_station_id" => optional($station4Data)->id,
            "sub_traffic4_time" => $traffic4Time,
            "sub_traffic4_bus_time" => $trafficBus4Time,
            "memo1" => $memo1,
            "memo2" => $memo2,
            "build_note" => $buildNote,
            "land_note" => $landNote,
        ];
    }

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

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

    private function updateVendor($article, $vendorManner)
    {
        $relationVendors = $article->relationVendors()->first();
        if ($relationVendors) {
            $relationVendors->update([
                "manner" => $this->getMannerVendor($vendorManner)
            ]);
        }
    }

    private function createOrUpdateCustomField($article, $code, $content)
    {
        $data = [
            "type" => 1,
            "code" => 1,
            "contents" => "",
        ];

        $custom = $article->customs()->where("code", $code)->first();

        if ($custom) {
            $custom->update([
                "contents" => $content
            ]);
        } else {
            $data["code"] = $code;
            $data["contents"] = $content;
            $data["company_id"] = $this->saiKyotoId;
            $article->customs()->create($data);
        }
    }

    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');
        }

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

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