<?php

namespace App\Http\Controllers\Channel\Welfare;

use App\Http\Controllers\Channel\BaseController;
use App\Modules\Channel\Services\ChannelUserService;
use App\Modules\Channel\Services\CompanyService;
use App\Modules\Welfare\Services\WelfareBookService;
use App\Modules\Welfare\Services\WelfarePriceSerivce;
use App\Modules\Welfare\Services\WelfareRecordService;
use App\Modules\Welfare\Services\WelfareUserService;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Log;
use Hashids;

class WelfareController extends BaseController
{
    private $_welfare_key = 'welfare^-^zhuishuyun^_^';

    /**
     * @apiDefine Welfare 福利
     */


    /**
     * @apiVersion 1.0.0
     * @api {GET} Welfare/welfare 查询奖励
     * @apiGroup Welfare
     * @apiName welfare
     * @apiSuccess {Object}  data 结果集
     * @apiSuccess {Object}  data.prize 抽奖信息
     * @apiSuccess {Number}  data.prize.is_has_prize 是否有奖励.
     * @apiSuccess {Number}  data.prize.url 抽奖地址.
     * @apiSuccess {Object}  data.book  图书信息
     * @apiSuccess {Object}  data.book.book_name 书名
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":
     *            prize:{
     *              "is_has_prize": 1,
     *              "url": "/aa?token=1233445fghdfthrthy45ktja",
     *            }
     *           books:[]
     *     }
     */
    public function welfare(Request $request)
    {
        $channel_user_id = $this->getChannelUserId();
        $res = WelfarePriceSerivce::isCanPrize($channel_user_id, date('Y-m-d'));
        $data = [];

        $data['prize']['is_has_prize'] = 0;
        $data['prize']['url'] = '';
        $data['prize']['is_alert'] = 0;
        $open_welfare_channel = env('OPEN_WELFARE_CHANNEL');
        $is_open_welfare = false;
        if($open_welfare_channel){
            if($open_welfare_channel == 'all'){
                $is_open_welfare = true;
            }else{
                $open_welfare_channel_array = explode(',',$open_welfare_channel);
                if(in_array($channel_user_id,$open_welfare_channel_array)){
                    $is_open_welfare = true;
                }
            }
        }
        if ($res > 0) {
            $now = time();
            $sign_array = ['channel_user_id' => $channel_user_id, 'time' => $now];
            $token = _sign($sign_array, $this->_welfare_key);
            DB::table('welfare_pre_prizes')->insert([
                'channel_user_id' => $channel_user_id,
                'token' => $token,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s', $now),
                'is_enable' => 1
            ]);
            $data['prize']['is_alert'] = 1;
            $data['prize']['is_has_prize'] = 1;
            $data['prize']['url'] = 'https://' . _domain() . '/welfare/prizeView?token=' . $token;
        }
        if($res == 0){
            $data['prize']['is_alert'] = 1;
            $data['prize']['is_has_prize'] = 0;
        }
        if($res == -1){
            $data['prize']['is_alert'] = 0;
            $data['prize']['is_has_prize'] = 0;
        }

        if(!$is_open_welfare){
            $data['prize']['is_alert'] = 0;
            $data['prize']['is_has_prize'] = 0;
        }
        $channel_user_info = ChannelUserService::getById($channel_user_id);
        $company = CompanyService::getCompany($channel_user_info->company_id);
        if ($company && $company->is_important == 1) {
            $data['books'] = WelfareBookService::getByImportantType(1);
        }else{
            $data['books'] = WelfareBookService::getByImportantType(0);
        }
        if( $data['books']){
            foreach ($data['books'] as &$v){
                $v->bid = Hashids::encode($v->bid);
            }
        }
        return response()->success($data);
    }

    //领取页面
    public function prizeView(Request $request)
    {
        $token = $request->get('token');
        if (empty($token)) {
            return view('channel.web.welfare.index', ['options' => json_encode(['is_access'=>0,'msg'=>'非法访问']),'amount'=>0]);

        }
        $openid = $request->get('openid');
        $welfare_user_id = Cookie::get('welfare_user');
        if (!$openid && !$welfare_user_id) {
            //没有coookie且没有openid 则授权获取openid
            $h5_scheme = 'https';
            $params = $request->except('_url');
            $url = str_replace('http://', $h5_scheme . '://', url()->current() . '?' . http_build_query($params));
            $auth_url = $this->getAuthUrl($url);
            return redirect($auth_url);
        }
        //根据token获取抽奖信息
        $res = DB::table('welfare_pre_prizes')->join('welfare_prizes', 'welfare_prizes.channel_user_id', '=', 'welfare_pre_prizes.channel_user_id')
            ->select('welfare_pre_prizes.channel_user_id', 'welfare_prizes.left', 'welfare_pre_prizes.id','welfare_prizes.id as prize_id')
            ->where('welfare_pre_prizes.token', $token)
            ->where('welfare_prizes.date', date('Y-m-d'))
            ->where('welfare_pre_prizes.created_at', '>', date('Y-m-d'))
            ->where('welfare_pre_prizes.is_enable', '=', 1)
            ->first();
        if (!$res) {
            return view('channel.web.welfare.index', ['options' => json_encode(['is_access'=>0,'msg'=>'非法访问']),'is_prize'=>0,'amount'=>0]);
        }
        if (!$welfare_user_id) {
            $welfare_user = WelfareUserService::createUser($openid, $res->channel_user_id);
            Cookie::queue('welfare_user', $welfare_user->id);
            $welfare_user_id = $welfare_user->id;
        }

        DB::table('welfare_pre_prizes')->where('id', $res->id)->update(['is_enable' => 0, 'updated_at' => date('Y-m-d H:i:s')]);
        if ($res->left <= 0) {
            return view('channel.web.welfare.index', ['options' => json_encode(['is_access'=>0,'msg'=>'']),'is_prize'=>0,'amount'=>0]);
        }

        //抽奖记录  一个用户一天只能抽一次
        $info = WelfareRecordService::getByUid($welfare_user_id);
        if ($info) {
            //已经抽过讲了
            return view('channel.web.welfare.index', ['options' => json_encode(['is_access'=>0,'msg'=>'']),'is_prize'=>0,'amount'=>0]);
        }
        //机会减一次
        WelfarePriceSerivce::decrementLeft($res->prize_id);
        //保存抽奖记录
        $price_pool =$this->getPriceList();
        $amount = array_random($price_pool);
        WelfareRecordService::create([
            'prize_id' =>  $res->prize_id,
            'welfare_uid' => $welfare_user_id,
            'amount' => $amount,
            'status' => 'PENDING'
        ]);
        return view('channel.web.welfare.index', ['options' => json_encode(['is_access'=>1,'msg'=>'']),'is_prize'=>1,'amount'=>$amount]);
    }

    private function getPriceList(){
        $str = '247,2,5,254,13,255,108,256,121,262,425,263,166,267,172,275,184,290,200,292,217,300,229,308,236,311,17,334,154,341,167,345,195,350,228,365,429,376,160,381,207,232,426,176,399,424,404';
        $channel_user_id = $this->getChannelUserId();
        if(in_array($channel_user_id,explode(',',$str))){
            //return $price_pool = [0.1, 0.1, 0.1];
        }
        return [1, 1, 1];
    }
    public function getAuthUrl($redirect_url){
        $params['redirect_url'] = $redirect_url;

        $params['timestamp'] = time();
        $params['gzh_app_id'] = 'wxe559e68b007476f6';

        $params['sign'] =  _sign($params,env('OAUTH_KEY') );
        $auth_base = 'https://zsyauth.aizhuishu.com/user_oauth';
        $redirect = $auth_base . '?' . http_build_query($params);
        return $redirect;
    }
    /**
     * @apiVersion 1.0.0
     * @api {GET} Welfare/prize 抽奖
     * @apiGroup Welfare
     * @apiName prize
     * @apiSuccess {Number}  is_prize 是否中奖
     * @apiSuccess {Number}  amount 中将金额
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data":
     *            {
     *              "is_prize": 1,
     *              "amount": 0,
     *            }
     *
     *     }
     */
    public function prize(Request $request)
    {
        $welfare_user_id = Cookie::get('welfare_user');
        if (!$welfare_user_id) {
            //没有用户信息
            return response()->success(['is_prize' => 0, 'amount' => 0]);
        }
        //抽奖记录  一个用户一天只能抽一次
        $info = WelfareRecordService::getByUid($welfare_user_id);
        if ($info) {
            //已经抽过讲了
            return response()->success(['is_prize' => 0, 'amount' => 0]);
        }

        $welfare_user = WelfareUserService::getByUid($welfare_user_id);
        $price = WelfarePriceSerivce::getByToday($welfare_user->channel_user_id);
        if (!$price) {
            //异常
            return response()->success(['is_prize' => 0, 'amount' => 0]);
        }
        if ($price->left <= 0) {
            //没有抽奖机会了
            return response()->success(['is_prize' => 0, 'amount' => 0]);
        }
        //机会减一次
        WelfarePriceSerivce::where('id', $price->id)->decrement('left');
        //保存抽奖记录
        $price_pool = [1.8, 5.8, 8.8];
        $amount = array_random($price_pool);
        WelfareRecordService::create([
            'prize_id' => $price->id,
            'welfare_uid' => $welfare_user_id,
            'amount' => $amount,
            'status' => 'PENDING'
        ]);
        return response()->success(['is_prize' => 1, 'amount' => $amount]);
    }
}
