<?php
/**
 * 获取用户信息
 ***/
defined('InShopNC') or exit('Access Invalid!');

require_once(BASE_ROOT_PATH . '/helper/text_filter.php');
require_once(BASE_ROOT_PATH . '/helper/FileUploader.php');
require_once(BASE_ROOT_PATH . '/helper/relation_helper.php');
require_once(BASE_ROOT_PATH . '/helper/util_helper.php');
require_once(BASE_ROOT_PATH . '/helper/url_helper.php');

require_once(BASE_RESOURCE_PATH . '/phpqrcode/index.php');


class member_infoControl extends mbMemberControl
{
    public function __construct()
    {
        parent::__construct();
    }

    public function getinfoOp()
    {
        $this->getOp();
    }

    public function getOp()
    {
        $fields = array('member_sex','member_nickname','member_truename','member_signname','member_birthday','member_mobile','member_avatar');

        $ret = array();
        foreach($fields as $key)
        {
            if(array_key_exists($key,$_SESSION))
            {
                if($key == 'member_birthday') {
                    $time = $_SESSION[$key];
                    $birthday = strtotime($time);
                    $ret[$key] = ($birthday == false) ? '0' : $birthday;
                }
                elseif($key == 'member_avatar')
                {
                    $path = $_SESSION[$key];
                    if(empty($path)) {
                        $ret['member_avatar'] = "";
                    }
                    else
                    {
                        if(strncasecmp($path,"http://",strlen("http://")) == 0) {
                            $ret['member_avatar'] = $path;
                        } else {
                            $url = UPLOAD_SITE_URL . "/shop/avatar{$path}";
                            $ret['member_avatar'] = $url;
                        }
                    }
                }
                else {
                    $ret[$key] = $_SESSION[$key];
                }
            }
        }
        $ret['qrcode'] = $this->qrcode();
        $ret['sub_titles'] = $this->sub_titles();

        if($ret['member_sex'] == 2) {
            $ret['member_sex'] = 0;
        }

        self::outsuccess($ret);
    }

    private function sub_titles()
    {
        $ret['qrcode'] = '邀请好友领5元全抵红包，好友得百元红包';

        $addr_num = session_helper::address_num();
        if($addr_num > 0) {
            $ret['addr_num'] = "{$addr_num}个";
        } else {
            $ret['addr_num'] = "尚未设置";
        }

        $favorate_num = session_helper::favorate_num();
        if($favorate_num > 0) {
            $ret['favorate_num'] = "{$addr_num}个";
        } else {
            $ret['favorate_num'] = "尚未收藏";
        }

        $fcode_num = session_helper::fcode_num();
        if($fcode_num > 0) {
            $ret['fcode_num'] = "{$fcode_num}个可用";
        } else {
            $ret['fcode_num'] = "没有F码";
        }

        return $ret;
    }

    private function upfile($img,&$err)
    {
        $member_id = $_SESSION['member_id'];

        $upload = new FileUploader();
        if($upload->init_files($img,$member_id,$err) == false) {
            return false;
        }

        $upload_dir = ATTACH_AVATAR.DS.$member_id.DS;
        $upload->set('default_dir',$upload_dir.$upload->getSysSetPath());
        $thumb_width	= '480,1024';
        $thumb_height	= '480,1024';

        $upload->set('max_size',C('image_max_filesize'));
        $upload->set('thumb_width', $thumb_width);
        $upload->set('thumb_height',$thumb_height);
        $upload->set('fprefix',$member_id);
        $upload->set('thumb_ext', '_240,_1024');
        $result = $upload->upfile('file');
        if($result == true) {
            return $upload->file_name;
        } else {
            $err = array('code' => errcode::ErrUpfile, 'msg' => $upload->error);
            return false;
        }
    }

    private function file_path()
    {
        $file_path = $_POST["file_path"];
        if(file_exists($file_path) == false) {
            $file_path = BASE_ROOT_PATH . '/data/upload/upfile' . $file_path;
        }
        return $file_path;
    }

    public function upavatarOp()
    {
        $file_path = $this->file_path();
        $member_id = $_SESSION['member_id'];
        $file_name = $this->upfile($file_path,$err);
        if($file_name == false) {
            return self::outerr(errcode::ErrUploadFileFailed);
        }
        $file_path = DS.$member_id.DS.$file_name;
        $ret = Model("member")->editMember(array('member_id' => $member_id),array('member_avatar' => $file_path));
        if ($ret) {
            $_SESSION['member_avatar'] = $file_path;
            $url = UPLOAD_SITE_URL . "/shop/avatar{$file_path}";
            return self::outsuccess(array('member_avatar' => $url));
        } else {
            return self::outerr(errcode::ErrDB);
        }
    }

    public function upcontactsOp()
    {
        $contacts = session_helper::parse_contacts($_POST["contact_list"]);
        if ($contacts == false) {
            return self::outerr(errcode::ErrParamter);
        }

        relation_helper::onUpContacts($_SESSION['member_id'],$contacts);
        return self::outsuccess(NULL);
    }

    public function updateinfoOp()
    {
        $this->editOp();
    }

    public function editOp()
    {
        $member_nickname = urldecode($_GET['nickname']);
        $member_truename = urldecode($_GET['truename']);
        $member_signname = urldecode($_GET['signname']);
        $member_sex      = trim(urldecode($_GET['sex']));
        $member_birthday = trim(urldecode(($_GET['birthday'])));

        $update = array();
        if (is_numeric($member_sex))
        {
            $iSex = intval($member_sex);
            if($iSex == 0 || $iSex == 1) {
                $update['member_sex'] = $member_sex;
            }
        }
        if(isset($member_nickname) && !empty($member_nickname)) {
            $member_nickname = text_filter::filter_input($member_nickname);
            $update['member_nickname'] = $member_nickname;
        }
        if(isset($member_truename) && !empty($member_truename)) {
            $member_truename = text_filter::filter_input($member_truename);
            $update['member_truename'] = $member_truename;
        }
        if(isset($member_signname) && !empty($member_signname)) {
            $member_signname = text_filter::filter_input($member_signname);
            $update['member_signname'] = $member_signname;
        }
        if(isset($member_birthday))
        {
            $itm = intval($member_birthday);
            if($itm > 0 && $member_birthday = strftime("%Y-%m-%d",$member_birthday)) {
                $update['member_birthday'] = $member_birthday;
            }
        }
        if(empty($update)) {
            return self::outerr(errcode::ErrInputParam);
        }

        $mod = Model('member');
        $ret = $mod->editMember(array('member_id' => $_SESSION['member_id']),$update);
        if($ret && $mod->affected_rows() > 0)
        {
            foreach($update as $key => $val) {
                $_SESSION[$key] = $val;
            }
            self::outsuccess(array('ret' => 1 ));
        }
        else {
            self::outsuccess(array('ret' => 1 ));
        }
    }

    public function modifypassOp()
    {
        $oldpasswd = trim($_GET['oldpasswd']);
        $newpasswd = trim($_GET['newpasswd']);

        // 校验原有用户内容
        $model = Model('member');
        $oldpasswd = empty($oldpasswd) ? '' : md5($oldpasswd);
        $newpasswd = empty($newpasswd) ? '' : md5($newpasswd);
        $ret = $model->editMember(array('member_id' => $_SESSION['member_id'],'member_passwd' => $oldpasswd))->update(array('member_passwd' => $newpasswd));
        if ($ret === false) {
            return self::outerr(errcode::ErrPasswd);
        } else {
            return self::outsuccess(NULL);
        }
    }

    private function qrcode()
    {
        $passwd = util::passwd;
        $member_id = $_SESSION['member_id'];

        $path = DS.ATTACH_MQRCODE.DS;
        $en_name = md5("{$member_id}.{$passwd}");
        $name = "{$en_name}.png";

        $filename = BASE_UPLOAD_PATH . $path . $name;
        if (!file_exists($filename)) {
            $url = url_helper::member_index($member_id);
            util::qrcode($url,$name);
        }

        $qurl = UPLOAD_SITE_URL . $path . $name;
        return $qurl;
    }

    public function qrcodeOp()
    {
        $url = $this->qrcode();
        return self::outsuccess(['url' => $url]);
    }

    /**
     * 微信绑定
     *
     * 输入参数：
     * wx_openid 微信id
     * user_info: 用户信息
     */
//    public function bindOp()
//    {
//        $wx_openid = trim($_GET['wx_openid']);
//        $wx_info = trim($_GET['user_info']);
//
//        Log::record("wechat info={$wx_info}",Log::DEBUG);
//
//        // 输入内容判断
//        $validator = new Validate();
//        $validator->setValidate(Validate::verify_openid($wx_openid));
//        $err = $validator->validate();
//        if ($err != '') {
//            return self::outerr(errcode::ErrInputParam);
//        }
//
//        // 判断是否处理
//        $model = Model('member');
//        $ret = $model->editMember(array('member_id' => $_SESSION['member_id']), array('member_wxopenid' => $wx_openid, 'wx_info' => serialize($wx_info)));
//        if ($ret == false) {
//            return self::outerr(errcode::ErrDB);
//        } else {
//            return self::outsuccess(NULL);
//        }
//    }
}
