<?php

namespace app\common\api;

use app\admin\model\Role;
use app\admin\model\SysRelation;
use app\admin\model\Menu;

/**
 * Description of MenuApi
 *
 * @author sgq
 */
class MenuApi {

    public static function getOne($id) {
        $where = [];
        $where[] = ["t1.id", "=", $id];
        $where[] = ["t1.delete", "=", 0];
        $menu = Menu::alias("t1")->leftJoin("sys_menu t2", "t1.pcode=t2.code")->field("t1.*,if(t2.code is null,'顶级',t2.name) as pcodeName,t2.id as pid")->where($where)->findOrEmpty();
        return $menu;
    }

    public static function getOneByCode($code) {
        $where = [];
        $where[] = ["code", "=", $code];
        $where[] = ["delete", "=", 0];
        $menu = Menu::where($where)->findOrEmpty();
        return $menu;
    }

    public static function getList($params = []) {
        $where = [];
        $where[] = ["delete", "=", 0];
        if ($params["menuName"]) {
            $where[] = ["name", "like", "%" . $params["menuName"] . "%"];
        }
        if ($params["level"]) {
            $where[] = ["levels", "=", $params["level"]];
        }
        $list = Menu::where($where)->order("num asc")->select()->toArray();
        return $list;
    }

    public static function getMenuIdsByNewUrls(array $urls) {
        $where = [];
        $where[] = ["new_url", "in", $urls];
        $where[] = ["status", "=", 1];
        $where[] = ["delete", "=", 0];
        return Menu::where($where)->column("id");
    }

    public static function save($params) {
        $data["name"] = $params["name"];
        $data["new_url"] = $params["url"];
        $data["code"] = $params["code"];
        $data["num"] = $params["num"];
        $data["icon"] = $params["icon"];
        $data["ismenu"] = $params["ismenu"];
        $data["status"] = $params["status"] ?: 1;
        $tmp = [];
        $parent = self::getOne($params["pcode"]);
        $data["pcode"] = $parent["code"] ?: 0;
        $_pcodes = array_filter(explode(",", $parent["pcodes"]));
        $_pcodes[] = "[" . $data["pcode"] . "]";
        $data["pcodes"] = implode(",", $_pcodes);
        $data["levels"] = count($_pcodes);
        if ($params["id"]) {
            $data["id"] = $params["id"];
            return Menu::update($data);
        }
        return Menu::insert($data);
    }

    public static function delete($id) {
        $data["id"] = $id;
        $data["delete"] = 1;
        return Menu::update($data);
    }

    public static function getAllMenus($fields = "*") {
        $where[] = ["status", "=", 1];
        $where[] = ["delete", "=", 0];
        $menus = Menu::where($where)->field($fields)->order("levels asc,num asc")->select()->toArray();
        $menus = self::buildMenu($menus);
        return $menus;
    }

    public static function getMenuListByRoleid($roleid) {
        $roleids = explode(",", $roleid);
        $tmpArray = [];
        foreach ($roleids as $roleid) {
            $role = Role::find($roleid);
            $menu_ids = $role->sysRelation->column("menuid");
            $tmpArray = array_merge((array) $tmpArray, (array) $menu_ids);
        }
        $tmp = [];
        if ($tmpArray) {
            $where[] = ["status", "=", 1];
            $where[] = ["delete", "=", 0];
            $where[] = ["ismenu", "=", 1];
            $where[] = ["new_url", "<>", ""];
            $where[] = ["id", "in", $tmpArray];
            $whr[] = ["levels", "=", 1];
            $menus = Menu::whereOr([$where, $whr])->order("levels asc,num asc")->select()->toArray();
            $menus = self::buildMenu($menus);
            for ($i = 0; $i < count($menus); $i++) {
                $menu_items_count = count($menus[$i]["children"]);
                $empty_url_count = 0;
                for ($n = 0; $n < $menu_items_count; $n++) {
                    if ($menus[$i]["children"][$n]["new_url"] == null)
                        $empty_url_count++;
                }
                if ($empty_url_count != $menu_items_count)
                    $tmp[] = $menus[$i];
            }
        }
        return $tmp;
    }

    public static function getPrivilagesByRoleid($roleid) {
        $role = Role::find($roleid);
        $menu_ids = $role->sysRelation->column("menuid");
        $where[] = ["status", '=', 1];
        $where[] = ["delete", '=', 0];
        $menus = Menu::where($where)->order("levels asc,num asc")->select()->toArray();
        $codeToPid = [];
        foreach ($menus as &$menu) {
            $codeToPid[$menu["code"]] = $menu["id"];
            $menu["checked"] = in_array($menu["id"], $menu_ids) ? true : false;
            $menu["pid"] = isset($codeToPid[$menu["pcode"]]) ? $codeToPid[$menu["pcode"]] : 0;
        }unset($menu);
        return $menus;
    }

    /**
     * 递归获取多级菜单集合
     * @param type $menus
     * @param type $pcode
     * @return type
     */
    private static function buildMenu($menus, $pcode = "0") {
        $result = [];
        foreach ($menus as $key => $menu) {
            if ($pcode == $menu["pcode"]) {
                unset($menus[$key]);
                $menu["children"] = self::buildMenu($menus, $menu["code"]);
                if ($menu["pcode"] == 0) {
                    $result[] = $menu;
                }
            }
        }
        return $result;
    }

    /**
     * 权限检查
     * @param type $url 新权限url
     * @param type $old_url 旧系统权限url
     * @return boolean
     */
    public static function chkPermission($url, $old_url) {
        $url = strtolower($url);
        $old_url = strtolower($old_url);
        $menu = Menu::whereRaw("`status`=1 and (new_url=:new_url or `url`=:url)", ["new_url" => $url, "url" => $old_url])->findOrEmpty()->toArray();
        if (!$menu)
            return true;

        $menuid = $menu["id"];
        $roleids = explode(",", session("user")["roleid"]);
        $tmpArray = [];
        foreach ($roleids as $roleid) {
            $role = Role::find($roleid);
            $menu_ids = $role->sysRelation->column("menuid");
            $tmpArray = array_merge((array) $tmpArray, (array) $menu_ids);
        }
        return in_array($menuid, $tmpArray);
    }

    public static function getEnterpriseMenuByType($type) {
        $menus = [];
        $menus[] = ["type" => [1, 2, 3], "code" => "qyzx", "pcode" => "0", "name" => "机构用户中心", "url" => "/enterprise/index/centerPage", "icon" => "fa-user", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "yhfk", "pcode" => "0", "name" => "用户反馈", "url" => "", "icon" => "fa-bug", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "rcrd", "pcode" => "0", "name" => "人才认定", "url" => "#", "icon" => "fa-pencil-square-o", "status" => 1];
        //$menus[] = ["type" => [1, 2], "code" => "jctjsb", "pcode" => "rcrd", "name" => "基础条件申报", "url" => "/enterprise/base", "icon" => "fa-thumbs-o-up", "status" => 1];
        //$menus[] = ["type" => [1, 2], "code" => "rcrdsb", "pcode" => "rcrd", "name" => "人才认定申报", "url" => "/enterprise/talent", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "rcrdsbnew", "pcode" => "rcrd", "name" => "人才认定申报(新)", "url" => "/enterprise/talent/index/isMix/1", "icon" => "fa-thumbs-up", "status" => 1];
        //$menus[] = ["type" => [1, 2], "code" => "rczrzlbc", "pcode" => "rcrd", "name" => "人才直认资料补充", "url" => "/enterprise/talent/zrIndex", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [2], "code" => "jfsb", "pcode" => "rcrd", "name" => "积分申报", "url" => "/enterprise/integral/index", "icon" => "fa-credit-card", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "yxrck", "pcode" => "rcrd", "name" => "优秀人才库", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "lzsb", "pcode" => "rcrd", "name" => "离职申报", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "gzdwbg", "pcode" => "rcrd", "name" => "工作单位变更", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "yhzhbg", "pcode" => "rcrd", "name" => "银行账号变更", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "rcccbg", "pcode" => "rcrd", "name" => "人才层次变更", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "jcxxbg", "pcode" => "rcrd", "name" => "基础信息变更", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "jbtmanage", "pcode" => "0", "name" => "津补贴申报", "url" => "", "icon" => "fa-money", "status" => 0];
        $menus[] = ["type" => [1, 2], "code" => "jbtsb", "pcode" => "jbtmanage", "name" => "津补贴申报", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [1, 2], "code" => "gfbt", "pcode" => "0", "name" => "购房补贴", "url" => "", "icon" => "fa-university", "status" => 0];
        $menus[] = ["type" => [1, 2], "code" => "gfbtsb", "pcode" => "gfbt", "name" => "购房补贴申报", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [2], "code" => "pxbtmanage", "pcode" => "0", "name" => "培训补贴", "url" => "", "icon" => "fa-building", "status" => 1];
        $menus[] = ["type" => [2], "code" => "pxbt", "pcode" => "pxbtmanage", "name" => "培训补贴", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [2], "code" => "zdzxmanage", "pcode" => "0", "name" => "重大专项", "url" => "", "icon" => "fa-life-ring", "status" => 1];
        $menus[] = ["type" => [2], "code" => "zdzx", "pcode" => "zdzxmanage", "name" => "重大专项", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [2], "code" => "znjy", "pcode" => "0", "name" => "子女教育", "url" => "", "icon" => "fa-graduation-cap", "status" => 1];
        $menus[] = ["type" => [2], "code" => "xzfbz", "pcode" => "znjy", "name" => "学杂费补助", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [2], "code" => "ylbzmanage", "pcode" => "0", "name" => "医疗补助", "url" => "", "icon" => "fa-hospital-o", "status" => 1];
        $menus[] = ["type" => [2], "code" => "ylbz", "pcode" => "ylbzmanage", "name" => "医疗补助", "url" => "", "icon" => "fa-thumbs-up", "status" => 1];
        $menus[] = ["type" => [2], "code" => "zfbz", "pcode" => "0", "name" => "住房保障", "url" => "", "icon" => "fa-home", "status" => 1];
        $menus[] = ["type" => [2], "code" => "zfsq", "pcode" => "zfbz", "name" => "租房申请", "url" => "", "icon" => "fa-home", "status" => 1];
        $menus[] = ["type" => [2], "code" => "fzbz", "pcode" => "zfbz", "name" => "房租补助", "url" => "", "icon" => "fa-money", "status" => 1];
        $menus[] = ["type" => [2], "code" => "gfsq", "pcode" => "zfbz", "name" => "购房申请", "url" => "", "icon" => "fa-envira", "status" => 1];
        $menus[] = ["type" => [2], "code" => "gfbz", "pcode" => "zfbz", "name" => "购房补助", "url" => "", "icon" => "fa-envira", "status" => 1];
        $menus[] = ["type" => [1], "code" => "sbrc", "pcode" => "0", "name" => "硕博人才", "url" => "", "icon" => "fa-graduation-cap", "status" => 0];
        $menus[] = ["type" => [1], "code" => "shbt", "pcode" => "sbrc", "name" => "生活补贴", "url" => "", "icon" => "fa-graduation-cap", "status" => 1];
        $menus[] = ["type" => [3], "code" => "hxjh", "pcode" => "0", "name" => "海峡计划", "url" => "", "icon" => "fa-plane", "status" => 1];
        $menus[] = ["type" => [3], "code" => "hxjhsb", "pcode" => "hxjh", "name" => "海峡计划申报", "url" => "", "icon" => "fa-pencil", "status" => 1];
        foreach ($menus as $key => $menu) {
            if (!in_array($type, $menu["type"]) || ($menu["pcode"]) != "0" && $menu["url"] == "" || $menu["status"] == 0)
                unset($menus[$key]);
        }
        return self::buildMenu($menus);
    }

}
