<?php
namespace User\Controller;

class BaseUserController extends BackendController
{
    public function _initialize()
    {
        $menu = $this->getMenuTree();
        $this->assign('menu', $menu);
    }

    protected function ajaxReturnSuccess($data = array(), $errcode = 0, $errmsg = null, $type = '')
    {
        $this->ajaxReturn(array('errcode' => $errcode, 'errmsg' => $errmsg, 'data' => $data),
            $type);
    }

    protected function ajaxReturnError($errcode, $errmsg, $data = null, $type = null)
    {
        $this->ajaxReturn(array('errcode' => $errcode, 'errmsg' => $errmsg, 'data' => $data),
            $type);
    }

    protected function getMenuTree()
    {
        // [ item(id|parent_id|title|url|active|type| children => [item] )
        // db, item
        $item_list = [
            ['id' => 1, 'parent_id' => 0, 'title' => '数据统计', 'url' => 'User/Report/index', 'seq' => 1,
                'default' => true, 'match_type' => 'url', 'children' => null, 'css_class' => null],
            ['id' => 2, 'parent_id' => 0, 'title' => '中奖信息', 'url' => 'User/Check/index', 'seq' => 1,
                'default' => false, 'match_type' => 'url', 'children' => null, 'css_class' => null],
            ['id' => 3, 'parent_id' => 0, 'title' => '照片', 'url' => 'User/Photo/index', 'seq' => 1,
                'default' => false, 'match_type' => 'url', 'children' => null, 'css_class' => null],
        ];
        $tree = $this->buildTreeChildren($item_list, 0);
        return $tree;
    }

    private function buildTreeChildren($item_list, $parent_id)
    {
        $children = [];
        foreach ($item_list as $item) {
            if ($item['parent_id'] == $parent_id) {
                $item['children'] = $this->buildTreeChildren($item_list, $item['id']);
                if (preg_match('@^([^/]*?)/([^/]*?)/([^/]*?)$@', $item['url'], $m)) {
                    if (CONTROLLER_NAME == $m[2] && ACTION_NAME == $m[3]) {
                        $item['active'] = true;
                    }
                }
                $item['href'] = U($item['url']);
                $children[] = $item;
            }
        }
        if ($children) {
            usort($children, function ($a, $b) {
                if ($a['seq'] - $b['seq']) {
                    return $a['seq'] - $b['seq'];
                }
                return $a['id'] - $b['id'];
            });
        }
        return empty($children) ? null : $children;
    }
}