<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\love\controller;

use app\common\Wechat;
use app\love\model\LotteryLogModel;
use app\love\model\LotteryPrizeModel;
use app\love\model\UserModel;
use cmf\controller\HomeBaseController;
use think\facade\Request;

class LotteryController extends HomeBaseController
{
    public function initialize()
    {
        parent::initialize();

        //分享页面
        $wx_api_sign = Wechat::instance()->getJsSign(Request::url(true));
        $this->assign('domain', $this->request->domain());
        $this->assign('wx_api_sign', json_encode($wx_api_sign));
    }

    //抽奖页
    public function index()
    {
        //验证
        $user_id = cmf_get_current_user_id();
        $user    = UserModel::get($user_id);
        if ($user['is_marry'] == 2 || $user['sex'] == 1) {
            $this->redirect('/');
        }

        $prize       = LotteryPrizeModel::all();
        $ids         = [];
        $restaraunts = [];
        $colors      = [];
        $images      = [];
        foreach ($prize as $v) {
            $ids[]         = $v->id;
            $restaraunts[] = $v->name;
            $colors[]      = $v->bg;
            $images[]      = cmf_get_image_url($v->image);
        }
        $this->assign('prize', $prize);
        $this->assign('ids', $ids);
        $this->assign('restaraunts', $restaraunts);
        $this->assign('colors', $colors);
        $this->assign('images', $images);

        return $this->fetch();
    }

    /**
     * 抽奖
     */
    public function lotteryPost()
    {
        //抽奖次数
        $user_id = cmf_get_current_user_id();
        $user    = UserModel::get($user_id);
        //已婚
        if ($user['is_marry'] == 2) {
            $this->error('已结婚的才能抽奖');
        }
        if ($user['sex'] == 1) {
            $this->error('女生才能抽奖');
        }

        $lottery = LotteryLogModel::where('user_id', $user_id)->find();
        if (!empty($lottery)) {
            $this->error('一个人只能抽一次奖',url('log'));
        }

        //奖品列表
        $prize_arr = LotteryPrizeModel::where('number', '>', 0)->select();
        $arr       = [];
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['odds'] * 100;
        }
        $rid = $this->_get_rand($arr); //根据概率获取奖项id

        //增加奖品
        $prize = LotteryPrizeModel::where('id', $rid)->find();
        $prize->number--;
        $prize->save();

        LotteryLogModel::create([
            'user_id'     => $user_id,
            'prize_id'    => $rid,
            'create_time' => time(),
            'prize_name'  => $prize['name'],
        ]);

        $this->success('恭喜你，获得' . $prize['name'],'',['id' => $rid]);
    }

    /**
     * 中奖记录
     */
    public function log()
    {
        //奖品
        $user_id = cmf_get_current_user_id();
        $lottery = LotteryLogModel::with('lottery')->where('user_id',$user_id)->find();
        if (empty($lottery) || $lottery['status'] == 1) {
            $this->redirect('/');
        }
        $lottery['lottery']['image'] = cmf_get_image_url($lottery['lottery']['image']);
        $this->assign('lottery',$lottery);

        return $this->fetch();
    }

    /**
     * 获取奖品
     */
    private function _get_rand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        return $result;
    }
}
