<?php
// +----------------------------------------------------------------------
// | Yershop 开源网店系统
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.yershop.com All rights reserved.
// +----------------------------------------------------------------------
use think\Db;
use think\AjaxPage;
/**
 * 判断是否菜单显示
 * @param int $id   传入要比较的id
 * @param int $pid 传入当前id
 * @return bool
 */
function in_checked($pid,$id){
	if($pid==$id){
		return true; 
	}
    $arr=getParent($pid);
    if(in_array($id,$arr)){
	  return true; 
   }else{
	  return false;  
   }
} 

/**
 * 配置读取函数，ot内置函数
 * @param string $name   传入配置英文名称
 * @return string 配置值
 */
function C($name=''){
	 $map['name']=$name; 
     $info =db('config')->where($map)->find();
	 if($info["type"]&&$info["type"]=="picture"){ 
		 $cover_id=$info["value"];
	     $info["value"]=get_cover_path($cover_id); 
	 }
     return  $info["value"];
}	

function getColumns($model){

 

       $sql = 'SHOW COLUMNS FROM `'.config('database.prefix').$model.'`';

       $data= Db::query($sql);

       if ($data=== false) return array();

       $list = array();

       if (!empty($data)) {

           foreach ($data as $k=>$v) {

               $list[$v['Field']] = [

                   'name'    => $v['Field'],

                   'type'    => $v['Type'],

                   'null'       => $v['Null'],

                   'default' => $v['Default'],

                   'primary' => (strtolower($v['Key']) == 'pri'),

                   'autoinc' => (strtolower($v['Extra']) == 'auto_increment'),

               ];

           }

       }
       return $list;

   }


   /**
    * 获取数据库字段注释
    */
function getDbColumnComment($model = '', $field = true, $table_schema = ''){
       $database = config('database');
       $schema = config('database.database');;
       $table =config('database.prefix'). $model;
       $param = [$table,$schema];
       $columnName = '';
       if($field !== true){
           $param[] = $field;
           $columnName = "AND COLUMN_NAME = ?";

       }
	   $sql="SELECT COLUMN_NAME as field,column_comment 
	   as comment FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ?
	   AND table_schema = ? $columnName";
       $result = Db::query($sql, $param);
       if(empty($result) && $field !== true){
           return '';
       }
       foreach($result as $k => $v){

           $data[$v['field']] = $v['comment'];

           if(strpos($v['comment'], '#*#') !== false){

               $array = explode('#*#', $v['comment']);

               $data[$v['field']] = json_decode(end($array), true);

           }

       }
       if(empty($data)){

           return '';

       }

       return count($data) == 1 ? reset($data) : $data;

   }


function getMemberList($pid = 0,$data){
	   
		if(!$data){
			
			$data=M("ucenterMember")->field("id,pid")->select();
        }
		$arr = array( ); 
		$temp = array();
		   foreach ( $data as $key => $v ) {
		   //判断，如果$v['pid'] == $pid的则压入数组Child
		       if ($v['pid'] == $pid) {
					//递归执行
					  $temp[] = $v['id']; 
                      $temp = array_merge($temp,getMemberList($v['id'],$data));				
		       }
		   }
         
		return $temp;
	}
/**
 * 查询条件
 */
function getcondition(){
	  if($_POST){
			foreach ($_POST as $key=>$value){
				if($value){
					$map[$key]  = array('like', '%'.$value.'%');
				 }
			}
        }
	  $map=isset($map)?$map:'';
	  return $map;  
   
}
/**
 * 切换风格
 * @return string 
 */
function getStyle(){
    $ISDES=C('ISDES');	
    if($ISDES){ 
	     $msg="v3风格";
     }else{
		 $msg="v2风格";	
     }
	 return $msg;
}



/**
 * 获取配置分组
 * @return array 
 */
function get_config_group(){
   $type   = C("GROUP");
	$type=explode("|",$type);
    return $type;
}
/**
 * 获取属性类型信息
 * @return string  
 */
function get_config_type($type=""){
    // TODO 可以加入系统配置
     $data= array(
        'text'    => '字符串',
        'textarea'  => '文本框',
        'date'      => '日期',
		'select'     => '枚举',
        'picture'   => '上传图片',
		'color'     => '拾色器',
       
    );
    return $type?$data[$type]:$data;
}

function get_type($type=""){
    // TODO 可以加入系统配置
     $data= array(
        'text'    => '文本输入框',
        'textarea'  => '多行文本输入框',	
        'picture'   => '单图上传',
		'photo'     => '多图上传',
		'editor'     => '编辑器',
        'date'      => '日期',
    );
    return $type?$data[$type]:$data;
}
function get_search_html($title='',$name=''){
	
	if($name=="id"){
		return '';
	}else{		
		$v=":input('$name')";
		$html=' <div class="group">
							   '.$title.'：<input type="text" name="'.$name.'" class="search_ipt" value="{'.$v.'}"/>
						  
						  </div>';
		return $html;				  
	}
}

function get_index_html($title="",$name=''){
	//$value="{$"."vo['$name']|default=''}";
  	if($name=="id"){
			$v=' <th>序号</th>';
	}else{

	    $v=' <th>'.$title.'</th>';
	}
	return $v;		
			  
	
}

function get_td_html($title="",$name=''){ 
  
	$value="$"."vo['$name']|default=''";
	
	$v=' <td>{'.$value.'}</td>';
	return $v;				  
	
}

function get_type_html($type="",$title="",$name=''){
	//$value="$"."info['$name']";
	if($name=="id"){
		return '';
	}
	$value="$"."info['$name']|default=''";
	$v="$"."info['$name']";$lists="$"."info['$name']";
	$path='';
	if($type=="picture"){
		
		$path=get_cover_path($value);
	}
    // TODO 可以加入系统配置
     $data= array(
        'text'    => ' <div class="form-item">
									                 <label>'.$title.'<span></span></label>
													 <div class="form-input">
									                     <input type="text" name="'.$name.'" value="{'.$value.'}">
													  </div>
								                 </div>',
        'textarea'  => '  <div class="form-item">
									                 <label>'.$title.'<span></span></label>
													 <div class="form-input">
									                    <textarea name="'.$name.'"/>{'.$value.'}</textarea>
													 </div>
								                 </div>',
        'date'      => '	<div class="form-item">
									<label>'.$title.'<span>('.$title.')</span></label>
									<div class="form-input">
										<input type="text"name="'.$name.'" id="'.$name.'" class="laydate-icon"
									    value="{notempty name="info.id"}{$info.'.$name.'|time_format}{/notempty}"/>
									    <script type="text/javascript" src="__COMMON__/laydate/laydate.js"></script>		
										<script>
											laydate({
											  elem: "#'.$name.'",
											  format: "YYYY-MM-DD hh:mm:ss", 
											  min: laydate.now(), //设定最小日期为当前日期//目标元素。
											  
											  event:"focus" //响应事件。如果没有传入event，则按照默认的click
											});
										</script>
									</div>
							   </div>
',
		'radio'     => '单选',
		'select'     => '下拉选择',
        'picture'   => ' <div class="form-item">
														<label>'.$name.'<span>(图片名称)</span></label> 
														<div id="'.$name.'" class="container">
															<div id="file_'.$name.'">你的浏览器不支持flash,Silverlight或者HTML5！</div>
															<input type="hidden" name="'.$name.'"  value="{'.$value.'}">
														
															<a id="select_'.$name.'" href="javascript:void(0);" class="btn">选择文件</a>
															<a id="post_'.$name.'" href="javascript:void(0);" class="btn">开始上传</a>
														</div>
				
													   <div class="uploader_preview">
															 {notempty name="config.value"}  
																  <div class="upload-pre-item"> 
																	<img class="'.$name.'" src="'.$path.'"/>
																	</div>
															  {/notempty}
														</div>

														<script type="text/javascript">  
															var field="'.$name.'";	
															
															upload(field);
														</script>	
                                                  </div>',
		'color'     => '拾色器',
		'editor'     => ' <div class="form-item">
									    <label>'.$title.'<span>(详细内容)</span></label>
										<div class="form-input w100">
												<textarea class="am-validate" id="'.$name.'" name="'.$name.'" required>{$info.'.$name.'|default=""}</textarea>	
												<link rel="stylesheet" href="__COMMON__/kindeditor/default/default.css" />
												<script charset="utf-8" src="__COMMON__/kindeditor/kindeditor-min.js"></script>
												<script charset="utf-8" src="__COMMON__/kindeditor/zh_CN.js"></script>
												<script type="text/javascript">
													var editor_'.$name.';
													KindEditor.ready(function(K) {
														editor_'.$name.' = K.create("textarea[name=\''.$name.'\']", {
															allowFileManager : false,
															themesPath: K.basePath,
															width: "90%",
															height: "350",
															resizeType:1,
															pasteType : 2,
															urlType : "absolute",
															fileManagerJson :"{:url("fileManagerJson")}",
															uploadJson : "{:url("Uploads/ke_upimg")}"
														});
													});
													$(function(){
														$("textarea[name=\''.$name.'\']").closest("form").submit(function(){
															editor_'.$name.'.sync();
														});
													})
											    </script> 
										</div>
                                   </div>',
        'photo'     => '  
							  <div class="form-item">
									<label>'.$title.'<span>('.$title.')</span></label>
									<input type="hidden" name="'.$name.'"  value="'.$value.'"	>
									<div id="'.$name.'" class="container">
													<div id="file_'.$name.'">你的浏览器不支持flash,Silverlight或者HTML5！</div>
													
													<a id="select_'.$name.'" href="javascript:void(0);" class="btn">选择文件</a>
													<a id="post_'.$name.'" href="javascript:void(0);" class="btn">开始上传</a>
									</div>
									  <div class="uploader_preview">
											    {notempty name="'.$v.'"}
											     {php}$list=explode(",",'.$lists.');{/php}
												{foreach name="list" item="vo" }  
												<div class="upload-pre-item"> <img src="{$vo|get_cover_path}" data-id="{$vo}"/>
												   <span class="close"  onclick="delimage(this,"'.$name.'");"></span>
											 	</div>
												 {/foreach}	
												{/notempty} 
									   </div>
									 <script type="text/javascript">  
								             var field="'.$name.'";
						     	             uploads(field);
                                       </script>
							</div>',
    );
    return $type?$data[$type]:$data;
}

/**
 * 获取属性类型信息
 * @return string  
 */
function get_attribute_type($type=''){
    // TODO 可以加入系统配置
    static $_type = array(
        'num'       =>  array('数字','int(10) UNSIGNED NOT NULL'),
        'string'    =>  array('字符串','varchar(255) NOT NULL'),
        'textarea'  =>  array('文本框','text NOT NULL'),
        'date'      =>  array('日期','int(10) NOT NULL'),
        'datetime'  =>  array('时间','int(10) NOT NULL'),
        'bool'      =>  array('布尔','tinyint(2) NOT NULL'),
        'select'    =>  array('枚举','char(50) NOT NULL'),
        'radio'     =>  array('单选','char(10) NOT NULL'),
        'checkbox'  =>  array('多选','varchar(100) NOT NULL'),
        'editor'    =>  array('编辑器','text NOT NULL'),
        'picture'   =>  array('上传图片','int(10) UNSIGNED NOT NULL'),
        'file'      =>  array('上传附件','int(10) UNSIGNED NOT NULL'),
        'pictures'   =>  array('上传多图','varchar(255) NOT NULL'),
    );
    return $type?$_type[$type][0]:$_type;
}
/**
 * 模块的生成url
 * @param int $id   传入的模块id
 * @return string 
 */
function get_moude_url($id){
	 $map['id']=$id;
            // 查找当前子菜单
    $info =Db::name('Module')->where($map)->find();
	$url=$info["url"];
    switch ($url) {
        case 'http://' === substr($url, 0, 7):
        case '#' === substr($url, 0, 1):
            break;        
        default:
            $url =url($url,array('module_id'=>$id));
            break;
    }
    return  $url;
}
/**
 * excel导出
 * @param string $expTitle 导出保存的文件名称
 * @param array  $expCellName 单元格格式
 * @param object $expTableData 查询的数据
 */
function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName ="yershop".date('YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        //vendor("PHPExcel.PHPMailerAutoload");
		include(ROOT_PATH.'extend/PHPExcel.php');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
        } 
          // Miscellaneous glyphs, UTF-8   
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
          }             
        }  
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
        $objWriter->save('php://output'); 
        exit;   
    }
 /**
 * 分组的生成url	
 * @param int $id   传入的模块id
 * @return string 
 */
function get_group_url($id){
	 $where["id"]=$id; 
	 $info =Db::name('group')->where($where)->order("sort desc")->find();
	 if($info["url"]){
		 $map['url']=$info["url"];$url=$info["url"];   
	 }else{
	   $map['group_id']=$id; 
	   $map['pid']=array("gt",0);
	  }
	  unset($info);
            // 查找当前子菜单
     $data =Db::name('Module')->where($map)->order("sort desc")->find();
	 if($data){
	    $url=$data["url"];
	 } 
	
    switch ($url) {
        case 'http://' === substr($url, 0, 7):
        case '#' === substr($url, 0, 1):
            break;        
        default:
            $url =url($url,array('module_id'=>$data["id"],'group_id'=>$id));
            break;
    }
    return  $url;
}
 /**
 * 获取分组的函数	
 * @param int $id   传入的id
 * @param mixed $field  输出的字段 
 * @return string 
 */
function get_group($id,$field){
	 $map['id']=$id; 
     $info =Db::name('group')->field($field)->where($map)->find();
    return  $info[$field];
}
 /**
 * 获取模块的父id列表	
 * @param int $id   传入的id
 * @return object 
 */
function getModuleParent($id = 0){
	    $data= Db::name("module")->field("id,pid")->select();
		$arr = array( ); 
		$temp = array();
		   foreach ( $data as $key => $v ) {
		   //判断，如果$v['pid'] == $pid的则压入数组Child
		       if ($v['id'] == $id&&$v['pid']!=0) {
					//递归执行
					  $temp[] = $v['pid']; 
                      $temp = array_merge($temp,getModuleParent($v['pid'],$data));				
		       }
		   }
		return $temp;
	}

 function getHtmlList($data,$pid=0,$html="|——",$level=0){
        $temp = array();
        foreach ($data as $k => $v) {
            if($v['pid'] == $pid&&$level<2){
                $str = str_repeat($html, $level);
                $v['html'] = $str;
                $temp[] = $v;
                $temp = array_merge($temp,getHtmlList($data,$v['id'],'|——',$level+1));
            }
        }
        return $temp;
 }
 /**
 * 无限分类循环的html格式输出	
 * @param object $data  传入的数据对象
 * @param int $pid  传入的id
 * @param string $html  组合的html格式
 * @param int $level  循环的等级
 * @return string 
 */
 function getSort($data,$pid=0,$html="|——",$level=0){
        $temp = array();
		//$field="id,number,level,pid,username";
		/* 查询条件初始化 */
		//$data=M("UcenterMember")->where($condition)->field($field)->order("id asc")->select();
        foreach ($data as $k => $v) {
            if($v['pid'] == $pid){
                $str = str_repeat($html, $level);
                $v['html'] = $str;
                $temp[] = $v;
                $temp = array_merge($temp,getSort($data,$v['id'],'|——',$level+1));
            }
        }
        return $temp;
 }	
 /**
 * 分析枚举类型配置值 格式 a:名称1,b:名称2	
 * @param string $string  组合的字符串
 * @return string 
 */
function parse_config_attr($string) {
    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if(strpos($string,':')){
        $value  =   array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k]   = $v;
        }
    }else{
        $value  =   $array;
    }
    return $value;
}