<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class BaseController extends Controller
{
	protected $url;
    protected $data;

    public function __construct()
    {
        parent::__construct();
        $this->url =  'https://'.$_SERVER['SERVER_NAME'].'/canyin2';
        $this->data = I('post.');
        
        if (!isset($this->data['business_id']) || empty($this->data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

        $this->business_status($this->data['business_id']);//查询商户状态
    }

     /**
     * 判断openid
     */
    protected function check_openid()
    {
        if (empty($this->data['openid'])) apiReturn(['status' => -1, 'msg' => 'openid不能为空']);
    }

    /**
     * 判断page参数
     */
    protected function check_page()
    {
        if (empty($this->data['page'])) apiReturn(['status' => -1, 'msg' => 'page参数必须']);
    }

    /**
     * 检测新用户并添加分享积分
     */
    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' => '获取分享积分失败'];
    }

    /**
     * 获取中奖奖品
     * $prize_list 中奖奖品列表
     */
    protected function get_win_goods($prize_list)
    {       
        if (empty($prize_list)) apiReturn(['status' => -1, 'msg' => '后台没有中奖奖品，无法抽奖']);

        $prize_arr = array();
        foreach ($prize_list as $key => $value) {
            $prize_arr[$value['id']]['id'] = $value['id'];
            $prize_arr[$value['id']]['prize'] = $value['goods_name'];
            $prize_arr[$value['id']]['v'] = $value['probability'];
            $prize_arr[$value['id']]['status'] = $value['status'];
        }

        // $prize_arr = array(
        //  '0' => array('id'=>1,'prize'=>'平板电脑','v'=>1),
        //  '1' => array('id'=>2,'prize'=>'数码相机','v'=>5),
        //  '2' => array('id'=>3,'prize'=>'音箱设备','v'=>10),
        //  '3' => array('id'=>4,'prize'=>'4G优盘','v'=>12),
        //  '4' => array('id'=>5,'prize'=>'10Q币','v'=>22),
        //  '5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>50),
        // );

        $actor = 100;
        foreach ($prize_arr as $v) {
            $arr[$v['id']] = $v['v'];
        }
        foreach ($arr as &$v) {
            $v = $v*$actor;
        }
        asort($arr);
        $sum = array_sum($arr);   //总概率
        $rand = mt_rand(1,$sum);
        $result = '';    //中奖产品id
        foreach ($arr as $k => $x){
            if($rand <= $x) {
                $result = $k;
                break;
            } else {
                $rand -= $x;
            }
        }
        
        $res['yes'] = $prize_arr[$result]; //中奖项
        return $res;
    }

     /**
     * 查询商户状态
     */
    private function business_status($business_id = '')
    {
        $result = M('admin')->where('id = '.$business_id.' AND is_business <> 2')->field('status')->select();
        if (empty($result)) {
            apiReturn(['status' => -1, 'msg' => '该商户不存在']);
        } elseif ($result[0]['status'] == -1) {
            apiReturn(['status' => -1, 'msg' => '该商户已被禁用']);
        }
    }
}