<?php

namespace App\Http\Controllers;

use App\Facades\CommonService;
use App\Facades\WechatService;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Jobs\SendEasySms;
use App\Models\Collaborator;
use App\Models\Message;
use App\Models\Order;
use App\Models\Partner;
use App\Models\User;
use App\Models\UserStepApply;
use App\Services\ImService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Overtrue\EasySms\EasySms;
use Exception;

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)->first();
//            if($is_exists){
//                $is_exists->mobile = null;
//                $is_exists->save();
//            }
            //绑定订单
            Order::getHaveOrder($user->id,$mobile);

            $is_exists = User::where("mobile",$mobile)->where('source', User::SOURCE_APP)->first();
            if($is_exists){
                User::updateAppUser($mobile,$user->id);
            }else{
                $user->mobile = $mobile;
                $user->save();
            }

            //查看手机号是否存在服务人员信息
//            $collaborator = User::getOfficialUser($mobile);
//            if($collaborator && $collaborator->user_id != $user->id){
//                User::sameDataToUser($collaborator->user_id,$user->id);
//            }
            DB::commit();
            return $this->success('ok');
        }
        //头像
        $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;
        $user->save();

        //更新网易云信数据
        $imService = new ImService();
        $imService->updateImUser($user->id,$user);
        DB::commit();
        return $this->success('ok');
    }

    /**
     * 用户信息
     * @param Request $request
     */
    public function userInfo(Request $request)
    {
        $user = auth()->user();
        $user->makeVisible('mobile');
        $user->is_complete_profile = $user->baseUserInfo();
        return $this->success('ok', $user);
    }

    public function mobileCode(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = CommonService::random(6, 1);
        $data = [
            'code' => $code,
            'message' => '绑定手机号验证码：' . $code . '，十分钟有效【友福同享】',
        ];
        $area_code = $request->input('area_code', 86);
        SendEasySms::dispatch($mobile, $data, $area_code)->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(trans('app.user_not_exists'));
            }
            $user->language = $language;
            $user->save();
            return $this->success('ok',$user);
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    /**
     * 获取用户token
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getUserToken(Request $request){
        $id = $request->input('id');
        $secret = $request->input('secret');
        if($secret != 'krT$zQl$5LR6sZbExnhUoY%y'){
            return $this->failure('请求失败');
        }
        $user = User::where('id',$id)->first();
        $carbon_expire_at = Carbon::now()->addDays(30);
        $expire_at = $carbon_expire_at->toDateTimeString();
        $api_token = $user->createToken($user->id, ['*'], $carbon_expire_at)->plainTextToken;
        User::where('id',$user->id)->update(['api_token'=>$api_token, 'expire_at'=>$expire_at]);
        $user->api_token = $api_token;
        return $this->success('ok',$api_token);
    }

    /**
     * 设置体脂秤
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function setFatDevice(Request $request){
        try {
            $fat_device = $request->get('fat_device',0);
            $user = Auth()->user();
            if(!$user){
                return $this->failure(trans('app.user_not_exists'));
            }
            $user->fat_device = $fat_device;
            $user->save();
            return $this->success('ok',$user);
        } catch (Exception $e) {
            Log::error('setFatDevice:'.$e->getMessage());
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function getUserStep(Request $request)
    {
        $code = $request->input('code');
        $iv = $request->input('iv');
        $encryptedData = $request->input('encryptedData');
        if (empty($code)) throw new \Exception("未获取到code");
        $stepInfoList = WechatService::getUserStep($code,$iv,$encryptedData);
        return $this->success('ok', $stepInfoList);
    }

    public function getMyInfo(){
        try {
            $user = auth()->user();
            $step_apply = UserStepApply::where('user_id',$user->id)->orderByDesc('id')->first();
            $user->step_apply_status = $step_apply->status??null;
            $user->step_reject_reason = $step_apply->reason??null;
            return $this->success('ok',$user);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getMyInfo file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }
}
