<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/22
 * Time: 11:50
 */

namespace app\api\controller;

use app\common\model\Comment as CommentModel;
use think\Validate;
use app\common\model\Order as OrderModel;

class Comment extends Base
{
    /**
     * 获取活动评论
     * @param pid 活动id
     * @param p 页数
     * @param page 一页条数
     * @return json
     */
    public function getCommentByPid()
    {
        if (!input('?post.pid')) {
            return ['code' => 1, 'msg' => '缺少参数pid'];
        }
        $p       = input('post.p/d', 1);
        $page    = input('post.p/d', 8);
        $comment = CommentModel::with('user')
            ->where(['pid' => input('post.pid'), 'status' => config('comment_status.pass')])
            ->page($p, $page)
            ->select();
        if (!$comment) {
            return ['code' => 1, 'msg' => '没有更多'];
        }
        $comment = collection($comment)->hidden(['user.id', 'user.large_avatar', 'user.ip', 'user.city', 'user.province', 'user.phone', 'user.gender', 'user.openid', 'user.unionid', 'user.is_vip', 'user.vip_endtime', 'user.created_at'])->toArray();
        if (!$comment) return ['code' => 1, 'msg' => '没有更多'];
        return ['code' => 0, 'msg' => 'success', 'data' => $comment];
    }

    /**
     * 评论
     * @param grade 评分
     * @param content 评论内容
     * @param order_id 订单id
     * @return json
     */
    public function insert()
    {
        //验证
        $validate = Validate::make([
            'content'  => 'require',
            'grade'    => 'require',
            'order_id' => 'require'
        ]);
        $res      = $validate->check(input('post.'));
        if (!$res) return ['code' => 1, 'msg' => $validate->getError()];

        $order = OrderModel::get([
            'uid'        => $this->userinfo[0],
            'id'         => input('post.order_id'),
            'is_comment' => ['in', [config('comment_status.no'), config('comment_status.no_pass')]]
        ]);
        //检验是否重复写入
        if (!$order) {
            return ['code' => 1, 'msg' => '无此订单!'];
        }
        
        //写入数据库
        CommentModel::create([
            'content'  => input('post.content'),
            'grade'    => input('post.grade'),
            'pid'      => $order->pid,
            'uid'      => $this->userinfo[0],
            'order_id' => $order->id,
        ]);
        $order->is_comment = config('comment_status.to_examine');
        $order->save();
        //查询订单
        return ['code' => 0, 'msg' => '评论成功'];
    }
}