<?php
/**
 * 获取配置的类型
 * @param string $type 配置类型
 * @return string
 */
function get_config_type($type = 0){$list = strtoarray(C('CONFIG_TYPE_LIST'));return $list[$type];}
/**
 * 获取配置的分组
 * @param string $group 配置分组
 * @return string
 */
function get_config_group($group = 0){$list = strtoarray(C('CONFIG_GROUP_LIST'));$list[0]='隐藏';return $list[$group];}
/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name){return "Addons\\{$name}\\{$name}Addon";}
/**
 * 自定义配置
 * @param $name 配置名称
 * @param $arr 配置数组
 */
function extentionconfig($arr='',$modname='Common',$configname='extention_config.php')
{
    $configfile=APP_PATH.$modname.'/Conf/'.$configname;
    $config_old=require($configfile);
	if(is_array($arr)) $config_new = $config_old?array_merge($config_old,$arr):$arr;
	arr2file($configfile,$config_new);
}
/**
 * 获取行为类型
 * @param intger $type 类型
 * @param bool $all 是否返回全部类型
 */
function get_action_type($type, $all = false){
	$list = array(1=>'系统',2=>'用户',3=>'店铺',);
	if($all){return $list;}
	return $list[$type];
}
/**
 * 获取行为数据
 * @param string $id 行为id
 * @param string $field 需要获取的字段
 */
function get_action($id = null, $field = null){
	if(empty($id) && !is_numeric($id)){return false;}
	$list = S('action_list');
	if(empty($list[$id])){
		$map = array('status'=>array('gt', -1), 'id'=>$id);
		$list[$id] = M('Action')->where($map)->field(true)->find();
	}
	return empty($field) ? $list[$id] : $list[$id][$field];
}
/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 */
function addons_url($url, $param = array()){
    $url        = parse_url($url);
    $case       = C('URL_CASE_INSENSITIVE');
    $addons     = $case ? parse_name($url['scheme']) : $url['scheme'];
    $controller = $case ? parse_name($url['host']) : $url['host'];
    $action     = trim($case ? strtolower($url['path']) : $url['path'], '/');    
    if(isset($url['query'])){parse_str($url['query'], $query);$param = array_merge($query, $param);}/* 解析URL带的参数 */
    $params = array('_addons'=> $addons,'_controller'=> $controller,'_action'=> $action,);/* 基础参数 */
    $params = array_merge($params, $param); //添加额外参数
    return U('Addons/execute', $params);
}
//排序
function orderurl($name,$field='',$type=''){
    if(empty($name) && empty($field))return false;
    if(empty($field))$field='id';
    $name=str_exists($name,'LAN_')?L(str_replace('LAN_','',$name)):$name;
    $param=array_filter(I('param.'));
    if(empty($param['_field']))$param['_field']='id';
    if($param['_field']==$field){$now_sort='1';}else {$now_sort='0';}
    if(!empty($param['id']) && $param['id']=='index')unset($param['id']);
    if(empty($param['_order']))$param['_order']='desc';
    if($param['_order']=='desc')$param['_order']='asc';
    else if($param['_order']=='asc')$param['_order']='desc';
    $param['_field']=$field;if($now_sort==0)$param['_order']='desc';
    $url= U(CONTROLLER_NAME.'/'.ACTION_NAME,$param);
    if($type)return $url;
    $str='<a href="'.$url.'" title="'.$name.'" class="order_'.$param['_order'].'">'.$name;
    $ordersort=I('param._order','desc');
    if($now_sort)$str.=$ordersort=='desc'?'<span class="glyphicon glyphicon-save"></span>':'<span class="glyphicon glyphicon-open"></span>';
    $str.='</a>';
    return $str;
}
/**
 * 记录审核日志
 * @param   int     $pro_id     商品/店铺/活动ID
 * @param   int     $type       类型：1商品2店铺3活动4店铺经营类目加入5店铺经营类目退出6店铺标签
 * @param   int     $status     1通过/2不通过
 * @param   string  $remark     备注
 */
function add_audit_log($pro_id, $type, $status, $remark)
{
    /*$data = array();
    $data['pro_id'] = $pro_id;
    $data['type'] = $type;
    $data['status'] = $status;
    $data['remark'] = $remark;
    $data['author'] = UID;
    $data['creat_time'] = NOW_TIME;
    M('AuditLog')->add($data);*/
}
/**
 * echarts 数组按时间格式化，填补时间中空值为0
 * @param  $array       所有需要格式化的数组
 * @param  $arraykey    所有需要格式化的键名
 */
function echarts_time_formarts($array,$arraykey){
    foreach($arraykey as $k1 => $v1){       //空值补零
        foreach($array as $k2 => $v2){
            if(empty($v2[$v1])){$array[$k2][$v1] =0;}
        }   
    }
    foreach($array as $k1 => $v1){ksort($array[$k1]);}          //按时间排序排序
    return $array;
}

/**
   *展示用户
   */
function showuser($uid){
    if(empty($uid))return false;
    // return '<a href="#" onclick="$.openUrl(\''.U('Admin/Member/view',array('id'=>$uid)).'\',\'查看会员\')">'.idtoname($uid,'Member','nickname;username')."(".$uid.")".'</a>';
	return '<span href="#">'.idtoname($uid,'Member','nickname;username;mobile')."(".$uid.")".'</span>';
}
// function show_user_name($uid){
    // if(empty($uid))return false;
	// return idtoname($uid,'Member','username;nickname');
// }
/**会员关怀发送
 * @param $id
 * @param int $page
 * @param int $pagesize
 * @param $data=array('type'=>发送类型，1即时发送2指定时间发送，'send_time'=>发送时间)
 * @return bool
 */
function send_care($id,$page=0,$pagesize=100,$data){
    if(!$id)return false;
    $map['id'] = $id;
    $info = M('MemberCare')->where($map)->find();
    $map = array();
    $map['name'] = 'FIXED_SIGNATURE';
    $sign = M('Config')->where($map)->getField('value');
    /*$smsclass = new \Common\Vendor\Sms('Hanchaosms');
    $ret =$smsclass->balance();//条数
    $sms_num = $ret['data'];*/
    if(empty($data) || empty($data['type'])){
        $return['status'] = 3;
        $return['msg'] = '参数错误';
        return $return;
    }
    if($data['type']==2 && empty($data['send_time'])){
        $return['status'] = 3;
        $return['msg'] = '参数错误';
        return $return;
    }
    if($info){
        $map=array();
        $map['id']=array('in',$info['uid']);
        $member_count= M('Member')->where($map)->count();
        if($data['type']==1){
           $res= member_send_care($info,$pagesize,$page);
            if($res['status']==3){
                $return['msg']=$res['msg'];
                return $return;
            }else{
                $return['status']=1;
                $return['count']=$res['count'];
            }
        }else{
            $m_care['id'] = $info['id'];
            $m_care['status'] = 0;
            $m_care['type'] = $data['type'];
            $m_care['send_time'] = $data['send_time'];
            $m_care['message_num'] = $member_count;
            M('MemberCare')->save($m_care);
            $return['id'] = $id;
            $return['count'] = $member_count;
            $return['page'] = $page+$pagesize;
            $jindu = $page/$pagesize/ceil($member_count/$pagesize)*100;
            $return['jindu'] = sprintf("%.2f",$jindu);
            return $return;
        }
    }
    return $return;
}
function member_send_care($info,$pagesize=0,$page=0){
    $return=array('status'=>1);
    if(empty($info)){$return['status']=3;$return['msg']='参数错误'; return $return;};
    $map = array();
    $map['name'] = 'FIXED_SIGNATURE';
    $sign = M('Config')->where($map)->getField('value');
    $map=array();
    $map['id']=$info['coupons_id'];
    $coupons = M('Coupons')->where($map)->field(true)->find();
    $map=array();
    $map['id']=array('in',$info['uid']);
    $member_count= M('Member')->where($map)->count();
    if($member_count>0){
        $member_list = M('Member')->where($map)->limit($page,$pagesize)->select();
        if($member_list){
            if($info['send_type']==1 || empty($info['send_type'])) {
                foreach ($member_list as $key => $val) {
                    account_change($val['id'], $info['points'], 4, 5, "会员关怀".$info['festival_name']."赠积分");
                    $u_name = idtoname($val['id'], 'Member', 'real_name;username;nickname;mobile');
                    $rep_arr = array('[关怀名称]' => $info['festival_name'], '[会员名称]' => $u_name, '[积分数量]' => Intval($info['points']));
                    $content = strtr($info['content'], $rep_arr);
                    if ($info['wx_message'] == 1) {
                        $code_data = array();
                        $code_data['to'] = $val['mobile'];
                        $code_data['user_name'] = $u_name;
                        $code_data['goods_name'] = "赠送积分".intval($info['points']);
                        $code_data['send_time'] = date('Y-m-d H:i:s', NOW_TIME);
                        $code_data['content'] = $content;
                        $code_data['remark'] = $content;
                        $code_data['wx_message'] = 1;
                        $add_data['type'] = 4;
                        sendbytheme($code_data, 'MEMBER_CARE');
                    }
                    if ($info['sms_message'] == 1) {
                        if (strpos($info['content'], '[') !== false) {
                            $content = $content . '【' . $sign . '】';
                        } else {
                            $content = $content . '退订回N' . '【' . $sign . '】';
                        }
                        $send_data=array();
                        $send_data['form'] = 1;
                        $send_data['title'] = '';
                        $send_data['content'] = $content;
                        $send_data['type'] = 1;
                        $send_data['is_yingxiao'] = 1;
                        $send_data['addtime'] = NOW_TIME;
                        $send_data['touid'] = $val['id'];
                        $send_data['to'] = $val['mobile'];
                        send_method(2, $send_data);
                    }
                }
                unset($key, $val);
            }
            if($info['send_type'] == 2){
                kaquan($info,$member_list);
            }
            $m_care['id'] = $info['id'];
            $m_care['status'] = 1;
            $m_care['type'] = 1;
            $m_care['send_time'] = NOW_TIME;
            $m_care['message_num'] = $member_count;
            M('MemberCare')->save($m_care);
            $return['count'] = 0;
            return $return;
        }
    }
}

function kaquan($info,$member_list){
	$map = array();
	$map['name'] = 'FIXED_SIGNATURE';
	$sign = M('Config')->where($map)->getField('value');
	$coupons = M('Coupons')->where('id='.$info['coupons_id'])->find();
	foreach($member_list as $key=>$val){
		$goods_name = idtoname($info['coupons_id'],'Coupons','title','id',false);
		$u_name = idtoname($val['id'],'Member','real_name;username;nickname;mobile');
		$rep_arr=array('[关怀名称]'=>$info['festival_name'],'[会员名称]'=>$u_name,'[优惠券名称]'=>$goods_name,'[积分数量]'=>Intval($info['points']));
		$content=strtr($info['content'],$rep_arr);
		if($info['wx_message'] == 1){
            $add_data=array();
            $add_data['first'] = '会员关怀';
            $add_data['to'] = $val['mobile'];
            if($val['username']){
                $add_data['user_name']=$val['username'];
            }elseif($val['nickname']){
                $add_data['user_name']=$val['nickname'];
            }else{
                $add_data['user_name']=$val['mobile'];
            }
            $add_data['goods_name']="优惠券".$goods_name;
            $add_data['send_time'] = date('Y-m-d H:i:s',NOW_TIME);
            $add_data['remark'] = $content;
            $add_data['type'] = 4;
            $add_data['content'] = $content;
            $url=U("Mobile/Index/coupons_give",array('id'=>$info['coupons_id'],'type'=>3),true,true);
            sendbytheme($add_data,"MEMBER_CARE",$url);
		}
		if($info['sms_message'] == 1){
            $send_data=array();
			$send_data['form'] = 1;
			$send_data['title'] = '';
			$send_data['content'] = $content;
			$send_data['type'] = 1;
			$send_data['is_yingxiao'] = 1;
			$send_data['addtime'] = NOW_TIME;
			$send_data['touid'] = $val['id'];
			$send_data['to'] = $val['mobile'];
			send_method(2,$send_data);
		}
	}unset($key,$val);
}	
 /** 
 * 查找供应商
 * @param  int  $storage_id   有仓库id就查这个仓库id的所有供货商，没有就查所有供货商；
 * @return array  $data   响应数据 
 */ 
function search_supplier($storage_id='')
{
	$storage_id=intval($storage_id);
    if (!empty($storage_id)) {
        $where = array();
        $where['storage_id'] = $storage_id;
        $Suppliers_id=M('StorageStock')->where($where)->getField('supplier_id',true);  
        if (!$Suppliers_id) {//该供货商没有查询到
            $data = '';
            return $data;
        }
        $map = array();
        $map['id']=array('in',$Suppliers_id);
    }
    $Suppliers=M('Suppliers')->cache(true)->field('id,name')->where($map)->order('name')->limit(50)->select();  
    if(empty($Suppliers)){
        $data = '';
        return $data;
    }
    $data = format_array2select($Suppliers,'name','id');
    return $data;
}    

    
/** 
 * 查找仓库
 * @param  int  $is_all   是否要全部仓库 0:获取权限的所有仓库 1:获取全部仓库
 * @return array  $data   响应数据 
 */ 
function search_storage($is_all=0)
{
    if (empty($is_all)) {
        $storage_ids = D('Admin/Storage') -> get_storage_ids(UID);//当前管理员的仓库ids
        if ($storage_ids['status'] == 0) {
            $data = '';
            return $data;
        }
        if ($storage_ids['data'] != 'all') {//不是超级管理员
            $map['id']=array('in',$storage_ids['data']);
        }
    }
    $Storage=M('Storage')->cache(true)->where($map)->field('id,name')->order('name')->limit(50)->select(); 
    if (empty($Storage)) {
        $data = '';
        return $data;
    } 
    $data = format_array2select($Storage,'name','id');
    return $data;
} 
/** 
 * 判断是否添加了第一个仓库
 */ 
function check_shop_num(){
	$map=array();
	$map['site_id'] = C('appid');
	$map['status'] = 1;
	$site_info = M('SiteInfo')->where($map)->field('uid,shop_max_num')->find();
	
	$map=array();
	$map['id'] = array('gt',0);
	$shop_num = M('Shops')->where($map)->count();
	if($site_info['shop_max_num'] > 0 && $shop_num == 0){
		$ret = D('App/ShopLogin')->addparentid($site_info['uid']);
		if($ret){
			$url = U('Shops/first_index');
			redirect($url);
			// $this->error('您还没添加仓库',$url);
		}
	}
}
/** 
 * 导入函数
 */ 
function input_csv($filename) {
	if(empty($filename))return false;
	$handle = fopen($filename, 'r');
	$out = array ();
	$n = 0;
	while ($data = fgetcsv($handle, 10000)) {
		$num = count($data);
		for ($i = 0; $i < $num; $i++) {
			$out[$n][$i] = $data[$i];
		}
		$n++;
	}
	return $out;
}
function quick_time($type){
    $map=array();
    $start_time = strtotime(date('Y-m-d',NOW_TIME)); 
    if($type == 1){
        $date_from=$start_time;
        $date_to =$start_time+86399;
        $map[] = $date_from;
        $map[] = $date_to;
    }elseif($type == 2){
        $date_from=$start_time-86400;
        $date_to =$start_time-1;
        $map[] = $date_from;
        $map[] = $date_to;
    }elseif($type == 7){
        $date_from=$start_time-6*86400;
        $date_to =$start_time+86399;
        $map[] = $date_from;
        $map[] = $date_to;
    }elseif($type == 14){
        $date_from=$start_time-23*86400;
        $date_to =$start_time+86399;
        $map[] = $date_from;
        $map[] = $date_to;
    }elseif($type == 30){
        $date_from=$start_time-29*86400;
        $date_to =$start_time+86399;
        $map[] = $date_from;
        $map[] = $date_to;
    }elseif($type == 60){
        $date_from=$start_time-59*86400;
        $date_to =$start_time+86399;
        $map[] = $date_from;
        $map[] = $date_to;
    }
    return $map;
}
?>