<?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 BuyCodeForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        DB::beginTransaction();
        try {
            $aftercode = trim($input['buycode']); //修改后直购码
            $uid = trim($input['userid']);
            $uObj = User::find($uid);
            if (!is_numeric($aftercode)) {
                throw new Exception('该直购码不是数字!');
            }
            $isExist = Merchant::where('buycode', $aftercode)->count();
            if (!$isExist) {
                throw new Exception('该直购码错误!');
            }
            if ($uObj) {
                if (!$uObj->buycode) {
                    throw new Exception('该用户还没绑定直购码!');
                }
                $checkObj = new UserBuycodeCheck();
                $checkObj->uid = $uid;
                $checkObj->before_code = $uObj->buycode;
                $checkObj->after_code = $aftercode;
                $checkObj->save();
            }
            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->display('current', '当前直购码');
        $this->text('buycode', '修改直购码')->help('输入商家直购码');
        $this->hidden('userid');
    }

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