<?php namespace Place\Api;
use Dever;
use Place;
use Place\Lib\Main;
class Agent extends Main
{
    #protected $login = true;
    protected $entry = true;

    # 会员列表
    public function list()
    {
        $data = Dever::load('agent', 'place')->getData();
        return Place::result($data);
    }


    # 信息
    public function info()
    {
        if (!Place::$uid) {
            $this->showLogin();
        }
        $data = Dever::load('agent', 'place')->getInfo();
        # 代理邀请码
        $data['code'] = Dever::load('code', 'invite')->get(Place::$uid);

        $data['parent'] = 2;
        # 获取我的上级
        $relation = Dever::load('relation', 'invite')->getParent(Place::$uid);
        if ($relation) {
            $data['parent'] = 1;
            $data['parent_info'] = Dever::db('member', 'place')->find($relation['uid'], array('col' => 'id,name,avatar'));
        }
        return Place::result($data);
    }

    # 我的下级列表
    public function getChild()
    {
        if (!Place::$uid) {
            $this->showLogin();
        }
        $relation = Dever::load('relation', 'invite')->getChild(Place::$uid);
        $result = array();
        if ($relation) {
            foreach ($relation as $k => $v) {
                $result[$k] = Dever::db('member', 'place')->find($v['to_uid'], array('col' => 'id,name,avatar'));
                $result[$k]['cdate_str'] = date('Y-m-d H:i:s', $v['cdate']);
            }
        }
        return $result;
    }

    # 填写邀请码，添加上级
    public function addParent()
    {
        if (!Place::$uid) {
            $this->showLogin();
        }
        $relation = Dever::load('relation', 'invite')->getParent(Place::$uid);
        if ($relation) {
            Dever::error('您已经有上级了');
        }
        $invite = Dever::input('invite', 'is_numeric', '请填写邀请码');
        $parent_uid = Dever::load('code', 'invite')->getUid($invite);
        if (!$parent_uid) {
            Dever::error('邀请码不存在');
        }
        $parent = Dever::db('member', 'place')->find($parent_uid);
        if (!$parent) {
            Dever::error('邀请码不存在');
        }
        if ($parent && $parent['agent_id'] && $parent['agent_id'] > 0) {
            Dever::load('relation', 'invite')->set($parent_uid, Place::$uid);
        } else {
            Dever::error('上级已不是'.Place::$info['agent_name'].'，请联系您的上级');
        }
        return 'ok';
    }

    # 购买
    public function buy()
    {
        if (!Place::$uid) {
            $this->showLogin();
        }
        return Dever::load('agent', 'place')->pay();
    }
}