<?php

    /** 
        +---------------------------------------------------------------
        | 房哨（专业的房产运营ERP管理系统）
        +---------------------------------------------------------------
        | © 2019 http://fs.ytsofts.cn/ All rights reserved.
        +---------------------------------------------------------------
        | 本系统由淮南市银泰软件科技有限公司提供技术支持
        +---------------------------------------------------------------
        | QQ号：984784483
        +---------------------------------------------------------------
    */

function http($url, $params, $method = 'GET', $header = array(), $multi = false) {
    $opts = array(
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header
    );
    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)){
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    return $data;
}


/**
 * 换行打印数组字符串
 * @Author   L
 * @DateTime 2018-09-19
 * @param    array     $arr                需要输出的数组
 * @return   string                        输出字符串
 */
function p($arr)
{
	echo '<pre>' . print_r($arr,true) . '</pre>';
}

/**
 * 代码加密
 * @Author   L
 * @DateTime 2018-09-19
 * @param    string     $pass               需要加密的字符串
 * @return   string                         加密过后的字符串
 */
function admin_pass_salt($pass){
    return md5(C('ADMIN_PASS_SALT').$pass);
}

/**
 * 代码加密
 * @Author   L
 * @DateTime 2018-09-19
 * @param    string     $pass               需要加密的字符串
 * @return   string                         加密过后的字符串
 */
function pass_salt($pass){
    return md5(C('PASS_SALT').$pass);
}

/**
 * 唯一订单号生成
 * @Author   L
 * @DateTime 2018-09-19
 */
function StrOrderOne()
{
    return  (strtotime(date('YmdHis', time()))) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
}

/**
 * 返回json数据并die
 * @Author   L
 * @DateTime 2018-09-19
 * @param    int        $code               返回的提示码
 * @param    string     $msg                返回的字符串
 * @param    array      $data               返回的数据
 * @return   json                           输出json数据
 */
function return_msg($code,$msg='',$data=array())
{
	$return_data['code'] = $code;
	$return_data['msg'] = $msg;
	$return_data['data'] = $data;
	echo json_encode($return_data);die;
}




//递归
function tree_data($data,$pid=0,$p,$s){
    $arr = array();
    foreach ($data as $v) {
        if ($v[$p]==$pid) {
            $v[$s] = tree_data($data,$v['id'],$p,$s);
            $arr[]=$v;
        }
    }
    return $arr;
}

/*
-------------------------------------------新权限开始
 */

/**
 * 获取路径权限范围
 * @Author   L
 * @DateTime 2018-10-24
 * @param    string     $app                应用名称
 * @param    string     $modules            控制器名称
 * @param    string     $action             方法名称
 * @param    int        $state              资源状态
 * @return   int or false                   范围
 */
function get_node_range($app = MODULE_NAME,$modules = CONTROLLER_NAME,$action = ACTION_NAME,$state = 0) {
    // 获取session中的权限列表
    $accessList = $_SESSION['_ACCESS_LIST'];
    // 判断路径节点是否在session中
    if(!isset($accessList[strtoupper($app)][strtoupper($modules)][strtoupper($action)])) {
        return false;
    } else {
        // 判断是否为公司管理员
        if ($_SESSION['admin'] == 1) {
            return 1;
        } else {
            return $accessList[strtoupper($app)][strtoupper($modules)][strtoupper($action)]['rbac'][$state];
        }
    }
}


//返回操作部门范围(array)
function get_node_range_arr($app = MODULE_NAME,$modules = CONTROLLER_NAME,$action = ACTION_NAME,$state = 0) {
    $groups = session('groups');
    $groups = explode(',',$groups);
    $range = get_node_range($app,$modules,$action,$state);
    if ($range  == false) {
        return false;
    }
    // 获取缓存中的公司配置
    // $config = get_company_config('config');
    // 获取配置中的部门级别
    $base_set = k_get_option('base_set',2);
    // 判断是否个人
    
    $grouplevel = count($base_set['grouplevel']['level']) == 0 ? 1 : count($base_set['grouplevel']['level']);

    if ($range == $grouplevel + 1) {
        return 'personal';
    }

    $range_node_group = $groups[$range-1];
    
    
    $bumen = M('bumen')->where(array('gongisid'=>session('gongsiid')))->select();
    $group_arr = getSonNode($bumen,$range_node_group);
    return $group_arr;
}

//返回操作部门范围(str)
function get_node_range_str($app = MODULE_NAME,$modules = CONTROLLER_NAME,$action = ACTION_NAME,$state = 0) {
    $group_arr = get_node_range_arr($app,$modules,$action,$state);
    if ($group_arr  == false) {
        return false;
    }
    if ($group_arr == 'personal') {
        return 'personal';
    }
    $group_str = implode(',',$group_arr);
    return $group_str;
}

//针对列表中的按钮
function get_node_range_to_group($app = MODULE_NAME,$modules = CONTROLLER_NAME,$action = ACTION_NAME,$state = 0,$uid = 0,$group = 0) {
    $group_arr = get_node_range_arr($app,$modules,$action,$state);
    if ($group_arr  == false) {
        return false;
    }
    if ($group_arr == 'personal') {
        if ($uid == session('uid')) {
            return true;
        } else {
            return false;
        }
    }
    if (!in_array($group, $group_arr)) {
        return false;
    } else {
        return true;
    }
    
}


/*设置权限页面是否选中*/
function _is_have_node($arr,$fanwei,$zhuangtai,$type){
    if ($arr['rbac'][$zhuangtai] == $fanwei) {
        if ($type==1) {
            return "checked";
        }else{
            return "selected";
        }
    } else {
        return "";
    }
}

/**
 * 递归获取下级数组，可指定ID，一维数组
 * @Author   L
 * @DateTime 2018-10-24
 * @param    array      $data               [description]
 * @param    int        $pid                [description]
 * @param    array      $SonNode            [description]
 * @return   array                          一维数组
 */
function getSonNode($data,$pid=0,$SonNode = array()){
    $SonNode[] = $pid;
    foreach($data as $k=>$v){
        if($v['parentid'] == $pid){
            $SonNode = getSonNode($data,$v['id'],$SonNode);
        }
    }
    return $SonNode;
}




/**
 * 设置系统配置，通用
 * @param string $key     配置键值,都小写
 * @param array  $data    配置值，数组
 * @param bool   $replace 是否完全替换
 * @return bool 是否成功
 */
function k_set_option($key, $data,$type = 1, $replace = false)
{
    if (!is_array($data) || empty($data) || !is_string($key) || empty($key)) {
        return false;
    }

    switch ($type) {
        case '1':
            $obj_id = 0;
            break;
        case '2':
            $obj_id = session('org.id');
            break;
        case '3':
            $obj_id = session('user.id');
            break;
        
        default:
            $type = 1;
            $obj_id = 0;
            break;
    }

    $where['option_name'] = $key;
    $where['obj_id'] = $obj_id;
    $where['obj_type'] = $type;

    $key        = strtolower($key);
    $option     = [];
    $findOption = M('options')->where($where)->find();
    if ($findOption) {
        if (!$replace) {
            $oldOptionValue = json_decode($findOption['option_value'], true);
            if (!empty($oldOptionValue)) {
                $data = array_merge($oldOptionValue, $data);
            }
        }

        $option['option_value'] = json_encode($data);
        M('options')->where($where)->save($option);
    } else {
        $option['obj_id']  = $obj_id;
        $option['obj_type']  = $type;
        $option['option_name']  = $key;
        $option['option_value'] = json_encode($data);
        M('options')->add($option);
    }

    F('options/type' . $type . '/org' . $obj_id . '/' . $key, null);//删除缓存

    return true;
}

/**
 * 获取系统配置，通用
 * @param string $key 配置键值,都小写
 * @param int $type 配置类型 1 运营端  2 公司段  3 个人
 * @return array
 */
function k_get_option($key,$type = 1)
{
    if (!is_string($key) || empty($key)) {
        return [];
    }

    static $cmfGetOption;

    if (empty($cmfGetOption)) {
        $cmfGetOption = [];
    } else {
        if (!empty($cmfGetOption[$key])) {
            return $cmfGetOption[$key];
        }
    }


    switch ($type) {
        case '1':
            $obj_id = 0;
            break;
        case '2':
            $obj_id = session('org.id');
            break;
        case '3':
            $obj_id = session('user.id');
            break;
        
        default:
            $type = 1;
            break;
    }

    $optionValue = F('options/type' . $type . '/org' . $obj_id . '/' . $key);

    if (empty($optionValue)) {
        $where['option_name'] = $key;
        $where['obj_id'] = $obj_id;
        $where['obj_type'] = $type;

        $optionValue = M('options')->where($where)->getField('option_value');
        if (!empty($optionValue)) {
            $optionValue = json_decode($optionValue, true);

            F('options/type' . $type . '/org' . $obj_id . '/' . $key, $optionValue);
        }
    }

    $cmfGetOption[$key] = $optionValue;

    return $optionValue;
}


    
function get_obj_img($table,$id){
    $img_urlf=M('photo')->where(array("org_id"=>session("org.id"),'table_name'=>$table,'table_id'=>$id,'is_cover'=>1))->getField('img_path');
    if ($img_urlf) {
        return $img_urlf;
    } else {
        $img_url=M('photo')->where(array("org_id"=>session("org.id"),'table_name'=>$table,'table_id'=>$id))->getField('img_path');
        return $img_url;
    }
}




//上传图片
function upload($table_name,$table_id){
    ini_set('max_execution_time', '0');

    if(!empty($_FILES)){
        // 上传文件配置
        $config=array(
            'maxSize' => 3292200, // 上传文件最大为50M
            'rootPath' => './', // 文件上传保存的根路径
            'savePath' => './Upload/admin/', // 文件上传的保存路径（相对于根路径）
            'saveName' => array('uniqid',''), // 上传文件的保存规则，支持数组和字符串方式定义
            'autoSub' => true, // 自动使用子目录保存上传文件 默认为true
            'exts' => array('jpg', 'gif', 'png', 'jpeg') //isset($ext_arr[$format])?$ext_arr[$format]:'',
        );
        // 实例化上传
        $upload = new \Think\Upload($config);
        // 调用上传方法
        $info = $upload->upload();
        $data=array();
        $Img = D('Photo');
        if(!$info){
            // 返回错误信息
            $error = $upload->getError();
            $data['error_info'] = $error;
        }else{
            $info = $info['file'];
            // 返回成功信息
            $d['org_id'] = session('org.id');
            $d['table_name'] = $table_name;
            $d['table_id'] = $table_id;
            $d['img_name'] = $info['savename'];
            $d['img_path'] = trim($info['savepath'].$info['savename'],'.');
            $d['adduid'] = session('user.id');
            $d['img_ext'] = $info['ext'];
            $d['img_size'] = $info['size'];
            $d['create_time'] = time();
            $d['status'] = 1;
            $Img->add($d);

            $data['img_path'] = trim($info['savepath'].$info['savename'],'.');
            
        }

        return $data;
            
    }
}

/*------------------------------------------------------------------------------*/
//获取地铁站
function ditie_option($selected){
    $tree = new \Org\Util\Tree();
    $parentid = $selected;
    $result = M('ditie')->where(array('gongsiid'=>session('gongsiid')))->order(array("sort"=>"ASC"))->select();
    foreach ($result as $key => $r) {
        $r['selected'] = $r['id'] == $parentid ? 'selected' : '';
        $r['parentid'] = $r['pid'];
        $array[] = $r;
    }
    $str = "<option value='\$id' title='\$dtming' \$selected>\$spacer \$dtming</option>";
    $tree->init($array);
    $select_categorys = $tree->get_tree(0, $str);
    return $select_categorys;
}

//获取地铁名
function ditiezhan($id,$lx){
    if ($id) {
        $find = M('ditie')->where(array('id'=>$id))->find();
        $ditie = $find['dtming'];
        if ($find['pid'] && $lx == 1) {
            $dtming=M('ditie')->where(array('id'=>$find['pid']))->getField('dtming');
            $ditie = $dtming."—".$ditie;
        }
        return $ditie;
    }
}


//获取资源名
function zym($zyid,$zylx){
    if ($zylx == 1) {
        $zym=M('xingzhengqu')->where(array('id'=>$zyid))->getField('xzqming');
    } elseif ($zylx == 2) {
        $zym=M('pianqu')->where(array('id'=>$zyid))->getField('pianqum');
    } elseif ($zylx == 3) {
        $zym=M('xiaoqu')->where(array('id'=>$zyid))->getField('xiaoqum');
    } elseif ($zylx == 4) {
        $zym=M('xuequ')->where(array('id'=>$zyid))->getField('xuexiaom');
    } elseif ($zylx == 5) {
        $zym=M('yonghu')->where(array("gongsiid"=>session("gongsiid"),'id'=>$zyid))->getField('ygmingcheng');
    } elseif ($zylx == 6) {
        $find = M('bumen')->where(array("gongsiid"=>session("gongsiid"),'id'=>$zyid))->find();
        $zym = $find['bmming'];
        $u = $find['level'];
        for ($i=0; $i < $u; $i++) { 
            $find = M('bumen')->where(array("gongsiid"=>session("gongsiid"),'id'=>$find['parentid']))->find();
            if ($find['bmming']) {
                $zym = $find['bmming']."—".$zym;
            }
        }
    } elseif ($zylx == 7) {
        $zym=M('bumen')->where(array("gongsiid"=>session("gongsiid"),'id'=>$zyid))->getField('bmming');
    } elseif ($zylx == 8) {
        $zym=M('role')->where(array("gongsiid"=>session("gongsiid"),'id'=>$zyid))->getField('remark');
    } elseif ($zylx == 9) {
        $s = k_get_option('bumen_options',2);
        $s = $s['bumen_array'];
        $zym = $s[$zyid];
    } elseif ($zylx == 10) {
        $zym=M('zdxinxi')->where(array('id'=>$zyid))->getField('zdming');
    } elseif ($zylx == 11) {
        $zym=M('dyxinxi')->where(array('id'=>$zyid))->getField('dyming');
    } elseif ($zylx == 12) {
        $zym=M('lcxinxi')->where(array('id'=>$zyid))->getField('lcming');
    } elseif ($zylx == 13) {
        $zym=M('fjxinxi')->where(array('id'=>$zyid))->getField('fanghao');
    } elseif ($zylx == 14) {
        $zym=M('yonghu')->where(array("gongsiid"=>session("gongsiid"),'id'=>$zyid))->getField('dianhua');
    } elseif ($zylx == 15) {
        $zym=M('yonghu')->where(array("gongsiid"=>session("gongsiid"),'id'=>$zyid))->getField('ygbianhao');
    }
    return $zym;
}

function get_peizhi($pzm,$cxz,$lx){
    if ($lx == 1) {
        $peizhi=M('peizhi')->where(array('pzming'=>$pzm,'zhuangtai'=>1))->order('xsshunxu asc')->select();
    } elseif ($lx == 2) {
        $peizhi=M('peizhi')->where(array('pzming'=>$pzm,'zhuangtai'=>1))->order('xsshunxu asc')->field($cxz)->select();
    } elseif ($lx == 3) {
        $peizhi=M('peizhi')->where(array('pzming'=>$pzm,'lxid'=>$cxz))->getField('lxming');
    } elseif ($lx == 4) {
        $peizhi=M('peizhi')->where(array('pzming'=>$pzm,'zhuangtai'=>1))->order('lxid asc')->limit(1)->getField('lxming');
    } elseif ($lx == 5) {
        $peizhi=M('peizhi')->where(array('pzming'=>$pzm,'zhuangtai'=>1))->order('lxid asc')->limit(1)->getField('lxid');
    } elseif ($lx == 6) {
        $peizhi=M('peizhi')->where(array('pzming'=>$pzm,'lxming'=>$cxz,'zhuangtai'=>1))->getField('lxid');
    }
    return $peizhi;
}

    //获取配置名或注释
function get_pzmzs($pz,$lx){
    if ($lx == 1) {
        $pzmzs=M('peizhi')->where(array("gongsiid"=>session("gongsiid"),'id'=>$pz))->getField('pzming');
    } elseif ($lx == 2) {
        $pzmzs=M('peizhi')->where(array("gongsiid"=>session("gongsiid"),'id'=>$pz))->getField('zhushi');
    } elseif ($lx == 3) {
        $pzmzs=M('peizhi')->where(array("gongsiid"=>session("gongsiid"),'pzming'=>$pz))->getField('pzming');
    } elseif ($lx == 4) {
        $pzmzs=M('peizhi')->where(array("gongsiid"=>session("gongsiid"),'pzming'=>$pz))->getField('zhushi');
    } elseif ($lx == 5) {
        $pzmzs=M('peizhi')->where(array("gongsiid"=>session("gongsiid"),'zhushi'=>$pz))->getField('pzming');
    } elseif ($lx == 6) {
        $pzmzs=M('peizhi')->where(array("gongsiid"=>session("gongsiid"),'zhushi'=>$pz))->getField('zhushi');
    }
    return $pzmzs;
}

//获取审核配置
function get_shenhe($val){
    $examine_arr = k_get_option('examine',2);
    return $examine_arr[$val];
}

//获取全站配置
function get_options($val,$zd){
    $options = k_get_option($val,1);
    if ($zd) {
        $options=$options[$zd];
    }
    return $options;
}