<?php
/**
 * 会员中心
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author lss <lss@qq.com>
 */

namespace Common\Model;
use Think\Model;
class MemberModel extends Model
{
    /**
     * 查询会员收藏的商品
     * @return array
     */
    public function get_collect_goods($map=array(),$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($p)?1:$p;
        $map['a.status']=1;
        $map['a.uid']=$memberinfo['id'];
        $field='g.*,a.*';
        $order="a.id desc";
        $join=" LEFT JOIN __GOODS__ g ON a.goods_id=g.id ";
        $collectgoods=page_list('GoodsCollect',$map,$order,$field,$pagesize,$join,$p);
        return $collectgoods;
    }
    /**
     * 查询会员收藏的店铺
     * @return array
     */
    public function get_collect_shops($map=array(),$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($p)?1:$p;
        $map['a.status']=1;
        $map['a.uid']=$memberinfo['id'];
        $field='s.*,a.*';
        $join=" LEFT JOIN __SHOPS__ s ON a.shop_id=s.id ";
        $collectshops=page_list('ShopsCollect',$map,$order,$field,$pagesize,$join,$p);
        foreach($collectshops['list'] as $key=>$val){
            $n_map['shop_id']=$val['shop_id'];
            $n_map['status']=1;
            $n_map['is_new']=1;
            $new_count=M('Goods')->where($n_map)->count('id');
            $collectshops['list'][$key]['new_count']=$new_count;
        }
        return $collectshops;
    }
    /**
       *删除收藏的类型
       *@param int $id 收藏的商品或是店铺ID
       *@param string $type 所要删除的是商品还是店铺
       *@return array
       */
    public function delete_collect($id,$type){
        $memberinfo=checkuserauthtype();
        if(empty($id)){
            $return['msg'] = '参数错误';
            $return['status']=0;
            return $return;
        }
        $map['id']=$id;
        $map['uid']=$memberinfo['id'];
        if($type=='goods'){
            $result=M('GoodsCollect')->where($map)->delete();
        }else if($type=='shops'){
            $result=M('ShopsCollect')->where($map)->delete();
        }
        if($result){
                $return['msg']='删除成功';
                $return['status']=1;
            }else{
                $return['msg']='删除失败';
                $return['status']=0;
            }
        return $return;
    }
    /**
       *修改会员信息，登录密码，支付密码，卡支付密码
       *@return array
       */
    public function user_infor($data=array()){
        $return['status']=0;
        $memberinfo=checkuserauthtype();
        $map['id']=$memberinfo['id'];
        $userinfo=M('Member')->where($map)->field(true)->find();
        if($data) $regular= new \Common\Vendor\Regular();
        if($data['infos']=='pwd') {
            if(!$regular->isEmpty($data['password']) || !$regular->isEmpty($data['newpassword'])){
                $return['msg']="必填项不能为空";
                 return $return;
             }
            $password=creatpwd($data['password'],'HANCHAO'.$userinfo['salt']);
            if ($password != $userinfo['password']){
                $return['msg']='旧密码输入错误';
                return $return;
            }
            if($data['newpassword'] == $data['password']){
                    $return['msg']='新密码和旧密码一样，请重新输入';
                    return $return;
             }
            if(!$regular->passWord(6,16,$data['newpassword'])){
                 $return['msg']='密码长度应为6-16位，可包含数字、字母、特殊符号';
                return $return;
            }
            if ($data['newpassword'] != $data['repassword']) {
                    $return['msg']='两次输入密码不一致';
                    return $return;
            }
            $savedata['password'] = creatpwd($data['newpassword'],'HANCHAO'.$userinfo['salt']);
        }else if($data['infos']=='paypwd'){
            $paypassword=creatpwd($data['paypassword'],'HANCHAO'.$userinfo['salt']);
            if ($paypassword != $userinfo['paypassword'] && !empty($data['paypassword'])){
                $return['msg']='旧密码输入错误';
                return $return;
            }
            if(empty($data['newpaypassword'])){
                $return['msg']="必填项不能为空";
                return $return;
            }
            /*if(!$regular->passWord(6,16,$data['newpaypassword'])){
                $return['msg']='密码长度应为6-16位，可包含数字、字母、特殊符号';
                return $return;
            }*/
            if(!preg_match("/^\d{6}$/",$data['newpaypassword'])){
                $return['msg']='支付密码必须为六位数字';
                return $return;
            }
            if($data['newpaypassword'] == $data['paypassword']){
                    $return['msg']='新密码和旧密码一样，请重新输入';
                    return $return;
            }
            if ($data['newpaypassword'] != $data['repaypassword']) {
                $return['msg']='两次输入密码不一致';
                return $return;
            }
            if(empty($userinfo['salt'])){$userinfo['salt']=randStr();}
            $savedata['paypassword'] = creatpwd($data['newpaypassword'],'HANCHAO'.$userinfo['salt']);
            $savedata['salt'] = $userinfo['salt'];
        }else if($data['infos']=='card_paypwd'){
			$paypassword=creatpwd($data['card_paypass'],'HANCHAO'.$userinfo['salt']);
            if ($paypassword != $userinfo['card_paypass'] && !empty($data['card_paypass'])){
                $return['msg']='旧密码输入错误';
                return $return;
            }
            if(empty($data['newpaypassword'])){
                $return['msg']="必填项不能为空";
                return $return;
            }
            if(!$regular->passWord(6,16,$data['newpaypassword'])){
                $return['msg']='密码长度应为6-16位，可包含数字、字母、特殊符号';
                return $return;
            }
            if($data['newpaypassword'] == $data['card_paypass']){
                    $return['msg']='新密码和旧密码一样，请重新输入';
                    return $return;
            }
            if ($data['newpaypassword'] != $data['repaypassword']) {
                $return['msg']='两次输入密码不一致';
                return $return;
            }
            $savedata['card_paypass'] = creatpwd($data['newpaypassword'],'HANCHAO'.$userinfo['salt']);
		}else if($data['infos']=='user'){
            /*if(!$regular->isEmpty($data['nickname'])){
                $return['msg']='昵称不能为空';
                return $return;
            }
            if(!$regular->isEmpty($data['username'])){
                $return['msg']='会员名不能为空';
                return $return;
            }
            if($data['username']){
                $where['id']=array('neq',$memberinfo['id']);
                $where['username']=$data['username'];
                $count=M('Member')->where($where)->count('id');
                if($count>0){
                    $return['msg']='会员名已存在，请更换会员名';
                    return $return;
                }
            }*/
            // echo "<pre>";print_r($data);exit;
            if(!empty($data['email']) && !$regular->isEmail($data['email'])){
                $return['msg']='邮箱格式不正确';
                return $return;
            }
            $con_where = array();
            $con_where['name'] = 'MEMBERATTRIBUTE';
            $con_have = M("Config")->where($con_where)->field("id,name,value")->find();
            if($con_have){
                $con_data = unserialize($con_have['value']);
                if($con_data['real_name']['is_member']){
                    if(empty($data['real_name'])){
                        $return['msg']='真实姓名不能为空';
                        return $return;
                    }
                }
                if($con_data['birthday']['is_member']){
                    if(empty($data['birthday'])){
                        $return['msg']='生日不能为空';
                        return $return;
                    }
                }
                if($con_data['sex']['is_member']){
                    if(empty($data['sex'])){
                        $return['msg']='性别不能为空';
                        return $return;
                    }
                }
                if($con_data['address']['is_member']){
                    if(empty($data['province'])){
                        $return['msg']='请选择地区';
                        return $return;
                    }
                }
            }
            // echo "<pre>";print_r($data);exit;
            if($data['name']){
                $where = $data_con = $map_con = array();
                $map_con['name'] = 'ATTRIBUTE';
                $c_have = M("Config")->where($map_con)->getField("value");
                $c_list = json_decode($c_have,true);
                
                $where['uid'] = $memberinfo['id'];
                foreach ($data['name'] as $key => $value) {
                    if($value){
                        $where['aid'] = $key;
                        $have = M("MemberAttribute")->where($where)->count();
                        $value = ltrim($value, ",");
                        if($c_list[$key]['type'] == 'date'){
                            $value = strtotime($value);
                        }
                        if($have){
                            $save_data = array();
                            $save_data['content'] = $value;
                            M("MemberAttribute")->where($where)->save($save_data);
                        }else{
                            $add_data = array();
                            $add_data['uid'] = $memberinfo['id'];
                            $add_data['aid'] = $key;
                            $add_data['content'] = $value;
                            M("MemberAttribute")->add($add_data);
                        }
                        // if($c_list[$key]['type'] == 'date'){
                        //     $value = date('Y-m-d',$value);
                        // }
                        // $data_con[] = array('id'=>$key,'name'=>$value);
                    }
                }unset($key,$value);
            }
            unset($data['name']);
            $savedata=$data;
            $savedata['updatetime']=NOW_TIME;
        }else if($data['infos']=='member_user'){ // zjn 1-30 会员信息修改
            if(!$regular->isEmpty($data['username'])){
                $return['msg']='会员名不能为空';
                return $return;
            }
            if($data['username']){
                $where['id']=array('neq',$memberinfo['id']);
                $where['username']=$data['username'];
                $count=M('Member')->where($where)->count('id');
                if($count>0){
                    $return['msg']='会员名已存在，请更换会员名';
                    return $return;
                }
            }
            if(!empty($data['email']) && !$regular->isEmail($data['email'])){
                $return['msg']='邮箱格式不正确';
                return $return;
            }
            $savedata=$data;
            $savedata['updatetime']=NOW_TIME;
        }
		
        $result=M('Member')->where($map)->save($savedata);
        if($result) {
            if($data['infos']=='pwd'){
                $data=D('Common/Login')->logout();
                $return['url']=$data['url'];
                $return['msg']='修改成功，请重新登录';
            }else{
                $return['url']=getjumpurl('JUMP_4');
                $return['msg']='修改成功';
            }
            $return['status']=1;
        } else {
            $return['msg']='修改失败';
        }
        return $return;
    }
    /**
      *会员地址列表
      *@return array
      */
    public function get_address_list($map=array(),$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        $map['uid']=$memberinfo['id'];
        $order='id desc';
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($p)?1:$p;
        $address_list=page_list('MemberAddress',$map,$order,true,$pagesize,'',$p);
        foreach($address_list['list'] as $key=>$val){
            $address_list['list'][$key]=$this->format_address_item($val);
        }
        return $address_list;
    }
    /**
      *获取会员地址
      */
    public function address_cont($id){
        $memberinfo=checkuserauthtype();
        $map['uid']=$memberinfo['id'];
        $map['id']=$id;
        $address=M('MemberAddress')->where($map)->field(true)->find();
        $address=$this->format_address_item($address);
        return $address;
    }
    /**
     * 格式化地址数据
     * @param array $data
     * @return array
     */
    public function format_address_item($data=array()){
        $result=$data;
        $result['username']=idtoname($data['uid'],"Member",'username');
        $regions['province']=idtoname($data['province'],"Area",'name');
        $regions['city']=idtoname($data['city'],"Area",'name');
        $regions['district']=idtoname($data['district'],"Area",'name');
        $result['region']=$regions['province'].$regions['city'].$regions['district'];
        $result['best_time']=time_format($data['best_time'],'Y-m-d');
        $result['updatetime']=time_format($data['updatetime'],'Y-m-d');
        return $result;
    }
    /**
      *修改配送地址
      * @param array $param
      * @param array $param['changetype'] == 1 只修改默认状态
      * @return array
      */
    public function modify_address($param=array()){
        $id = intval($param['id']);
        $memberinfo=checkuserauthtype();
        $return['status'] = 0;
        $num=C('MEMBER_RECRIVE_ADDRESS_NUM');
        if(!isset($param['changetype'])){
            if($param) $regular= new \Common\Vendor\Regular();
            if(!$regular->isEmpty($param['consignee'])){
                $return['msg']='收件人不能为空';
                return $return;
            }
            if(!$regular->isEmpty($param['province']) || !$regular->isEmpty($param['city_id']) || !$regular->isEmpty($param['district'])){
                $return['msg'] = '请填写完整的所在地区';
                return $return;
            }
            if(!$regular->isEmpty($param['address'])){
                $return['msg'] = '请填写完整的收货地址';
                return $return;
            }
            if(!$regular->isEmpty($param['mobile'])){
                $return['msg'] = '手机号不能为空';
                return $return;
            }
            if(!$regular->isPhone($param['mobile'])){
                $return['msg']='手机号格式不正确';
                return $return;
            }
            if(!$regular->isTel($param['tel']) && $regular->isEmpty($param['tel'])){
                $return['msg']='固定电话格式不正确';
                return $return;
            }
            if(!$regular->isEmpty($param['house_no'])){
                $return['msg']='门牌号不能为空';
                return $return;
            }
        }
        $data = $param;
        if(!empty($param['city_id']))$data['city']=$param['city_id'];
        $data['updatetime']=NOW_TIME;
        if($param['status']==1){
            $d_map['uid']=$memberinfo['id'];
            $d_data['status']=0;
            $d_id=M('MemberAddress')->where($d_map)->save($d_data);
        }
        if($id>0){
            $map['id'] = $id;
            if($param['status']==0 || empty($param['status'])){
                $data['status']=0;
            }
            $result = M('MemberAddress')->where($map)->save($data);
            $return['address_id'] = $id;
        }else{
            $where['uid']=$memberinfo['id'];
            $count=M('MemberAddress')->where($where)->count();
            if($count<$num){
                unset($data['id']);
                $data['uid'] = $memberinfo['id'];
                $result = M('MemberAddress')->add($data);
                $return['address_id'] = $result;
            }else{
                $return['msg']='收货地址最多为'.$num.'个';
                return $return;
            }
        }
        if($result){
            $jump=session('jump');
            if($jump==1 || $jump==2){
                $m_map['id'] = $return['address_id'];
            }else{
                $m_map['status'] = 1;
            }
            $m_map['uid'] = $memberinfo['id'];
            $ma_info = M('MemberAddress')->where($m_map)->field('xpoint,ypoint,address,city,province,district')->find();
            if($ma_info){
                $siteinfo['province'] = $ma_info['province'];
                $siteinfo['city_id'] = $ma_info['city'];
                $siteinfo['district'] = $ma_info['district'];
                $siteinfo['temp_lng'] = $ma_info['xpoint'];
                $siteinfo['temp_lat'] = $ma_info['ypoint'];
                $siteinfo['temp_name'] = $ma_info['address'];
                $siteinfo['city'] = idtoname($ma_info['city'],"Area","name");
                session('siteinfo',$siteinfo);
                cookie('siteinfo',$siteinfo);
                session('loc',1);

                $shop_id=get_wxsmall_shop_id();
                $upshop=true;
                $IS_LOCK_USER= C('IS_LOCK_USER');
                if($shop_id && empty($IS_LOCK_USER)){//检测当前店铺是否满足当前情况
                    $distribution_area=D('Wxsmall/Login')->judge_shop($ma_info['xpoint'],$ma_info['ypoint'],$shop_id);
                    if($distribution_area['status']!=3){$upshop=false;}
                }
                if($upshop && empty($IS_LOCK_USER)){
                    save_session();
                    $shop_id=get_wxsmall_shop_id();
                }

                $distribution_area=D('Wxsmall/Login')->judge_shop($ma_info['xpoint'],$ma_info['ypoint'],$shop_id);

                if($distribution_area['status']==3){
                    $return['order_status']=0;
                }else{
                    $return['order_status']=1;
                }
            }else{
                $siteinfo['temp_lng'] = '';
                $siteinfo['temp_lat'] = '';
                $siteinfo['temp_name'] = '';
                $siteinfo['city'] = '';
                session('siteinfo',$siteinfo);
                cookie('siteinfo',$siteinfo);
                $return['order_status']=0;
            }
            $return['status'] = 1;
            $return['msg'] = '操作成功';
            $return['url']=getjumpurl('JUMP_6');
        }else{
            $return['status'] = 0;
            $return['msg'] = '操作失败';
        }
        return $return;
     }
     public function delete_address($id){
        $return['status']=0;
        if(empty($id)){
            $return['msg'] = '参数错误';
            return $return;
        }
        $memberinfo=checkuserauthtype();
        $map['id']=$id;
        $map['uid']=$memberinfo['id'];
        $result=M('MemberAddress')->where($map)->delete();
        if($result){
                $m_map['uid'] = $memberinfo['id'];;
                $m_map['status'] = 1;
                $ma_info = M('MemberAddress')->where($m_map)->field('xpoint,ypoint,address,city')->find();
                if($ma_info){
                    $siteinfo['temp_lng'] = $ma_info['xpoint'];
                    $siteinfo['temp_lat'] = $ma_info['ypoint'];
                    $siteinfo['temp_name'] = $ma_info['address'];
                    $siteinfo['city'] = idtoname($ma_info['city'],'Area','name');
                    session('siteinfo',$siteinfo);
                    cookie('siteinfo',$siteinfo);
                }else{
                   $siteinfo['temp_lng'] = '';
                    $siteinfo['temp_lat'] = '';
                    $siteinfo['temp_name'] = '';
                    $siteinfo['city'] = '';
                    session('siteinfo',$siteinfo);
                    cookie('siteinfo',$siteinfo); 
                }
                $return['msg']='删除成功';
                $return['status']=1;
            }else{
                $return['msg']='删除失败';
            }
        return $return;
     }
     /**
        *推广分成
        */
     public function my_extension($postdata=array()){
        $memberinfo=checkuserauthtype();
        $map = array();
        $map['id'] = $memberinfo['id'];
        $comm_money = M('Member')->where($map)->getField('comm_money');
        if($comm_money){
            $data['comm_money'] = $comm_money;   
        }else{ 
            $data['comm_money'] = '0.00';          
        }
        $map = array();
        //推广列表
         if($postdata['uid']){
             $map['uid']=$postdata['uid'];
         }else {
             $map['uid'] = $memberinfo['id'];
         }
        if(!empty($postdata['order_sn'])){
            $where['order_sn']=$postdata['order_sn'];
            $order_id=M('OrderInfo')->where($where)->getField('id');
            $map['order_id']=$order_id;
        }
        $order='id desc';
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($postdata['page'])?1:$postdata['page'];
        $my_extension=page_list('AffiliateLog',$map,$order,true,$pagesize,'',$p);
        foreach ($my_extension['list'] as $key => $val) {
            $my_extension['list'][$key]=$this->format_extension_item($val);
        }
		if($my_extension['count'] > $pagesize*$p){
            $data['show'] = 1;
        }else{
            $data['show'] = 0;
        }
        $data['extension_list']=$my_extension;
        return $data;
     }
     public function extension_list($postdata=array()){
        $memberinfo=checkuserauthtype();        
        $map = array();
        if(!empty($postdata['parent_id'])){
            $where_m['id'] = $postdata['parent_id'];
            $m_list = M('Member')->where($where_m)->field('id')->select();
            if (!empty($m_list)) {
                foreach ($m_list as $k => $v) {
                    $me_list[] = $v['id'];
                }
                $map['parent_id'] = array(array('in', $me_list));
            }
        }else{
            if($postdata['uid']){
                $map['parent_id']=$postdata['uid'];
            }else {
                $map['parent_id'] = $memberinfo['id'];
            }
        }
        $order='id desc';
        $pagesize=empty($pagesize)?C('WEB_DEFAULT_PAGE'):$pagesize;;
        $p=empty($postdata['page'])?1:$postdata['page'];
        $extension_list = page_list('Member',$map,$order,true,$pagesize,'',$p);
		if($extension_list['count'] > $pagesize*$p){
            $data['show'] = 1;
        }else{
            $data['show'] = 0;
        }
        $data['extension_list']=$extension_list;
        return $data;
     }
     public function extension(){
        $memberinfo=checkuserauthtype();
        $data['uid']=$memberinfo['id'];
        //推广列表
        $map['uid']=$memberinfo['id'];
        //返利总数
        $sum_separate=M('AffiliateLog')->where($map)->sum('money');
        $data['sum_separate']=$sum_separate;
        //$uid=base64_encode($memberinfo['id']);
        //推广链接
        $extensionurl=U('Home/Login/register',array('eid'=>$memberinfo['id']),true,true);
        $extension_mobileurl=U('Mobile/Login/register',array('eid'=>$memberinfo['id']),true,true);
        $data['extensionurl']=$extensionurl;
        $data['extension_mobileurl']=$extension_mobileurl;
        //推广二维码
        $url = U('Mobile/Login/register',array('eid'=>$memberinfo['id']),true,true);
        $data['img_url'] = U('Home/Qrcode/index',array('data'=>urlencode($url)));
        return $data;
     }
     public function format_extension_item($data=array()){
        $result=$data;
        $order_info=idtoname($data['order_id'],"OrderInfo",'order_sn,pay_code,goods_amount,uid');
        $result['order_sn']=$order_info['order_sn'];
        $result['pay_code']=$order_info['pay_code'];
        $result['goods_amount']=$order_info['goods_amount'];
        $result['addtime']=time_format($data['addtime'],'Y-m-d');
        $result['extensionname']=show_user_name($order_info['uid']);
        $result['extensionid']=$order_info['uid'];
        if($data['is_separate']==0) {
            $result['is_separate']='未分成';
        }elseif ($data['is_separate']==1) {
            $result['is_separate']='已分成';
        }else{
            $result['is_separate']='取消分成';
        }
        $result['username']=show_user_name($data['uid']);
        return $result;
     }
     /**
       *积分明细
       */
     public function integral($data=array(),$type=4,$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        $map['id']=$memberinfo['id'];
        $points=M('Member')->where($map)->field('points,usepoints')->find();
        $allpoints=$points['points']+$points['usepoints'];
        $return['allpoints']=format_decimal($allpoints,2);
        if(!empty($data['keyword']))$where['change_desc']=array('like','%'.$data['keyword'].'%');
        if(!empty($data['from_time']))$where['change_time'][]=array('EGT',strtotime($data['from_time']));
        if(!empty($data['to_time']))$where['change_time'][]=array('ELT',strtotime($data['to_time']));
        if(!empty($data['status'])){
            $where['status']=$data['status'];
        }else{
            $where['status']=array('gt',0);
        }
        $where['uid']=$memberinfo['id'];
        if($type==4){
            $usepoints=M('Member')->where($map)->getField('usepoints');
            $return['allpoints']=format_decimal($usepoints,2);
        }else{
            $points=M('Member')->where($map)->getField('points');
            $return['allpoints']=format_decimal($points,2);
        }
        $where['type']=$type;
        $order='id desc';
        $pagesize=empty($pagesize)?C('WEB_DEFAULT_PAGE'):$pagesize;
        $p=empty($data['page'])?1:$data['page'];
        $points_details=page_list('AccountLog',$where,$order,true,$pagesize,'',$p);
        foreach($points_details['list'] as $key=>$val){
            $points_details['list'][$key]=$this->format_integral_item($val);
        }
        if($points_details['count'] > $pagesize*$p){
            $return['show'] = 1;
        }else{
            $return['show'] = 0;
        }
        $return['points_details']=$points_details;
        return $return;
     }
     /**
        *格式化积分
        */
     public function format_integral_item($data=array()){
        $result=$data;
        if($data['change_type']==0){$result['change_type']='+';}else{$result['change_type']='-';}
        return $result;
     }
     /**
        *红包列表
        */
     public function redPacket($type,$postdata=array(),$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        $order='id desc';
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($postdata['page'])?1:$postdata['page'];
        $map['user_id']=$memberinfo['id'];
        $map['used_time']=0;
        if($type==1){
            $map['end_time']=array('gt',NOW_TIME);
        }elseif ($type==2) {
            $map['used_time']=array('gt',0);
        }else{
            $map['end_time']=array('lt',NOW_TIME);
        }
        $bonu_list=page_list('MemberBonus',$map,$order,true,$pagesize,'',$p);
        $n_where['used_time']=0;
        $n_where['user_id']=$memberinfo['id'];
        $n_where['end_time']=array('gt',NOW_TIME);
        $bonu_list['n_count']=M('MemberBonus')->where($n_where)->count('id');
        $u_where['used_time']=array('gt',0);
        $u_where['user_id']=$memberinfo['id'];
        $bonu_list['u_count']=M('MemberBonus')->where($u_where)->count('id');
        $o_where['user_id']=$memberinfo['id'];
        $o_where['end_time']=array('lt',NOW_TIME);
         $o_where['used_time']=0;
        $bonu_list['o_count']=M('MemberBonus')->where($o_where)->count('id');
        return $bonu_list;
     }                                                                                                                     
     public function delete_redPacket($id){
        $memberinfo=checkuserauthtype();
        $return['status']=0;
        if(empty($id)){
            $return['msg'] = '参数错误';
            return $return;
        }
        $map['id']=$id;
        $map['uid']=$memberinfo['id'];
        $result=M('MemberBonus')->where($map)->delete();
        if($result){
            $return['msg']='删除成功';
            $return['status']=1;
        }else{
            $return['msg']='删除失败';
        }
        return $return;
     }
     /**
       *提交投诉、咨询
       *@param array
       *@return array
       */
     public function submit_service($postdata=array()){
        $return['status']=0;
        if(empty($postdata['content'])){
            $return['msg']='请输入内容，以便我们及时解决您的问题';
            return $return;
        }        
        $adddata=$postdata;
        $adddata['type']=$postdata['type'];
        $adddata['goods_id']=$postdata['goods_id'];
        $adddata['order_id']=$postdata['order_id'];
        if($postdata['sid'])$adddata['shop_id']=$postdata['sid'];
        if($postdata['uid'])$adddata['uid']=$postdata['uid'];
        $adddata['addtime']=NOW_TIME;
        $adddata['status']=0;
        $adddata['is_delete']=0;
        $return['adddata']=$adddata;
        $result=M('Service')->add($adddata);
        if($result){
            $return['status'] = 1;
            $return['msg'] = '提交成功';
            if($postdata['type']==1){
                $return['url']=U('Member/CustomerService/complaint_list');
            }else{
                $return['mobile_url']=U('Mobile/Member/index');
                $return['url']=U('Member/CustomerService/platform_service');
            }
        }else{
            $return['status'] = 0;
            $return['msg'] = '提交失败';
        }
        return $return;
     }
     /**
        *咨询，投诉列表
        */
     public function service_list($postdata=array(),$type,$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        $map['uid']=$memberinfo['id'];
        $map['type']=$type;
        $map['is_delete']=0;
        if(!empty($postdata)){
            if($postdata['status']==1){
                $map['status']=0;
            }elseif($postdata['status']==2){
                $map['status']=1;
            }elseif($postdata['status']==3){
                $map['status']=2;
            }
        }
        $order='id desc';
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($p)?1:$p;
        $list=page_list('Service',$map,$order,true,$pagesize,'',$p);
        foreach ($list['list'] as $key => $val) {
            $list['list'][$key]=$this->format_service_item($val);
        }
        return $list;
     }
     public function service_cont($id){
        $memberinfo=checkuserauthtype();
        $map['uid']=$memberinfo['id'];
        $map['id']=$id;
        $data=M('Service')->where($map)->field(true)->find();
        $list=$this->format_service_item($data);
        return $list;
     }
     /**
        *取消咨询、投诉
        */
     public function cancel_service($id){
        $return['status']=0;
        $memberinfo=checkuserauthtype();
        if(empty($id)){
            $return['msg']='参数错误';
            return $return;
        }
        $map['id']=$id;
        $map['uid']=$memberinfo['id'];
        $savedata['status']=2;
        $result=M('Service')->where($map)->save($savedata);
        if($result){
            $return['msg']='取消成功';
            $return['status']=1;
        }else{
            $return['msg']='取消失败';
        }
        return $return;
     }
     /**
        *删除咨询、投诉
        */
     public function del_service($id){
        $return['status']=0;
        $memberinfo=checkuserauthtype();
        if(empty($id)){
            $return['msg']='参数错误';
            return $return;
        }
        $map['id']=$id;
        $map['uid']=$memberinfo['id'];
        $savedata['is_delete']=1;
        $result=M('Service')->where($map)->save($savedata);
        if($result){
            $return['msg']='删除成功';
            $return['status']=1;
        }else{
            $return['msg']='删除失败';
        }
        return $return;
     }
     /**
       *格式化投诉、咨询数据
       */
     public function format_service_item($data=array()){
        $result=$data;
        if($data['type']==1) {
            $result['type_name']='投诉';
        }elseif ($data['type']==2) {
            $result['type_name']='商品咨询';
        }else{
            $result['type_name']='订单咨询';
        }
        $result['goods_name']=idtoname($data['goods_id'],"Goods",'goods_name');
        $shop_id=idtoname($data['goods_id'],"Goods",'shop_id');
        $result['shop_name']=idtoname($shop_id,"Shops",'name');
        $result['addtime']=time_format($data['addtime'],'Y-m-d');
        $result['updatetime']=time_format($data['updatetime'],'Y-m-d');
        if($data['status']==0){
            $result['status_name']='进行中';
        }elseif($data['status']==1){
            $result['status_name']='已完成';
        }else{
            $result['status_name']='已取消';
        }
        return $result;
     }
	 //会员卡的基本信息
	 public function member_card($arr){
		$data['card'] = C('CARD_BACKGROUND');
		$data['card_logo'] = C('CARD_LOGO');
		$data['card_name'] = C('CARD_NAME');
		$data['card_sn'] = $arr['card_sn'];
		return $data;
	 }
	 /**
       *套餐记录
       */
     public function package_hxlist($data=array(),$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        // $map['id']=$memberinfo['id'];
        // $points=M('Member')->where($map)->field('points,usepoints')->find();
        // $allpoints=$points['points']+$points['usepoints'];
        // $return['allpoints']=format_decimal($allpoints,2);
        if(!empty($data['keyword']))$where['change_desc']=array('like','%'.$data['keyword'].'%');
        if(!empty($data['from_time']))$where['change_time'][]=array('EGT',strtotime($data['from_time']));
        if(!empty($data['to_time']))$where['change_time'][]=array('ELT',strtotime($data['to_time']));
        
        $where['uid']=$memberinfo['id'];
        // if($type==4){
            // $usepoints=M('Member')->where($map)->getField('usepoints');
            // $return['allpoints']=format_decimal($usepoints,2);
        // }else{
            // $points=M('Member')->where($map)->getField('points');
            // $return['allpoints']=format_decimal($points,2);
        // }
        // $where['type']=$type;
        $order='id desc';
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($data['page'])?1:$data['page'];
        $packages_details=page_list('PackageHx',$where,$order,true,$pagesize,'',$p);
        // foreach($points_details['list'] as $key=>$val){
            // $points_details['list'][$key]=$this->format_integral_item($val);
        // }
        $return['packages_details']=$packages_details;
        return $return;
     }

    /**获取奖品列表
     * @param array $map
     * @param string $join
     * @param string $order
     * @param int $p
     * @param int $pagesize
     */
    public function get_win_gift_list($map=array(),$join='',$order='',$p=1,$pagesize=0){
        $memberinfo=checkuserauthtype();
        $pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
        $p=empty($p)?1:$p;
        $map['user_id']=$memberinfo['id'];
        $gift_list=page_list('WinGift',$map,$order,true,$pagesize,$join,$p);
        if($gift_list['list']){
            foreach($gift_list['list'] as $key=>$val){
                $l_map=array();
                $l_map['id']=$val['location_id'];
                $gift_list['list'][$key]['location_name']=M("Shops")->where($l_map)->getField('name');
                $g_map=array();
                $g_map['id']=$val['gift_id'];
                $goods_info=M("Goods")->where($g_map)->field('goods_name,img')->find();
                $gift_list['list'][$key]['goods_name']=$goods_info['goods_name'];
                $gift_list['list'][$key]['img']=$goods_info['img'];
                $gift_list['list'][$key]['check_time']=time_format($val['check_time']);
                $order_map=array();
                $order_map['order_id']=$val['order_id'];
                $order_info=M("OrderGoods")->where($order_map)->field('goods_price,goods_integral')->find();
                $gift_list['list'][$key]['shop_price']=$order_info['goods_price'];
                $gift_list['list'][$key]['goods_integral']=$order_info['goods_integral'];
            }
        }
        return $gift_list;
    }
	public function set_sn_code($postdata){
		$return = array();$return['status'] = 0;
		if(!$postdata ['gift_id']){
			$return['info'] = '谢谢参与，恭喜下次中奖！';
			return $return;
		}
		$data ['sn_number'] = createOrderNo();
		$data ['order_id'] = $postdata['order_id'];
		$data ['gift_id'] = $postdata['gift_id'];
		$prize_type = M('Prize')->where('id='.$postdata['gift_id'])->getField('prize_type');
		if($prize_type != 1 && $prize_type != 4){
			$data ['gift_type'] = 1;
		}
		$data ['win_type'] = 2;
		$data ['user_id'] = $postdata['uid'];
		$data ['check_time'] = 0;
		$data ['check_status'] = 0;
		$data ['add_time'] = NOW_TIME;
		$data ['gift_number'] = 1;
        if(empty($data ['gift_id'])){
			$return['info'] = '谢谢参与，恭喜下次中奖！';
			return $return;
		}
		$title = '';
		$map['id'] = $data ['gift_id'];
		if (! empty ( $map ['id'] )) {
			$title = M ( 'Prize' )->where ( $map )->getField ( 'prize_goods' );
			$title || $title = '';
		}
		// $data ['prize_title'] = $title;
		$w_map = array();$w_map['order_id'] = $data ['order_id'];
		// $w_map['user_id'] = $postdata['uid'];
		$count = M('WinGift')->where($w_map)->count();
		if($count == 0){
			M ('WinGift')->add ( $data );
			
			if($data ['gift_type'] == 1){
				$return = $this->go_prize($postdata['order_id'],$postdata['uid']);
				return $return;
			}else{
				if($prize_type == 4){
					$return = $this->q_prize_type($data['order_id'],$data['user_id']);
				}else{
					$return['status'] = 1;
					$return['info'] = '抽取成功，请在抽奖记录中查看！';
				}
				return $return;
			}
		}else{
			$return['status'] = 2;
			$return['info'] = '您已经抽过礼品了，不能再次抽奖，请在抽奖记录中查看！';
			return $return;
		}
	}
	public function q_prize_type($order_id,$uid) {
		$return['status'] = 0;
		
		$map = array();
		$map['order_id'] = $order_id;
		$map['user_id'] = $uid;
		$map['win_type'] = 2;
		$map['check_status'] = 0;
		$info = M('WinGift')->where($map)->field('id,gift_id')->find();
		if($info){
			$prize_info = M('Prize')->where('id='.$info['gift_id'])->field('prize_type,prize_goods')->find();
			if(!$prize_info){
				$return['status'] = 2;
				$return['info'] = '奖品出错';
				return $return;
			}
			$c_map = array();$c_map['id'] = $prize_info['prize_goods'];
			$c_map['quantity'] = array('gt',0);$c_map['status'] = 1;
			$coupons = M('Coupons')->where($c_map)->field(true)->find();
			
			if($prize_info['prize_type'] == 4 && $coupons){
				$add_data = array();
				$map=array();$map['id']=$uid;
				$member_info=M("Member")->where($map)->field('mobile,username,nickname')->find();
				$add_data['to']=$member_info['mobile'];
				if($member_info['username']){
					$add_data['user_name']=$member_info['username'];
				}elseif($member_info['nickname']){
					$add_data['user_name']=$member_info['nickname'];
				}else{
					$add_data['user_name']=$member_info['mobile'];
				}
				$add_data['first'] = '小票抽奖赠券';
				$add_data['goods_name']=$coupons['title'];
				$add_data['send_time'] = date('Y-m-d H:i:s',NOW_TIME);
				$add_data['remark'] = "尊敬的会员，您获得一张卡券，请及时领取";
				$add_data['type'] = 4;
				$add_data['content'] = "请领取卡券";
				$url=U("Mobile/Index/coupons_give",array('id'=>$coupons['id'],'type'=>2,'order_id'=>$order_id),true,true);
				sendbytheme($add_data,"MEMBER_CARE",$url);
				
				$return['status'] = 1;
				$return['info'] = '抽取成功，您获得一张卡券，请及时领取！';
			}else{
				$return['status'] = 2;
				$return['info'] = '优惠券已领完，欢迎下次再来！';
			}
			return $return;
		}
	}
	public function go_prize($order_id,$uid) {
		$return['status'] = 0;
		
		$map = array();
		$map['order_id'] = $order_id;
		$map['user_id'] = $uid;
		$map['win_type'] = 2;
		$map['check_status'] = 0;
		$info = M('WinGift')->where($map)->field('id,gift_id')->find();
		if($info){
			$prize_info = M('Prize')->where('id='.$info['gift_id'])->field('prize_type,prize_goods')->find();
			if(!$prize_info){
				$return['status'] = 2;
				$return['info'] = '奖品出错';
				return $return;
			}
			if($prize_info['prize_type'] == 2){
				account_change($uid,$prize_info['prize_goods'],1,14,'小票抽奖');
			}
			if($prize_info['prize_type'] == 3){
				account_change($uid,$prize_info['prize_goods'],4,14,'小票抽奖');
			}
			$return['status'] = 1;
			$return['info'] = '领取成功，请在抽奖记录中查看！';
			$save['id'] = $info['id'];
			$save['check_status'] = 1;
			$save['check_time'] = NOW_TIME;
			M('WinGift')->save($save);
			M('Prize')->where('id='.$info['gift_id'])->setDec('goods_num',1);
		}else{
			$return['status'] = 2;
			$return['info'] = '无礼品领取';
		}
		return $return;
	}
	//修改win_gift状态（$is_type(1:order_id,2:w_id)）
	public function change_win_gift($order_id,$uid,$is_type){
		$return = array();$return['status'] = 0;
		if(empty($order_id)){
			$return['info'] = '参数错误！';return $return;
		}
		$map = array();
		if($is_type == 1){
			$map['order_id'] = $order_id;
		}else{
			$map['id'] = $order_id;
		}
		$map['user_id'] = $uid;
		$map['check_status'] = 0;
		$info = M('WinGift')->where($map)->field('id,gift_id')->find();
		if($info){
			$save = array();$save['id'] = $info['id'];
			$save['check_status'] = 1;$save['check_time'] = NOW_TIME;
			M('WinGift')->save($save);
			$map = array();$map['id'] = $info['gift_id'];
			M('Prize')->where($map)->setDec('goods_num',1);
			
			$return['status'] = 1;
		}else{
			$return['info'] = '没有优惠券可以领取';
		}
		return $return;
	}
    public function get_memberattrs($id){
        $user_info = D('Member')->get_memberinfo($id);
        $return = array("status"=>0,"msg"=>'');
        $where = $map = $data = array();
        $where['name'] = 'ATTRIBUTE';
        $have = M("Config")->where($where)->field("id,name,value")->find();
        $attr_list = json_decode($have['value'],true);
        $map['uid'] = $id;
        foreach ($attr_list as $key => $value) {
            if($value['is_shop']){
                $data[$key] = $value;
                $map['aid'] = $value['id'];
                $data[$key]['value'] = M("MemberAttribute")->where($map)->getField("content");
                if($value['type'] == 'date' && $data[$key]['value']){
                    $data[$key]['value'] = date("Y-m-d",$data[$key]['value']);
                }
                if(($value['type'] == 'radio') && $value['content']){
                    $data[$key]['data'] = explode(",",$value['content']);
                }
                if($value['type'] == 'checkbox' && $value['content']){
                    $data[$key]['data'] = explode(",",$data[$key]['value']);
                }
            }
        }unset($key,$value);
        $label_list = $this->label_lists($id);
        if($user_info['status'] == 1){
            $return['data'] = $data;
            $return['info'] = $user_info['data'];
            $return['status'] = 1;
            $return['label_list'] = $label_list;
        }else{
            $return['status'] = 3;
            $return['msg'] = $user_info['msg'];
        }
        return $return;
    }
    public function label_lists($id){
        $map = array();
        $map['id'] = $id;
        $label_ids = M('Member')->where($map)->getField('label_ids');
        $label_ids_arr = array_filter(explode(',',$label_ids));
        $map = array();$map['pid'] = 40;
        $label_list = M('Type')->where($map)->field('id,name')->select();
        foreach ($label_list as $key => $value) {
            if(in_array($value['id'], $label_ids_arr)){
                $label_list[$key]['is_on'] = 1;
            }else{
                $label_list[$key]['is_on'] = 0;
            }
        }unset($key,$value);
        return $label_list;
    }
    public function memberattrinfo_list($postdata){
        $return = array('status'=>0,'msg'=>'');
        if(empty($postdata['id'])){
            $return['msg'] = "参数错误";
            return $return;exit;
        }
        $member_mod = D('Member');
        $info = $member_mod->field(true)->find($postdata['uid']);
        $where = $map = $info = array();
        $where['name'] = 'ATTRIBUTE';
        $have = M("Config")->where($where)->field("id,name,value")->find();
        $list = json_decode($have['value'],true);
        $map['uid'] = $postdata['uid'];
        $map['aid'] = $postdata['id'];
        $content = M("MemberAttribute")->where($map)->getField("content");
        $content = explode(",",$content);
        $text = explode(",",$list[$postdata['id']]['content']);
        if($text){
            foreach ($text as $key => $value) {
                if($value){
                    $info[$key]['name'] = $value;
                    $info[$key]['is_show'] = 0;
                }
            }unset($key,$value);
            foreach ($content as $key => $value) {
                if($value){
                    $k = array_search($value, $text);
                    if(in_array($value, $text)){
                        $info[$k]['is_show'] = 1;
                    }else{
                        $info[$k]['is_show'] = 0;
                    }
                }
            }unset($key,$value);
        }
        $return['status'] = 1;
        $return['data'] = $info;
        $return['count'] = count($info);
        return $return;
    }
    public function addmemberattribute($postdata){
        $return = array('status'=>0,'msg'=>'');
        if(empty($postdata['uid'])){
            $return['msg'] = "参数错误";
            return $return;exit;
        }
        $where = $data = $map = array();
        $map['name'] = 'ATTRIBUTE';
        $c_have = M("Config")->where($map)->getField("value");
        $c_list = json_decode($c_have,true);
        // $postdata['name'] = explode(',', $postdata['name']);
        $where['uid'] = $postdata['uid'];
        $postdata['name'] = json_decode(htmlspecialchars_decode($postdata['name']),true);
        foreach ($postdata['name'] as $key => $value) {
            if($value){
                $where['aid'] = $key;
                $where['uid'] = $postdata['uid'];
                $have = M("MemberAttribute")->where($where)->count();
                if($c_list[$key]['type'] == 'date'){
                    $value = strtotime($value);
                }
                if($c_list[$key]['type'] == 'checkbox'){
                    $value= preg_replace("/(\n)|(\s)|(\t)|(\')|(')|(，)/" ,',' ,$value); 
                }
                $value = ltrim($value, ",");
                if($have){
                    $save_data = array();
                    $save_data['content'] = $value;
                    M("MemberAttribute")->where($where)->save($save_data);
                }else{
                    $add_data = array();
                    $add_data['uid'] = $postdata['uid'];
                    $add_data['aid'] = $key;
                    $add_data['content'] = $value;
                    M("MemberAttribute")->add($add_data);
                }
                if($c_list[$key]['type'] == 'date'){
                    $value = date('Y-m-d',$value);
                }
            }
            $data[] = array('id'=>$key,'name'=>$value);
        }unset($key,$value);
        
        if($data){
            $return = $this->get_memberattrs($postdata['uid']);
        }else{
            $return['msg'] = "保存失败";
        }
        return $return;
    }
    public function savelabels($post){
        $return = array();
        $map = array();$map['id'] = $post['uid'];
        $label_ids = M('Member')->where($map)->getField('label_ids');
        $new_label_ids = ',';
        $new_ids = $post['label_id'].',';
        if($label_ids){
            if(strpos($label_ids,','.$new_ids) !== false){
                $label_ids = str_replace(','.$new_ids,',',$label_ids);
            }else{
                $label_ids .= $new_ids;
            }
            $new_label_ids = $label_ids;
        }else{
            $new_label_ids .= $new_ids;
        }
        if($new_label_ids){
            $save_label_ids = array();$save_label_ids['label_ids'] = $new_label_ids;
            $ret = M('Member')->where($map)->save($save_label_ids);
            if($ret){
                $return['status'] = 1;
            }else{
                $return['status'] = 0;
            }
        }
        return $return;
    }
    public function addlabel($post){
        $return = array();
        $new_label = $post['new_label'];
        $new_label_arr = array_filter(explode(' ',$new_label));
        if($new_label_arr){
            $save_data = array();
            $ret = 1;$html = '';$ha = 0;
            foreach($new_label_arr as $v){
                $save_data['pid'] = 40;
                $save_data['sort'] = 0;
                $save_data['status'] = 1;
                $save_data['name'] = $save_data['temp'] = $v;
                $have = M("Type")->where($save_data)->count();
                if(!$have){
                    $id = M('Type')->add($save_data);
                    if(!$id){$ret = 0;}
                    else{
                        $html .= "<li @click='add_memberlaber(".$id.")' id='laber_".$id."'>".$v."</li>";
                    }
                }else{
                    $ha = 1;
                }
                
            }
            if($ret){
                if($ha){$return['msg'] = '已有填写的部分标签';}
                $return['status'] = 1;
                $return['html'] = $html;
                $return['label_list'] = $this->label_lists($post['uid']);
            }else{
                $return['status'] = 0;
            }
        }
        return $return;
    }
}
?>