<?php

namespace App\Admin\Actions\User;

use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use RuLong\Identity\Models\Identity;

class ReCode extends RowAction
{

    public $name = '重置规则';
 
    public function handle(Model $model)
    {
        if ($model->identity_id != 1) {
            return $this->response()->error('只有渠道才能刷新');
        }

        $all_codes  = Identity::find(1)->codes;
        $user_codes = $model->code;

        if ($all_codes->count() == $user_codes->count()) {
            return $this->response()->success('操作成功')->refresh();
        }

        foreach ($all_codes as $key => $code) {
            $model->code()->updateOrCreate([
                'code' => $code->code,
            ], [
                'name'   => $code->name,
                'code'   => $code->code,
                'profit' => $code->profit,
            ]);
        }

        return $this->response()->success('操作成功')->refresh();
    }

    public function dialog()
    {
        $this->confirm('确定要重置卡券规则吗？刷新后将重置此渠道卡券规则');
    }

}
