<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class UserController extends Controller
{   
    /**
     * 获取用户openid
     */
    public function get_openid()
    {
        $data = I('post.');
        if (empty($data['code'])) apiReturn(['status' => -1, 'msg' => 'code不能为空']);
        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

        $return_param = $this->get_openid_session_key($data['code'], $data['business_id']);// appid, appsecret
        // dump($return_param);die;
        apiReturn(['status' => 1, 'msg' => '已获取数据','openid' => $return_param['openid']]);
    }

    /**
     * 保存用户信息
     */
    public function save_user_info()
    {
        $data = I('post.');
        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['openid'])) apiReturn(['status' => -1, 'msg' => 'openid不能为空']);

        $item = M('users')->where(array('openid' => $data['openid']))->limit(1)->select();
        if (empty($item)) {
            $data['admin_id'] = $data['business_id'];
            $data['create_time'] = time();
            $insert_id = M('users')->add($data);

            if ($insert_id) {
                // 新用户，推客检测并添加用户积分
                if (!empty($data['u_openid'])) {
                    $this->add_share($data['u_openid'], $data['openid'], $data['business_id']);
                }

                apiReturn(['status' => 1, 'msg' => '保存用户信息成功', 'users_id' => $insert_id]);
            } else {
                apiReturn(['status' => -1, 'msg' => '保存用户信息失败']);
            }
        } else {
            $data['update_time'] = time();
            $data['id'] = $item[0]['id'];
            if (M('users')->where('id='.$data['id'])->save($data)) {
                apiReturn(['status' => 1, 'msg' => '更新成功', 'users_id' => $item[0]['id']]);
            } else {
                apiReturn(['status' => -1, 'msg' => '更新失败', 'users_id' => $item[0]['id']]);
            }
        }
    }

    /**
     * 获取获取商户appid和appsecret
     */
    private function get_appid_appsecret($business_id = '')
    {
        $config = M('wechat_config')->where(array('admin_id' => $business_id))->field('appid, appsecret')->find();
        return $config;
    }

    /**
     * 获取openid和session_key
     */
    private function get_openid_session_key($code = '', $business_id = '')
    {
        $appid_appsecret = $this->get_appid_appsecret($business_id);

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid_appsecret['appid'].'&secret='.$appid_appsecret['appsecret'].'&js_code='.$code.'&grant_type=authorization_code';
        $return_param = curlGet($url);
        return json_decode($return_param, true);
    }

    /**
     * 检测新用户并添加分享积分
     */
    protected function add_share($u_openid = '', $s_openid = '', $business_id = '')
    {   
        if (empty($u_openid)) return ['status' => -1, 'msg' => 'u_openid参数必须'];

        if (empty($s_openid)) return ['status' => -1, 'msg' => 's_openid参数必须'];

        if (empty($business_id)) return ['status' => -1, 'msg' => 'business_id参数必须'];

        $config = M('share_config')->where(array('admin_id' => $business_id))->find();

        if (empty($config)) {
            M('share_config')->add(array(
                    'admin_id' => $business_id,
                    'create_time' => time()
                ));
            $config = M('share_config')->where(array('admin_id' => $business_id))->find();
        }

        // 检测推客开关
        if ($config['status'] == 2) return ['status' => -1, 'msg' => '商户已经关闭了推客功能'];


        // 被分享者信息
        $s_info = M('users')->where(array('admin_id' => $business_id, 'openid' => $s_openid))->find();
        // 分享者信息
        $u_info = M('users')->where(array('admin_id' => $business_id, 'openid' => $u_openid))->find();

        // 检测分享次数
        $start_time = strtotime(date('Y-m-d'));// 当天开始时间
        $end_time = $start_time + 24 * 60 * 60;// 当天结束时间
        $list = M('share')->where(array('user_id' => $u_info['id'], 'create_time' => array('>=' => $start_time), 'create_time' => array('<' => $end_time)))->select();
        if (count($list) >= $config['num']) return ['status' => -1, 'msg' => '用户每天可以转发获取积分'.$config['num'].'次'];

        // 添加分享记录
        $add = array(
                'user_id' => $u_info['id'],
                'share_id' => $s_info['id'],
                'int' => $config['acc'],
                'create_time' => time()
            );
        $share_log = M('share')->add($add);
        
        // 添加积分
        if ($share_log) {
            $user_int = M('user_int')->where(array('user_id' => $u_info['id']))->find();
            if (empty($user_int)) {
                $int_log = M('user_int')->add(array('user_id' => $u_info['id'], 'int' => $config['acc'], 'create_time' => time()));
            } else {
                $int_log = M('user_int')->where(array('user_id' => $u_info['id']))->save(array('int' => $user_int['int'] + $config['acc'], 'update_time' => time()));
            }
        }

        if ($int_log) {
            return ['status' => 1, 'msg' => '获取分享积分成功'];
        } 

        M('share')->where(array('id' => $share_log))->delete();

        return ['status' => -1, 'msg' => '获取分享积分失败'];
    }

    //用户签到
    public function UserSignIn(){
    	$openid = I('post.openid');
    	$business_id = I('post.business_id');
    	if (empty($openid)) apiReturn(['status' => -1, 'msg' => 'openid不能为空']);
    	if (empty($business_id)) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

    	$userData = M('Users') -> field('id') -> where("openid = '{$openid}'") -> find();
    	$uid = $userData['id'];
    	if(!$uid){
    		apiReturn(['status' => -3, 'msg' => '无此用户']);
    	}

    	$nowtime = time();
        $todayBegin = strtotime(date('Y-m-d',$nowtime));
        $todayEnd = $todayBegin + 24 * 3600 - 1;

        $check = M('Sign_in') -> where("uid = {$uid} AND business_id={$business_id} AND create_time >= {$todayBegin} AND create_time <= {$todayEnd}") -> count();
        if($check){
        	apiReturn(['status' => -2, 'msg' => '已签到过']);
        }

        $adminData = M('Admin') -> field('sign_in') -> find($business_id);
        if(empty($adminData['sign_in'])){
        	apiReturn(['status' => -4, 'msg' => '商家未开启签到']);
        }

        $data['uid'] = $uid;
        $data['create_time'] = $nowtime;
        $data['business_id'] = $business_id;

        $success = M('Sign_in') -> add($data);
        if(!$success){
        	apiReturn(['status' => -5, 'msg' => '添加签到记录失败']);
        }

        $user_int = M('user_int')->where(array('user_id' => $uid))->find();
        
        if (empty($user_int)) {
            $int_log = M('user_int')->add(array('user_id' => $uid, 'int' => $adminData['sign_in'], 'create_time' => $nowtime));
        } else {
            $int_log = M('user_int')->where(array('user_id' => $uid))->save(array('int' => $user_int['int'] + $adminData['sign_in'], 'update_time' => $nowtime));
        }


        if ($int_log) {
            apiReturn(['status' => 1, 'msg' => '签到成功']);
        }

    }

    //检测用户是否已签到
    public function CheckUserSignIn(){
    	$openid = I('post.openid');
    	$business_id = I('post.business_id');
    	if (empty($openid)) apiReturn(['status' => -1, 'msg' => 'openid不能为空']);
    	if (empty($business_id)) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

    	$userData = M('Users') -> field('id') -> where("openid = '{$openid}'") -> find();
    	$uid = $userData['id'];
    	if(!$uid){
    		apiReturn(['status' => -3, 'msg' => '无此用户']);
    	}

    	$nowtime = time();
        $todayBegin = strtotime(date('Y-m-d',$nowtime));
        $todayEnd = $todayBegin + 24 * 3600 - 1;

        $check = M('Sign_in') -> where("uid = {$uid} AND business_id={$business_id} AND create_time >= {$todayBegin} AND create_time <= {$todayEnd}") -> count();
        if($check){
        	apiReturn(['status' => -2, 'msg' => '已签到过']);
        }else{
        	apiReturn(['status' => 1, 'msg' => '未签到']);
        }
    }
}