<?php

namespace BYDAuto\Commands;

use BYDAuto\Models\Dealer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class GeocodingCommand extends Command
{
    protected $signature = 'bydauto:geocoding {action}';

    protected $description = '使用百度地图 API 把地址转换为经纬度';

    public function handle()
    {
        $action = $this->argument('action');
        if (method_exists($this, 'action_' . $action)) {
            $this->{'action_' . $action}();
        } else {
            $this->error('Action not found');
        }
    }

    public function action_update()
    {
        $items = Dealer::query()->orderBy('id')->get();
        dump($items[0]);
    }

    public function xlsx($chunk, $index)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', '门店名称（必填）');
        $sheet->setCellValue('B1', '门店编码');
        $sheet->setCellValue('C1', '省份名称（必填）');
        $sheet->setCellValue('D1', '城市名称（必填）');
        $sheet->setCellValue('E1', '描述');
        $sheet->setCellValue('F1', '地址（必填）');
        $sheet->setCellValue('G1', '经度（必填）');
        $sheet->setCellValue('H1', '纬度（必填）');
        $sheet->setCellValue('I1', '电话（必填）');
        $sheet->setCellValue('J1', '营业时间（必填）');
        $sheet->setCellValue('K1', '标签');
        $sheet->setCellValue('L1', '业务扩展字段');

        $sn = 2;
        foreach ($chunk as $dealer) {
            $except1 = ['北京', '上海', '天津', '重庆']; // 直辖市
            $except2 = ['内蒙古', '内蒙古（蒙东）', '内蒙古（蒙西）']; // 内蒙古自治区
            $except3 = ['新疆']; // 新疆维吾尔自治区
            $except4 = ['西藏']; // 西藏自治区
            $except5 = ['广西']; // 广西壮族自治区
            $except6 = ['宁夏']; // 宁夏回族自治区
            $except7 = ['香港', '澳门']; // 香港特别行政区、澳门特别行政区

            $province = $dealer->province;
            if (in_array($province, $except1)) {
                $province .= '市';
            } elseif (in_array($province, $except2)) {
                $province = '内蒙古自治区';
            } elseif (in_array($province, $except3)) {
                $province = '新疆维吾尔自治区';
            } elseif (in_array($province, $except4)) {
                $province = '西藏自治区';
            } elseif (in_array($province, $except5)) {
                $province = '广西壮族自治区';
            } elseif (in_array($province, $except6)) {
                $province = '宁夏回族自治区';
            } elseif (in_array($province, $except7)) {
                $province .= '特别行政区';
            } else {
                $province .= '省';
            }

            $lng = $dealer->lng ? number_format($dealer->lng, 6) : '';
            $lat = $dealer->lat ? number_format($dealer->lat, 6) : '';

            $sheet->setCellValue('A' . $sn, $dealer->name);
            $sheet->setCellValue('B' . $sn, $dealer->erp);
            $sheet->setCellValue('C' . $sn, $province);
            $sheet->setCellValue('D' . $sn, $dealer->city);
            $sheet->setCellValue('E' . $sn, $dealer->alias);
            $sheet->setCellValue('F' . $sn, $dealer->address);
            $sheet->setCellValue('G' . $sn, $lng);
            $sheet->setCellValue('H' . $sn, $lat);
            $sheet->setCellValue('I' . $sn, '13000000000');
            $sheet->setCellValue('J' . $sn, '09:00-18:00');
            $sheet->setCellValue('K' . $sn, '');

            $vehicles = $dealer->vehicles->map(fn ($v) => $v->extra_code)->join(',');
            $vehicles = trim($vehicles, ',');
            $sheet->setCellValue('L' . $sn, $vehicles);

            ++$sn;
        }
        $writer = new Xlsx($spreadsheet);
        $writer->save(storage_path('app/dealers-' . $index . '.xlsx'));
    }

    public function csv($chunk, $index)
    {
        $headers = ['门店名称（必填）', '门店编码', '省份名称（必填）', '城市名称（必填）', '描述', '地址（必填）', '经度（必填）', '纬度（必填）', '电话（必填）', '营业时间（必填）', '标签', '业务扩展字段'];
        $file = fopen(storage_path('app/dealers-' . $index . '.csv'), 'w');
        fputcsv($file, $headers);
        $chunk->each(function (Dealer $dealer) use ($file) {
            $except1 = ['北京', '上海', '天津', '重庆']; // 直辖市
            $except2 = ['内蒙古', '内蒙古（蒙东）', '内蒙古（蒙西）']; // 内蒙古自治区
            $except3 = ['新疆']; // 新疆维吾尔自治区
            $except4 = ['西藏']; // 西藏自治区
            $except5 = ['广西']; // 广西壮族自治区
            $except6 = ['宁夏']; // 宁夏回族自治区
            $except7 = ['香港', '澳门']; // 香港特别行政区、澳门特别行政区

            $province = $dealer->province;
            if (in_array($province, $except1)) {
                $province .= '市';
            } elseif (in_array($province, $except2)) {
                $province = '内蒙古自治区';
            } elseif (in_array($province, $except3)) {
                $province = '新疆维吾尔自治区';
            } elseif (in_array($province, $except4)) {
                $province = '西藏自治区';
            } elseif (in_array($province, $except5)) {
                $province = '广西壮族自治区';
            } elseif (in_array($province, $except6)) {
                $province = '宁夏回族自治区';
            } elseif (in_array($province, $except7)) {
                $province .= '特别行政区';
            } else {
                $province .= '省';
            }

            $lng = $dealer->lng ? number_format($dealer->lng, 6) : '';
            $lat = $dealer->lat ? number_format($dealer->lat, 6) : '';

            fputcsv($file, [
                $dealer->name,
                $dealer->erp,
                $province,
                $dealer->city,
                $dealer->alias,
                $dealer->address,
                $lng,
                $lat,
                '13000000000',
                '09:00-18:00',
                '',
                $dealer->region,
            ]);
        });
        fclose($file);
    }

    public function action_csv()
    {
        $items = Dealer::query()->orderBy('id')->get();
        $chunks = $items->chunk(200);
        $chunks->each(fn ($chunk, $index) => $this->xlsx($chunk, $index));
    }

    public function action_xlsx()
    {
        $items = Dealer::query()->orderBy('id')->get();
        $chunks = $items->chunk(200);
        $chunks->each(fn ($chunk, $index) => $this->xlsx($chunk, $index));
    }

    public function action_dump()
    {
        $address = $this->ask('请输入地址');
        $response = $this->getGeocoding($address);
        dump($response);
    }

    public function action_show()
    {
        $items = Dealer::query()->take(4)->get();
        $this->table(['CODE', '经销商名称', '在售车型'], $items->map(fn (Dealer $d) => [$d->erp, $d->alias, $d->vehicles->map(fn ($v) => $v->spec_id)->join(',')]));
    }

    public function action_fix()
    {
        $dealers = Dealer::query()->orderBy('id')->whereNull('lat')->get();
        $dealers->each(function (Dealer $dealer) {
            $endpoint = 'https://api.map.baidu.com/geocoding/v3/';
            $address = str_replace("\n", " ", $dealer->address);
            $this->info($dealer->id . ':' . $address);
            $response = Http::get($endpoint, ['address' => $address, 'output' => 'json', 'ak' => config('services.baidulbs.ak')]);
            if ($response->json('status') === 0) {
                $location = $response->json('result.location');
                $dealer->update(['address' => $address, 'lat' => $location['lat'], 'lng' => $location['lng']]);
            }
        });
    }

    public function getGeocoding($address)
    {
        $endpoint = 'https://api.map.baidu.com/geocoding/v3/';
        $response = Http::get($endpoint, ['address' => $address, 'output' => 'json', 'ak' => config('services.baidulbs.ak')]);
        return $response->json();
    }
}
