<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\BaseDictionaryOptionModel;

use App\Models\BaseSettingsModel;
use App\Models\DreamInfoModel;
use App\Models\MeetInfoModel;
use App\Models\SupportDreamModel;
use App\Models\SystemInfoModel;
use App\Models\UserCareUser;
use App\Models\UserInfoModel;
use Illuminate\Http\Request;
use App\Services\Base\ErrorCode;
class HomeController extends Controller
{
    /**
     * @api {get} /api/user/show/ 用户信息
     * @apiDescription 用户信息
     * @apiGroup Home
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {int} user_id 用户ID
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     *{
     *   "status": true,
     *   "status_code": 0,
     *   "message": "",
     *  "data": {
     *      "user": {},             用户信息
     *      "near_dream": {},       当前梦想
     *      "sup_dreams": [],       支持的梦想
     *      "imgs": [],         封面图片
     *      "dreams": []            曾经的梦想
     *      "score": 2000           支持分数
     *  }
     *}
     * @apiErrorExample {json} Error-Response:
     *HTTP/1.1 400 Bad Request
     *{
     *  "status": false,
     *  " status_code": 1105,
     *  "message": "用户不存在",
     *  "data": null
     *  }
     */
    public function show(Request $request)
    {
        $user_id = $request->user_id;
//        获得的支持分数
        $info = SupportDreamModel::where('to_user_id',$user_id)->get();
        $score = 0;
        foreach ($info as $item) {
            $score += $item->score;
        }
        $care = UserCareUser::where('user_id',$user_id)->get();
        $fens = UserCareUser::where('other_user_id',$user_id)->get();
        $user = UserInfoModel::find($user_id);
        if (count($user) == 0) return $this->error(ErrorCode::USER_DOES_NOT_EXIST);
        $emotion = BaseDictionaryOptionModel::where(['dictionary_code' => 'emotion'])->
            where('dictionary_table_code','user_info')->
        where(['value' => $user->emotion])->first();
        $emotion = count($emotion) > 0 ? $emotion->name : '';
//        当前梦想

        $near_dream =DreamInfoModel::where('user_id',$user->id)->orderBy('id','desc')->first();
//         封面图片
        $imgs =$user->allImgs;
//        曾经的梦想
        $dreams = $user->dreams;
        if (!empty($dreams)) {
            foreach ($dreams as $dream){
                $dream->dream_imgs = $dream->imgs;
            }
        }

        $user->score = 1000;//自定义 算法
        $user->care = count($care);
        $user->fens = count($fens);
        $user->dreams =$dreams;
        $user->emotion = $emotion;
//         支持的梦想
        $sup_dreams = $user->supDream;

        foreach ($sup_dreams as $sup_dream){
            $sup_dream->pics = $sup_dream->imgs;
        }
        $login_user = $this->getUser();
        $is_care = UserCareUser::where('other_user_id',$user_id)->where('user_id',$login_user->id)->first();
        $is_care = empty($is_care) ? 0 : 1 ;
        return $this->api(compact('user','near_dream','sup_dreams','imgs','dreams','score','is_care'));
    }

    //    关注用户
    /**
     * @api {get} /api/user/care 关注用户
     * @apiDescription 关注用户
     * @apiGroup Dream
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {int} id 用户ID
     * @apiParam {int} is_care 0取消关注 1关注
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     *{
     *      "status": true,
     *      "status_code": 0,
     *      "message": "",
     *     "data": {
     *           1       1已关注 0 未关注
     *      }
     *}
     * @apiErrorExample {json} Error-Response:
     *HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     *
     */
    public function care(Request $request)
    {

        $validator = \Validator::make($request->all(),
            [
                'id'  => 'required',
                'is_care'  => 'required',
            ],
            [
                'id.required'  => '关注id不能为空',
                'is_care.required'  => '关注值不存在',
            ]
        );
        if($validator->fails()) return $this->validatorError($validator->messages()->all(),ErrorCode::CLIENT_WRONG_PARAMS);

        $user = $this->getUser();
        if(!$obj = UserInfoModel::find($request->id)){
            $this->error(ErrorCode::USER_DOES_NOT_EXIST);
        }

        $data = [
            'user_id' =>$user->id,
            'other_user_id' =>$request->id,
        ];
        $is_care = empty($request->is_care) ? 0 : $request->is_care;
        $user_care_user = UserCareUser::where('user_id',$user->id)->
        where('other_user_id',$request->id)->first();
        if ($is_care) {
            if (empty($user_care_user)) {
                UserCareUser::create($data);
//                关注成功发送私信
                $message = BaseSettingsModel::where('category','message')->first();
                $message = empty($message) ? '' : $message->value;
                $info = [
                    'user_id'=>$request->id,
                    'to_user_id' => $user->id,
                    'message' =>$message
                ];
                SystemInfoModel::create($info);
            }

        }else{
            UserCareUser::where('user_id',$user->id)->
            where('other_user_id',$request->id)->delete();
//            return $this->api(0);
        }
        return $this->api($is_care);

    }


//    见面
    /**
     * @api {get} /api/user/meet/ 见面
     * @apiDescription 见面
     * @apiGroup Home
     * @apiPermission Passport
     * @apiVersion 0.1.0
     * @apiParam {int} dream_id 梦想id
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
        "status": true,
        "status_code": 0,
        "message": "",
        "data": ""
    }
     * @apiErrorExample {json} Error-Response:
     *HTTP/1.1 400 Bad Request
    {
        "status": false,
        "status_code": 1412,
        "message": "梦想暂未实现",   /梦想不存在/不是最大支持者
        "data": null
    }
     */
    public function meet(Request $request)
    {
        $user = $this->getUser();
        $dream_id = $request->dream_id;
        $dream = DreamInfoModel::find($dream_id);
        if (empty($dream)) return $this->error(ErrorCode::DREAM_NOT_EXIST);
        $dream_user_id = $dream->user_id;
        if ($dream->get_coin < $dream->coin)  return $this->error(ErrorCode::DREAM_STATUS);
//        找到最大支持者
        $arr = [] ;//支持者 和支持分数
        $sups = SupportDreamModel::where('dream_id',$dream_id)->get()->groupBy('user_id')->toArray();
        foreach ($sups as $k => $sup) {
            $score = 0;
            foreach ($sup as $v){
                $score += $v['score'];
            }
            $arr[$k] = $score;
        }
        $sup_id= iconv('UTF-8', 'GBK', array_search(max($arr),$arr));

        if ($user->id != $sup_id) return $this->error(ErrorCode::SUP_ERROR);
//        见面成功写入数据记录
        $data = [
            'user_id'=>$user->id,
            'dream_id'=>$dream_id,
            'dream_user_id'=>$dream_user_id,
        ];
        MeetInfoModel::create($data);
        return $this->api('');
    }
}
