<?php
namespace Home\Controller;

use Think\Log;
use SignedCookie;

trait UserTrait
{
    protected function get_user_info_from_cookie()
    {
        if ($this->debug) {
            $user = M('User')->find();
            return $user;
        }
        $cookie_secret = C('cookie_sign');
        $openid = \SignedCookie::get_cookie($this->cookie_uid_key, $cookie_secret, 86400 * 60);
        if (!$openid) {
            return false;
        }

        $user = M('User')->where(array('openid' => $openid))->find();
        return $user;
    }

    protected function  request_auth($redirect_url = '/')
    {
//        跳转到美丽田园授权 回调地址为 /auth
        $site_url = C('SITE_URL');
        if (!$site_url) {
            $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
            $site_url = $sys_protocal . $_SERVER['HTTP_HOST'];
        }
        $callback_url = urlencode("{$site_url}/auth");
        $geturl = "http://as-vip.missfresh.cn/v1/interface/get_user_base_info?callback={$callback_url}";
        redirect($geturl);
        exit(0);
    }

    protected function get_url()
    {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }
//  授权接口 这里get拿到两个数据 openid和token todo 会员判断先关实现和位置思量
    public function auth()
    {
        //如果是分享出去的链接，重新授权
        if (!empty($_GET['from'])) {
            $this->request_auth();
            exit(0);
        }
        $openid = $_GET['openid'];
        $access_token = $_GET['access_token'];

        $user = array();
        $user['openid'] =$openid;
        $user['access_token'] =$access_token;
        $user['nickname'] = $_GET['nick_name'];
        $user['headimgurl'] = $_GET['head_image_url'];
        $user['info'] = json_encode($_GET);

        SignedCookie::set_cookie($this->cookie_uid_key, $openid, C('cookie_sign'), 86400 * 60);
        $old_user = M('User')->where(array('openid' => $openid))->find();
        if ($old_user) {
            M('User')->token(false)->where(array('openid' => $openid))->save(array(
                'access_token'=> $access_token,
                'last_visit' => time(),
                'last_ip' => $this->getIP(),
            ));
        } else {
            $user['expired_at'] = $_SERVER['REQUEST_TIME'];
            $user['reg_ip'] = $this->getIP();
            $user['last_visit'] = time();
            $user['last_ip'] = $this->getIP();
            $user['created_at']= time();
            M('User')->token(false)->add($user);
        }
        $_SESSION['is_wechat'] = 1;
        $_SESSION['openid'] = $openid;

        if ($old_user['member'] == 0) {
            $this->identify($openid);
        } else {
            redirect("/");
            exit(0);
        }
    }

    public function bind()
    {
        if (!$_GET['openid']) {
            die('回调地址错误');
        }
        $user = M('User')->where(array('openid' => $_GET['openid']))->find();
        if (!$user) {
            die('获取用户信息错误');
        }
        if (!($user['member'] == 1)) {
            die('非法访问');
        }
        $quan = M('Quan')->where(array(
            'taked' => 0,
            'user_id' => 0,
        ))->order('rand()')->limit(1)->find();
        if ($quan) {
            $content = "恭喜您微信绑定成功，哈根达斯单球券兑换码：{$quan['quan_num']}，兑换门店：哈根达斯直营店（机场店及加盟店不予兑换），有效期：5个月内，详询400-820-6142";
            $resp = $this->sendMessage($content, $user['tel']);
            parse_str($resp, $info);
            if ($info['mterrcode'] == '000') {
                M('Quan')->where(array(
                    'id' => $quan['id'],
                ))->save(array(
                    'taked' => 1,
                    'user_id' => $user['id'],
                    'taked_time' => time(),
                ));
                M('User')->where(array('openid' => $_GET['openid']))->save(array(
                    'bind' => 1,
                    'quan_taked' => 1
                ));
            } else {
                M('User')->where(array('openid' => $_GET['openid']))->save(array(
                    'bind' => 1,
                ));
            }
        } else {
            M('User')->where(array('openid' => $_GET['openid']))->save(array(
                'bind' => 1,
            ));
        }
        redirect("/");
    }
    private function identify($openid)
    {
//        todo 跳转到会员绑定页面 这里做会员判定 是否是会员 会员无绑定 则不会跳转到app 非会员非绑定再说
        $appid = 'bf_market';
        $appsecret = "Vit+HmAG8a+7JCyIEPmR5A==";
        $phone = '13916736934';
        $timestamp = time();
        $data = "appid={$appid}&secretkey={$appsecret}&timestamp={$timestamp}";
        $md5 = md5($data);
        $set = "http://pos.beautyfarm.com.cn:8070/customer/isBindVip?sign={$md5}&timestamp={$timestamp}&appid={$appid}&org_no=beautyfarm&mobile=aaaaaaaaaaa&openid={$openid}";
        $backData = file_get_contents($set);
        $status = json_decode($backData);
        if ($status->status == 1) {
//            网络请求成功
            if ($status->data->IS_BINDING == 1) {
//                用户已经绑定
                if ($status->data->IS_MEMBER == 1) {
                    M('User')->where(array('openid' => $openid))->save(array(
                        'member'=> 1,
                        'bind' => 1
                    ));
                } else {
                    M('User')->where(array('openid' => $openid))->save(array(
                        'member'=> 2,
                        'bind' => 1
                    ));
                }
            } else {
//              没有绑定
                M('User')->where(array('openid' => $openid))->save(array(
                    'bind' => 2
                ));
                redirect("/");
                exit(0);
            }
        } elseif ($status->Status == 0) {
            die('获取用户信息失败');
        }

//        $url='http://bfwechat.beautyfarm.com.cn/CheckBind.aspx?OpenId='.$openid;
//        $backData = file_get_contents($url);
//        $status = json_decode($backData);
//        if ($status->Status == 1) {
////            绑定成功用户
//            M('User')->where(array('openid' => $openid))->save(array(
//                'member'=> 1,
//                'bind' => 1
//            ));
//            redirect("/");
//            exit(0);
//        } elseif ($status->Status == 2) {
////            没有绑定用户
//            redirect("/");
//            exit(0);
//        } elseif ($status->Status == 0) {
//            die('获取用户信息失败');
//        }
    }

    public function member()
    {
        $appid = 'bf_market';
        $appsecret = "Vit+HmAG8a+7JCyIEPmR5A==";
        $phone = 'aaaaaaaaaaa';
        $timestamp = time();
        $data = "appid={$appid}&secretkey={$appsecret}&timestamp={$timestamp}";
        $md5 = md5($data);
        $set = "http://pos.beautyfarm.com.cn:8070/customer/isBindVip?sign={$md5}&timestamp={$timestamp}&appid={$appid}&org_no=beautyfarm&mobile=13916736934&openid=o5ZlRwn-MaiuIrhGYO8Qw100xc0w";
        var_dump($set);
        $backData = file_get_contents($set);
        $status = json_decode($backData);
        print_r($status);
    }
    
    protected function log_user_action($user_id, $action_name,
                                       $action_value_str,
                                       $action_value_int = null)
    {
        M('UserActionLog')->add(array(
            'user_id' => $user_id,
            'action_name' => $action_name,
            'action_key' => hexdec(substr(md5($action_name), 0, 15)),
            'action_value_str' => $action_value_str,
            'action_value_int' => $action_value_int,
        ));
    }
    function getIP()
    {
        if (isSet($_SERVER)) {
            if (isSet($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } elseif (isSet($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $realip = getenv('HTTP_CLIENT_IP');
            } else {
                $realip = getenv('REMOTE_ADDR');
            }
        }
        return current(explode(',', $realip));
    }

    function isWeixin()
    {
        //return true;
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }
    public function debug_open()
    {
        session('X-DEBUG', 1);
        echo 'success';
        redirect("/");
    }

    public function debug_close()
    {
        session('X-DEBUG', null);
        echo 'success';
    }

    public function test_magic()
    {
        cookie('X-PUB_MODE', 'development');
        redirect("/");
    }
}