<?php

# 前台

Doo::loadController('front');
require ROOT.'library/qiniu/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class welcome extends front{	
    # 入口页
    public function index(){
        $view = 'lists';
        if ($this->request->hasQuery('view')){
            $view = $this->request->get('view');
        }
        $this->data['view'] = $view;
        $pay = 0;
        if ($this->request->hasQuery('pay') && $this->request->get('pay')){
            $pay = 1;
        }
        $this->data['pay'] = $pay;
        $this->renderc('welcome/index', $this->data);
    }
    
    # 会员中心
    public function user(){
        $pay = 0;
        if ($this->request->hasQuery('pay') && $this->request->get('pay')){
            $pay = 1;
        }
        $this->data['pay'] = $pay;
        # 订单数
        Doo::loadModel('ShopOrders');
        $SO = new ShopOrders();
        $SO->userid = $this->user->id;
        $SO->status = 1;
        $orderCount = $SO->count();
        $this->data['orderCount'] = $orderCount;
        # 我的邀请
        Doo::loadModel('ShopLinks');
        $one = new ShopLinks();
        $one->level1 = $this->user->id;
        $this->data['oneCount'] = $one->count();
        $two = new ShopLinks();
        $two->level2 = $this->user->id;
        $this->data['twoCount'] = $two->count();
        $three = new ShopLinks();
        $three->level3 = $this->user->id;
        $this->data['threeCount'] = $three->count();
        # 今日人脉
        $date = date('Y-m-d');
        $start = strtotime($date.' 00:00:01');
        $end = strtotime($date.' 23:59:59');
        $today = new ShopLinks();
        $this->data['todayCount'] = $today->count(array(
            'where' => 'level3 = ? and dateline >= ? and dateline <= ?',
            'param' => array($this->user->id, $start, $end)
        ));
        # 佣金总额
        $this->data['moneys'] = $this->_myMoney();        
        # 我的提现
        $this->data['cash'] = $this->_myCash();
        # 微信管理员
        $isAdmin = 0;
        $wxAdminOpenID = service::get_option('wxAdminOpenID');
        if ($this->user->openid == $wxAdminOpenID){
            $isAdmin = 1;
        }
        $this->data['isAdmin'] = $isAdmin;
        $this->renderc('welcome/user', $this->data);
    }
    
    private function _myCash($userid = 0){
        $uid = $userid ? $userid : $this->user->id;
        $cashs = Doo::db()->fetchRow("select sum(price) as count from shop_cash where userid='".$uid."' and (status='1' or status='0')");
        return floatval($cashs['count']);
    }
    
    # 二维码列表
    public function lists(){
        if($this->ios){
            $this->data['cssFixed'] = 'position: -webkit-sticky; position:sticky; top: 0px; z-index: 999;';
            $this->data['cssMgtop'] = '';
        }else{
            $this->data['cssFixed'] = 'position: fixed; left: 0; top: 0; right: 0; z-index: 899;';
            $this->data['cssMgtop'] = 'margin-top: 60px;';
        }
        $this->renderc('welcome/lists', $this->data);
    }
    
    # 搜索页
    public function search(){
        $this->renderc('welcome/search', $this->data);
    }
    
    # 发布页
    public function post(){
        Doo::loadModel('ShopQrcode');
        $SQ = new ShopQrcode();
        $SQ->userid = $this->user->id;
        $SQ->type1 = 0;
        $db = $SQ->getOne(array('asArray' => true));
        $this->data['db'] = $db;
        $this->renderc('welcome/post', $this->data);
    }
    
    # 发布微信群
    public function postMore(){
        $this->renderc('welcome/post_more', $this->data);
    }
    
    # 我的群
    public function myQun(){
        $this->renderc('welcome/user_qun', $this->data);
    }
    
    # 我的订单
    public function myOrder(){
        $this->renderc('welcome/user_order', $this->data);
    }
    
    # 购买
    public function buy(){
        Doo::loadModel('ShopOrders');
        $SO = new ShopOrders();
        $SO->userid = $this->user->id;
        $db = $SO->getOne(array('asArray' => true, 'desc' => 'id'));
        $this->data['lastInsert'] = $db;
        $this->renderc('welcome/buy', $this->data);
    }
    
    # 微信支付
    public function pay(){
        #免费版本不提供支付功能
		#需要的朋友可以加QQ群咨询价格
		#QQ群:304479564
    }
    
    # 微信支付配置
    private function wxconfig(){
        return array(
            'APPID' => service::get_option('wxappId'),
            'MCHID' => service::get_option('wxMchid'),
            'KEY' => service::get_option('wxPayKey'),
            'APPSECRET' => service::get_option('wxappSecret'),
            'JS_API_CALL_URL' => $this->url(array('c' => 'welcome', 'm' => 'buy')),
            'SSLCERT_PATH' => Doo::conf()->SITE_PATH.'cert/apiclient_cert.pem',
            'SSLKEY_PATH' => Doo::conf()->SITE_PATH.'cert/apiclient_key.pem',
            'NOTIFY_URL' => Doo::conf()->APP_URL.'notify.php',
            'CURL_TIMEOUT' => 60
        );
    }
    
    # 我的邀请
    public function myInvite(){
        $this->renderc('welcome/user_invite', $this->data);
    }
    
    # 我的提现
    public function myCash(){
        $money = $this->_myMoney();
        $this->data['moneys'] = array_sum($money);
        $this->data['cash'] = $this->_myCash();
        Doo::loadModel('ShopCash');
        $SC = new ShopCash();
        $SC->userid = $this->user->id;
        $this->data['lists'] = $SC->find(array(
            'asArray' => true, 'desc' => 'id', 'limit' => '0,20', 
        ));
        $this->renderc('welcome/user_cash', $this->data);
    }
    
    private function _myMoney($userid = 0){
        $uid = $userid ? $userid : $this->user->id;
        # 佣金总额
        $price1 = Doo::db()->fetchRow("select sum(price1) as count from shop_moneys where level1='".$uid."'");
        $price2 = Doo::db()->fetchRow("select sum(price2) as count from shop_moneys where level2='".$uid."'");
        $price3 = Doo::db()->fetchRow("select sum(price3) as count from shop_moneys where level3='".$uid."'");
        $price4 = Doo::db()->fetchRow("select sum(ceoprice) as count from shop_moneys where ceo='".$uid."'");
        return array(floatval($price1['count']), floatval($price2['count']), floatval($price3['count']), floatval($price4['count']));
    }
    
    # 提现管理
    public function myAdmin(){
        if ($this->request->hasQuery('get') && $this->request->hasQuery('get') == 1){
            $allow = $this->_isAdmin() == 'allow' ? 'allow' : 'deny';
            if ($allow == 'allow'){
                Doo::loadModel('ShopCash');
                $SC = new ShopCash();
                $SC->status = 0;
                $lists = $SC->find(array('asArray' => true, 'asc' => 'id', 'limit' => '0,10'));
            }else{
                $lists = array();
            }
            $ret = array();
            if ($lists){
                foreach ($lists as $item){
                    $item['_face'] = $this->getFace($item['userid']);
                    $item['_date'] = date('Y-m-d H:i', $item['dateline']);
                    $ret[] = $item;
                }
            }
            echo json_encode(array('lists' => $ret, 'allow' => $allow));
            return;
        }
        $this->renderc('welcome/user_cash_admin', $this->data);
    }
    
    private function _isAdmin(){
        $wxAdminOpenID = service::get_option('wxAdminOpenID');
        if (empty($wxAdminOpenID)){
            return '请先配置管理员OPENID';
        }
        if ($wxAdminOpenID != $this->user->openid){
            return '你无权操作';
        }
        return 'allow';
    }
    
    ///// 以下为交互数据 //////////
    
    public function deleteMyQrcode(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            Doo::loadModel('ShopQrcode');
            $SQ = new ShopQrcode();
            $SQ->userid = $this->user->id;
            $SQ->type1 = 0;
            $SQ->delete();            
        }
    }
    
    public function topped(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            if ($this->user->type == 0){
                echo '此功能仅限VIP会员使用';
                return;
            }
            Doo::loadModel('ShopQrcode');
            $SQ = new ShopQrcode();
            $SQ->userid = $this->user->id;
            $SQ->type1 = 0;
            $db = $SQ->getOne();
            if ($db){
                $time = time();
                if ($time - $db->uptime >= 600){
                    # 刷新
                    $db->uptime = $time;
                    $db->update();
                    echo '刷新成功';
                }else{
                    echo '请在'.(11 - ceil(($time - $db->uptime)/60)).'分钟后再刷新';
                }
            }else{
                echo '请先发布您的个人二维码';
            }
            return;
        }
        echo '非法操作';
    }
    
    public function adminCashConfirm(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            $allow = $this->_isAdmin();
            if ($allow != 'allow'){
                echo $allow;
                return;
            }
            $id = intval($this->request->getPost('id'));
            Doo::loadModel('ShopCash');
            $SC = new ShopCash();
            $SC->id = $id;
            $SC->status = 0;
            $db = $SC->getOne();
            if ($db){
                # 存在
                $moneys = $this->_myMoney($db->userid);
                $moneys = array_sum($moneys);
                $cash = Doo::db()->fetchRow("select sum(price) as count from shop_cash where userid='".$db->userid."' and status='1'");
                $cashOut = floatval($cash['count']);
                $left = $moneys - $cashOut;
                if ($db->price >= $this->cachOutMinPrice && $left >= $db->price){
                    $GLOBALS['wxconfig'] = $this->wxconfig();
                    include_once Doo::conf()->SITE_PATH.'class/pay/WxPayPubHelper.php';
                    $openid = $db->openid;
                    if ($openid){
                        $com = new Wxpay_client_pub();
                        $no = $db->id.date('His').rand(10000, 99999).$db->userid;
                        $com->setParameter('mch_appid', $GLOBALS['wxconfig']['APPID']);
                        $com->setParameter('mchid', $GLOBALS['wxconfig']['MCHID']);
                        $com->setParameter('nonce_str', $com->createNoncestr());
                        $com->setParameter('partner_trade_no', $no);
                        $com->setParameter('openid', $openid);
                        $com->setParameter('check_name', 'NO_CHECK');
                        $com->setParameter('amount', $db->price*100);
                        $com->setParameter('desc', $this->sitename.'佣金提现');
                        $com->setParameter('spbill_create_ip', $this->clientIP());
                        $com->setParameter('re_user_name', $this->sitename);
                        $com->setParameter('sign', $com->getSign($com->parameters));
                        $postXml = $com->arrayToXml($com->parameters);
                        $responseXml = $this->_curl_post($postXml);
                        $responseObj = simplexml_load_string($responseXml);
                        if( $responseObj->result_code=="SUCCESS" && $responseObj->return_code=="SUCCESS"){
                            # 提现成功
                            $db->status = 1;
                            $db->dateline = time();
                            $db->update();
                            echo '操作成功';
                        }else{
                            echo $responseObj->return_msg;
                        }
                    }else{
                        echo '提现用户错误';
                    }                    
                }else{
                    echo '提现金额错误';
                }
            }else{
                echo '你确认的提现数据错误';
            }
            return;
        }
        echo '非法操作';
    }
    
    private function _curl_post($vars, $second = 30, $aHeader = array()){
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        curl_setopt($ch,CURLOPT_SSLCERT, $GLOBALS['wxconfig']['SSLCERT_PATH']);
        curl_setopt($ch,CURLOPT_SSLKEY, $GLOBALS['wxconfig']['SSLKEY_PATH']);
        curl_setopt($ch,CURLOPT_CAINFO, Doo::conf()->SITE_PATH.'cert/rootca.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }else{
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n"; 
            curl_close($ch);
            return false;
        }
    }
    
    public function cashOut(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            $price = floatval($this->request->getPost('price'));
            if ($price <= $this->cachOutMinPrice){
                echo '请输入大于等于'.$this->cachOutMinPrice.'的数';
                return;
            }
            $moneys = $this->_myMoney();
            $moneys = array_sum($moneys);
            $cash = $this->_myCash();
            $left = $moneys - $cash;
            if ($price > $left){
                echo '您最多可提'.$left.'元';
                return;
            }
            # 写入数据
            Doo::loadModel('ShopCash');
            $SC = new ShopCash();
            $SC->dateline = time();
            $SC->userid = $this->user->id;
            $SC->userid_value = $this->user->nickname;
            $SC->openid = $this->user->openid;
            $SC->status = 0;
            $SC->price = $price;
            if ($SC->insert()){
                echo '您的提现请求已提交';
            }else{
                echo '提现失败';
            }
            return;
        }
        echo '非法操作';
    }
    
    public function getInvite(){
        $page = intval($this->request->get('page'));
        if ($page <= 1){
            $page = 1;
        }
        $tpp = 20;
        $start = ($page - 1)*$tpp;
        $limit = $start.','.$tpp;
        $next = $page*$tpp;
        $next_limit = $next.','.$tpp;
        Doo::loadModel('ShopUsers');
        Doo::loadModel('ShopLinks');
        $SL = new ShopLinks();
        $SL->level3 = $this->user->id;
        $lists = $SL->find(array('asArray' => true, 'desc' => 'id', 'limit' => $limit));
        $nexts = $SL->find(array('asArray' => true, 'desc' => 'id', 'limit' => $next_limit));
        $ret = array();
        if ($lists){
            foreach ($lists as $item){
                $item['_face'] = $this->getFace($item['userid']);
                $item['_dateline'] = date('Y-m-d H:i', $item['dateline']);
                $ret[] = $item;
            }
        }
        echo json_encode(array('lists' => $ret, 'count' => count($nexts)));  
    }
    
    private function getFace($uid){
        $SU = new ShopUsers();
        $SU->id = $uid;
        $db = $SU->getOne();
        if ($db){
            return $db->headimgurl;
        }
        return '';
    }
    
    public function follow(){
        Doo::loadModel('ShopFollows');
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            $id = intval($this->request->getPost('id'));
            Doo::loadModel('ShopQrcode');
            $SQ = new ShopQrcode();
            $SQ->id = $id;
            $db = $SQ->getOne(array('asArray' => true));
            if ($db){
                $SF = new ShopFollows();
                $SF->userid = $this->user->id;
                $SF->qrcodeid = $id;
                $fl = $SF->getOne(array('asArray' => true));
                if ($fl){
                    
                }else{
                    $SF->dateline = time();
                    $SF->userid_value = $this->user->nickname;
                    $SF->qrcodeid_value = $db['nickname'];
                    $SF->insert();
                }
            }
        }
        $FO = new ShopFollows();
        $FO->userid = $this->user->id;
        echo $FO->count();
    }
    
    public function getQrcode(){
        if ($this->user->subscribe == 0){
            echo '请先关注我们公众号';
            return;
        }
        if ($this->user->type == 1 || $this->user->type == 2){
            
        }else{
            echo 'VIP会员方可生成二维码';
            return;
        }
        $qrcodeParams = service::get_option('qrcodeParams');
        if (empty($qrcodeParams)){
            echo '请设置二维码参数';
            return;
        }        
        service::qrcode($this->user, $this->wx, $qrcodeParams);
    }
    
    public function deleteQun(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            Doo::loadModel('ShopQrcode');
            $SQ = new ShopQrcode();
            $SQ->id = intval($this->request->getPost('id'));
            $SQ->type1 = 1;
            $SQ->userid = $this->user->id;
            $SQ->delete();
        }
    }
    
    public function getOrders(){
        $page = intval($this->request->get('page'));
        if ($page <= 1){
            $page = 1;
        }
        $tpp = 10;
        $start = ($page - 1)*$tpp;
        $limit = $start.','.$tpp;
        $next = $page*$tpp;
        $next_limit = $next.','.$tpp;
        Doo::loadModel('ShopOrders');
        $SO = new ShopOrders();
        $SO->status = 1;
        $SO->userid = $this->user->id;
        $lists = $SO->find(array('asArray' => true, 'desc' => 'id', 'limit' => $limit));
        $nexts = $SO->find(array('asArray' => true, 'desc' => 'id', 'limit' => $next_limit));
        $ret = array();
        if ($lists){
            foreach ($lists as $item){
                $item['_time'] = date('H:i', $item['dateline']);
                $item['_date'] = date('Y/m/d', $item['dateline']);
                $item['_title'] = '购买VIP会员';
                $ret[] = $item;
            }
        }
        echo json_encode(array('lists' => $ret, 'count' => count($nexts)));        
    }
    
    public function getWeixin(){
        $this->getData();
    }
    
    private function getData($type = 0, $tpp = 20){        
        $page = intval($this->request->get('page'));
        if ($page <= 1){
            $page = 1;
        }
        $start = ($page - 1)*$tpp;
        $limit = $start.','.$tpp;
        $next = $page*$tpp;
        $next_limit = $next.','.$tpp;
        $opt1 = array(
            'asArray' => true, 'desc' => 'uptime', 'limit' => $limit
        );
        $opt2 = array(
            'asArray' => true, 'desc' => 'uptime', 'limit' => $next_limit
        );
        $param = array();
        if ($this->request->hasQuery('type')){
            $type = intval($this->request->get('type'));
        }
        $where = 'type1 = ? ';
        $param[] = $type;
        if ($type == 1){
            # 微信群二维码有效期为7天
            $filter = 604800;
            $diff = time() - $filter;
            $where .= ' and dateline >= ? ';
            $param[] = $diff;
        }
        if ($this->request->hasQuery('my')){
            $where .= ' and userid = ? ';
            $param[] = $this->user->id;
        }
        if ($this->request->hasQuery('sex') && $this->request->get('sex') > 0){
            $where .= ' and sex = ? ';
            $param[] = $this->request->get('sex');
        }
        $condition = array();
        if ($this->request->hasQuery('city') && $this->request->get('city')){
            $condition[] = ' city like ? ';
            $param[] = '%'. str_replace('%20', ' ', $this->request->get('city')).'%';
        }
        if ($this->request->hasQuery('keyword') && $this->request->get('keyword')){
            $condition[] = 'nickname like ? ';
            $param[] = '%'. str_replace('%20', ' ', $this->request->get('keyword')).'%';
        }
        if ($condition){
            $where .= 'and ('.implode(' or ', $condition).')';
        }
        $opt1['where'] = $opt2['where'] = $where;
        $opt1['param'] = $opt2['param'] = $param;
        Doo::loadModel('ShopQrcode');
        $SQ = new ShopQrcode();
        $lists = $SQ->find($opt1);
        $nexts = $SQ->find($opt2);
        echo json_encode(array('lists' => $lists, 'count' => count($nexts), 'type' => $where));
        # count 是否存在下一组数据
    }
    
    public function getQun(){
        $this->getData(1);
    }
    
    public function postQrcode(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            if ($this->user->type == 0 && $this->joinNums <= 15){
                echo '只有VIP会员或普通会员加满15个好友(已加' .$this->joinNums. '个)方可发布';
                return;
            }
            $nickname = $this->request->getPost('nickname');
            if (empty($nickname)){
                echo '请输入昵称';
                return;
            }
            $weixin = $this->request->getPost('weixin');
            $province = $this->request->getPost('province');
            if (empty($province)){
                echo '请输入省份';
                return;
            }
            $city = $this->request->getPost('city');
            if (empty($city)){
                echo '请输入城市';
                return;
            }
            $intro = $this->request->getPost('intro');
            if (empty($intro)){
                echo '请简单描述下自己';
                return;
            }
            $industry = $this->request->getPost('industry');
            if (empty($industry)){
                echo '请选择行业';
                return;
            }
            $qrcode = $this->request->getPost('qrcode');
            if (strstr($qrcode, 'http')){
                
            }else{
                $res = $this->wx->getMedia($qrcode);
                $path = ROOT.PROJECT.'/cache/'.$this->user->id.'.jpg';
                file_put_contents($path, $res);
                $bucket = service::get_option('qiniubucket');
                $secretKey = service::get_option('qiniusecretKey');
                $accessKey = service::get_option('qiniuaccessKey');
                $auth = new Auth($accessKey, $secretKey);
                $token = $auth->uploadToken($bucket);
                $key = md5($this->user->id.time()).'.jpg';
                $uploadMgr = new UploadManager();
                list($ret, $err) = $uploadMgr->putFile($token, $key, $path);
                if ($err !== null) {
                    # 失败
                    echo '二维码上传失败';
                    return;
                }else{
                    # 成功
                    @unlink($path);
                    $domain = service::get_option('qiniudomain');
                    $qrcode = $domain.$key;
                }
            }
            // 检查是否存在
            Doo::loadModel('ShopQrcode');
            $SQ = new ShopQrcode();
            $SQ->userid = $this->user->id;
            $SQ->type1 = 0;
            $db = $SQ->getOne();
            if ($db){
                $db->dateline = time();
                $db->avatar = $this->user->headimgurl;
                $db->nickname = $nickname;
                $db->weixin = $weixin;
                $db->province = $province;
                $db->city = $city;
                $db->intro = $intro;
                $db->qrcode = $qrcode;
                $db->industry = $industry;
                $db->update();
            }else{
                $SQ->dateline = time();
                $SQ->userid_value = $this->user->nickname;
                $SQ->avatar = $this->user->headimgurl;
                $SQ->sex = $this->user->sex;
                $SQ->nickname = $nickname;
                $SQ->weixin = $weixin;
                $SQ->province = $province;
                $SQ->city = $city;
                $SQ->intro = $intro;
                $SQ->qrcode = $qrcode;
                $SQ->industry = $industry;
                $SQ->uptime = time();
                $SQ->insert();
            }
            echo 'ok';
            return;
        }
        echo '发布失败1, 请联系我们';
    }
    
    public function postQun(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            if ($this->user->type == 0){
                echo '只有VIP会员方可发布微信群';
                return;
            }
            $nickname = $this->request->getPost('nickname');
            if (empty($nickname)){
                echo '请输入昵称';
                return;
            }
            $province = $this->request->getPost('province');
            if (empty($province)){
                echo '请输入省份';
                return;
            }
            $city = $this->request->getPost('city');
            if (empty($city)){
                echo '请输入城市';
                return;
            }
            $intro = $this->request->getPost('intro');
            if (empty($intro)){
                echo '请简单描述下群';
                return;
            }
            $industry = $this->request->getPost('industry');
            if (empty($industry)){
                echo '请选择行业';
                return;
            }
            $bucket = service::get_option('qiniubucket');
            $secretKey = service::get_option('qiniusecretKey');
            $accessKey = service::get_option('qiniuaccessKey');
            $domain = service::get_option('qiniudomain');
            $avatar = $this->request->getPost('qunavatar');
            if (strstr($avatar, 'http')){
                
            }else{
                $res = $this->wx->getMedia($avatar);
                $path = ROOT.PROJECT.'/cache/'.$this->user->id.'.jpg';
                file_put_contents($path, $res);
                $auth = new Auth($accessKey, $secretKey);
                $token = $auth->uploadToken($bucket);
                $key = md5($this->user->id.time()).'.jpg';
                $uploadMgr = new UploadManager();
                list($ret, $err) = $uploadMgr->putFile($token, $key, $path);
                if ($err !== null) {
                    # 失败
                    echo '头像上传失败';
                    return;
                }else{
                    # 成功
                    @unlink($path);
                    $avatar = $domain.$key;
                }
            }
            $qrcode = $this->request->getPost('qunqrcode');
            if (strstr($qrcode, 'http')){
                
            }else{
                $res = $this->wx->getMedia($qrcode);
                $path = ROOT.PROJECT.'/cache/'.$this->user->id.'.jpg';
                file_put_contents($path, $res);
                $auth = new Auth($accessKey, $secretKey);
                $token = $auth->uploadToken($bucket);
                $key = md5($this->user->id.time()).'.jpg';
                $uploadMgr = new UploadManager();
                list($ret, $err) = $uploadMgr->putFile($token, $key, $path);
                if ($err !== null) {
                    # 失败
                    echo '头像上传失败';
                    return;
                }else{
                    # 成功
                    @unlink($path);
                    $qrcode = $domain.$key;
                }
            }
            Doo::loadModel('ShopQrcode');
            $SQ = new ShopQrcode();
            $SQ->userid = $this->user->id;
            $SQ->type1 = 1;
            $SQ->dateline = time();
            $SQ->userid_value = $this->user->nickname;
            $SQ->avatar = $avatar;
            $SQ->nickname = $nickname;
            $SQ->weixin = '';
            $SQ->province = $province;
            $SQ->city = $city;
            $SQ->intro = $intro;
            $SQ->qrcode = $qrcode;
            $SQ->industry = $industry;
            $SQ->sex = $this->user->sex;
            $SQ->uptime = time();
            $SQ->insert();
            echo 'ok';
            return;
        }
        echo '发布失败2, 请联系我们';
    }
    
    public function postNickname(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            Doo::loadModel('ShopUsers');
            $SU = new ShopUsers();
            $SU->id = $this->user->id;
            $SU->nickname = $this->request->getPost('name');
            $SU->dateline = time();
            $SU->update();
        }
    }
    
    # 积分商城
    public function jiFen(){
        $this->renderc('welcome/jifen', $this->data);
    }
    
    public function getjiFen(){
        $page = intval($this->request->get('page'));
        if ($page <= 1){
            $page = 1;
        }
        $tpp = 20;
        $start = ($page - 1)*$tpp;
        $limit = $start.','.$tpp;
        $next = $page*$tpp;
        $next_limit = $next.','.$tpp;
        Doo::loadModel('ShopJifenshop');
        $SL = new ShopJifenshop();
        $lists = $SL->find(array('asArray' => true, 'where' => 'nums <> 0 and (starttime <= ? and endtime >= ?) or endtime = 0', 'desc' => 'id', 'param' => array(time(),time()), 'limit' => $limit));
        $nexts = $SL->find(array('asArray' => true, 'where' => 'nums <> 0 and (starttime <= ? and endtime >= ?) or endtime = 0', 'desc' => 'id', 'param' => array(time(),time()), 'desc' => 'id', 'limit' => $next_limit));      
        echo json_encode(array('lists' => $lists, 'count' => count($nexts)));  
    }
    
    public function duiHuan(){
        if ($this->request->isAjax() == true && $this->request->isPost() == true){
            $id = intval($this->request->getPost('id'));
            Doo::loadModel('ShopJifenshop');
            Doo::loadModel('ShopJifenorder');
            Doo::loadModel('ShopUsers');
            $SU = new ShopJifenshop();
            $SU->id = $id;
            if($SUS = $SU->getOne()){
                if(($SUS->starttime <= time && $SUS->end >= time()) ||  empty($SUS->endtime)){
                    $month = "+{$SUS->months} months";
                    $US = new ShopUsers();
                    $US->id = $this->user->id;
                    $USS = $US->getOne();
                    if($USS->jifen >= $SUS->jifen && $SUS->nums > 0){
                        $US = new ShopUsers();
                        $US->id = $this->user->id;
                        $US->jifen = $USS->jifen - $SUS->jifen;
                        $US->type = 1;
                        if ($USS->endtime && $USS->endtime >= time()){
                            $time = strtotime($month, $USS->endtime);
                        }else{
                            $time = strtotime($month);
                        }
                        $US->endtime = $time;
                        if($US->update()){
                            $SU = new ShopJifenshop();
                            $SU->id = $id;
                            $SU->nums = $SUS->nums - 1;
                            if($SU->update()){
                                $IS = new ShopJifenorder();
                                $IS->sid = $id;
                                $IS->sid_value = $SUS->title;
                                $IS->uid = $this->user->id;
                                $IS->uid_value = $this->user->nickname;
                                $IS->nums = 1;
                                $IS->months = $SUS->months;
                                $IS->jifen = $SUS->jifen;
                                $IS->dateline = time();
                                if($IS->insert()){
                                    $say = '兑换成功';
                                }else{
                                    $say = '兑换失败';
                                }
                            }else{
                                $say = '兑换失败1';
                            }
                        }else{
                            $say = '兑换失败2';
                        }
                    }else{
                        $say = '积分或商品库存不足';
                    }
                }else{
                    $say = '没有可兑换的商品';
                }                
                echo $say;   
            }            
        }
    }
    
    # 兑换历史
    public function jiFenList(){
        $this->renderc('welcome/jifen_list', $this->data);
    }
    
    public function getjiFenList(){
        $page = intval($this->request->get('page'));
        if ($page <= 1){
            $page = 1;
        }
        $tpp = 20;
        $start = ($page - 1)*$tpp;
        $limit = $start.','.$tpp;
        $next = $page*$tpp;
        $next_limit = $next.','.$tpp;
        Doo::loadModel('ShopJifenorder');
        $SL = new ShopJifenorder();
        $lists = $SL->find(array('asArray' => true, 'desc' => 'id', 'limit' => $limit));
        $nexts = $SL->find(array('asArray' => true, 'desc' => 'id', 'limit' => $next_limit));
        $ret = array();      
        foreach($lists as $v){
            $v['_time'] = date('H:i',$v['dateline']);
            $v['_date'] = date('Y/m/d',$v['dateline']);
            $v['_dateline'] = date('Y-m-d H:i:s',$v['dateline']);
            $ret[] = $v;
        }
        echo json_encode(array('lists' => $ret, 'count' => count($nexts)));  
    }
    
}