<?php

namespace App\Http\Controllers\Admin;

use App\Events\OperationLoggedEvent;
use App\Exports\ServiceOrderExport;
use App\Exports\ServiceUserExport;
use App\Facades\UploadService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\SendEasySms;
use App\Models\ChefUser;
use App\Models\Coach;
use App\Models\Collaborator;
use App\Models\CustomerServiceUser;
use App\Models\Guide;
use App\Models\MainCoach;
use App\Models\NoticeUser;
use App\Models\Order;
use App\Models\Partner;
use App\Models\ServiceRoleOrder;
use App\Models\ServiceRoleUser;
use App\Models\ServiceUser;
use App\Models\UpdateUserLog;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\Wechat;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class ServiceUsersController extends Controller
{
    use ResponseJson;

    private string $role;
    private MainCoach|Coach|CustomerServiceUser|ChefUser $serviceUser;

    public function index(Request $request)
    {
        try {
            $this->serviceUser = $request->serviceUser;
            $keyword = $request->get('keyword');
            $status = $request->get('status', null);
            $page_size = $request->get('page_size', 15);
            //是否关注公众号
            $type = $request->get('type', 0);
            $list = $this->serviceUser->with('partner:id,name,mobile,birthday,sex,pic,weight,user_id', 'service_user')
                ->when($keyword, function ($query) use ($keyword) {
                    $query->whereHas('partner', function ($query) use ($keyword) {
                        $query->where(function ($query) use ($keyword) {
                            $query->where("name", 'like', '%' . $keyword . '%')
                                ->orWhere('mobile', 'like', '%' . $keyword . '%');
                        });
                    });
                })
                ->when($status !== null, function ($query) use ($status) {
                    $query->where('status', $status);
                })
                ->orderByDesc('updated_at')
                ->orderByDesc('id')
                ->paginate(perPage: $page_size);

            //查看查询条件是否需要关注公众号
            foreach ($list as $key => $value) {
                $value->trade_no = '';
                $value->order_id = '';
                if (empty($value->service_user)) {
                    continue;
                }
                $order = Order::where('mobile', $value->partner->mobile)->orderByDesc('id')->first();
                if ($order) {
                    $value->trade_no = $order->trade_no;
                    $value->order_id = $order->id;
                }
                if (!$type) {
                    continue;
                }
                $is_subscribe = User::where('id', $value->service_user->user_id)->value('is_subscribe');
                if (!$is_subscribe) {
                    unset($list->$key);
                }
            }
            return $this->success('ok', $list);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 获取已关注公众号服务人员
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getServiceUser(Request $request)
    {
        try {
            $this->serviceUser = $request->serviceUser;
            $keyword = $request->get('keyword');
            $list = $this->serviceUser->with('partner:id,name,mobile,birthday,sex,pic,weight', 'service_user')
                ->when($keyword, function ($query) use ($keyword) {
                    $query->whereHas('partner', function ($query) use ($keyword) {
                        $query->where(function ($query) use ($keyword) {
                            $query->where("name", 'like', '%' . $keyword . '%')
                                ->orWhere('mobile', 'like', '%' . $keyword . '%');
                        });
                    });
                })
                ->where('status', 1)
                ->orderByDesc('id')->get()->toArray();

            //查看是否关注公众号
            foreach ($list as $key => $value) {
                $is_subscribe = User::where('id', $value['service_user']['user_id'])->value('is_subscribe');
                if (!$is_subscribe) {
                    unset($list[$key]);
                }
            }
            return $this->success('ok', $list);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function audit(Request $request)
    {
        try {
            $this->serviceUser = $request->serviceUser;
            //获取参数
            $id = intval($request->get('id'));
            $role = $request->get('role');
            $data = $request->only(['status', 'refusal_reason']);

            if (!$id)
                throw new Exception('请选择要处理的申请');

            DB::beginTransaction();
            //查找申请信息
            $user = $this->serviceUser->where('status', 0)->findOrFail($id);

            //更新审核状态
            $data['audit_at'] = now();
            $user->update($data);
            $roleExist = $serviceUser = [];
            //审核通过后加入服务用户表
            //服务用户信息
            $partner = $user->partner;
            if ($data['status'] == 1) {
                //检查小伙伴是否绑定用户
                if (!$partner->user_id) {
                    $partner->user_id = $partner->wechat->user_id;
                    $partner->save();
                }

                //构建服务用户数据
                $serviceUserInfo = [
                    'name' => $partner->name,
                    'mobile' => $partner->mobile,
                    'user_id' => $partner->user_id
                ];
                //添加服务用户
                $serviceUser = $user->service_user;
                if (!$serviceUser) {
                    $serviceUser = $user->service_user()->create($serviceUserInfo);
                }

                //添加对应角色
                $roleExist = $serviceUser->service_roles()->where('role_id', $role)->exists();
                if (!$roleExist) {
                    $roleData = ['user_id' => $partner->user_id];
                    $serviceUser->service_roles()->attach($role, $roleData);
                }

                //同步修改合作商信息
                $collaborator = Collaborator::where('user_id', $partner->user_id)->first();
                if ($collaborator) {
                    $collaborator->name = $partner->name;
                    $collaborator->mobile = $partner->mobile;
                    $collaborator->avatar = !empty($partner->pic) ? $partner->pic : $collaborator->avatar;
                    $collaborator->save();
                }
                //同步更新用户表数据
                $user = User::where('id', $partner->user_id)->first();
                if ($user) {
                    $user->name = $partner->name;
                    $user->mobile = $partner->mobile;
                    $user->avatar = !empty($partner->pic) ? $partner->pic : $user->avatar;
                    $user->save();
                }
            }
            DB::commit();
            //审核通过后加入服务用户表
//            if ($data['status'] == 1) {
//                //服务用户信息
//                $partner = $user->partner;
//                //审核通过以后如果小程序有用户数据，则同步用户数据
//                $user_data = User::where('mobile',$partner->mobile)->first();
//                if($user_data){
//                    User::sameDataToUser($partner->user_id,$user_data->id);
//                }
//            }
            //操作记录
            $roleStr = [1 => '主教练', 2 => '副教练', 3 => '客服', 4 => '企业介绍人', 6 => '餐饮人员'][$role];
            $statusStr = [1 => '通过', 2 => '拒绝'][$data['status']];
            OperationLoggedEvent::dispatch("$statusStr 了 $user->name 的 $roleStr 申请");

            $sex = "先生";
            if ($partner->sex == 2) {
                $sex = "女士";
            }
            if ($data['status'] == 1) {
                $str = "恭喜您通过[" . $roleStr . "]申请，期待您接下来成为一名优秀的[" . $roleStr . "]";
            } else {
                $str = "很抱歉的通知您，您本次申请的[" . $roleStr . "]暂未通过，期待您在学习提升后再一次申请";
            }
            //发送短信通知
            $messageData = [
                'message' => "尊敬的" . $partner->name . $sex . $str . "【友福同享】",
            ];
            SendEasySms::dispatch($partner->mobile, $messageData)->onQueue('health');
            //生成绑定企业微信二维码

            return $this->success('ok', compact('roleExist', 'serviceUser'));


        } catch (ModelNotFoundException) {
            return $this->jsonResponse(1, '未找到对应申请');
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function getBindQrcode($role)
    {
        return $this->success('ok', route('admin.service_user.qrcode', ['role' => $role]));
    }

    public function serviceUserQrCode($role)
    {
        try {
            $role_str_arr = [
                1 => 'chiefCoachInfo',
                3 => 'serviceInfo',
                9 => 'partnerInfo',
            ];

            $url = config('app.url') . '/api/h5/wechat/user/auth?target_path=';

            $url .= $role_str_arr[$role];

            $path = storage_path('qrcode/' . $role_str_arr[$role] . '_bind_qrcode.svg');
            QrCode::generate($url, $path);
            if (file_exists($path)) {
                $pic = UploadService::uploadFile($path);
                @unlink($path);
                return $this->success('ok', $pic);
            }
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }

    }

    /**
     * 导出服务人员
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function serviceUserExport(Request $request)
    {
        return Excel::download(new ServiceUserExport($request->all()), '服务人员.xlsx');
    }

    /**
     * 获取通知人列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getNoticeUserList(Request $request)
    {
        try {
            $keyword = $request->get('keyword');
            $page_size = $request->get('page_size', 15);
            $list = NoticeUser::when($keyword, function ($query) use ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->where('name', 'like', "%{$keyword}%")
                        ->orWhere('mobile', 'like', "%{$keyword}%");
                });
            })
                ->orderByDesc('id')
                ->paginate($page_size);
            return $this->success('ok', $list);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 添加通知人员
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function addNoticeUser(Request $request)
    {
        try {
            $id = $request->input('id');
            $role = $request->input('role');
            if (empty($id) || empty($role)) {
                return $this->failure('缺少参数');
            }
            $info = Partner::where('id', $id)->first();
            if (!$info) {
                return $this->failure('信息不存在');
            }
            $exists = NoticeUser::where('open_id', $info->openid)->exists();
            if ($exists) {
                return $this->failure('用户已存在,无需重复添加');
            }
            $map = [];
            $map['open_id'] = $info->openid;
            $open_id = Wechat::where('user_id', $info->user_id)->where('type', 'official')->value('openid');
            if (!$open_id) {
                return $this->failure('openid查询失败或未关注公众号');
            }
            $map['open_id'] = $open_id;
            $map['user_id'] = $info->user_id;
            $map['mobile'] = $info->mobile;
            $map['name'] = $info->name;
            $map['role'] = $role;
            $result = NoticeUser::create($map);
            return $this->success('ok', $result);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 删除通知人员
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function deleteNoticeUser(Request $request)
    {
        try {
            $id = $request->get('id');
            if (empty($id)) {
                return $this->failure('id不为空');
            }
            NoticeUser::where('id', $id)->delete();
            return $this->success('ok');
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 修改用户数据
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function updateNoticeUser(Request $request)
    {
        try {
            $id = $request->input('id');
            if (empty($id)) {
                return $this->failure('id不为空');
            }
            if ($request->has('send_message')) {
                $data['send_message'] = $request->input('send_message');
            }
            if ($request->has('send_wecom_message')) {
                $data['send_wecom_message'] = $request->input('send_wecom_message');
            }
            NoticeUser::where('id', $id)->update($data);
            return $this->success('ok');
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 获取服务人员订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getServiceOrder(Request $request, $id)
    {
        try {
            $this->serviceUser = $request->serviceUser;
            $keyword = $request->get('keyword');
            $role = $request->get('role');
            $is_export = $request->get('is_export');
            $user_role = $this->serviceUser->with('partner:id,name,mobile,birthday,sex,pic,weight,user_id')->where('id', $id)->first();

            $service_order_ids = ServiceRoleOrder::where('user_id', $user_role->partner->user_id ?? 0)->where('role_id', $role)->pluck('order_id');

            $query = Order::query();
            $query->whereIn('id', $service_order_ids)
                ->when($keyword, function ($query) use ($keyword) {
                    $query->where('name', 'like', '%' . $keyword . '%')->orWhere('mobile', 'like', '%' . $keyword . '%');
                });

            if ($is_export) {
                $list = $query->get();
            } else {
                $list = $query->paginate();
            }

            foreach ($list as $item) {
                $item->guide_time = Guide::where('user_id', $item->user_id)->where('order_id', $item->id)->where('status', Guide::STATUS_SCHEDULED)->value('created_at');
                if (!empty($item->guide_time)) {
                    $item->guide_time = $item->guide_time->toDateTimeString();
                }
            }

            if ($is_export) {
                return Excel::download(new ServiceOrderExport($list), '订单统计.xlsx');
            }
            return $this->success('ok', $list);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }
}
