<?php

namespace Push\Lib;

use Dever;

class Data
{
    public function get($key, $name, $total = 10, $page = false, $limit = false)
    {
        $info = Dever::db('push/info')->one(array('key' => $key));

        if (!$info) {
            $insert['key'] = $key;
            $insert['name'] = $name;
            $insert['num'] = $total;
            $insert['col'] = '1,2,3,4';
            $info['id'] = Dever::db('push/info')->insert($insert);
            $info['num'] = $insert['num'];
        }

        $data = array();
        if ($info) {
            if (!$info['num']) {
                $info['num'] = 20;
            }
            if ($limit > 0) {
                $info['num'] = $limit;
            }

            $where = array();
            $where['info_id'] = $info['id'];

            if ($page) {
                $where['page'] = array($info['num'], 'list');
                $data = Dever::db('push/data')->getAllPage($where);
            } else {
                $where['limit'] = '0,' . $info['num'];
                $data = Dever::db('push/data')->getAll($where);
            }

            if ($data) {
                foreach ($data as $k => $v) {
                    $data[$k] = $this->getOne($v);
                }
            }
        }

        return $data;
    }

    private function getOne($info)
    {
        $info['id'] = 0;
        if ($info['type'] < 10 || $info['type'] == 13) {
            $method = 'one';
            if ($info['type'] == 1) {
                $id = $info['demand_id'];
                $table = 'demand/info';
            }

            unset($info['demand_id']);
            if ($id > 0) {
                $info['id'] = $id;
                $data = Dever::db($table)->$method($id);
                if (isset($data) && $data) {
                    if (isset($data['name']) && $data['name'] && !$info['name']) {
                        $info['name'] = $data['name'];
                    }

                    if (isset($data['pic_cover']) && $data['pic_cover'] && !$info['pic']) {
                        $info['pic'] = $data['pic_cover'];
                    }

                    if (isset($data['link']) && $data['link']) {
                        $info['link'] = $data['link'];
                    }
                }
            }
        } else {
            unset($info['demand_id']);
        }

        if ($info['link']) {
            if (!strstr($info['link'], 'http')) {
                $info['link'] = 'http://' . $info['link'];
            }
        }

        $info['cdate'] = date('Y-m-d', $info['cdate']);

        return $info;
    }
}