<?php

namespace App\Http\Controllers\H5;

use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\ChefUser;
use App\Models\Coach;
use App\Models\Collaborator;
use App\Models\CustomerServiceUser;
use App\Models\Group;
use App\Models\MainCoach;
use App\Models\Message;
use App\Models\Partner;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Models\ServiceUserBindRole;
use App\Models\User;
use App\Models\Wechat;
use App\Validators\ServiceUserValidator;
use Illuminate\Support\Facades\DB;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class ServiceUserController extends Controller
{
    use ResponseJson;

    private Coach $coach;
    private MainCoach $mainCoach;
    private CustomerServiceUser $customerServiceUser;
    private ServiceUserValidator $validator;
    private ChefUser $chefUser;
    private User $user;
    private mixed $openid = '';

    public function __construct(Coach $coach,MainCoach $mainCoach,CustomerServiceUser $customerServiceUser,ServiceUserValidator $validator,ChefUser $chefUser)
    {
        Log::info("ServiceUserController 初始化");
//        $wechat_user = session('wechat_user');
//        Log::info($wechat_user);
//        $openid = $wechat_user['id']??null;
//        Log::info("ServiceUserController 初始化1".$openid);
//        //构造函数不能直接返回错误提示,这里返回会报错,微调一下
//        if (config('app.env') == 'production') {
//            if (empty($openid)){
////                $openid = $request->input('open_id');
//                if (empty($openid)) return $this->jsonResponse(3,"微信授权失败");
////                if (empty($openid)) throw new \Exception("微信授权失败");;
////                $wechat_user['id'] = explode("?", $openid)[0];
//            }
//        }else {
//            $wechat_user['id'] = 'o1by95wyeY3tBVWbtQSF8yJGCzi8';
//        }
//        Log::info("ServiceUserController 初始化2".$openid);
//
//        $this->openid = $wechat_user['id'];
        $this->coach = $coach;
        $this->mainCoach = $mainCoach;
        $this->customerServiceUser = $customerServiceUser;
        $this->chefUser = $chefUser;

        $this->validator = $validator;
        Log::info("ServiceUserController 初始化3".$this->openid);
    }


    /**
     * @throws Exception
     */
    public function detail(Request $request)
    {
        try {
            $user = auth()->user();
            $openid = $user->officialWechat?$user->officialWechat->openid:null;
            //获取用户信息
            $user = $this->checkUserRoles($openid);
            $role = $request->get('role',null);
            if (!in_array($role,['main_coaches','coaches','customer_service_user','chef_user']))throw new Exception('参数错误');
            //获取合作商信息
            $collaborator = Collaborator::where('user_id',$user->id)->first();
            //获取对应角色信息
            $service_user_info = $user->$role;
            $partner = $user->partner??new Partner([
                'id'=>null,
                'name'=>null,
                'mobile'=>null,
                'sex'=>0,
                'birthday'=>date('Y-m-d'),
                'weight'=>0,
            ]);
            if (!$service_user_info){
                $is_str = 'is_'.$role;
                $user->service_user_info = [
                    'partner_id'=>$partner->id,
                    'openid'=>$openid,
                    'customer_num'=>0,
                    'agree_user'=>null,
                    'disagree_user'=>null,
                    'outlook'=>null,
                    'reason'=>null,
                    'think'=>null,
                    'idea'=>null,
                    'filing_at'=>date('Y-m-d'),
                    'status'=>$user->$is_str?1:3
                ];

            }else{
                $user->service_user_info = $user->$role;
                unset($user->$role);
            }

            //调整结构
            $user->sex = $partner->sex;
            $user->birthday = $partner->birthday;
            $user->name = $collaborator->name ?? $partner->name;
            $user->mobile = $collaborator->mobile?? $partner->mobile;
            $user->avatar = $collaborator->avatar?? $partner->pic;
            $user->weight = $partner->weight;
            $user->makeVisible('mobile');
            unset($user->partner);
            unset($user->service_roles);

            return $this->success('ok', $user);
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'未找到用户信息');
        }catch (\Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * 保存
     *
     * @throws Exception
     */
    public function store(Request $request)
    {
        try {
            $user = auth()->user();
            $openid = $user->officialWechat?$user->officialWechat->openid:null;
            $role = $request->get('role',null);
            if (!in_array($role,['main_coaches','coaches','customer_service_user','chef_user']))throw new Exception('参数错误');

            //数据验证
            $data = $request->all();
            // $this->validator->scene($role)->validate($data);
            //获取此用户合伙人信息
            $user = $this->checkUserRoles($openid);

            DB::beginTransaction();
            $partner = [
                'openid'=>$openid,
                'name'=>$data['name'],
                'mobile'=>$data['mobile'],
                'pic'=>$data['pic']??'',
                'sex'=>$data['sex']??0,
                'birthday'=>$data['birthday']??'',
                'weight'=>$data['weight']??0,
                'intro'=>null,
                'specialty'=>null,
                'attach'=>null,
                'status' => 1,
                'user_id'=>$user->id
            ];
            Partner::updateOrCreate(['openid'=>$openid],$partner);

            //获取用户角色
            $service_user = match ($role) {
                "main_coaches" => new MainCoach(),
                "coaches" => new Coach(),
                "customer_service_user" => new CustomerServiceUser(),
                "chef_user" => new ChefUser(),
            };

            $is_str = 'is_'.$role;
            $service_user->updateOrCreate(
                ['openid' => $openid],
                [
                    'partner_id'=>$user->partner->id,
                    'openid'=>$openid,
                    'customer_num'=>$data['customer_num']??0,
                    'agree_user'=>$request->get('agree_user'),
                    'disagree_user'=>$request->get('disagree_user'),
                    'outlook'=>$data['outlook']??'',
                    'reason'=>$data['reason'],
                    'think'=>$data['think']??'',
                    'idea'=>$data['idea']??'',
                    'status'=>$user->$is_str?1:0,
                    'filing_at'=>date('Y-m-d')
                ]
            );

            //同步修改合作商信息
            $collaborator = Collaborator::where('user_id',$user->id)->first();
            if($collaborator && $user->$is_str){
                $collaborator->name = $data['name'];
                $collaborator->mobile = $data['mobile'];
                $collaborator->avatar = !empty($data['pic']) ? $data['pic'] : $collaborator->avatar;
                $collaborator->save();
            }


            DB::commit();
            return $this->success('ok');

        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'未找到用户信息');
        }catch (Exception $e){
            DB::rollBack();
            return $this->jsonResponse(1,$e->getMessage());
        }


    }

    /**
     * 获取服务用户信息
     *
     * @param $service_user_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getServiceUserInfo($service_user_id)
    {
        try {
            $user = auth()->user();
            $openid = $user->officialWechat?$user->officialWechat->openid:null;
            $service_user = ServiceUser::with(['service_roles'])->findOrFail($service_user_id);

            $wechat = Wechat::where('openid',$openid)->first();
            $user = $wechat->user;

            $service_user->is_subscribe = $user->is_subscribe;

            return $this->success("ok",$service_user);

        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'服务用户不存在');
        }
    }

    /**
     * 绑定服务用户
     *
     * @param Request $request
     * @param $service_user_id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function bindServiceUser(Request $request, $service_user_id)
    {
        try {
            $user = auth()->user();
            $openid = $user->officialWechat?$user->officialWechat->openid:null;
            $service_user = ServiceUser::with('service_roles')->findOrFail($service_user_id);

            $wechat = Wechat::where('openid',$openid)->first();


            DB::beginTransaction();
            //查看此微信是否绑定其他服务人员
            $wechat_service_uesr = ServiceUser::where('user_id',$wechat->user_id)->exists();
            if ($wechat_service_uesr){
                throw new Exception('此微信已绑定其他服务人员');
            }

//            $data = $request->all();
//            $this->validator->scene('partner')->validate($data);
            //更新合伙人信息
            $partner = [
                'openid'=>$openid,
                'name'=>$service_user['name'],
                'mobile'=>$service_user['mobile'],
                'pic'=>null,
                'sex'=>0,
                'birthday'=>null,
                'intro'=>null,
                'specialty'=>null,
                'attach'=>null,
                'status' => 1,
                'user_id'=>$wechat->user_id
            ];
            Partner::updateOrCreate(['openid'=>$openid],$partner);

            //绑定服务人员
            $service_user->user_id = $wechat->user_id;
            $service_user->save();
            //同步服务人员角色信息
            $role_ids = [];
            foreach ($service_user->service_roles as $role){
                $role_ids[] = $role->id;
            }

            $service_user->service_roles()->syncWithPivotValues($role_ids,['user_id'=>$wechat->user_id]);

            DB::commit();
            return $this->success("ok");
        }catch (ModelNotFoundException){
            return $this->jsonResponse(1,'服务用户不存在');
        }catch (Exception $e){
            DB::rollBack();
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    /**
     * @param $openid
     * @return User
     */
    private function checkUserRoles($openid)
    {
        //获取用户角色
        $user = User::with('service_roles')
            ->whereHas('officialWechat', function ($query) use ($openid) {
                $query->where('openid', $openid);
            })
            ->firstOrFail();

        $user->is_main_coaches = 0;
        $user->is_coaches = 0;
        $user->is_customer_service_user = 0;
        $user->is_partner = 0;
        $user->is_chef_user = 0;

        $user->service_roles()->each(function ($service_role) use ($user) {
            switch ($service_role->pivot->role_id){
                case 1://主教练
                    $user->is_main_coaches = 1;
                    break;
                case 2://副教练
                    $user->is_coaches = 1;
                    break;
                case 3://客服
                    $user->is_customer_service_user = 1;
                    break;
                case 4://小伙伴
                    $user->is_partner = 1;
                    break;
                case 6://餐饮人员
                    $user->is_chef_user = 1;
                    break;
            }
        });
        return $user;
    }

    /**
     * 企业微信绑定服务人员
     */
    public function bindWorkServiceUser(Request $request)
    {
        DB::beginTransaction();
        try {
            $mobile = $request->input('mobile');
            if (empty($mobile)) throw new Exception("缺少参数mobile");
            $service_user = ServiceUser::where('mobile', $mobile)->first();
            $status = 0; //未注册服务人员
            if (empty($service_user)) return $this->success("ok", compact('status'));
            $work_id = $request->get('work_id');
            if(!empty($work_id)){
                $work_user_id = $work_id;
            }else{
                //用户企业微信信息
                $work_wechat_user = session('work_wechat_user');
                $work_user_id = $work_wechat_user['raw']['userid'];
            }
            //查看服务人员是否已存在
            $is_exists = ServiceUser::where('work_user_id',$work_user_id)->whereNotNull('mobile')
                ->whereNotNull('name')->first();
            if($is_exists){
                return $this->success("ok", compact('status'));
            }
            //将旧的，不存在手机号和姓名的账号更新，并更新wechat表
            $is_exists->update(['work_user_id'=>null]);
            Wechat::where('openid',$work_user_id)->where('type','work')->update(['user_id'=>$service_user->user_id]);
            $service_user->update(['work_user_id'=>$work_user_id]);
            $status = 1; //绑定成功
            DB::commit();
            return  $this->success('ok', compact('status'));
        }catch (\Exception $e){
            DB::rollBack();
            return $this->success("ok", compact('status'));
        }
    }

    public function workGroupRoles(Request $request)
    {
        $chat_id = $request->input('chat_id');
        if(!$chat_id){
            return $this->failure('参数chat_id不存在');
        }
        $service_user_id = $request->input('service_user_id');
        if($service_user_id){
            $group = Group::with('order')->where('im_chat_id', $chat_id)->first();
            $service_user = ServiceUser::where("user_id", $service_user_id)->first();;
        }else{
            $group = Group::with('order')->where('chat_id', $chat_id)->first();
            //服务角色信息
//            $work_wechat_user = session('work_wechat_user');
//            $work_user_id = $work_wechat_user['raw']['userid'];
//            $service_user = ServiceUser::where("work_user_id", $work_user_id)->first();
            $service_user = $request->service_user;
        }
        $roles = [];
        if(!empty($group)){
            $order = $group->order;
            if (!empty($service_user)) {
                $service_roles = $service_user->serviceRoleOrders()->with('role')->where('order_id', $order->id)->get();
                foreach ($service_roles as $role) {
                    $roles[] = $role->role->name;
                }
            }
        }else{
            if (!empty($service_user)) {
                $service_roles_ids = ServiceUserBindRole::where('chat_id',$chat_id)
                    ->where('user_id',$service_user->user_id)
                    ->select('role_id')
                    ->get()
                    ->toArray();
                $roleName = ServiceRole::whereIn('id',$service_roles_ids)->select('name')->get();
                foreach ($roleName as $name){
                    $roles[] = $name['name'];
                }
            }
        }

        return $this->success('ok', compact('roles', 'service_user'));
    }

    /**
     * 绑定临时服务人员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function bindUserService(Request $request){
        DB::beginTransaction();
        try {
            $data = $request->only(['name','avatar','mobile','code','intro', 'specialty', 'sex','customer_num','reason','weight','agree_user','disagree_user','outlook','think','idea']);

            if(empty($data['mobile'])){
                return $this->failure('手机号不为空');
            }
            //验证手机号和验证码
            $res = Message::checkCode($data['mobile'], $data['code']);
            if (empty($res)) return $this->failure("验证码无效");

            $order_id = $request->input('order_id');

            $role_id = $request->input('role');

            $role = Partner::ROLE[$role_id]??null;
            if(empty($role)){
                return $this->failure('参数错误');
            }
            if (!in_array($role,['main_coaches','coaches','customer_service_user','chef_user'])) return $this->failure('参数错误');

            $user = auth()->user();

            $group = Group::where('order_id',$order_id)->first();

            //先加入友福,自动通过
            $openid = $user->officialWechat?$user->officialWechat->openid:null;

            $user = $this->checkUserRoles($openid);

            $is_collaborator = Collaborator::where('user_id',$user->id)->exists();
            if(!$is_collaborator){
                $collaborator = [
                    'user_id' => $user->id,
                    'openid' => $openid,
                    'avatar' => $data['avatar'],
                    'name' => $data['name'],
                    'mobile' => $data['mobile'],
                    'type' => Collaborator::TYPE_PART_TIME,
                    'intro' => $data['intro']??'',
                    'specialty' => $data['specialty']??null,
                    'status' => Collaborator::STATUS_PASS,
                ];
                Collaborator::create($collaborator);
            }

            //再申请服务人员身份,自动通过
            $is_partner = Partner::where('user_id',$user->id)->exists();
            if(!$is_partner){
                $partner = [
                    'openid'=>$openid,
                    'name'=>$data['name'],
                    'mobile'=>$data['mobile'],
                    'pic'=>$data['avatar']??'',
                    'sex'=>$data['sex']??0,
                    'birthday'=>$data['birthday']??'',
                    'weight'=>$data['weight']??0,
                    'intro'=>$data['intro']??'',
                    'specialty'=>$data['specialty']??null,
                    'status' => 1,
                    'user_id'=>$user->id
                ];
                Partner::create($partner);
            }

            //获取用户角色
            $service_user = match ($role) {
                "main_coaches" => new MainCoach(),
                "coaches" => new Coach(),
                "customer_service_user" => new CustomerServiceUser(),
                "chef_user" => new ChefUser(),
            };

            $is_service_user = $service_user->where('openid',$openid)->exists();
            if(!$is_service_user){
                $service_user->create(
                    [
                        'partner_id'=>$user->partner->id,
                        'openid'=>$openid,
                        'customer_num'=>$data['customer_num']??0,
                        'agree_user'=>$data['agree_user']??'',
                        'disagree_user'=>$data['disagree_user']??'',
                        'outlook'=>$data['outlook']??'',
                        'reason'=>$data['reason']??'',
                        'think'=>$data['think']??'',
                        'idea'=>$data['idea']??'',
                        'status'=>1,
                        'filing_at'=>date('Y-m-d')
                    ]
                );
            }

            $is_role = $service_user->where('openid',$openid)->first();
            if($is_role){
                $exists = ServiceRoleOrder::where('user_id',$user->id)
                    ->where('role_id',$role_id)
                    ->where('order_id',$order_id)
                    ->exists();
                if(!$exists){
                    ServiceRoleOrder::create(['order_id'=>$order_id,'user_id'=>$user->id,'role_id'=>$role_id]);
                }
            }
            //查看服务人员表是否存在
            $service_user_work = ServiceUser::where('user_id',$user->id)->first();
            if(empty($service_user_work)){
                $newServiceUserWork = ServiceUser::create(['user_id'=>$user->id,'name'=>$data['name'],'mobile'=>$data['mobile']]);
                $service_user_work_id = $newServiceUserWork->id;
            }else{
                $service_user_work_id = $service_user_work->id;
            }
            //查看是否有角色
            $service_role = ServiceRoleUser::where('user_id',$user->id)->where('role_id',$role_id)->first();
            if(empty($service_role)){
                ServiceRoleUser::create(['user_id'=>$user->id,'role_id'=>$role_id,'s_user_id'=>$service_user_work_id]);
            }
            //同步用户信息
//            $user_data = User::getMpUser($data['mobile']);
//            if($user_data && $user_data->id != $user->id){
//                User::sameDataToUser($user->id,$user_data->id);
//            }
            DB::commit();
            return $this->success('ok',$group->chat_qr_code??null);
        }catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            AddErrorLog::dispatch('bindUserService file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("申请失败");
        }
    }

    public function getGroup(Request $request){
        $user = auth()->user();
        $order_id = $request->get('order_id');
        $role = $request->get('role');

        $openid = $user->officialWechat?$user->officialWechat->openid:null;
        $user = $this->checkUserRoles($openid);
        $group = Group::where('order_id',$order_id)->first();

        $role_mode = Partner::ROLE[$role]??null;
        if(empty($role_mode)){
            return $this->failure('参数错误');
        }
        //获取用户角色
        $service_user = match ($role_mode) {
            "main_coaches" => new MainCoach(),
            "coaches" => new Coach(),
            "customer_service_user" => new CustomerServiceUser(),
            "chef_user" => new ChefUser(),
        };
        $is_role = $service_user->where('openid',$openid)->first();
        if($is_role){
            $exists = ServiceRoleOrder::where('user_id',$user->id)
                ->where('role_id',$role)
                ->where('order_id',$order_id)
                ->exists();
            if(!$exists){
                ServiceRoleOrder::create(['order_id'=>$order_id,'user_id'=>$user->id,'role_id'=>$role]);
            }
        }
        return $this->success('ok',$group);
    }
}
