<?php

namespace App\Console\Commands;

use App\Models\MstLine;
use App\Models\MstStation;
use App\Models\MstStationPortal;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class MapLineStationPortal extends Command
{
    protected $signature = 'map:line-station';
    protected $description = 'Mapping line station of bukken with portal';

    protected $notfounds = [];
    protected $stationNotFounds = [];
    protected $lineNotFounds = [];
    protected $companyRunning = 1;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $data = MstStationPortal::selectRaw('MIN(staion_unique_id) as staion_unique_id, count(*) as count')->groupBy(['line_id', 'type', 'line_name', 'station_name', 'station_id'])->havingRaw('count > 1')->get();
        foreach ($data as $item){
            $first = MstStationPortal::find($item->staion_unique_id);
            MstStationPortal::where('line_id', $first->line_id)
                ->where('line_name', $first->line_name)
                ->where('station_name', $first->station_name)
                ->where('type', $first->type)
                ->where('staion_unique_id', '!=', $first->staion_unique_id)
                ->delete();
        }

        MstStationPortal::whereNotNull('line_id')->update(['line_nickname' => '']);
        $companies = [1, 2, 3, 4, 999, 998];
        foreach ($companies as $company){
            auth()->company = $company;
            $this->companyRunning = $company;
            $lines = MstLine::all();
            foreach ($lines as $line){
                $stations = MstStation::where('line_id', $line->id)->get();
                foreach ($stations as $station) {
                    $this->updateStationPortalHomes($line->name, $station->name);
                    $this->updateStationPortalSummo($line->name, $station->name);
                    $this->updateStationPortalAtHome($line->name, $station->name);
                }
            }
        }

        Storage::disk('public')->put('linestation_notfound.json', json_encode($this->notfounds));
        Storage::disk('public')->put('lines_notfound.json', json_encode($this->lineNotFounds) );
        Storage::disk('public')->put('station_notfound.json', json_encode($this->stationNotFounds));
    }

    private function updateStationPortalHomes($line_name, $station_name){
        $maps = [
            'JR神戸線' => 'JR東海道・山陽本線',
            'JR京都線' => 'JR東海道・山陽本線',
            '神戸電鉄神戸高速線' => '神戸高速南北線',
            '横浜市営ブルーライン' => '横浜市営地下鉄ブルーライン',
            '横浜市営グリーンライン' => '横浜市営地下鉄グリーンライン',
            '横浜シーサイドライン' => '金沢シーサイドライン',
            'JR京浜東北線' => 'ＪＲ京浜東北・根岸線',
            'JR山陰本線・嵯峨野線' => 'ＪＲ山陰本線',
            '京福嵐山本線' => '京福電気鉄道嵐山本線',
            '京福北野本線' => '京福電気鉄道北野線',
            '嵯峨野観光線' => '嵯峨野観光鉄道',
            '叡山本線' => '叡山電鉄叡山本線',
            '叡山鞍馬線' => '叡山電鉄鞍馬線',
            '阪急神戸線' => '阪急神戸本線',
            '阪急今津線' => '阪急今津線',
            '阪急宝塚線' => '阪急宝塚本線',
            '阪神本線' => '阪神本線',
            '阪急箕面線' => '阪急箕面線',
            '阪急千里線' => '阪急千里線',
            'JRおおさか東線' => 'おおさか東線',
            'JR和田岬線' => 'ＪＲ東海道・山陽本線',
            '神戸高速鉄道東西線' => '神戸高速東西線',
            '阪神なんば線' => '阪神なんば線',
            '地下鉄西神・山手線' => '神戸市西神・山手線',
            '地下鉄海岸線' => '神戸市海岸線',
            '地下鉄北神線' => '神戸市北神線',
            'ポートアイランド線' => '神戸新交通ポートアイランド線',
            '六甲アイランド線' => '神戸新交通六甲アイランド線',
            '地下鉄御堂筋線' => 'Osaka Metro御堂筋線',
            '地下鉄今里筋線' => 'Osaka Metro今里筋線',
            '北大阪急行' => '北大阪急行電鉄',
            '大阪モノレール本線' => '大阪モノレール本線',
            '大阪モノレール彩都線' => '大阪モノレール彩都線',
            '横浜高速鉄道みなとみらい線' => 'みなとみらい線',
            'JR根岸線' => 'JR京浜東北・根岸線',
            '京阪鴨東線' => '京阪本線',
            '京都地下鉄烏丸線' => '京都市営烏丸線',
            '阪急京都線' => '阪急京都本線',
            '神戸電鉄有馬線' => '神鉄有馬線',
            '神戸電鉄三田線' => '神鉄三田線',
            '神戸電鉄粟生線' => '神鉄粟生線'
        ];
        $stationMaps = [
            '地下鉄御堂筋線' => ['西中島' => '西中島南方'],
            '京福北野本線' => ['常磐' => '常盤']
        ];

        $lineName = $maps[$line_name] ?? $line_name;
        $lineName = str_replace("JR", "ＪＲ", $lineName);
        $stationName = $stationMaps[$line_name][$station_name] ?? $station_name;
        $stationNames = [$stationName, str_replace("駅", "", $stationName)];
        $lines = MstStationPortal::where('type', 1)
            ->where('line_name', $lineName)
            ->whereIn('station_name', $stationNames)
            ->orderByRaw('FIELD(station_name, '.'"'.implode('", "', $stationNames).'")')
            ->get();

        if (count($lines) <= 0){
            $firstStation = MstStationPortal::where('type', 1)
                ->whereIn('station_name', $stationNames)
                ->first();
            $firstLine = MstStationPortal::where('type', 1)
                ->where('line_name', $lineName)
                ->first();
            if (!isset($firstStation) && !isset($firstLine)){
                $this->notfounds['homes'][$line_name][$station_name] = ['line_name' => $line_name, 'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
            if (!isset($firstLine)){
                $this->lineNotFounds['homes'][$line_name] = ['line_name' => $line_name, 'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
            if (!isset($firstStation)){
                $this->stationNotFounds['homes'][$station_name] = ['line_name' => $line_name, 'line_portal' => $firstLine->line_name ?? '', 'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
        }

        foreach ($lines as $lineItem){
            $lineItem->line_nickname = $line_name;
            $lineItem->save();
        }
    }

    private function updateStationPortalSummo($line_name, $station_name){
        $maps = [
            '横浜シーサイドライン' => 'シーサイドライン',
            'JR京都線' => 'ＪＲ東海道本線（富士川～神戸）',
            '神戸電鉄神戸高速線' => '神戸高速鉄道南北線',
            '横浜市営ブルーライン' => 'ブルーライン',
            '横浜市営グリーンライン' => 'グリーンライン',
            '横浜高速鉄道みなとみらい線' => 'みなとみらい線',
            'JR京浜東北線' => 'ＪＲ京浜東北線（東京～大船）',
            'JR東海道本線' => 'ＪＲ東海道本線（東京～富士）',
            'JR横須賀線' => 'ＪＲ横須賀線（保土ヶ谷～久里浜）',
            '江ノ島電鉄' => '江ノ島電鉄線',
            'JR山陰本線・嵯峨野線' => 'ＪＲ山陰本線',
            '京都地下鉄東西線' => '地下鉄東西線',
            '京都地下鉄烏丸線' => '地下鉄烏丸線',
            '京福嵐山本線' => '京福電鉄嵐山本線',
            '京福北野本線' => '京福電鉄北野線',
            '嵯峨野観光線' => '嵯峨野観光鉄道',
            '叡山本線' => '叡山電鉄叡山本線',
            '叡山鞍馬線' => '叡山電鉄鞍馬線',
            'JR神戸線' => 'ＪＲ東海道本線（富士川～神戸）',
            '阪神なんば線' => '阪神電鉄阪神なんば線'
        ];
        $stationMaps = [
            '地下鉄御堂筋線' => ['西中島' => '西中島南方'],
            '京福北野本線' => ['常磐' => '常盤']
        ];

        $lineName = $maps[$line_name] ?? $line_name;
        $lineName = str_replace("JR", "ＪＲ", $lineName);
        $station_name = str_replace("JR", "ＪＲ", $station_name);
        $stationName = $stationMaps[$line_name][$station_name] ?? $station_name;
        $lines = MstStationPortal::where('type', 2)->where('line_name', $lineName)->where('station_name', $stationName)->get();

        if (count($lines) <= 0){
            $firstStation = MstStationPortal::where('type', 2)
                ->where('station_name', $station_name)
                ->first();
            $firstLine = MstStationPortal::where('type', 2)
                ->where('line_name', $lineName)
                ->first();

            if (!isset($firstStation) && !isset($firstLine)){
                $this->notfounds['suumo'][$line_name][$station_name] = ['line_name' => $line_name, 'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
            if (!isset($firstLine)){
                $this->lineNotFounds['suumo'][$line_name] = ['line_name' => $line_name,  'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
            if (!isset($firstStation)){
                $this->stationNotFounds['suumo'][$station_name] = ['line_name' => $line_name, 'line_portal' => $firstLine->line_name ?? '',  'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
        }
        foreach ($lines as $line) {
            $line->line_nickname = $line_name;
            $line->save();
        }
    }

    public function updateStationPortalAtHome($line_name, $station_name){
        $sameName = str_replace('JR', 'ＪＲ', $line_name);
        $maps = [
            '京都地下鉄東西線' => '京都市営地下鉄東西線',
            '京阪京津線' => '京阪電鉄京津線',
            '嵯峨野観光線' => '嵯峨野観光鉄道',
            '京阪石山坂本線' => '京阪電鉄石山坂本線',
            '京阪本線' => '京阪電鉄鴨東線',
            '叡山鞍馬線' => '叡山電鉄',
            '叡山本線' => '叡山電鉄',
            'ＪＲ山陰本線・嵯峨野線' => 'ＪＲ山陰本線',
            'ＪＲ東海道・山陽本線' => 'ＪＲ東海道本線(米原～神戸)',
            'ＪＲ根岸線' => 'ＪＲ京浜東北・根岸線',
            '横浜シーサイドライン' => '金沢シーサイドライン',
            '横浜市営グリーンライン' => '横浜市グリーンライン',
            '横浜市営ブルーライン' => '横浜市ブルーライン',
            'ＪＲ京浜東北線' => 'ＪＲ京浜東北・根岸線',
            'ＪＲ京都線' => 'ＪＲ東海道本線(米原～神戸)',
            '神戸電鉄神戸高速線' => '神戸高速南北線',
            '阪急神戸線' => '阪急電鉄神戸線',
            '阪急宝塚線' => '阪急電鉄宝塚線',
            '阪急箕面線' => '阪急電鉄箕面線',
            '阪急千里線' => '阪急電鉄千里線',
            'ＪＲおおさか東線' => 'おおさか東線',
            'ＪＲ和田岬線' => 'ＪＲ山陽本線(神戸～下関)',
            '阪神本線' => '阪神電鉄本線',
            '神戸高速鉄道東西線' => '神戸高速東西線',
            '阪神なんば線' => '阪神電鉄阪神なんば線',
            '地下鉄西神・山手線' => '神戸市営地下鉄西神山手線',
            '地下鉄海岸線' => '神戸市営地下鉄海岸線',
            '地下鉄北神線' => '神戸市営地下鉄北神線',
            'ポートアイランド線' => '神戸新交通ポートアイランド線',
            '六甲アイランド線' => '神戸新交通六甲アイランド線',
            '地下鉄御堂筋線' => '大阪メトロ御堂筋線',
            '地下鉄今里筋線' => '大阪メトロ今里筋線',
            '北大阪急行' => '北大阪急行南北線',
            'ＪＲ東海道本線' => 'ＪＲ東海道本線(東京～熱海)',
            '京福嵐山本線' => '京福電鉄嵐山本線',
            '京福北野本線' => '京福電鉄北野線',
            'ＪＲ神戸線' => 'ＪＲ東海道本線(米原～神戸)',
            '阪急伊丹線' => '阪急電鉄伊丹線',
            '阪神武庫川線' => '阪神電鉄武庫川線',
            '能勢電鉄妙見線' => '能勢電鉄',
            '能勢電鉄日生線' => '能勢電鉄',
            '阪急甲陽線' =>  '阪急電鉄甲陽線',
            '阪急今津線' =>  '阪急電鉄今津線'
        ];

        $lineStationMaps = [
            'ＪＲ神戸線,塚本駅' => 'ＪＲ東海道本線(米原～神戸)',
            'ＪＲ神戸線,神戸駅' => 'ＪＲ東海道本線(米原～神戸)',
            'ＪＲ神戸線,甲南山手駅' => 'ＪＲ東海道本線(米原～神戸)',
            'ＪＲ神戸線,魚住駅' => 'ＪＲ山陽本線(神戸～下関)',
            'ＪＲ神戸線,兵庫駅' => 'ＪＲ山陽本線(神戸～下関)',
        ];
        $stationMaps = [
            '地下鉄御堂筋線' => ['西中島' => '西中島南方'],
            '京福北野本線' => ['常磐' => '常盤']
        ];
        $sameName = $lineStationMaps[$sameName.','.$station_name] ?? $sameName;
        $sameName = $maps[$sameName] ?? $sameName;
        $stationName = $stationMaps[$line_name][$station_name] ?? $station_name;
        $stationName = str_replace("JR", "ＪＲ", $stationName);
        $lines  = MstStationPortal::where('type', 3)->where('line_name', $sameName)
            ->where('station_name', $stationName)
            ->get();

        if (count($lines) <= 0){
            $firstStation = MstStationPortal::where('type', 3)
                ->where('station_name', $station_name)
                ->first();
            $firstLine = MstStationPortal::where('type', 3)
                ->where('line_name', $sameName)
                ->first();
            if (!isset($firstStation) && !isset($firstLine)){
                $this->notfounds['athome'][$line_name][$station_name] = ['line_name' => $line_name, 'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
            if (!isset($firstLine)){
                $this->lineNotFounds['athome'][$line_name] = ['line_name' => $line_name, 'station_name' => $station_name,  'company'=> $this->companyRunning];
            }

            if (!isset($firstStation)){
                $this->stationNotFounds['athome'][$station_name] = ['line_name' => $line_name, 'line_portal' => $firstLine->line_name ?? '', 'station_name' => $station_name, 'company'=> $this->companyRunning];
            }
        }

        foreach ($lines as $line) {
            $line->line_nickname = $line_name;
            $line->save();
        }
    }
}
