<?php
namespace common\models\forms;


use common\components\Model;
use common\helpers\bonus\CalcServeBonusCalc;
use common\helpers\bonus\CalcServePerfCalc;
use common\models\Period;
use yii\base\Exception;

class CalcServePeriodForm extends Model
{
    public $periodNum;

    private $_periodModel;

    /**
     * @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 = Period::findOne(['PERIOD_NUM' => $this->periodNum]);
        if(!$periodModel){
            $this->addError($attributes, '所传期数不存在');
        }

        $this->_periodModel = $periodModel;
    }

    /**
     * 累计用户业绩
     * @param $handleUserId
     * @return bool|null
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function perfAsync($handleUserId,$periodNum){
        if(!$this->validate()){
            return null;
        }
        $bonusCalc = CalcServePerfCalc::instance();
        $periodNum = $periodNum ? $periodNum : $this->periodNum;
        $asyncResult = $bonusCalc->calcStep($periodNum, $handleUserId);
        if($asyncResult){
            $bonusCalc->endCalcTask();
        } else {
            $bonusCalc->errorCalcTask();
            // $this->addErrors($bonusCalc->getErrors());
        }
        return $asyncResult;
    }

    /**
     * 计算用户奖金
     * @param $handleUserId
     * @return bool|null
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function calcAsync($handleUserId){
        if(!$this->validate()){
            return null;
        }
        $bonusCalc = CalcServeBonusCalc::instance();
        $asyncResult = $bonusCalc->calcStep($this->periodNum, $handleUserId);
        if($asyncResult){
            $bonusCalc->endCalcTask();
        } else {
            $bonusCalc->errorCalcTask();
            $this->addErrors($bonusCalc->getErrors());
        }
        return $asyncResult;
    }
}
