<?php

namespace App\Admin\Forms;


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;


class CheckBuycode extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        DB::beginTransaction();
        $checkObj = UserBuycodeCheck::find($this->payload['id']);
        $userId = $checkObj->uid;
        $after_code = $checkObj->after_code;
        $merObj = Merchant::where('buycode', $after_code)->first();
        if (!$merObj) {
            return $this->response()->error('该商户不存在!')->refresh();
        }
        try {
            $status = (int)$input['status']; //审核状态 0:审核中 1:通过 2:拒绝
            $checkObj->status = $status;
            if ($status == 1) {
                $uObj = User::find($userId);
                $uObj->buycode = $checkObj->after_code;
                $uObj->merchant_id = $merObj->id;
                $uObj->save();
            }

            $checkObj->save();
            DB::commit();
            Log::add('直购码变更', $checkObj->toArray());
        } catch (\Exception $exception) {
            DB::rollBack();

            Log::add('直购码变更失败', $exception->getMessage());
            return $this->response()->error($exception->getMessage())->refresh();
        }
        return $this->response()->success('提交成功')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->radio('status', '审核')->options([1 => '同意', 2 => '拒绝'])
            ->required();
    }

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