<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/21/021
 * Time: 10:22
 */

namespace frontend\controllers;

use frontend\models\forms\PartnerApplyForm;
use frontend\models\forms\RegisterForm;
use Yii;
use frontend\models\IndexApi;
use frontend\models\LottoRecordApi;
use frontend\models\LottoSmsApi;
use yii\helpers\Html;
use yii\web\Controller;

class ApiController extends BaseController
{
    public $enableCsrfValidation = false;

    /**
     * 保存首页报名信息
     */
    public function actionSaveRegister()
    {
        $form = new RegisterForm();
        if (Yii::$app->getRequest()->post()) {
            $data = Yii::$app->getRequest()->post();
            $form->setAttributes($data);
            if ($form->register()) {
                return $this->asJson([
                    'isSuccess' => true,
                    'msg' => '操作成功',
                ]);
            } else {
                return $this->asJson([
                    'isSuccess' => false,
                    'msg' => Html::errorSummary($form),
                ]);
            }
        }
        return $this->asJson([
            'isSuccess' => false,
            'msg' => 'invalid request',
        ]);
    }

    /**
     * 保持合伙人报名信息
     */
    public function actionSavePartnerApply()
    {
        $model = new PartnerApplyForm();
        if (Yii::$app->getRequest()->post()) {
            $data = Yii::$app->getRequest()->post();
            $model->setAttributes($data);
            if ($model->savePartnerApply()) {
                return $this->asJson([
                    'isSuccess' => true,
                    'msg' => '操作成功',
                ]);
            } else {
                return $this->asJson([
                    'isSuccess' => false,
                    'msg' => Html::errorSummary($model),
                ]);
            }
        }
        return $this->asJson([
            'isSuccess' => false,
            'msg' => 'invalid request',
        ]);
    }

    /**
     * 保存原落地页报名信息
     */
    public function actionSaveEnroll()
    {
        $request = \Yii::$app->request->post();
        if (empty($request['nickname'])) {
            return false;
        }
        $indexApi = new IndexApi();
        $rs = $indexApi->saveEnroll($request);
        return $this->asJson($rs);
    }
    
    /**
     * 保存中奖记录
     */
    public function actionSaveLottoRecord()
    {
        $response = ['isSuccess' => false, 'msg' => ''];
        
        $request = array_merge(Yii::$app->request->get(), Yii::$app->request->post());
        $params = [];
        $params['mobile'] = isset($request['mobile']) ? trim($request['mobile']) : '';
        $params['lottery'] = isset($request['lottery']) ? trim($request['lottery']) : '';
        $params['activity_type'] = isset($request['activity_type']) ? intval($request['activity_type']) : (isset($request['activityType']) ? intval($request['activityType']) : 0);
        
        // 类型必须是正整数
        if (empty($params['mobile']) || empty($params['lottery']) || empty($params['activity_type'])) {
            $response['msg'] = '缺少中奖信息参数';
            return $this->asJson($response);
        }

        $api = new LottoRecordApi();
        $result = $api->add($params);
        
        $response['isSuccess'] = $result['code'] == 1 ? true : false;
        $response['msg'] = $result['message'];
        return $this->asJson($response);
    }
    
    /**
     * 发送短信
     */
    public function actionLottoSendSmsCode()
    {
        $response = ['isSuccess' => false, 'msg' => ''];
        
        $request = array_merge(Yii::$app->request->get(), Yii::$app->request->post());
        $params = [];
        $params['mobile'] = isset($request['mobile']) ? trim($request['mobile']) : '';
        
        if (empty($params['mobile'])) {
            $response['msg'] = '请输入手机号码';
            return $this->asJson($response);
        }
        
        $api = new LottoSmsApi();
        $result = $api->sendSmsCode($params);

        $response['isSuccess'] = $result['code'] == 1 ? true : false;
        $response['msg'] = $result['message'];
        return $this->asJson($response);
    }

    /**
     * 验证短信验证码是否正确
     */
    public function actionLottoVerifySmsCode()
    {
        $response = ['isSuccess' => false, 'msg' => '', 'object' => null];
        
        $request = array_merge(Yii::$app->request->get(), Yii::$app->request->post());
        $params = [];
        $params['mobile'] = isset($request['mobile']) ? trim($request['mobile']) : '';
        $params['code'] = isset($request['code']) ? trim($request['code']) : '';

        if (empty($params['mobile'])) {
            $response['msg'] = '请输入手机号码';
            return $this->asJson($response);
        }

        if (empty($params['code'])) {
            $response['msg'] = '请输入验证码';
            return $this->asJson($response);
        }

        $api = new LottoSmsApi();
        $result = $api->verifySmsCode($params);

        $response['isSuccess'] = $result['code'] == 1 ? true : false;
        $response['msg'] = $result['message'];
        $response['object'] = $this->chanceSelect();
        return $this->asJson($response);
    }
    
    /**
     * 保存中间记录
     */
    public function actionLottoSaveLottery()
    {
        $response = ['isSuccess' => false, 'msg' => ''];
        
        header('Access-Control-Allow-Origin: *');
        
        $request = array_merge(Yii::$app->request->get(), Yii::$app->request->post());
        $params = [];
        $params['mobile'] = isset($request['mobile']) ? trim($request['mobile']) : '';
        $params['lottery'] = isset($request['lottery']) ? trim($request['lottery']) : '';

        if (empty($params['mobile'])) {
            $response['msg'] = '请输入手机号码';
            return $this->asJson($response);
        }

        if (empty($params['lottery'])) {
            $response['msg'] = '缺少lottery参数';
            return $this->asJson($response);
        }

        $api = new LottoSmsApi();
        $result = $api->saveLottery($params);

        $response['isSuccess'] = $result['code'] == 1 ? true : false;
        $response['msg'] = $result['message'];
        return $this->asJson($response);
    }

    /**
     * 概率生成
     * @param keyChanceMap
     *            key为唯一标识，value为该标识的概率，是去掉%的数字
     * @return 被选中的key。未选中返回null
     */
    private function chanceSelect()
    {
        $result = null;
        $keyChanceMap = [];
        $keyChanceMap[1] = 5;
        $keyChanceMap[2] = 5;
        $keyChanceMap[3] = 7;
        $keyChanceMap[4] = 10;
        $keyChanceMap[5] = 5;
        $keyChanceMap[6] = 18;
        $keyChanceMap[7] = 50;

        if (count($keyChanceMap) == 0) {
            return null;
        }
        $sum = array_sum($keyChanceMap);
        foreach ($keyChanceMap as $key => $item) {
            $randNum = mt_rand(1, $sum);
            if ($randNum <= $item) {
                $result = $key;
                break;
            } else {
                $sum -= $item;
            }
        }
        unset($keyChanceMap);
        return $result;
    }
}