<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2018/7/12
 * Time: 16:03
 */

namespace App\Http\Controllers\Api\V1;


use App\Models\MessagesFollowerModel;
use App\Models\MessagesInfoModel;
use App\Models\MessagesTagModel;
use App\Models\PaymentInfoModel;
use App\Models\SeenModel;
use App\Models\UserInfoModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator,Auth;
use App\Services\Base\ErrorCode;

class IndexController extends Controller
{

    /**
     * @api {get} /api/index/tag 筛选标签（indexTag）
     * @apiDescription 筛选标签（indexTag）indexTag
     * @apiGroup Index
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}  keywords   关键词
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *     "status": true,
     *     "status_code": 0,
     *     "message": "",
     *     "data": [
     *        {
     *            "id": 1,
     *            "name": "标签1",
     *            "sort": 1,
     *            "deleted_at": null,
     *            "created_at": "2018-07-12 17:03:07",
     *            "updated_at": "2018-07-12 17:03:11"
     *         }
     *     ]
     * }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */

    public function indexTag(Request $request)
    {

        $keywords = $request->input('keywords');
        $keywords = '%'.$keywords.'%';
        $data = MessagesTagModel::where([['name','like',$keywords]])->get();
        return $this->api($data);
    }


    /**
     * @api {get} /api/index/menu 知识列表（indexMenu）
     * @apiDescription 知识列表（indexMenu）indexMenu
     * @apiGroup Index
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {string}  tag_id   标签ID
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *       "menu": [
     *           {
     *               "id": 4,
     *               "name": "标签4",
     *               "sort": 4,
     *               "deleted_at": null,
     *               "created_at": "2018-07-12 17:04:31",
     *               "updated_at": "2018-07-12 17:04:34"
     *           }
     *       ],
     *       "message": {
     *       "current_page": 1,
     *       "data": [
     *           {
     *               "id": 1,
     *               "title": "爱我的",
     *               "type": 0,
     *               "owner": "Richod"
     *           }
     *       ],
     *       "first_page_url": "http://zsff.xcx.com/api/index/menu?page=1",
     *       "from": 1,
     *       "last_page": 1,
     *       "last_page_url": "http://zsff.xcx.com/api/index/menu?page=1",
     *       "next_page_url": null,
     *       "path": "http://zsff.xcx.com/api/index/menu",
     *       "per_page": 1,
     *       "prev_page_url": null,
     *       "to": 1,
     *       "total": 1
     *       }
     *   }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */
    public function indexMenu(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'tag_id' => 'integer'
            ],
            [
                'tag_id.integer' => '标签参数格式不对！'
            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $data = $request->input();
        $menu = MessagesTagModel::orderBy('sort','Desc')->take(3)->get();
        if(!isset($data['tag_id']) || $data['tag_id'] == 0){
            $message = MessagesInfoModel::where('state',0)->select('id','title','type')->orderBy('id','Desc')->paginate(1);
        } else {;
            $message = MessagesTagModel::find($data['tag_id'])->messgaes()->where('state',0)->select('id','title','type')->orderBy('id','Desc')->paginate(1);
            //dd($message);
        }
        foreach ($message as $item){
            $user = UserInfoModel::find($item->user_id);
            if($user){
                $item->owner = $user->nickname;
            }
        }
        return $this->api(compact('menu','message'));
    }


    /**
     * @api {get} /api/index/message 知识详情（indexMessage）
     * @apiDescription 知识详情（indexMenu）indexMessage
     * @apiGroup Index
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}  id   知识ID
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *       "message": {
     *              "id": 1,
     *              "title": "爱我的",
     *              "content": "爱我的",
     *              "user_id": 1,
     *              "price": 0,
     *              "phone": "18228068397",
     *              "comment": "瓦坎达入口",
     *              "type": 0,
     *              "sort": 1,
     *              "deleted_at": null,
     *              "created_at": "2018-07-12 17:06:23",
     *              "updated_at": "2018-07-12 17:06:26",
     *              "state": 0,
     *              "is_pay": "是否需要付费 0 需要付费 1 不需要"
     *          }
     *      }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */
    public function indexMessage(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'id' => 'required'
            ],
            [
                'id.required' => 'id不能为空!'
            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $userAuth = Auth('api')->user();
        if(!$userAuth){
            $msg = 'token已过期，请重新登录';
            return $this->api($msg);
        }
        //echo 111;
        $id = $request->input('id');

        $message = MessagesInfoModel::where([['state',0],['id',$id]])->first();
        if(!$message){
            $msg = '该信息不存在或者已完成';
            return $this->api($msg);
        }

        if($message->type ==0) {
            $user = UserInfoModel::find($userAuth->id);
            $followers['messages_id'] = $message->id;
            $followers['user_id'] = $user->id;
            $followers['username'] = $user->nickname;
            $followers['mobile'] = $user->mobile;
            $followers['state'] = 2;
            MessagesFollowerModel::create($followers);
        }

        if($message->type == 2){
            if($message->user_id != $this->getUserId()) {
                $check_message = MessagesFollowerModel::where([['message_id',$message->id],['user_id',$userAuth->id],['type',1]])->first();
                if(!$check_message){
                    $message->is_pay = 0;
                } else {
                    $message->is_pay = 1;
                }
            } else {
                $message->is_pay = 1;
            }

        } else {
            $message->is_pay = '';
        }
        return $this->api(compact('message'));
    }



    /**
     * @api {get} /api/index/get_message 获取知识（indexGetMessage）
     * @apiDescription 获取知识（indexMenu）indexGetMessage
     * @apiGroup Index
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}  id    知识ID
     * @apiParam {int}  type  知识类型 1 悬赏 2 付费
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * "data": {
     *      "code": 1
     *      "msg": "添加成功"
     *    }
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */
    public function indexGetMessage(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'id' => 'required',
                'type' => 'required',
            ],
            [
                'id.required' => 'id不能为空!',
                'type.required' => 'type不能为空!'
            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $userAuth = Auth('api')->user();
        if(!$userAuth){
            $msg = 'token已过期，请重新登录';
            return $this->api($msg);
        }
        $id = $request->input('id');
        $type = $request->input('type');
        $message = MessagesInfoModel::where([['id',$id],['type',$type],['state',0]])->first();
        if(!$message){
            $msg = '该信息不存在或者已完成';
            return $this->api($msg);
        }

        $check_is_buy = MessagesFollowerModel::where([['user_id',$userAuth->id],['messages_id',$message->id]])->first();
        if($check_is_buy){
            $msg = '您已获取该知识，请勿重复操作';
            return $this->api($msg);
        }
        $user = UserInfoModel::find($userAuth->id);
        if($type == 2) {
            DB::beginTransaction();
            $out_trade_no = 'We'.date('YmdHis').rand(1000,9999);
            $user->money -= $message->price;
            if($user->money<0){
                $msg = '您的余额已不足，请先充值';
                return $this->api($msg);
            }
            if(!$user->save()){
                $msg = '购买失败';
                DB::rollback();
                return $this->api($msg);
            }
            //dd(111);
            $save['openid'] = $user->openid;
            $save['out_trade_no'] = $out_trade_no;
            $save['user_id'] = $userAuth->id;
            $save['to_user'] = $message->user_id;
            $save['price'] = $message->price;
            $save['type'] = 2;
            $res = PaymentInfoModel::create($save);
            if(!$res) {
                $msg = '购买失败';
                DB::rollback();
                return $this->api($msg);
            }

        }
        $followers['messages_id'] = $message->id;
        $followers['user_id'] = $user->id;
        $followers['username'] = $user->nickname;
        $followers['mobile'] = $user->mobile;
        $followers['state'] = $type == 1?0:1;
        if(MessagesFollowerModel::create($followers)){
            $msg = '获取成功';
            DB::commit();
        } else {
            $msg = '购买失败';
            DB::rollback();
        }
        return $this->api($msg);
    }
}