<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\BaseSettingsModel;
use App\Models\CommentInfoModel;
use App\Models\DreamInfoModel;
use App\Models\SearchInfoModel;
use App\Models\UserCareDream;
use App\Models\UserCareUser;
use App\Models\UserInfoModel;
use Illuminate\Http\Request;
class IndexController extends Controller
{

    /**
     * @api {get} /api/index/home 首页
     * @apiDescription 首页
     * @apiGroup Index
     * @apiParam {string}  [type=hot]   (热门)hot/(潮流)trend/(最新)news
     * @apiParam {int}      [page=1]            页码（分页参数）
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     *{
     *   "status": true,
     *   "status_code": 0,
     *   "message": "",
     *   "data": {
     *   "banners": [
     *       {
     *           "id": 32,
     *           "key": "2",
     *           "value": "http://w17.9026.com/img/banner/banner_2.png",
     *           "sort": 2,
     *           "category": "banner",
     *           "pid": 0,
     *           "status": 1,
     *           "created_at": null,
     *            "updated_at": "2017-06-26 09:21:36",
     *           "deleted_at": null
     *       }
     *   ],
     *   "users": [                  动态用户
     *      {
     *          "id": 3,
     *          "user_id": 1,
     *          "other_user_id": 2,
     *          "dream_number": 1,    >0 表示有最新动态
     *          "created_at": null,
     *          "updated_at": null,
     *          "other_user": {
     *              "id": 2,
     *              "phone": "13880642881",
     *              "nickname": "name2",
     *              "avatar": "http://www.miao.com/upload/user/20170630/08e235d7211944e9b6482965b4d7c42e.jpg",
     *          }
     *      },
     *  ],
     *   "dreams": {
     *       "current_page": 1,
     *       "data": [
     *           {
     *               "id": 5,
     *               "user_id": 1,
     *               "name": "梦想标题1",
     *               "about": "梦想介绍",
     *               "coin": 2500,
     *               "end_time": "2017-05-11 17:00:00",
     *               "get_coin": 0,
     *               "mark": 0,
     *               "status": 2,
     *               "video": "url",
     *               "score": 100079365,
     *               "sign": "梦想达人",
     *               "code": "",
     *               "parameter": 100,
     *               "created_at": "2017-06-25 12:45:22",
     *               "updated_at": "2017-07-03 12:23:37",
     *              "care_num": 1,
     *               "img": {
     *                   "title": "",
     *                   "pic": "http://www.miao.com/upload/dream/20170629/a18cadd1560f21453a08fdd81fb8fb2d.jpg"
     *               },
     *               "user": {
     *                   "id": 1,
     *                   "avatar": "/upload/user/20170629/e77068cc14c82086fb6b16e5bb7c3dd1.jpg",
     *               }
     *           },
     *       }
     *  ],
     *   "from": 1,
     *   "last_page": 1,
     *   "next_page_url": null,
     *   "path": "http://www.miao.com/api/index/home",
     *   "per_page": 20,
     *   "prev_page_url": null,
     *   "to": 11,
     *   "total": 11
     *   }
     *   }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */
    public function home(Request $request)
    {
        $login_user = $this->getUser();
        $id = $login_user->id;
        $arr1 =DreamInfoModel::orderBy('score','desc')->limit(30)->select('id')->get()->toArray();
        $id_arr1 = array_column($arr1,'id');
        $arr2 =DreamInfoModel::orderBy('score','desc')->offset(15)->limit(120)->select('id')->get()->toArray();
        $id_arr2 = array_column($arr2,'id');
        $users =UserCareUser::where('user_id',$id)->with('other_user')->orderBy('dream_number','desc')->get()->toArray();
      /*  $hdusers = CommentInfoModel::where(function ($query) use ($id) {
//            $query->where('user_id',$id)->orWhere('to_user_id',$id);
            $query->where('user_id',$id);
        })->where('is_read',0)->with('to_user')->orderBy('created_at')->get()->toArray();*/
        /*$users = [] ;
        foreach ($dtusers as $k => $v){
            $users[] = $v['other_user'];
        }*/
      /*  foreach ($hdusers as $k => $v){
            $users[] = $v['to_user'];
        }*/
        $type = $request->type;
        if ($type == 'trend') {
            $dreams = DreamInfoModel::orderBy('score','desc')->with('user')->whereNotIn('id', $id_arr1)->limit(100)->paginate(20);
            $this->dreams($dreams);
            return $this->api(compact('users','dreams'));
        } elseif ($type == 'news') {
            $dreams = DreamInfoModel::orderBy('score','desc')->orderBy('created_at','desc')->with('user')->whereNotIn('id', $id_arr2)->limit(500)->paginate(20);
            $this->dreams($dreams);
            return $this->api(compact('users','dreams'));
        } else{
            $banners = $this->getBanner();
            $dreams = DreamInfoModel::orderBy('score','desc')->with('user')->limit(15)->paginate(15);
            $this->dreams($dreams);
            return $this->api(compact('banners','users','dreams'));
        }
    }

    /**
     * @api {get}  /api/index/search 搜索
     * @apiDescription 搜索
     * @apiGroup Index
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}  [keyword]   关键字可选  (ha/name)
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     *           get
     *{
     *  "status": true,
     *  "status_code": 0,
     *   "message": "",
     *  "data": {
     *       "hot_searches": {
     *          "name": 1,
     *          "梦想": 1,
     *          "ha": 1
     *      },
     *      "history_searches": [
     *          {
     *              "id": 3,
     *              "user_id": 1,
     *              "search": "ha",
     *               "times": 1,
     *              "created_at": "2017-06-25 16:21:47",
     *               "updated_at": "2017-06-25 16:21:47"
     *          },
     *      ]
     *  }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */

    public function search(Request $request)
    {
        $user = $this->getUser();
        $keyword ='%'.$request->keyword.'%';
        $user_infos = UserInfoModel::where('nickname','like',$keyword)->get();
        $dream_infos =  DreamInfoModel::where(function ($query) use($keyword) {
            $query->where('name','like',$keyword)
                ->where('end_time','>=',time());
        })
        ->orWhere(function ($query) use($keyword){
            $query->where('sign','like',$keyword)
                ->where('end_time','>=',time());
        })->with(['user','img'])->get();
        $this->dreams($dream_infos);
        $signs  = BaseSettingsModel::where('category','sign')->where('value','like',$keyword)->get();
        if (empty($request->keyword)) {
//            历史搜索
                $history_searches  = $user->search()->orderBy('id','desc')->limit(10)->get();
//            热门搜索
                $data2 = SearchInfoModel::get();
                 $hot_searches = [];
                foreach ($data2 as $k => $v) {
                    if (count($hot_searches) == 6) {
                        break;
                    }
                    if (!array_key_exists($v->search,$hot_searches)) {
                        $hot_searches[$v->search] = $v->times;
                    }else{
                        $hot_searches[$v->search] += $v->times;
                    }
                }
                arsort($hot_searches);
                return $this->api(compact('hot_searches','history_searches'));
        }
//        写入搜索记录
        $this->insertSearchTable($user->id,$request->keyword);
        return $this->api(compact('user_infos','dream_infos','signs'));
    }

    /**
     * @api {get}  /api/index/user_search 用户搜索
     * @apiDescription 用户搜索
     * @apiGroup Index
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}  keyword   关键字
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     *{
     *    "status": true,
     *    "status_code": 0,
     *    "message": "",
     *    "data":[
     *      {
     *         "nickname": "ha",  昵称
     *         "pic": "",    头像
     *          ...
     *      },
     *   ]
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function userSearch(Request $request)
    {
        $user = $this->getUser();
        if (empty($request->keyword)) {
            return $this->api('');
        }
        $keyword ='%'.$request->keyword.'%';
        $users = UserInfoModel::where('nickname','like',$keyword)->get();
        $this->insertSearchTable($user->id,$request->keyword);
        return $this->api($users);
    }

    //获取轮播图
    public function getBanner()
    {
        $banner =  BaseSettingsModel::where(['category' => 'banner'])->where(['status' => '1'])
            ->orderBy('sort')->get()->toArray();
        return $banner;
    }

//    完善梦想信息
    public function dreams($dreams)
    {
        foreach ($dreams as $k => $dream) {
            $data = UserCareDream::where('dream_id',$dream->id)->get();
            $dream->care_num = count($data);
            $dream->img = $dream->img?$dream->img->pic:'';
        }
    }
//    查看关注用户的最新动态

//    public function newsInfo(Request $request)
//    {
////        查看后user_care_user dream_info 更新为零 首页不再显示
//        $user = $this->getUser();
//        $other_id = $request->id;
//        if (empty($other_id))  return $this->error(ErrorCode::MEMBER_NOT_EXIST);
//        UserCareDream::where('user_id',$user->id)->where('dream_user_id',$other_id)->update(['interaction_number'=>0]);
//        $data = UserInfoModel::where('id',$other_id)->with(['allInteraction'=>function ($query){
//            $query->orderBy('id','desc');
//        }])->first();
////        $data = UserInfoModel::find($other_id)->allInteraction;
////        dd($data) ;
////        dd($data->allInteraction);
//        foreach ($data->allInteraction as $item) {
//            $item->time = DreamInfoModel::find($item->dream_id)->time;
//            $item->comments = $item->comments;
//            foreach ($item->comments as $k => $v) {
//                $v->pic = UserInfoModel::find($v->user_id)->pic;
//                $v->replay = $v->replay;
//                foreach ($v->replay as $k1 => $v1) {
//                    $v1->pic = UserInfoModel::find($v1->user_id)->pic;
//                }
//            }
//        }
//        return $this->api($data);
//    }
    public function insertSearchTable($id,$keyword)
    {
        $info = SearchInfoModel::where('user_id',$id)->
        where('search',trim($keyword))->first();
        if (count($info) == 0) {
            SearchInfoModel::create(['user_id'=>$id,'search'=>trim($keyword),'times'=>1]);
        }else{
            $info->times += 1;
            $info->save();
        }

    }

    /**
     * @api {get}  /api/index/filter 筛选
     * @apiDescription 筛选
     * @apiGroup Index
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}  [sex]   性别   //1男,2女,0:全部,
     * @apiParam {string}  [age]   年龄段  0:全部,1:18-21,2:22-25,3:26-29,4:30-33,5:34-37,6:>37,
     * @apiParam {string}  [area]   地区   例：成都
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     *{
     *    "status": true,
     *    "status_code": 0,
     *    "message": "",
     *    "data":[
     *      {
     *         "nickname": "ha",  昵称
     *         "pic": "",    头像
     *          ...
     *      },
     *   ]
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     */
    public function filter(Request $request)
    {
        $sex = $request->sex;
        $age = $request->age;
        $area = $request->area;
        $login_user = $this->getUser();
        $id = $login_user->id;
        $query = new DreamInfoModel();
        if (($sex) == 1) {
            $query = $query->whereHas('user', function ($select) use ($sex) {
                $select->where('sex',0);
            });
        }
        if (($sex) == 2) {
            $query = $query->whereHas('user', function ($select) use ($sex) {
                $select->where('sex',1);
            });
        }
        if ($age == 1) {
            $query = $query->whereHas('user', function ($select) use ($age) {
                $select->where('birthday','>=',date('Y-m-d',strtotime(date('Y')-21)))->where('birthday','<=',date('Y-m-d',strtotime(date('Y')-18)));
            });
        }
        if ($age == 2) {
            $query = $query->whereHas('user', function ($select) use ($age) {
                $select->where('birthday','>=',date('Y-m-d',strtotime(date('Y')-25)))->where('birthday','<=',date('Y-m-d',strtotime(date('Y')-22)));
            });
        }
        if ($age == 3) {
            $query = $query->whereHas('user', function ($select) use ($age) {
                $select->where('birthday','>=',date('Y-m-d',strtotime(date('Y')-29)))->where('birthday','<=',date('Y-m-d',strtotime(date('Y')-26)));
            });
        }
        if ($age == 4) {
            $query = $query->whereHas('user', function ($select) use ($age) {
                $select->where('birthday','>=',date('Y-m-d',strtotime(date('Y')-33)))->where('birthday','<=',date('Y-m-d',strtotime(date('Y')-30)));
            });
        }
        if ($age == 5) {
            $query = $query->whereHas('user', function ($select) use ($age) {
                $select->where('birthday','>=',date('Y-m-d',strtotime(date('Y')-37)))->where('birthday','<=',date('Y-m-d',strtotime(date('Y')-34)));
            });
        }
        if ($age == 6) {
            $query = $query->whereHas('user', function ($select) use ($age) {
                $select->where('birthday','>=',date('Y-m-d',strtotime(date('Y')-38)));
            });
        }

        if (!empty($area)) {
            $query = $query->whereHas('user', function ($select) use ($area) {
                $select->where('city','like','%'.$area.'%');
            });
        }
        $arr1 =DreamInfoModel::limit(20)->select('id')->get()->toArray();
        $id_arr1 = array_column($arr1,'id');
        $arr2 =DreamInfoModel::orderBy('score','desc')->limit(120)->select('id')->get()->toArray();
        $id_arr2 = array_column($arr2,'id');
        $dtusers =UserCareUser::where('user_id',$id)->with('other_user')->
        where('dream_number','>',0)->orderBy('created_at')->get()->toArray();
        $hdusers = CommentInfoModel::where(function ($query) use ($id) {
            $query->where('user_id',$id)->orWhere('to_user_id',$id);
        })->where('is_read',0)->with('to_user')->orderBy('created_at')->get()->toArray();
        $users = [] ;
        foreach ($dtusers as $k => $v){
            $users[] = $v['other_user'];
        }
        foreach ($hdusers as $k => $v){
            $users[] = $v['to_user'];
        }
        $type = $request->type;
        if ($type == 'trend') {
            $dreams = $query->orderBy('score','desc')->with('user')->whereNotIn('id', $id_arr1)->limit(100)->paginate(20);
            $this->dreams($dreams);
            return $this->api(compact('users','dreams'));
        } elseif ($type == 'news') {
            $dreams = $query->orderBy('score','desc')->orderBy('created_at','desc')->with('user')->whereNotIn('id', $id_arr2)->limit(500)->paginate(20);
            $this->dreams($dreams);
            return $this->api(compact('users','dreams'));
        } else{
            $banners = $this->getBanner();
            $dreams = $query->orderBy('score','desc')->with('user')->limit(20)->paginate(20);
            $this->dreams($dreams);
            return $this->api(compact('banners','users','dreams'));
        }
    }
}
