<?php

namespace App\Console\Commands\Pair;

use App\Models\Fpdx\GroupMemberModel;
use App\Models\Fpdx\GroupModel;
use App\Models\Fpdx\PairModel;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '城市专场';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $stageId = $this->ask('选择期数?');
        $city = $this->ask('选择城市?');
        $groups = explode(',', $this->ask('群ID'));
        $activityType = '72h';
        $pairs = \DB::table('kdgx_partner_charge_pair')
            ->select('kdgx_partner_charge_pair.*')
            ->join('kdgx_partner_charge_user', 'kdgx_partner_charge_pair.uid', '=', 'kdgx_partner_charge_user.uid')
            ->where('kdgx_partner_charge_user.address', 'like', "%$city%")
            ->where([
                'kdgx_partner_charge_pair.activity_type' => $activityType,
                'kdgx_partner_charge_pair.stage_id' => $stageId,
                'kdgx_partner_charge_pair.partner' => 2
            ])->whereNotNull('kdgx_partner_charge_pair.assoc_id')
            ->where('group_id', 0)
            ->get();
        foreach ($pairs as $pair) {
            $left = PairModel::find($pair->assoc_id);
            $right = $pair;
            $group = GroupModel::whereIn('id', $groups)->where('activity_type', $activityType)
                ->where('type', 'pair')->whereColumn('number', '>', 'total_number')->first();
            if (!$group) {
                throw new \Exception("配对群组不够用");
            }
            PairModel::where(['id' => $left->id])->update(['group_id' => $group->id]);
            PairModel::where(['id' => $right->id])->update(['group_id' => $group->id]);
            GroupMemberModel::create([
                'uid' => $left->uid,
                'stage_id' => $stageId,
                'group_id' => $group->id,
                'type' => 'pair',
                'activity_type' => $activityType
            ]);
            GroupMemberModel::create([
                'uid' => $right->uid,
                'stage_id' => $stageId,
                'group_id' => $group->id,
                'type' => 'pair',
                'activity_type' => $activityType
            ]);
            $group->increment('total_number', 2);
        }
    }
}
