<?php
namespace model\user;
use \model;
/**
 * Class userpowerMod
 * @author
 * @copyright
 */
class userpower extends model
{
    public $userID = 0;
    public $isAdmin = false; //管理员
    public $isSupperAdmin = false; //超级管理员
    public $modPower = null;
    public $allModData = null;
    public $userModData = null;
    public $allAction = [];
    public $userAction = [];
    public $tags = null;
    public $parts = null;
    public $part_params = null;
    public $brand = null;
    public $numberBrand = null;
    function __construct(){
		parent::__construct();
        $this->tags = [
            'view'=>1,
            'add'=>2,
            'edit'=>4,
            'delete'=>8,
            'import'=>16,
            'export'=>32,
            'done'=>64
        ];
    }
    /**
     * 绑定用户
     * @return array
     */
    function bind($userID){
        if(empty($userID)) exit('异常错误 Abnormal Error');
        $this->userID = $userID;
        $this->checkAdmin();
        $this->getAllModData();
        $this->getUserModData();
        $this->getModPower();
    }
    /**
     * 构建权限action
     * @return array
     */
    private function createAction($str,&$action,$type)
    {
        $arr = explode(',',$str);
        foreach($arr as $v){
            $v = trim($v);
            if($v!='' && !in_array($v,$action)){
                if(isset($action[$v])){
                    $action[$v] = (int)$action[$v] | (int)$this->tags[$type];
                }else{
                    $action[$v] = $this->tags[$type];
                }
            }
        }
    }
    /**
     * action是否存在某个权限
     * @param $val string 值 view 或者 1
     * @param $power  [int] 权限的值
     * @return bool
     */
    private function isHasPower($val,$power)
    {
        if(!is_numeric($val)) $val = $this->tags[$val];
        return ((int)$val ^ (int)$power) < (int)$power;
    }
    /**
     * 判断是否为管理员及级别
     * @return none
     */
    private function checkAdmin()
    {
        $this->isAdmin = false;
        $this->isSupperAdmin = false;
        $this->isAdmin = false;
    }
    /**
     * 获取全部权限模块数据
     * @return array
     */
    private function getAllModData()
    {
        if($this->allModData==null){
            $sql = sprintf("SELECT * from gsp_adm_mod where am_obj<>2");
            $this->allModData = $this->db->query($sql)->fetchAll();
            foreach($this->allModData as $row){
                $this->createAction($row['am_view_action'],$this->allAction,'view');
//                $this->createAction($row['am_add_action'],$this->allAction,'add');
//                $this->createAction($row['am_edit_action'],$this->allAction,'edit');
//                $this->createAction($row['am_delete_action'],$this->allAction,'delete');
//                $this->createAction($row['am_import_action'],$this->allAction,'import');
//                $this->createAction($row['am_export_action'],$this->allAction,'export');
//                $this->createAction($row['am_done_action'],$this->allAction,'done');
            }
        }
    }
    /**
     * 获取用户权限模块数据
     * @return array
     */
    private function getUserModData()
    {
        if($this->userModData==null){
            $sql = sprintf("SELECT gsp_user_role_link_mod.`urlm_power`,gsp_adm_mod.* FROM `gsp_adm_mod`
                            JOIN `gsp_user_role_link_mod` ON urlm_am_id=am_id
                            JOIN `gsp_user_link_role` ON ult_ur_id=urlm_ur_id
                            WHERE ult_u_id='%s' ORDER BY am_id",$this->userID);
            $this->userModData = $this->db->query($sql)->fetchAll();
            foreach($this->userModData as $row){
                $this->addActionPower($row,$this->userAction);
            }
        }
    }
    /**
     * action权限
     * @return array
     */
    private function addActionPower($row,&$arr){
        if($this->isHasPower('view',$row['urlm_power'])) $this->createAction($row['am_view_action'],$this->userAction,'view');
        if($this->isHasPower('add',$row['urlm_power'])) $this->createAction($row['am_add_action'],$this->userAction,'add');
        if($this->isHasPower('edit',$row['urlm_power'])) $this->createAction($row['am_edit_action'],$this->userAction,'edit');
        if($this->isHasPower('delete',$row['urlm_power'])) $this->createAction($row['am_delete_action'],$this->userAction,'delete');
        if($this->isHasPower('import',$row['urlm_power'])) $this->createAction($row['am_import_action'],$this->userAction,'import');
        if($this->isHasPower('export',$row['urlm_power'])) $this->createAction($row['am_export_action'],$this->userAction,'export');
        if($this->isHasPower('done',$row['urlm_power'])) $this->createAction($row['am_done_action'],$this->userAction,'done');
    }
    /**
     * 模块权限列表
     * @return string
     */
    private function getModPower(){
        $arr = [];
        foreach($this->userModData as $row){
            $am_id = $row['am_id'];
            $arlm_power = $row['urlm_power'];
            if(isset($arr[$am_id])){
                $arr[$am_id] = (int)$arr[$am_id] | (int)$arlm_power;
            }else{
                $arr[$am_id] = $arlm_power;
            }
        }
        $this->modPower = $arr;
    }
    /**
     * ids权限列表
     * @return string
     */
    private function getIds($tables)
    {
//        var_dump($table);
        $sql = sprintf("SELECT * FROM gsp_user_role_link_ids 
                JOIN `gsp_user_link_role` ON ult_ur_id=urr_ur_id
                WHERE urr_table='%s' AND ult_u_id='%s'",$tables,$this->userID);
        $table = $this->db->query($sql)->fetchAll();
        $arr =[];
        if($tables == 'nums'){
            foreach($table as $row){
                $arr_power = $row['urr_power'];
                if(isset($arr[$row['urr_table_id']])){
                    $arr[$row['urr_string']] = (int)$arr[$row['urr_string']] | (int)$arr_power;
                }else{
                    $arr[$row['urr_string']] = $arr_power;
                }
            }
        }else{
            foreach($table as $row){
                $arr_power = $row['urr_power'];
                if(isset($arr[$row['urr_table_id']])){
                    $arr[$row['urr_table_id']] = (int)$arr[$row['urr_table_id']] | (int)$arr_power;
                }else{
                    $arr[$row['urr_table_id']] = $arr_power;
                }
            }
        }
        return $arr;
    }
    /**
     * 零件权限列表
     * @return string
     */
    private function getPartPower(){
        if($this->parts == null)
            $this->parts = $this->getIds('part');
    }
    /**
     * 参数权限列表
     * @return string
     */
    public function getPartParamPower(){
        return $this->part_params==null ? $this->part_params=$this->getIds('part_param') : $this->part_params;
    }
    /**
     * model
     * @return string
     */
    public function getBrandPower()
    {
        return $this->brand==null ? $this->brand=$this->getIds('model_china') : $this->brand;
    }

    public function getNumBrandPower()
    {
        return $this->numberBrand ==null ? $this->numberBrand = $this->getIds('nums') : $this->numberBrand;
    }

    /**
     * MD5密码
     * @123456 的值为 15d70fe1e26e7f85df4619f160f832fb
     * @return string
     */
    private static function pass($value)
    {
        return md5(substr($value,-3).md5($value.substr($value,0,3)).'^8mR3Hc7&98s5*62Q/');
    }
    /**
     * 登录
     * @return bool
     */
    public static function login($userID,$pass)
    {
        
    }

    /**
     * 检测action是否拥有权限
     * @return bool
     */
    public function checkPowerAction($path,$class,$method,$params){
        $result = true;
        $action = $class.'/'.$method;
        if(isset($params['func'])) $action.='/?func='.$params['func'];
        if(!$this->isAdmin && isset($this->allAction[$action])){ //权限表里存在当前类与方法 并且不是管理员
            if(isset($this->userAction[$action])){ //用户存在此方法
                //是否拥有权限
                $result = (int)$this->userAction[$action] ^ (int)$this->allAction[$action] < (int)$this->allAction[$action];
            }else{
                $result = false;
            }
        }
        return $result;
    }
    /**
     * 检测是否拥有模块的指定权限
     * @param $mod string|array 模块编码
     * @param $types  array|string|int] 指定权限 view,add,edit,delete,import,export,done
     * @param $isall bool 为false如果一个type符合就为真，为true需要全部符合
     * @return bool
     */
    public function m($mod,$type,$isall=false){ //简写
		//soul 2021/10/30
		return true;

        return $this->checkPowerMod($mod,$type,$isall);
    }
    public function checkPowerMod($mod,$type,$isall=false){
        $result = false;
        if($this->isAdmin) 
            $result = true;
        else{
            $mods = $mod;
            $types = $type;
            if(!is_array($mods)) $mods = [$mod];
            if(!is_array($types)) $types = [$type];
            foreach($mods as $mod){
                $has = false;
                foreach($types as $type){
                    if(!is_numeric($type)) $type = $this->tags[$type];
                    if(isset($this->modPower[$mod])){
                        $has = (((int)$type ^ (int)$this->modPower[$mod]) < (int)$this->modPower[$mod]);
                        if(!$isall && $has) break;
                        if($isall && !$has) break;
                    }
                }
                $result = $has;
                if(!$result) break;
            }
        }
        return $result===true;
    }
    /**
     * 检测是否拥有part的指定权限
     * @param $id string 零件ID
     * @param $type  [string|int] 指定权限 view,add,edit,delete,import,export,done
     * @return bool
     */
    public function checkPowerPart($id,$type){
        $result = false;
        $this->getPartPower();
        if($this->isAdmin) 
            $result = true;
        else{
            if($this->parts && isset($this->parts[$id])){
                if(!is_numeric($type)) $type = $this->tags[$type];
                $result = (((int)$type ^ (int)$this->parts[$id]) < (int)$this->parts[$id]);
            }
        }
        return $result;
    }
    /**
     * 检测是否拥有part_param的指定权限
     * @param $id string 参数ID
     * @param $type  [string|int] 指定权限 view,add,edit,delete,import,export,done
     * @return bool
     */
    public function checkPowerPartParam($id,$type){
        $result = false;
        $this->getPartParamPower();
        if($this->isAdmin) 
            $result = true;
        else{
            if($this->part_params && isset($this->part_params[$id])){
                if(!is_numeric($type)) $type = $this->tags[$type];
                $result = (((int)$type ^ (int)$this->part_params[$id]) < (int)$this->part_params[$id]);
            }
        }
        return $result;
    }
    /**
     * 拥有权限的零件总成ID集
     * @param $type  [string|int] 指定权限 view,add,edit,delete,import,export,done
     * @return string 管理员返回的是一个sql
     */
    public function getPowerPartGroups($type){
        $result = 0;
        $this->getPartPower();
        if($this->isAdmin) 
            $result = 'select pg_id from gsp_part_group';
        else{
            if($this->parts){
                $ids = $this->getPowerParts($type);
                if($ids){
                    $sql = sprintf("SELECT DISTINCT pg_id FROM `gsp_part_group`
                                    JOIN `gsp_part` ON pt_pg_id = pg_id
                                    WHERE pt_id IN (%s);
                                    ",$ids);
                    $table = $this->db->query($sql)->fetchAll();
                    $arr = [];
                    foreach($table as $row){
                        $arr[] = $row['pg_id'];
                    }
                    if(count($arr)>0) 
                        $result = implode(',',$arr);
                }
            }
        }
        return $result;
    }

    /**
     * 拥有权限的零件ID集
     * @param $type  [string|int] 指定权限 view,add,edit,delete,import,export,done
     * @return string 管理员返回的是一个sql
     */
    public function getPowerParts($type){
        $result = 0;
        $this->getPartPower();
        if($this->isAdmin) 
            $result = 'select pt_id from gsp_part';
        else{
            if($this->parts){
                $arr = [];
                if(!is_numeric($type)) $type = $this->tags[$type];
                foreach($this->parts as $k=>$v){
                    if(((int)$type ^ (int)$v) < (int)$v){
                        $arr[] = $k;
                    }
                }
                if(count($arr)>0) 
                    $result = implode(',',$arr);
            }
        }
        return $result;
    }

    /**
     * 拥有权限的零件ID集
     * @param $type  [string|int] 指定权限 view,add,edit,delete,import,export,done
     * @return string 管理员返回的是一个sql
     */
    public function getNumBrand($type){
        $result = 0;
        $this->getPartPower();
        if($this->isAdmin)
            $result = 'select pt_id from gsp_part';
        else{
            if($this->parts){
                $arr = [];
                if(!is_numeric($type)) $type = $this->tags[$type];
                foreach($this->parts as $k=>$v){
                    if(((int)$type ^ (int)$v) < (int)$v){
                        $arr[] = $k;
                    }
                }
                if(count($arr)>0)
                    $result = implode(',',$arr);
            }
        }
        return $result;
    }

    /**
     * 拥有权限的指定零件的参数ID集
     * @param $type  [string|int] 指定权限 view,add,edit,delete,import,export,done
     * @return string 管理员返回的是一个sql
     */
    public function getPowerPartParams($pt_id,$type){
        $result = 0;
        $this->getPartParamPower();
        if($this->isAdmin) 
            $result = sprintf("SELECT ptpa_id FROM `gsp_part_param`");
        else{
            if($this->part_params){
                $arr = [];
                if(!is_numeric($type)) $type = $this->tags[$type];
                $sql = sprintf("select ptpa_id from gsp_part_param where ptpa_cate_id=%d",$pt_id);
                $table = $this->db->query($sql)->fetchAll();
                foreach($table as $row){
                    if(isset($this->part_params[$row['ptpa_id']])){
                        $v = $this->part_params[$row['ptpa_id']];
                        if(((int)$type ^ (int)$v) < (int)$v){
                            $arr[] = $row['ptpa_id'];
                        }
                    }
                }
                if(count($arr)>0) 
                    $result = implode(',',$arr);
                else
                    $result = 0;
            }
        }
        return $result;
    }
    /**
     * 拥有权限的指定Brand的参数ID集
     * @param $type  [string|int] 指定权限 view,add,edit,delete,import,export,done
     * @return string 管理员返回的是一个sql
     */
    public function getPowerBrand($type){
        $result = 0;
        $this->getPartParamPower();
        if($this->isAdmin) 
            $result = sprintf("SELECT mc_brand_id FROM `gsp_model_china` GROUP BY mc_brand_id");
        else{
            if($this->brand){
                $ids = $this->getPowerBrand($type);
                if($ids){
                    $sql = sprintf("SELECT mc_brand_id FROM `gsp_model_china` WHERE mc_brand_id IN(%s) GROUP BY mc_brand_id",$ids);
                    $table = $this->db->query($sql)->fetchAll();
                    $arr = [];
                    foreach($table as $row){
                        $arr[] = $row['mc_brand_id'];
                    }
                    if(count($arr)>0) 
                        $result = implode(',',$arr);
                }
            }
        }
        return $result;
    }

    public function getPowerNumberBrand($type)
    {
        $result = [];
        $this->getNumBrandPower($type);
        $result = array_keys($this->getNumBrandPower($type));
        foreach ($result as &$v){
            switch ($v){
                case '新编码':
                    $v = 'P_NUM_NEW';
                    break;
                case '老编码':
                    $v = 'P_NUM_OLD';
                    break;
                case '老编码不带ABS':
                    $v = 'P_NUM_OLD_NOABS';
                    break;
                case 'ENERTEK编码':
                    $v = 'P_NUM_ENERTEK';
                    break;
                case 'Y品牌编码':
                    $v = 'P_NUM_G';
                    break;
                case 'NCV编码':
                    $v = 'P_NUM_NCV';
                    break;
                case '合并前新编码':
                    $v = 'gsp_new';
                    break;
                case '合并前老编码':
                    $v = 'gsp';
                    break;
                case '合并前老编码不带ABS':
                    $v = 'gsp_noabs';
                    break;
                case '合并前ENERTEK编码':
                    $v = 'num_enertek';
                    break;
                case '合并前品牌编码':
                    $v = 'g';
                    break;
                case '合并前CV编码':
                    $v = 'num_ncv';
                    break;
            }
        }
        return $result;
    }

    /**
     * @param $data
     * @return bool
     */
    public function addUserLog($data)
    {
        
    }
}

