<?php
/**
 * JYmusic音乐管理系统
 *
 * @version     2.0
 * @author      战神~~巴蒂 <jyuucn@163.com>
 * @license     http://jyuu.cn/license
 * @copyright   2014 - 2017 JYmusic
 */

namespace Addons\Comment\controller;

use app\services\Actions;
use addons\Comment\model\Comment;
use app\common\controller\AddonsController;

class LocalController extends AddonsController
{

    public function index()
    {
        $type = $this->request->param('type');
        $id   = intval($this->request->param('page_id'));
        $page = intval($this->request->param('page', 1));
        $limit = intval($this->request->param('limit', 10));

        if (empty($type) || !$id || !$page  || !$limit) {
            return $this->retErr(40004);
        }
    
        $config = get_addon_config('comment');
        $orders = ['1' => 'id desc', '2' => 'digg desc', '3' => 'id asc'];
        
        $limit = $limit > 30? 30 : $limit;
        $model = new Comment();
        $type  = $this->getType($type);
        $list  = $model->getList($id, $type, $page, $limit, $orders[$config['local_list_sort']]);
        return $this->retSucc([
            'code'   => 0,
            'msg'    => 'ok',
            'result' => $list,
        ]);
    }

    /**
     * 保存发布的评论
     * @return \think\Response
     */
    public function send()
    {
        $config = get_addon_config('comment');
    
        if ( $config['local_audit'] == 3) {
            return $this->retErr(40404, '抱歉，评论功能已暂时关闭');
        }
        
        if (Actions::isGap('comment', $config['local_gap_time'])) {
            return $this->retErr(40406);
        }

        if (!$uid = is_login()) {
            return $this->retErr(40401);
        }

        $post        = $this->request->post();
        $post['uid'] = $uid;
        //分类ID,2音乐,2歌手，3，专辑，4，文章，5用户
        $post['type'] = $this->getType($post['type']);

        $rule = [
            'content' => 'require|length:2,255',
            'uid'     => 'require|number',
            'type'    => 'require|number|in:1,2,3,4',
            'page_id' => 'require|number',
        ];

        $msg = [
            'content.require' => '请输入评论的内容',
            'content.length'  => '评论内容长度2-255个字符之间',
            'uid.require'     => '发表评论的用户不能为空',
            'uid.number'      => '发表评论的用户无效',
            'type.require'    => '评论的类型不正确',
            'type.number'     => '评论的类型只能为数字',
            'page_id.require' => '指定评论的内容不能为空',
            'page_id.number'  => '指定评论的内容ID只能为数字',
        ];

        $result = $this->validate($post, $rule, $msg);
        if (true !== $result) {
            // 验证失败 输出错误信息
            return $this->retErr(40403, $result);
        }
        
        $post['status'] = $config['local_audit'];

        $model = new Comment($post);
        if ($model->allowField(true)->save()) {
            $return['msg']       = '评论发布成功';
            $data                = $model->getData();
            $data['create_time'] = '刚刚';
            $return['result']    = $data;
            
            return $this->retSucc($return);
        } else {
            return $this->retErr(40400, '评论失败，请稍后重试');
        }
    }

    /**
     * 回复指定评论
     * @return \think\response
     */
    public function reply()
    {
        $config = get_addon_config('comment');
        if ( $config['local_audit'] == 3) {
            return $this->retErr(40404, '抱歉，评论功能已暂时关闭');
        }
        if (Actions::isGap('comment', $config['local_gap_time'])) {
            return $this->retErr(40406);
        }

        if (!$uid = is_login()) {
            return $this->retErr(40401);
        }
        $post = $this->request->post();

        $rule = [
            'content'  => 'require|length:2,255',
            'uid'      => 'require|number',
            'reply_id' => 'require|number',
        ];

        $msg = [
            'content.require' => '请输入评论的内容',
            'content.length'  => '评论内容长度2-255个字符之间',
            'uid.require'     => '发表评论的用户不能为空',
            'uid.number'      => '发表评论的用户无效',
            'reply_id.number' => '回复评论ID只能为数字',
        ];
    
        $post['uid'] = $uid;
        $result = $this->validate($post, $rule, $msg);
        if (true !== $result) {
            // 验证失败 输出错误信息
            return $this->retErr(40403, $result);
        }
        
        $model = new Comment();
        $reply = $model->where('id', $post['reply_id'])
            ->field('id,type,uid,reply_id,page_id,root_id')
            ->with('user')
            ->find();
        
        if (!$reply) {
            return $this->retErr(40403, '抱歉，你回复的评论不存在！');
        }
        
        $post['status'] = $config['local_audit'];
        $post['root_id'] = !empty($reply['root_id']) ? $reply['root_id'] : $reply['id'];
        $post['page_id'] = $reply['page_id'];
        $post['type'] = $reply['type'];
        
        //楼层暂时不做
        //$post['layer']  = ++$con['layer'];

        if ($model->allowField(true)->save($post)) {
            $data                = $model->getData();
            $data['create_time'] = '刚刚';
            $data['by_user']     = $reply['user'];
            $return['result']    = $data;
            $return['msg']       = '回复发布成功';
            return $this->retSucc($return);
        } else {
            return $this->retErr(40500, '回复失败，请稍后重试');
        }
    }

    /**
     * 点赞指定评论
     * @return \think\response
     */
    public function digg()
    {
        if (Actions::isBan('comment_digg')) {
            return $this->retErr(40405);
        }

        $id = intval($this->request->param('id'));
        if (!$id) {
            return $this->retErr(40403, '参数不正确');
        }

        //点赞防刷新
        $uid = is_login();
        $ip  = $uid ? $uid : get_client_ip(1);

        $cacheKey  = 'digg_comment_' . $ip;
        $cacheDigg = cache($cacheKey);

        if ($cacheDigg && in_array($id, $cacheDigg)) {
            return $this->retErr(40403, '你已经赞过了哦!');
        }

        $model   = new Comment;
        $comment = $model->find($id);

        if (empty($comment)) {
            return $this->retErr(40403, '你点赞的评论不存在');
        }

        $res = Actions::update('comment', 'digg', $id);
        if (false !== $res) {
            //缓存点赞
            $cacheDigg[] = $id;
            $cacheTime   = (strtotime(date('Y-m-d')) + 24 * 3600) - time();
            cache($cacheKey, $cacheDigg, $cacheTime);
            return $this->retSucc(['msg' => 'ok', 'result' => $res]);
        } else {
            return $this->retErr(40500, '点赞失败，请稍后重试');
        }
    }

    protected function getType($type)
    {
        //分类ID,2音乐,2歌手，3，专辑，4，文章，5用户
        if (is_string($type)) {
            $types = ['song' => 1, 'artist' => 2, 'album' => 3, 'article' => 4, 'user' => 5, 'member' => 5];
            $type  = $types[$type];
        }

        return $type;
    }
}
