<?php

namespace App\Domains\Real\Commands\Sync;

use App\Models\Real\FlowPool;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Domains\Real\Repositories\CompanyRepository;
use App\Domains\Real\Repositories\PackageRepository;
use App\Domains\Real\Repositories\FlowPoolRepository;

class FlowPoolSync extends Command
{
    protected $name = 'real:sync-flow-pool';

    protected $description = '同步RD流量池';

    protected $carrier_operator = ['lt' => 0, 'yd' => 1, 'dx' => 2, 'qw' => 3];

    public function handle()
    {
        $companies = app(CompanyRepository::class)->withTrashed()->get()->keyBy('sn');
        $packages = app(PackageRepository::class)->withTrashed()->get()->keyBy('sn');

        $select = ['id', 'type_id', 'shared_type as shared', "level_type as level", 'custom_no', 'cell_number as sn', 'name', 'flows', 'status', 'del', 'create_time'];

        $types = DB::connection('real')->table('jxc_flow_cell_type')->select(['id', 'carrieroperator'])->get()->pluck('carrieroperator', 'id')->toArray();

        foreach ($types as $key => &$type) {
            $type = $this->carrier_operator[$type];
        }

        $flowPools = DB::connection('real')->table('jxc_flow_cell')->select($select)
            ->whereIn('custom_no', $companies->keys()->toArray())
            ->get()->collect()->toArray();

        $flowPackages = DB::connection('real')->table('jxc_flow_cell_package')->select([
            'flow_cell_id',
            DB::raw('group_concat(distinct package_sn) as package_sn'),
        ])->whereIn('flow_cell_id', array_pluck($flowPools, 'id'))->groupBy('flow_cell_id')->get()->pluck('package_sn', 'flow_cell_id')->toArray();

        foreach ($flowPackages as $flowPoolId => $flowPackage) {
            $array = explode(',', $flowPackage);

            $ids = [];

            foreach ($array as $key => $value) {
                if (!$packages[$value]) {
                    continue;
                }

                $ids[] = $packages[$value]['id'];
            }

            $flowPackages[$flowPoolId] = $ids;
        }

        $data = [];

        foreach ($flowPools as $value) {
            $carrier_operator = $types[$value['type_id']] ?? 3;
            $package_ids = $flowPackages[$value['id']] ?? [];

            $data[] = [
                'id' => $value['id'],
                'sn' => $value['sn'],
                'company_id' => $companies[$value['custom_no']]['id'],
                'name' => $value['name'],
                'flows' => $value['flows'] == -255 ? -1 : intval($value['flows']),
                'carrier_operator' => $carrier_operator,
                'shared' => $value['shared'],
                'package_ids' => json_encode($package_ids),
                'created_at' => date('Y-m-d H:i:s', $value['create_time']),
                'updated_at' => date('Y-m-d H:i:s'),
                'deleted_at' => ($value['status'] == 0 || $value['del'] == 1) ? date('Y-m-d H:i:s') : null,
            ];
        }

        FlowPool::upsert($data, 'id');

        app(FlowPoolRepository::class)->forgetCached();
    }
}
