<?php

namespace Agent\Src;

use Dever;

class Children
{
	# 当前节点颜色
	private $cur_color = 'blue';
	# 父级节点颜色
	private $parent_color = '#d71345';
	# 直属子节点颜色
	private $child_color = 'green';
	# 默认节点颜色
	private $color = '#bababa';

	public function home()
	{
		$cur = Dever::input('mid');
		$parent = Dever::load('invite/api')->getParentAll($cur, 5, 2);

		$data = array();
		$parents = array();

		if ($parent) {
			foreach ($parent as $k => $v) {
				$parents[] = $v['uid'];
			}

			$top = Dever::db('agent/member')->find($parent[0]['uid']);
			if (!$top) {
				Dever::alert('错误的上级用户信息');
			}
			$color = $this->parent_color;
			# 状态记录 为1时是父级别 2是子级别
			$state = 1;
		} else {
			Dever::alert('根用户无法查询');
			$top = Dever::db('agent/member')->find($cur);
			$color = $this->cur_color;
			# 状态记录 为1时是父级别 2是子级别
			$state = 2;
		}
		
		$i = 0;
		$data[$i]['id'] = $top['id'];
		$data[$i]['name'] = $top['name'];
		$data[$i]['parent_id'] = 0;
		$data[$i]['itemStyle']['color'] = $color;

		$this->getChild($data, $i, $top['id'], $parents, $cur, $state);
		
		$result = Dever::walk($data, 0);

		return $result[0];
	}

	private function getChild(&$data, &$i, $uid, $parents, $cur, $state, $next = true)
	{
		$child = Dever::db('agent/member')->select(array('parent_mid' => $uid));
		if ($child) {
			foreach ($child as $k => $v) {
				$i++;
				$data[$i]['id'] = $v['id'];
				$data[$i]['name'] = $v['name'] . substr($v['mobile'], -4);
				$data[$i]['parent_id'] = $v['parent_mid'];
				$data[$i]['itemStyle']['color'] = $this->color;

				$data[$i]['value'] = $v['name'] . '<br />' . $v['mobile'];
				if ($v['role']) {
					$role = Dever::db('setting/role')->find($v['role']);
					if ($role) {
						$data[$i]['value'] .= '<br />角色：' . $role['name'];
					}
				}
				if ($v['level_id'] && $v['level_id'] > 0) {
					$level = Dever::db('setting/level')->find($v['level_id']);
					if ($level) {
						$data[$i]['value'] .= '<br />等级：' . $level['name'];
					}
				}
				

				if ($cur == $uid) {
					$data[$i]['itemStyle']['color'] = $this->child_color;
				} 
				if ($cur == $v['id']) {
					$data[$i]['itemStyle']['color'] = $this->cur_color;
					$next = true;
					$state = 2;
				} elseif ($parents && in_array($v['id'], $parents)) {
					$data[$i]['itemStyle']['color'] = $this->parent_color;
					$next = false;
					$this->getChild($data, $i, $v['id'], $parents, $cur, $state, $next);
				} elseif ($state == 1) {
					$next = false;
				} else {
					$next = true;
				}

				if ($next) {
					$this->getChild($data, $i, $v['id'], $parents, $cur, $state, $next);
				}
			}
		}
	}
}