<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Facades\UploadService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class ServiceRoleController extends Controller
{
    use ResponseJson;
    public function roles()
    {
        $roles = ServiceRole::all();
        return $this->success('ok', $roles);
    }
    public function serviceUsers(Request $request, $role_id = null)
    {
        //        $users = ServiceUser::with('roles', 'user:id,name,avatar');
//        $keyword = $request->input('keyword');
//        if ($keyword) {
//            $keyword = trim($keyword);
//            $users = $users->where( function ($sql) use($keyword) {
//                $sql->where("name", 'like', '%'.$keyword.'%')
//                    ->orWhere('mobile', 'like', '%'.$keyword.'%');
//            });
//        }
//        if ($role_id) {
//            $users = $users->whereHas('roles', function ($sql) use($role_id) {
//                $sql->where('service_roles.id', $role_id);
//            });
//        }
//        $users = $users->orderByDesc('id')->paginate();
//        foreach ($users as $user)
//        {
//            $user->protocol = json_decode($user->protocol)?:[];
//        }
//        return $this->success('ok', $users);

        $users = ServiceUser::with('roles', 'user:id,name,avatar')
            ->when($request->filled('keyword'), function ($query) use ($request) {
                $keyword = trim($request->input('keyword'));
                $query->where(function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")
                        ->orWhere('mobile', 'like', "%{$keyword}%");
                });
            })
            ->when($role_id, function ($query) use ($role_id) {
                $query->whereHas('roles', function ($query) use ($role_id) {
                    $query->where('service_roles.id', $role_id);
                });
            })
            ->orderByDesc('id')
            ->paginate();

        $users->each(function ($user) {

            $user->protocol = json_decode($user->protocol) ?: [];
        });
        return $this->success('ok', $users);
    }

    public function getRoleUsers(Request $request, $role_id)
    {
        $per_page = $request->input('per_page', 15);
        $keyword = $request->get('keyword');
        $users = ServiceRole::find($role_id);
        $service_user = $users->service_user()
            ->when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")
                        ->orWhere('mobile', 'like', "%{$keyword}%");
                });
            })
            ->whereHas('user')
            ->orderByDesc('id')
            ->paginate($per_page);
        return $this->success('ok', $service_user);
    }

    public function storeServiceUser(Request $request)
    {
        DB::beginTransaction();
        $data['name'] = $request->input('name');
        $data['mobile'] = $request->input('mobile');
        if ($data['mobile']) {
            $is_exists = ServiceUser::where('mobile', $data['mobile'])->exists();
            if ($is_exists)
                return $this->failure("手机号已存在");
        }
        $data['card_num'] = $request->input('card_num');
        $data['protocol'] = json_encode($request->input(['protocol']) ?: []);
        $service_user = ServiceUser::create($data);
        $role_ids = $request->input('role_ids');
        if (is_array($role_ids) && count($role_ids)) {
            ServiceRoleUser::where('s_user_id', $service_user->id)->delete();
            $data = [];
            foreach ($role_ids as $role_id) {
                $data[] = ['role_id' => $role_id, 'user_id' => $service_user->user_id, 's_user_id' => $service_user->id, 'created_at' => date('Y-m-d H:i:s')];
            }
            ServiceRoleUser::insert($data);
        }
        $service_user->bind_qrcode = '';
        //生成绑定二维码 todo
//        if (config('app.env') == 'production') {
//            $scene = 'service_user_id='.$service_user->id;
//            $page = 'pages/service/bindServe';
//            $qrcode = WechatService::getMPQrcode($scene, $page);
//            $service_user->bind_qrcode = $qrcode;
//            $service_user->save();
//        }
        $domain = config('app.url');
        $path = storage_path('qrcode/service_user_' . $service_user->id . '_bind_qrcode.svg');
        //        QrCode::generate($domain.'/h5/#/bindingService?service_user_id='.$service_user->id, $path);
        QrCode::generate($domain . '/api/h5/wechat/user/auth?target_path=bindingService?service_user_id=' . $service_user->id, $path);
        if (file_exists($path)) {
            $pic = UploadService::uploadFile($path);
            @unlink($path);
            $service_user->bind_qrcode = $pic;
            $service_user->save();
        }

        DB::commit();


        //操作记录
        OperationLoggedEvent::dispatch("创建了服务人员:$service_user->id ");
        return $this->success('ok', $service_user);
    }

    public function updateServiceUser(Request $request, $id)
    {
        //        DB::beginTransaction();
//        $service_user = ServiceUser::find($id);
//        $data['name'] = $request->input('name');
//        $data['mobile'] = $request->input('mobile');
//        $data['card_num'] = $request->input('card_num');
//        $data['protocol'] = json_encode($request->input(['protocol'])?:[]);
//        ServiceUser::where('id', $id)->update($data);
//        $role_ids = $request->input('role_ids');
//        if (is_array($role_ids) && count($role_ids)) {
//            ServiceRoleUser::where('s_user_id', $service_user->id)->delete();
//            $data = [];
//            foreach ($role_ids as $role_id) {
//                $data[] = ['role_id'=>$role_id, 'user_id'=>$service_user->user_id, 's_user_id'=>$service_user->id, 'created_at'=>date('Y-m-d H:i:s')];
//            }
//            ServiceRoleUser::insert($data);
//        }
//        DB::commit();
//        return $this->success('ok');
        DB::beginTransaction();
        try {
            //获取服务人员
            $service_user = ServiceUser::find($id);
            //更新服务人员信息
            $service_user->update([
                'name' => $request->input('name'),
                'mobile' => $request->input('mobile'),
                'card_num' => $request->input('card_num'),
                'protocol' => json_encode($request->input('protocol', [])),
            ]);
            //同步服务人员角色
            $role_ids = $request->input('role_ids');
            $service_user->service_roles()->syncWithPivotValues($role_ids, ['user_id' => $service_user->user_id]);
            //如果服务人员有副教练资料
            if ($service_user->coaches) {
                //角色取消副教练
                if (!in_array(2, $role_ids)) {
                    //变更资料为待审核
                    $service_user->coaches->update(['status' => 0]);
                } elseif ($service_user->coaches->status == 0) {
                    //角色增加副教练 且 有申请中的资料 把资料审核通过
                    $service_user->coaches->update(['status' => 1]);
                }
            }
            DB::commit();

            //操作记录
            OperationLoggedEvent::dispatch("更新了服务人员:$service_user->id ");
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollback();
            return $this->jsonResponse(2, $e->getMessage());
        }
    }

    public function deleteServiceUser(Request $request, ServiceUser $service_user)
    {
        DB::transaction(function () use ($service_user) {
            //删除服务人员关联的订单订单
            if ($service_user->user_id) {
                ServiceRoleOrder::where('user_id', $service_user->user_id)->delete();
            }
            //删除服务人员关联的角色
            ServiceRoleUser::where('s_user_id', $service_user->id)->delete();
            //删除服务人员
            $service_user->delete();
            //操作记录
            OperationLoggedEvent::dispatch("删除了服务人员:$service_user->id ");
        });
        return $this->success('ok');
    }

    public function deleteRoleUser(Request $request, $id)
    {
        ServiceRoleUser::where('id', $id)->delete();
        return $this->success('ok');
    }

    public function setServiceUserRoles(Request $request, ServiceUser $service_user)
    {
        if (!$service_user->user_id)
            return $this->failure("服务人员未绑定微信");
        $role_ids = $request->input('role_ids');
        if (is_array($role_ids) && count($role_ids)) {
            ServiceRoleUser::where('user_id', $service_user->user_id)->delete();
            $data = [];
            foreach ($role_ids as $role_id) {
                $data[] = ['role_id' => $role_id, 'user_id' => $service_user->user_id, 'created_at' => date('Y-m-d H:i:s')];
            }
            ServiceRoleUser::insert($data);
        }
        //操作记录
        OperationLoggedEvent::dispatch("给服务人员:$service_user->id 添加角色");
        return $this->success('ok');
    }

    public function updateRole(Request $request, $role_id)
    {
        $data['type'] = $request->input('type');
        $data['value'] = $request->input('value');
        if ($data['type'] == "RATIO" && $data['value'] > 1)
            return $this->failure("收益比例不能超过100%");
        ServiceRole::where('id', $role_id)->update($data);
        return $this->success('ok');
    }
}
