<?php

namespace common\helpers\bonus\Calc;

use common\models\Period;
use common\traits\ResponseTrait;

class BaseBusiness
{
    use ResponseTrait;

    protected $_periodNum = 0;

    protected $_calc_db_name = 'dbCalcServer';

    const CALC_DB_NAME = 'dbCalcServer';

    protected $_limit = 10000;

    //最小生成自动合格订单的业绩
    public static $automaticEntitlementPerf = 30;

    public function __construct($periodNum)
    {
        if (is_numeric($periodNum)) {
            $this->_periodNum = $periodNum;
            $periodObj        = Period::instance();
//            $periodDataArr = $periodObj->setPeriodNum($periodNum);
//            $this->_periodId = $periodDataArr['ID'];
            $this->_isCalcMonth = $periodObj->isCalcMonth($periodNum);
            $this->_calcYear = $periodObj->getYear($periodNum);
            $this->_calcMonth     = $periodObj->getMonth($periodNum);
            $this->_calcYearMonth = $periodObj->getYearMonth($periodNum);
        } else {
            //todo
            return false;
        }
    }

    /**
     *  从结算系统拉取周期信息并更新
     * @return int
     */
    public static function pullPeriodForUpdate($periodNum = 0): int
    {
        if (empty($periodNum) || !is_numeric($periodNum)) {
            return 0;
        }
        $db = CalcConsole::CALC_DB_NAME;
        //同步字段去掉 IS_CALCULATED, 否则自动拉取的轮询间隔之间奖金计算完成后更新该字段则会认为已经拉取过奖金数据
        $period = \Yii::$app->$db->createCommand("SELECT 
                PERIOD_NUM,
                IS_PERFED,
                IS_PERFING,
                IS_CALCING,
                PERF_PERCENT,
                CALC_PERCENT,
                PERF_STARTED_AT,
                PERFED_AT,
                CALCULATE_STARTED_AT,
                CALCULATED_AT
                FROM AR_PERIOD where PERIOD_NUM = $periodNum")->queryOne();

        return Period::updateAll($period, ['PERIOD_NUM' => $periodNum]);
    }

    public function getCalcPeriod()
    {
        $db = $this->_calc_db_name;
        return \Yii::$app->$db->createCommand("SELECT * FROM AR_PERIOD where PERIOD_NUM = $this->_periodNum")->queryOne();
    }

    public function getMonthsForQuarterly()
    {
        $startTime  = strtotime(date('Y') . '0101');
        $calcMonth1 = date('Ym', strtotime('+' . ($this->_calcMonth - 1) . ' month', $startTime));
        $calcMonth2 = date('Ym', strtotime('+' . ($this->_calcMonth - 2) . ' month', $startTime));
        return [$calcMonth1, $calcMonth2];
    }

    public function getMonthsByPeriodNum($periodNum) {
        $currentPeriod = Period::getInfoByPeriodNum($periodNum);
        $currentYear = $currentPeriod['CALC_YEAR'];
        $currentMonth = $currentPeriod['CALC_MONTH'];
        $calcMonth1 = $currentYear . str_pad($currentMonth - 2,2,"0",STR_PAD_LEFT);
        $calcMonth2 = $currentYear . str_pad($currentMonth - 1,2,"0",STR_PAD_LEFT);
        return [$calcMonth1, $calcMonth2];
    }
}
