<?php

namespace App\Http\Controllers\App;

use App\Facades\CommonService;
use App\Facades\UploadService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\SendEasySms;
use App\Models\Collaborator;
use App\Models\CustomerService;
use App\Models\CustomerServiceUser;
use App\Models\Feedback;
use App\Models\Message;
use App\Models\ReportLog;
use App\Models\User;
use App\Models\Version;
use App\Models\VideoCollect;
use App\Models\VideoVisitor;
use App\Models\WangYiYun;
use App\Services\ChatService;
use App\Services\ImService;
use Carbon\Carbon;
use cccdl\yunxin_sdk\Im\User as ImUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Overtrue\EasySms\EasySms;
use Exception;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UserController extends Controller
{
    use ResponseJson;

    /**
     * code 换取手机号
     * @param Request $request
     */
    public function codeMobile(Request $request)
    {
        $code = $request->input('code');
        if (empty($code))
            throw new \Exception("为获取到获取手机号的code");
        $res = WechatService::phoneNuber($code);
        return $this->success('ok', $res);
    }

    /**
     * 修改用户信息包括手机号
     * @param Request $request
     */
    public function updateUserInfo(Request $request)
    {
        $user = auth()->user();
        //手机号
        $mobile = $request->input('mobile');
        if ($mobile) {
            //是否其他账户已存在手机号,把旧的账号号码置空
//            $is_exists = User::where("id", '<>', auth()->id())->where('mobile', $mobile)->whereIn('source',User::SERVER_USER_SOURCE)->first();
//            if($is_exists){
//                return $this->failure('手机号已被占用');
//            }
            $user->mobile = $mobile;

            //查看手机号是否存在服务人员信息
//            $collaborator = Collaborator::where('mobile',$mobile)->where('status',1)->first();
//            if($collaborator){
//                User::sameDataToUser($collaborator->user_id,$user->id);
//            }
        }
        //头像
        $avatar = $request->input('avatar');
        if ($avatar)
            $user->avatar = $avatar;

        //名称
        $name = $request->input("name");
        if ($name)
            $user->name = $name;
        //性别
        $sex = $request->input("sex");
        if ($sex)
            $user->sex = $sex;
        //生日
        $birthday = $request->input("birthday");
        if ($birthday)
            $user->birthday = $birthday;
        //升高
        $stature = $request->input('stature');
        if ($stature)
            $user->stature = $stature;
        //单位
        $unit = $request->input('unit');
        if ($unit)
            $user->unit = $unit;

        //更新网易云信数据
        $imService = new ImService();
        $imService->updateImUser($user->id, $user);

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

    /**
     * 用户信息
     * @param Request $request
     */
    public function userInfo(Request $request)
    {
        $version = $request->get('version');
        $user = auth()->user();
        //        $user->makeVisible('mobile');
        $user->is_complete_profile = $user->baseUserInfo();

        $status = "NOORDER";
        $order = $user->payOrders()->whereIn('status', ['NOTSTART', 'STARTING', 'FINISHED'])->orderByDesc('id')->first();
        if ($order) {
            $status = $order->status;
        }
        $user->order_status = $status;
        $user->service_status = $order->service_status ?? 'NOINFO';
        //查找版本号状态
        $user->version_status = Version::where('version', $version)->where('type', Version::TYPE_APP)->value('status');
        //获取视频相关信息
        $user->my_collect = VideoCollect::where('user_id', $user->id)->count();
        $user->collect_my = VideoCollect::where('video_user_id', $user->id)->count();
        // 获取当前时间
        $now = Carbon::now();
        // 获取7天前的时间
        $lastWeek = $now->subDays(7);
        $user->visitor = VideoVisitor::where('video_user_id', $user->id)->whereDate('created_at', '>=', $lastWeek)->count();

        //更新网易云信数据
        $imService = new ImService();
        $imService->updateImUser($user->id, $user);
        $user->qr_code = config('app.url') . "/go_html/role_apply#/appDownloadPageV2?user_id=" . $user->id;
        $user->id = make_user_id($user->id);
        return $this->success('ok', $user);
    }

    public function getAppUserQrCode($user_id)
    {
        $url = config('app.url') . "/go_html/role_apply#/appWatchesUse?user_id=" . $user_id;
        $path = storage_path('qrcode/' . $user_id . '_qrcode.png');
        QrCode::size(300)->format("png")->generate($url, $path);
        //        QrCode::generate($url, $path);
        $pic = "";
        if (file_exists($path)) {
            $pic = UploadService::uploadFile($path);
            @unlink($path);
        }
        return $pic;
    }
    public function mobileCode(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = CommonService::random(6, 1);
        $data = [
            'code' => $code,
            'message' => '绑定手机号验证码：' . $code . '，十分钟有效【友福同享】',
        ];
        SendEasySms::dispatch($mobile, $data)->onQueue('send.code.sms');
        return $this->success('ok');
    }

    /**
     * 用户切换语言
     * @param Request $request
     */
    public function changeLanguage(Request $request)
    {
        try {
            $language = $request->get('language', 0);
            $user = Auth()->user();
            if (!$user) {
                return $this->failure('用户信息不存在');
            }
            $user->language = $language;
            $user->save();
            return $this->success('ok', $user);
        } 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 sendFeedback(Request $request)
    {
        try {
            $user = Auth()->user();
            $type = $request->input('type');
            if (empty($type)) {
                return $this->failure('请选择反馈类型');
            }
            $desc = $request->input('desc', '');
            $images = $request->input('images');
            if (is_array($images)) {
                $images = json_encode($images);
            }
            $mobile = $request->input('mobile');
            $url = $request->input("url");

            $map = [];
            $map['user_id'] = $user->id;
            $map['type'] = $type;
            $map['desc'] = $desc;
            $map['images'] = $images;
            $map['mobile'] = !empty($mobile) ? $mobile : $user->mobile;
            $map['url'] = json_encode($url);
            $source = $request->header("source");
            $map['source'] = $source;
            $is_server = $request->header("isServer");
            if ($source == "ios" && $is_server == 1) {
                $map['source'] = "ios_server";
            } elseif ($source == "android" && $is_server == 1) {
                $map['source'] = "android_server";
            }
            $map['version'] = $request->header("version");

            Feedback::create($map);

            // 通知
            $services = CustomerService::where("type_name", "测试客服")->get();
            foreach ($services as $service) {
                $chatService = new ChatService();
                $user_id = 12;
                if (config('app.env') == 'production') {
                    $user_id = 4169;
                }
                $user_ac_cid = make_wangyiyun_accid(id: $user_id);
                $to_user_ac_cid = make_wangyiyun_accid(id: $service->user_id);
                $params['ext'] = json_encode(['is_system' => 1]);
                $chatService->sendImMsg($user_ac_cid, $to_user_ac_cid, 0, "系统通知", "用户" . $user->name . "提交了反馈，请查阅", "'https://image.fulllinkai.com/202403/29/dea3e0c27107cdf178635d2a41199e5e.png", config('app.url') . "/go_html/dma_h5_biz/app/application/feedbackList", $params);

            }
            return $this->success('ok', $map);
        } catch (\Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function sendReport(Request $request)
    {
        try {
            $data = $request->only(['user_id', 'type', 'img', 'remark']);
            $validated = Validator::make($data, [
                'user_id' => 'required',
                'type' => 'required',
                'img' => 'required',
                'remark' => 'required',
            ], [
                'user_id.required' => '举报用户不为空',
                'type.required' => '请选择举报类型',
                'img.required' => '请至少上传一张图',
                'remark.required' => '请填写描述',
            ]);
            if ($validated->fails()) {
                $errors = $validated->errors()->all();
                $error = count($errors) ? $errors[0] : null;
                return $this->failure($error);
            }
            $user_id = auth()->user()->id;
            $data['user_id'] = get_userid_by_accid($data['user_id']);
            $data['by_user_id'] = $user_id;
            $data['img'] = json_encode($data['img']);
            ReportLog::create($data);

            return $this->success('ok');
        } catch (\Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }
}
