<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/4/17
 * Time: 下午6:46
 */

require_once (BASE_ROOT_PATH . '/helper/algorithm.php');
require_once (BASE_ROOT_PATH . '/helper/relation_helper.php');
require_once (BASE_ROOT_PATH . '/helper/account_helper.php');
require_once (BASE_ROOT_PATH . '/helper/push_helper.php');
require_once (BASE_ROOT_PATH . '/helper/login_helper.php');
require_once (BASE_ROOT_PATH . '/helper/bonus_helper.php');

class session_helper
{
    const mobile_login = 1;
    const wxopen_login = 2;
    const mobile_len = 11;

    const device_ios = 1;
    const device_android = 2;

    static public function mobile_valid($mobile)
    {
        if (!isset($mobile) || empty($mobile) || strlen($mobile) < self::mobile_len) {
            return false;
        }

        $ret = preg_match('/^1(?:3[0-9]|5[012356789]|8[0256789]|7[0678])(-?)\d{4}\1\d{4}$/', $mobile, $arr);
        if ($ret == false || count($arr) <= 0) {
            return false;
        } else {
            $mobile = $arr[0];
        }
        $mobile = str_replace('-', '', $mobile);
        $mobile = substr($mobile, -self::mobile_len);
        $validate = new Validator();
        $validate->setValidate(Validator::verify_mobile($mobile));
        $err = $validate->validate();
        if (empty($err)) {
            return $mobile;
        } else {
            return false;
        }
    }

    static public function memberid()
    {
        return intval($_SESSION['member_id']);
    }

    static public function nickname()
    {
        if (isset($_SESSION['member_nickname']) && !empty($_SESSION['member_nickname'])) {
            return $_SESSION['member_nickname'];
        }

        if (array_key_exists('wx_author', $_SESSION)) {
            if (array_key_exists('handled', $_SESSION['wx_author'])) {
                $user_info = $_SESSION['wx_author']['user_info'];
                return $user_info['nickname'];
            }
        }

        if (isset($_SESSION['member_truename']) && !empty($_SESSION['member_truename'])) {
            return $_SESSION['member_truename'];
        }

        if (isset($_SESSION['member_mobile']) && !empty($_SESSION['member_mobile'])) {
            $mobile = $_SESSION['member_mobile'];
            if (strlen($mobile) == 11) {
                return substr_replace($mobile, '****', 3, 4);
            }
        }

        return '';
    }

    static public function isLogin()
    {
        return ($_SESSION['is_login'] == 1);
    }

    static public function logined()
    {
        return ($_SESSION['is_login'] == 1);
    }

    static public function isapp()
    {
        if (isset($_SESSION['is_app'])) {
            return ($_SESSION['is_app'] == true);
        } else {
            return false;
        }
    }

    static public function isVerfiyMobile()
    {
        if (self::isLogin()) {
            return true;
        } else {
            if (isset($_SESSION['member_mobile']) && !empty($_SESSION['member_mobile'])) {
                return true;
            } else {
                return false;
            }
        }
    }

    static public function is_man()
    {
        return (intval($_SESSION['member_sex']) == 1);
    }

    static public function sex()
    {
        $sex = intval($_SESSION['member_sex']);
        if ($sex == 1) {
            return $sex;
        } else {
            return 0;
        }
    }

    static function avatar()
    {
        if (empty($_SESSION['member_avatar'])) {
            if (array_key_exists('wx_author', $_SESSION)) {
                if (array_key_exists('handled', $_SESSION['wx_author'])) {
                    $user_info = $_SESSION['wx_author']['user_info'];
                    return $user_info['headimgurl'];
                }
            }

            if (self::is_man()) {
                $img = 'male.png';
            } else {
                $img = 'female.png';
            }
            return RESOURCE_SITE_URL . '/mobile/defimg/' . $img;
        } else {
            $path = $_SESSION['member_avatar'];
            if (strncasecmp($path, "http://", strlen("http://")) == 0) {
                $url = $path;
            } else {
                $url = UPLOAD_SITE_URL . "/shop/avatar{$path}";
            }

            return $url;
        }
    }

    static public function cur_mobile()
    {
        if (self::isVerfiyMobile()) {
            return $_SESSION['member_mobile'];
        } else {
            return '';
        }
    }

    static public function parase_wxinfo($wxinfo)
    {
        $user = urldecode($wxinfo);

        if (empty($user)) return false;

        $user = json_decode($user, true);
        if ($user == false) return false;

        $info = array();
        $info['member_nickname'] = $user['nickname'];
        $info['member_avatar'] = $user['headimgurl'];
        $info['member_sex'] = intval($user['sex']);

        return $info;
    }

    static public function filter_info($info)
    {
        $member_info = array();
        if (isset($info['member_nickname']) && !empty($info['member_nickname'])) {
            $member_info['member_nickname'] = $info['member_nickname'];
        }

        if (isset($info['member_truename']) && !empty($info['member_truename'])) {
            if (!isset($member_info['member_nickname'])) {
                $member_info['member_nickname'] = $info['member_truename'];
            }
            $member_info['member_truename'] = $info['member_truename'];
        }

        if (isset($info['member_mobile']) && !empty($info['member_mobile'])) {
            $mobile = $info['member_mobile'];
            if (!isset($member_info['member_nickname'])) {
                $member_info['member_nickname'] = substr_replace($mobile, '****', 3, 4);
            }
            $member_info['member_mobile'] = $info['member_mobile'];
        }

        return $member_info;
    }

    static public function filter_member_info($member_info, $openid)
    {
        field_helper::validate_null_string($member_info, 'member_mobile,member_wxopenid,member_name,' .
            'member_truename,member_signname,member_avatar,member_email,member_birthday');
        field_helper::validate_null_string($member_info, 'member_sex', '0');
        field_helper::validate_null_string($member_info, 'member_nickname', substr_replace($openid, '****', 3, 4));
        return $member_info;
    }

    static public function parse_contacts($contacts)
    {
        if (!isset($contacts)) {
            return false;
        }

        $contacts = json_decode(urldecode($contacts));
        if ($contacts == false) {
            return false;
        }

        $ar_contact = array();
        foreach ($contacts as $mobile)
        {
            $mobile = session_helper::mobile_valid($mobile);
            if ($mobile == false) {
                continue;
            }
            if (algorithm::bsearch($mobile, $ar_contact) != -1) {
                continue;
            }

            array_push($ar_contact, $mobile);
            sort($ar_contact);
        }

        return $ar_contact;
    }

    static public function session_id()
    {
        return empty($_SESSION['MPHPSESSID']) ? "" : $_SESSION['MPHPSESSID'];
    }

    static public function need_wechat_author()
    {
        if (BASE_SITE_URL != 'http://p.lrlz.com') {
            return false;
        }

        if (util::from_wechat() == false) {
            return false;
        }
        else
        {
            if (array_key_exists('wx_author', $_SESSION))
            {
                if (array_key_exists('handled', $_SESSION['wx_author']))
                {
                    $user_info = $_SESSION['wx_author']['user_info'];
                    $loginer = new login\unionid_log($user_info['unionid']);
                    if ($loginer->ismember() == true) {
                        $loginer->bind($user_info);
                        $loginer->login();
                        unset($_SESSION['wx_author']);
                    }
                }

                return false;
            }
            else
            {
                if (!empty($_SESSION['member_wxunionid']) && !empty($_SESSION['member_wxopenid']))
                {
                    $author_time = $_SESSION['wxauthor_time'];
                    $max_time = 2 * 86400;
                    if (time() - $author_time > $max_time) {
                        return true;
                    } else {
                        return false;
                    }
                }
                else {
                    return true;
                }
            }
        }
    }

    static public function pub_openid()
    {
        if (empty($_SESSION['member_wxopenid'])) {
            return false;
        } else {
            return $_SESSION['member_wxopenid'];
        }
    }

    static public function unionid()
    {
        if (!empty($_SESSION['member_wxunionid'])) {
            return $_SESSION['member_wxunionid'];
        }

        if (array_key_exists('wx_author', $_SESSION))
        {
            if (array_key_exists('handled', $_SESSION['wx_author'])) {
                $user_info = $_SESSION['wx_author']['user_info'];
                return $user_info['unionid'];
            }
        }

        return false;
    }

    static public function thief($fromid, &$err)
    {
        $thief = new bonus\thief_vilator($fromid);
        return $thief->thief($err);
    }

    static public function first_order()
    {
        if (array_key_exists('order_num', $_SESSION)) {
            $order_num = $_SESSION['order_num'];
        }
        else {
            $mod_member = Model('member');
            $minfo = $mod_member->getMemberInfoByID(self::memberid());
            if (empty($minfo)) return false;

            $order_num = intval($minfo['order_num']);
            if ($order_num > 0) {
                $_SESSION['order_num'] = $order_num;
            }
        }

        if ($order_num == 0) {
            return true;
        } else {
            return false;
        }
    }

    static public function can_send()
    {
        if (array_key_exists('order_num', $_SESSION)) {
            $order_num = $_SESSION['order_num'];
        }
        else
        {
            $mod_member = Model('member');
            $minfo = $mod_member->getMemberInfoByID(self::memberid());

            if (empty($minfo)) return false;

            $order_num = intval($minfo['order_num']);
            if ($order_num > 0) {
                $_SESSION['order_num'] = $order_num;
            }
        }
        return $order_num > 0;
    }

    static public function add_order()
    {
        if (!array_key_exists('order_num', $_SESSION)) {
            $mod_member = Model('member');
            $mod_member->editMember(['member_id' => self::memberid()],['order_num' => array('exp', 'order_num+1'),'lastest_order' => time()]);
            $minfo = $mod_member->getMemberInfoByID(self::memberid());
            $_SESSION['order_num'] = intval($minfo['order_num']);
        } else {
            $_SESSION['order_num'] += 1;
        }
    }

    static public function share_id()
    {
        if(self::logined()) {
            return self::memberid();
        }
        else
        {
            if(array_key_exists('relay_id',$_SESSION)) {
                return $_SESSION['relay_id'];
            } else {
                return 0;
            }
        }
    }

    static public function relay_id()
    {
        if(array_key_exists('relay_id',$_SESSION)) {
            return $_SESSION['relay_id'];
        } else {
            return 0;
        }
    }

    static public function set_relay($relay_id)
    {
        $relay_id = intval($relay_id);
        if($relay_id > 0) {
            $_SESSION['relay_id'] = $relay_id;
        }
    }


    static public function client_type()
    {
        if($_SESSION['client_type'] == 'android') {
            return self::device_android;
        }
        elseif($_SESSION['client_type'] == 'ios') {
            return self::device_ios;
        }
        else {
            return 0;
        }
    }

    static public function version_code()
    {
        if(self::client_type() == self::device_android) {
            return $_SESSION['client_version'];
        }
        elseif(self::client_type() == self::device_ios) {
            return $_SESSION['client_version'] * 100;
        }
        else {
            return 0;
        }
    }

    //缓存数据给个人页面使用
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    static public function address_num()
    {
        if(array_key_exists('address_num',$_SESSION)) {
            return $_SESSION['address_num'];
        }
        else
        {
            $mod_addr = Model('address');
            $_SESSION['address_num'] = $mod_addr->getAddressCount(['member_id' => self::memberid()]);
            return $_SESSION['address_num'];
        }
    }
    static public function clear_addr()
    {
        if (array_key_exists('address_num', $_SESSION)) {
            unset($_SESSION['address_num']);
        }
    }
    static public function favorate_num()
    {
        if(array_key_exists('favorate_num',$_SESSION)) {
            return $_SESSION['favorate_num'];
        }
        else
        {
            $mod_favorites = Model('favorites');
            $_SESSION['favorate_num'] = $mod_favorites->getFavoritesCount(['member_id' => self::memberid()]);
            return $_SESSION['favorate_num'];
        }
    }
    static public function clear_favorate()
    {
        if (array_key_exists('favorate_num', $_SESSION)) {
            unset($_SESSION['favorate_num']);
        }
    }

    static public function fcode_num()
    {
        if(array_key_exists('fcode_num',$_SESSION)) {
            return $_SESSION['fcode_num'];
        }
        else
        {
            $mod_favorites = Model('goods_fcode');
            $_SESSION['fcode_num'] = $mod_favorites->getUsableFcodeCount(self::cur_mobile());
            return $_SESSION['fcode_num'];
        }
    }
    static public function clear_fcode()
    {
        if (array_key_exists('fcode_num', $_SESSION)) {
            unset($_SESSION['fcode_num']);
        }
    }
}