<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2018/7/13
 * Time: 15:08
 */

namespace App\Http\Controllers\Api\V1;


use App\Models\FavoriteModel;
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;
use App\Services\Base\ErrorCode;

class UserController extends Controller
{

    /**
     * @api {post} /api/user/release 发布知识（userRelease）
     * @apiDescription 发布知识（userRelease）userRelease
     * @apiGroup User
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {text}  content    内容
     * @apiParam {string}  title    标题
     * @apiParam {number}  price  价格
     * @apiParam {int}  type  知识类型 1 悬赏 2 付费 0免费
     * @apiParam {text}  pic_url   图片
     * @apiParam {array}  tag['id']   标签ID  tag['name']  标签内容
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *      "msg": "添加成功"
     *    }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */
    public function userRelease(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'content' => 'required',
                'type' => 'required',
                'title' => 'required',
            ],
            [
                'content.required' => '内容不能为空!',
                'type.required' => 'type不能为空!',
                'title.required' => '标题不能为空!'
            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $userAuth = Auth('api')->user();
        if(!$userAuth){
            $msg = 'token已过期，请重新登录';
            return $this->api($msg);
        }
        DB::beginTransaction();
        $data = $request->input();
        $tag = $data['tag'];
        /*$tag[0]['name'] = 'asd';
        $tag[0]['id'] = 0;
        $tag[1]['id'] = 0;
        $tag[1]['name'] = 'dfse';*/
        $content['content'] = $data['content'];
        $content['title'] = $data['title'];
        $content['price'] = $data['price'];
        $content['type']  = $data['type'];
        $content['pic_url']  = $data['pic_url'];
        $content['sort'] = 1;
        $content['state'] = 0;
        $user = UserInfoModel::find($userAuth->id);
        $content['phone'] = $user->mobile;
        $content['user_id'] = $user->id;
        $create_res = MessagesInfoModel::create($content);
        if($data['type'] == 1){
            $out_trade_no = 'We'.date('YmdHis').rand(1000,9999);
            $user->money -= $data['price'];
            if($user->money<0){
                $msg = '您的余额已不足，请先充值';
                DB::rollback();
                return $this->api(compact('msg'));
            }
            if(!$user->save()){
                $msg = '购买失败';
                DB::rollback();
                return $this->api(compact('msg'));
            }
            $save['openid'] = $user->openid;
            $save['out_trade_no'] = $out_trade_no;
            $save['to_user'] = 0;
            $save['msg_id'] = $create_res->id;
            $save['user_id'] = $userAuth->id;
            $save['price'] = $data['price'];
            $save['type'] = 3;
            $res = PaymentInfoModel::create($save);
            if(!$res) {
                $msg = '购买失败';
                DB::rollback();
                return $this->api(compact('msg'));
            }
        }
        foreach($tag as $key=>$val) {
            if($val['id'] == 0){
                $save['name'] = $val['name'];
                $save['sort'] = 0;
                $res = MessagesTagModel::create($save);
                $id = $res->id;
            } else {
                $id = $val['id'];
            }
            $relation['messages_id'] = $create_res->id;
            $relation['tag_id'] = $id;
            DB::table('messages_tag_relation')->insert($relation);
        }
        $msg = '添加成功';
        DB::commit();
        return $this->api(compact('msg'));
    }


    /**
     * @api {get} /api/user/edit_favorite 添加/删除收藏（userEditFavorite）
     * @apiDescription 添加/删除收藏（userEditFavorite）userEditFavorite
     * @apiGroup User
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}  message_id  知识id
     * @apiParam {int}  type  操作类型 1 添加 0 删除
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *      "msg": "添加成功"
     *    }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */
    public function userEditFavorite(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'messages_id' => 'required',
                'type' => 'required',
            ],
            [
                'messages_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);
        }
        $data = $request->input();
        //dd($data);
        $check = FavoriteModel::where([['user_id',$userAuth->id],['messages_id',$data['messages_id']]])->first();
        if($data['type'] == 1) {
            if($check){
                $msg = '已添加收藏，请勿重复操作';
                return $this->api(compact('msg'));
            }
            $save['user_id'] = $userAuth->id;
            $save['messages_id'] = $data['messages_id'];
            $res = FavoriteModel::create($save);
            if($res){
                $msg = '添加成功';
            } else {
                $msg = '添加失败';
            }
            return $this->api(compact('msg'));
        } else {
            if(!$check){
                $msg = '已移除收藏，请勿重复操作';
                return $this->api(compact('msg'));
            }
            $favorite = FavoriteModel::find($check->id);
            $res = $favorite->delete();
            if($res){
                $msg = '删除成功';
            } else {
                $msg = '删除失败';
            }
            return $this->api(compact('msg'));
        }

    }


    /**
     * @api {get} /api/user/favorite 添加/删除收藏（userFavorite）
     * @apiDescription 添加/删除收藏（userFavorite）userFavorite
     * @apiGroup User
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *       "messages": {
     *              "id": 1,
     *              "title": "爱我的",
     *              "type": 0,
     *          }
     *    }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */

    public function userFavorite(Request $request)
    {
        $userAuth = Auth('api')->user();
        if(!$userAuth){
            $msg = 'token已过期，请重新登录';
            return $this->api($msg);
        }
        $data = FavoriteModel::where('user_id',$userAuth->id)->paginate(5);
        $messages = array();
        foreach ($data as $key=>$val){
            $messages[] = MessagesInfoModel::where('id',$val['messages_id'])->select('id','title','type')->first();
        }
        return $this->api(compact('messages'));
    }

    /**
     * @api {get} /api/user/my_message 我的发布（userMyMessage）
     * @apiDescription 我的发布（userMyMessage）userMyMessage
     * @apiGroup User
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}  state  类型 -1 全部 0 免费 1 悬赏 2 付费
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *       "messages": {
     *              "id": 1,
     *              "title": "爱我的",
     *              "type": 0,
     *          }
     *    }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */

    public function userMyMessage(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'state' => 'integer',
            ],
            [
                'state.integer' => 'state参数错误！',
            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $userAuth = Auth('api')->user();
        if(!$userAuth){
            $msg = 'token已过期，请重新登录';
            return $this->api($msg);
        }
        $state = $request->input('state');
        if(!empty($state)){
            $messages = MessagesInfoModel::where([['user_id',$userAuth->id],['type',$state]])->select('id','title','type')->paginate(5);
        } else {
            $messages = MessagesInfoModel::where([['user_id',$userAuth->id]])->select('id','title','type')->paginate(5);
        }
        return $this->api(compact('messages'));
    }

    /**
     * @api {get} /api/user/get_message 我的参与（userGetMessages）
     * @apiDescription 我的参与（userGetMessages）userGetMessages
     * @apiGroup User
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}  state  类型 -1 全部 0 免费 1 悬赏 2 付费
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "status": true,
     * "status_code": 0,
     * "message": "",
     * "data": {
     *       "messages": {
     *              "id": 1,
     *              "title": "爱我的",
     *              "type": 0,
     *          }
     *    }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */

    public function userGetMessages(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'state' => 'integer',
            ],
            [
                'state.integer' => 'state参数错误！',
            ]
        );
        if ($validator->fails()) {
            return $this->error(ErrorCode::CLIENT_WRONG_PARAMS, '传入参数不正确!', $validator->messages());
        }
        $userAuth = Auth('api')->user();
        if(!$userAuth){
            $msg = 'token已过期，请重新登录';
            return $this->api($msg);
        }
        $state = $request->input('state');
        if(!empty($state)){
            $messages = MessagesFollowerModel::where([['user_id',$userAuth->id]])->infos()->where('type',$state)->paginate(5);
        } else {
            $messages = MessagesFollowerModel::where([['user_id',$userAuth->id]])->infos()->paginate(5);
        }
        return $this->api(compact('messages'));
    }

    /**
     * @api {get} /api/user/message_detail 我的发布详情（userMessageDetail）
     * @apiDescription 我的发布详情（userMessageDetail）userMessageDetail
     * @apiGroup User
     * @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": {
     *          "messages": {
     *              "id": 1,
     *              "title": "爱我的",
     *              "content": "爱我的",
     *              "user_id": 1,
     *              "price": 1,
     *              "phone": "18228068397",
     *              "comment": "瓦坎达入口",
     *              "type": 1,
     *              "sort": 1,
     *              "deleted_at": null,
     *              "created_at": "2018-07-12 17:06:23",
     *              "updated_at": "2018-07-12 17:06:26",
     *              "state": 0,
     *              "pic_url": "",
     *              "followers_num": 1,
     *              "followers": [
     *                  {
     *                      "id": 5,
     *                      "messages_id": 1,
     *                      "user_id": 1,
     *                      "username": "Richod",
     *                      "mobile": "1111",
     *                      "deleted_at": null,
     *                      "created_at": "2018-07-17 09:21:18",
     *                      "updated_at": "2018-07-17 09:21:18",
     *                      "state": 0
     *                      }
     *                  ],
     *              "income": ""
     *            }
     *      }
     *}
     * @apiErrorExample {json} Error-Response:
     * HTTP/1.1 400 Bad Request
     * {
     *     "state": false,
     *     "code": 1000,
     *     "message": "传入参数不正确",
     *     "data": null or []
     * }
     */

    public function userMessageDetail(Request $request)
    {
        $id = $request->input('id');
        $messages = MessagesInfoModel::find($id);
        $messages->followers_num = MessagesFollowerModel::where([['messages_id',$messages->id]])->count();
        $messages->followers = array();
        if($messages->type == 1){
            $followers = MessagesFollowerModel::where([['messages_id',$messages->id]])->get();
            $messages->followers = $followers;
            $messages->income = '';
        }

        if($messages->type == 2){
            $followers = MessagesFollowerModel::where([['messages_id',$messages->id]])->get();
            $messages->followers = $followers;
            $messages->income = $messages->followers_num * $messages->price;
        }

        if($messages->type == 0) {
            $messages->followers = '';
            $messages->income = '';
        }
        return $this->api(compact('messages'));
    }


    /**
     * @api {get} /api/user/complete_message 结束悬赏（userCompleteMessages）
     * @apiDescription 结束悬赏（userCompleteMessages）userCompleteMessages
     * @apiGroup User
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {int}  message_id  知识id
     * @apiParam {int}  follower_id  悬赏者信息id
     * @apiParam {int}  type  操作类型 1 添加 0 删除
     * @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 userCompleteMessages(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'message_id' => 'require|integer',
                'follower_id' => 'require|integer',
            ],
            [
                'message_id.require|integer' => 'message_id参数错误！',
                'follower_id.require|integer' => 'follower_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);
        }
        $followers_id = $request->input('follower_id');
        $message_id = $request->input('message_id');
        $messages_followers = MessagesFollowerModel::find($followers_id);
        $messages = MessagesInfoModel::where([['id'=>$messages_followers->messages_id],['type',1],['state',0],['user_id',$userAuth->id]])->first();
        if(!$messages||$message_id!=$messages->id){
            $data['msg'] = '该知识不存在，或者已完成';
            $data['code'] = 0;
            return $this->api($data);
        }
        $user = UserInfoModel::find($messages_followers->user_id);
        $out_trade_no = 'We'.date('YmdHis').rand(1000,9999);
        $user->money += $messages->price;

        if(!$user->save()){
            $data['msg'] = '确认失败';
            $data['code'] = 0;
            return $this->api($data);
        }
        $save['openid'] = $user->openid;
        $save['out_trade_no'] = $out_trade_no;
        $save['to_user'] = $messages_followers->user_id;
        $save['user_id'] = 0;
        $save['msg_id'] = $messages->id;
        $save['price'] = $messages->price;
        $save['type'] = 3;
        $res = PaymentInfoModel::create($save);
        if(!$res) {
            $data['msg'] = '确认失败';
            $data['code'] = 1;
        } else {
            $data['msg'] = '确认成功';
            $data['code'] = 0;
        }
        $messages->state = 1;
        $messages->save();
        $messages_followers->state = 1;
        $messages_followers->save();
        return $this->api($data);
    }
}