<?php namespace Place_act\Lib;
use Dever;
use Place;
class Core
{
    private $db;
    private $type;
    private $type_id;
    public function __construct($name, $type = false, $type_id = false)
    {
        $this->type = Dever::input('type', '', '', $type);
        $this->type_id = Dever::input('type_id', '', '', $type_id);
        $this->db = Dever::db($name, 'place_act');
    }

    protected function check()
    {
        if (!$this->type || !$this->type_id) {
            Dever::error('传入参数错误');
        }
    }

    # 更新互动信息
    public function up($data = array(), $msg = '')
    {
        if ($this->getInfo($data)) {
            $msg && Dever::error($msg);
        } else {
            $this->db->insert($this->data);
        }
        return 'ok';
    }

    # 删除
    public function del($data = array())
    {
        if ($info = $this->getInfo($data)) {
            $this->db->delete($info['id']);
        }
        return 'ok';
    }

    # 获取用户互动相关的信息
    public function getInfo($data = array(), $get = false, $field = array())
    {
        $this->check();
        $this->data = $data;
        $this->data['type'] = $this->type;
        $this->data['type_id'] = $this->type_id;
        $this->data['uid'] = Place::$uid;
        $info = $this->db->find($this->data);
        if ($get) {
            return $this->handleInfo($info, $field);
        }
        return $info;
    }

    # 获取用户的互动列表
    public function getUserList($field = array(), $page = 10)
    {
        $where['uid'] = Place::$uid;
        if ($this->type) {
            $where['type'] = $this->type;
        }
        # 每页10条
        $set['num'] = $page;
        $data = $this->db->select($where, $set);
        $result = array();
        if ($data) {
            foreach ($data as $k => $v) {
                $info = $this->handleInfo($v, $field);
                if ($info) {
                    $result[] = $info;
                }
            }
        }
        return $result;
    }

    private function getTypeInfo($type, $type_id)
    {
        $app = Dever::config('setting')['type'][$type];
        if ($type > 0) {
            $info = Dever::load($app)->get($type_id);
            return $info;
        }
    }

    private function handleInfo($v, $field = array())
    {
        if (!$v) {
            return array();
        }
        $info = $this->getTypeInfo($v['type'], $v['type_id']);
        if ($info) {
            $info['type'] = $v['type'];
            $info['type_id'] = $v['type_id'];
            $info['data_id'] = $v['id'];
            $info['cdate_str'] = date('Y-m-d H:i:s', $v['cdate']);
            if ($field) {
                foreach ($field as $v1) {
                    $info[$v1] = $v[$v1];
                }
            }
            return $info;
        }
    }
}