<?php

namespace App\Admin\Forms;

use App\Admin\Actions\UserBuyCode;
use App\Command\Log;
use App\Models\Company;
use App\Models\Employee;
use App\Models\Income;
use App\Models\Merchant;
use App\Models\Pay;
use App\Models\User;
use App\Models\UserBuycodeCheck;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class EditShareUserForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        DB::beginTransaction();
        try {
            $user_id = $this->payload['uid'];
            $phone = trim($input['phone']); //推荐人手机号

            $spObj = User::where('phone', $phone)->first();
            if (!$spObj) {
                throw new Exception('该推荐人信息不存在!');
            }
            $uObj = User::find($user_id);
            Log::add('更改推荐人前信息uid:' . $user_id, ['spuid' => $uObj->spuid, 'second_spuid' => $uObj->second_spuid]);
            if ($uObj) {
                $uObj->spuid = $spObj->id; //直推
                $uObj->second_spuid = $spObj->spuid ?? 0; //间推
                $uObj->save();
                Log::add('更改推荐人后信息uid:' . $user_id, ['spuid' => $uObj->spuid, 'second_spuid' => $uObj->second_spuid]);
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error($exception->getMessage())->refresh();
        }
        return $this->response()->success('提交成功')->refresh();
    }


    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('phone', '推荐手机号');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        // 获取外部传递参数
        return [];
    }
}