<?php

namespace App\Admin\Actions\Users;

use App\Models\Course;
use App\Models\CourseUser;
use App\Models\User;
use App\Models\UserIdentify;
use App\Models\UserMessage;
use App\Models\UserVipLogModel;
use App\Models\VipModel;
use App\Services\TencentImMessage;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PHPUnit\Util\Exception;

class UserCourseForm extends Form implements LazyRenderable
{
    use LazyWidget;


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

    public function handle(array $input)
    {
        DB::beginTransaction();
        try {
            $userCourse = CourseUser::query()->find($input['id']);
            if ($input['status'] > 0) {
                if ($userCourse['type'] == 1) { //如果当前是主场，就把用户名下其他会员球场变为副场
                    DB::table('course_users')->where('user_id', $userCourse['user_id'])->where('id', '<>', $input['id'])->update(['type' => 2]);
                }
                $userCourse->status = $input['status'];
                $userCourse->save();

                $course = Course::query()->find($userCourse->course_id);
                //给用户添加消息记录
                $user = User::query()->find($userCourse->user_id);

                $lang = $user->lang ?: 'en';

                if ($input['status'] == 1) {
                    $content = trans('api.YOU_HAVE_PASSED', [], $lang) . ' ' . $course['name'] . ' ' . trans('api.MEMBERSHIP_CERTIFICATION', [], $lang);
                } elseif ($input['status'] == 2) {
                    $content = trans('api.YOU_DO_NOT_HAVE_PASSED', [], $lang) . ' ' . $course['name'] . ' ' . trans('api.MEMBERSHIP_CERTIFICATION', [], $lang);
                }
                //发送消息通知
                $im_message = new TencentImMessage();
                $send_data['from_user'] = 'IM_USER_1';
                $send_data['to_user'] = $user['tencent_im_user_id'];
                $send_data['msg'] = $content;
                $im_message->send_msg($send_data);
            }

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error('后台同意会员球场申请出错：'.$exception->getMessage());
            return $this->response()->error(trans('api.NETWORK_ERROR', [], $lang));
        }

        return $this->response()->success('success')->refresh();
    }


    public function form()
    {
        $this->hidden('id')->value($this->payload['id']);
        $this->radio('status')->options([0 => trans('course-user.fields.check_pending'), 1 => trans('course-user.fields.pass'), 2 => trans('course-user.fields.refuse')])->default(0);
    }
}
