<?php
namespace common\models\forms;

use common\helpers\bonus\BonusCalc;
use common\helpers\bonus\BonusSend;
use common\helpers\bonus\PerfCalc;
use common\helpers\Cache;
use common\helpers\Date;
use common\components\Model;
use common\helpers\bonus\PreparePerfCalc;
use common\helpers\Form;
use common\models\Period;
use common\models\PeriodPrepare;
use common\models\UserWallet;
use common\models\User;
use common\models\UserStatusAudit;
use common\models\Withdraw;
use yii\base\Exception;

/**
 * Login form
 */
class PreparePeriodForm extends Model
{
    public $periodNum;

    private $_periodModel;
    private $_limit = 1000;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['periodNum'], 'trim'],
            [['periodNum'], 'required'],
            [['periodNum'], 'integer'],
            [['periodNum'], 'isPeriod'],
        ];
    }

    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'close' => ['periodNum'],
            'perf' => ['periodNum'],
            'calc' => ['periodNum'],
            'send' => ['periodNum'],
            'autoClose' => ['periodNum'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels()
    {
        return [
            'periodNum' => '期数',
        ];
    }

    public function isPeriod($attributes){
        $periodModel = PeriodPrepare::findOne(['PERIOD_NUM' => $this->periodNum]);
        if(!$periodModel){
            $this->addError($attributes, '所传期数不存在');
        }

        $this->_periodModel = $periodModel;
    }

    /**
     * 页面请求异步处理生成业绩单
     * @return string | null
     */
    public function perfWebToAsync(){
        if(!$this->validate()){
            return null;
        }
        $model = $this->_periodModel;
        $model->IS_PERFING = 1;
        $model->PERF_ADMIN_ID = \Yii::$app->user->id;
        if(!$model->save()){
            $this->addError('perf', Form::formatErrorsForApi($model->getErrors()));
            return null;
        }
        // 异步处理添加任务
        $settings = \Yii::$app->params['swooleAsyncTimer'];
        $bonusSettings = \Yii::$app->params['swooleBonusConfig'];
        $settings = array_merge($settings, $bonusSettings);
        $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle('bonus/prepare-perf', \Yii::$app->request->get(), $settings);
        if($taskKey === false){
            $this->addError('perf', '请求失败');
            return null;
        }
        return $model;
    }

    /**
     * 异步处理逻辑
     * @param $handleUserId
     * @return bool|null
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function perfAsync($handleUserId,$periodNum){
        if(!$this->validate()){
            return null;
        }
        $bonusCalc = PreparePerfCalc::instance();
        $periodNum = $periodNum ? $periodNum : $this->periodNum;
        $asyncResult = $bonusCalc->calcStep($periodNum, $handleUserId);
        if($asyncResult){
            $bonusCalc->endCalcTask();
        } else {
            $bonusCalc->errorCalcTask();
            $this->addErrors($bonusCalc->getErrors());
        }
        return $asyncResult;
    }
}
