<?php
namespace App\Admin\Actions\Users;

use App\Models\User;
use App\Models\UserVipLogModel;
use App\Models\VipModel;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;

class UserVipForm extends Form implements LazyRenderable
{
    use LazyWidget;


    public function __construct($data = [], $key = null)
    {
        parent::__construct($data, $key);
    }

    public function handle(array $input)
    {
        DB::beginTransaction();
        try {
            $user = User::query()->find($input['id']);
            if(!$user){
                throw new Exception("请刷新后重试");
            }
            if($input['vip']>0){
                $vip_info = VipModel::query()->find($input['vip']);
                $user_vip_log = UserVipLogModel::query()->where(['user_id'=>$user->id])->first();
                if(!$user_vip_log){
                    UserVipLogModel::query()->create([
                        'user_id'=>$user->id,
                        'status'=>1,
                        'day'=>$vip_info['day'],
                        'end_day'=> date("Y-m-d H:i:s",strtotime("+".$vip_info['day']." day")),
                    ]);
                }elseif($user_vip_log->status==1){
                    $user_vip_log->end_day = date("Y-m-d H:i:s",strtotime($user_vip_log->end_day."+".$vip_info['day']." day"));
                    $user_vip_log->save();
                }elseif ($user_vip_log->status==0){
                    $user_vip_log->end_day = date("Y-m-d H:i:s",strtotime("+".$vip_info['day']." day"));
                    $user_vip_log->status = 1;
                    $user_vip_log->save();
                }
                $user->is_vip = 1;
                $user->save();
            }else{
                if($user_vip_log = UserVipLogModel::query()->where(['user_id'=>$user->id])->first()){
                    $user_vip_log->status = 0;
                    $user_vip_log->save();
                }
                $user->is_vip = 0;
                $user->save();
            }
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->response()->error($exception->getMessage());
        }

        return $this->response()->success('保存成功')->refresh();
    }


    public function form()
    {
        $vip = VipModel::query()->orderBy('id','asc')->get();
        $vip_arr = array('0'=>'无');
        $vip = $vip->toArray();
        foreach ($vip as $k=>$v){
            $vip_arr[$v['id']] = $v['title'];
        }
        $this->hidden('id')->value($this->payload['id']);
        $this->select('vip', 'VIP')->options($vip_arr);
    }
}
