<?php

namespace Act\Lib;

use Dever;

class Comment
{
    private function table($type) {
        if ($type == 3) {
            $table = 'act/live_comment';
        } else {
            $table = 'act/comment';
        }
        return $table;
    }
    # 获取评论列表
    public function get($id, $type, $uid = false)
    {
        $where['type'] = $type;
        $where['data_id'] = $id;
        $table = $this->table($type);
        $data = Dever::db($table)->getAll($where);

        if ($data) {
            foreach ($data as $k => $v) {
                $user = Dever::load('passport/api')->info($v['uid']);
                $data[$k]['time'] = Dever::mdate($v['cdate'], 2);
                $data[$k]['username'] = $user['username'];
                $data[$k]['avatar'] = $user['avatar'];
                $data[$k]['cdate_time'] = date('Y-m-d H:i:s', $v['cdate']);

                # 检查是否点赞
                if ($uid > 0) {
                    $data[$k]['up'] = Dever::load('act/lib/like')->get($uid, $v['id'], 11);
                } else {
                    $data[$k]['up'] = 2;
                }
            }
        }
        return $data;
    }

    # 获取当前用户的评论列表
    public function getList($uid)
    {
        $where['uid'] = $uid;
        $where['type'] = '1,2,3,6';
        $info = Dever::db('act/comment')->getAll($where);

        return $info;
    }

    # 发表评论
    public function submit($uid, $id, $type, $content)
    {
        $where['uid'] = $uid;
        $where['data_id'] = $id;
        $where['type'] = $type;
        $where['content'] = Dever::emoji($content);
        $table = $this->table($type);
        $info = Dever::db($table)->one($where);
        if (!$info) {
            $data_table = Dever::config('base')->type_table[$type];
            $data = Dever::db($data_table)->one($id);
            if (isset($data['name']) && $data['name']) {
                $where['data_name'] = $data['name'];
            }
            
            Dever::db($table)->insert($where);
        }
        Dever::score($uid, 'submit_commit', '发表评论');

        # 更新评论数
        if ($type == 5) {
            return true;
        }
        $where = array();
        $where['data_id'] = $id;
        $where['type'] = $type;
        $where['state'] = 1;
        $total = Dever::db($table)->total($where);
        $table = Dever::config('base')->type_table[$type];
        Dever::db($table)->update(array('where_id' => $id, 'num_comment' => $total));

        

        return true;
    }
}