<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */
namespace frontendApi\modules\v1\controllers;

use common\helpers\Cache;
use common\helpers\ChartData;
use common\helpers\Date;
use common\helpers\user\Reconsume;
use common\helpers\user\Info;
use common\models\Ad;
use common\models\Article;
use common\models\ArticleCategory;
use common\models\CalcBonus;
use common\models\FlowBonus;
use common\models\Period;
use common\models\ReconsumePool;
use common\models\RemainPv;
use common\models\Order;

class DashboardController extends BaseController
{
    public $modelClass = FlowBonus::class;
    public function behaviors() {
        $behaviors = parent::behaviors();
        return $behaviors;
    }

    /**
     * 控制台首页
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionIndex(){
        $nowTime = Date::nowTime();
        $baseInfo=Info::baseInfoZh(\Yii::$app->user->id);
        $news=ArticleCategory::find()->select('ID,CATE_NAME')->orderBy('SORT ASC')->asArray()->all();
        $where = ' CID=:CID AND STATUS=1';
        $time = time();
        foreach ($news as &$value){
            $params = [
                ':CID'=>$value['ID'],
            ];
            $value['LISTS']=Article::find()->select('ID,TITLE,CID,CREATED_AT')->where($where,$params)->orderBy('CREATED_AT DESC')->limit(6)->asArray()->all();
        }
        $empLv = $baseInfo['EMP_LV'];
        $empLvName = $baseInfo['EMP_LV_NAME'];
        if($baseInfo['SHOW_EMP_LV']){
            $empLv = $baseInfo['SHOW_EMP_LV'];
            $empLvName = Cache::getEmpLevelConfig()[$baseInfo['SHOW_EMP_LV']]['LEVEL_NAME'];
        }

        //会员级别
        $decLv = $baseInfo['DEC_LV'];
        $decLvName = $baseInfo['DEC_LV_NAME'];
        //期数显示
        $period = Period::instance();
        $periodNum = $period->getNowPeriodNum();
        //
        $curYM = Period::find()->select("CALC_YEAR,CALC_MONTH")->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM'=>$periodNum])->asArray()->one();

        $plist=Period::find()->select("PERIOD_NUM")->where('CALC_YEAR=:CALC_YEAR AND CALC_MONTH=:CALC_MONTH', [':CALC_YEAR'=>$curYM['CALC_YEAR'],':CALC_MONTH'=>$curYM['CALC_MONTH']])->orderBy('PERIOD_NUM ASC')->asArray()->all();

        $weeks = count($plist);
        $wkrd = '';
        foreach ($plist as $k=>$v){
            if($v['PERIOD_NUM']==$periodNum){
                $wkrd =$k+1;break;
            }
        }
        //剩余分期PV显示
        $myRemainPv = RemainPv::findOne(['USER_ID'=>$baseInfo['ID']])->REMAIN_PV ?? 0;
        // 找到当月的所有订单，计算总PV及总REMAIN_PV
        $myOrders = Order::fetchOrderCurrentMonth($periodNum, $baseInfo['ID']);

        $currentPv = $myOrders->SUM('PV');
        $currentRemainPv = $myOrders->SUM('REMAIN_PV');

        $totalRemainPv = $myRemainPv + $currentRemainPv;

        $sysConfig = Cache::getSystemConfig();
        $mesureUpCondition =  $sysConfig['monthPcsPvFxCondition']['VALUE']; // 月达标条件 NC默认300

        $remainMonth = round($totalRemainPv / $mesureUpCondition);

        if($currentPv >= $mesureUpCondition){ // 如果当月合格，则活跃资格延后一个月
            $activeEndStr = date("Y-m", strtotime('next month'));
        }else{
            $activeEndStr = date("Y-m");
        }

        $activeEndStr = $activeEndStr. " + $remainMonth months";
        $activeEnd = date("Y-m-d H:i:s", strtotime($activeEndStr));

        return static::notice([
            'nowTime' => $nowTime,
            'empLv'=>$empLv,
            'empLvName'=>$empLvName,
            'decLv'=>$decLv,
            'decLvName'=>$decLvName,
            'slides'=>Ad::findUseSlaves()->select('ID,IMAGE,LID,TITLE,CONTENT,TYPE')->where('LID=:LID AND STATUS=1', [':LID'=>'7EFF6260A16C3CC7E053693418AC03E4'])->orderBy('SORT ASC')->asArray()->all(),
            'news'=>$news,
            'periodNum'=>$periodNum.'期，'.$curYM['CALC_MONTH'].'月第'.$wkrd.'周，共'.$weeks.'周',
            'myRemainPv'=>$totalRemainPv,
            'activeEnd'=>$activeEnd
        ]);
    }

    /**
     * 移动端我的页面首页
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionMyIndex() {
        $nowTime = Date::nowTime();
        $baseInfo = Info::baseInfoZh(\Yii::$app->user->id);
        $empLv = $baseInfo['EMP_LV'];
        $empLvName = $baseInfo['EMP_LV_NAME'];
        if ($baseInfo['SHOW_EMP_LV']) {
            $empLv = $baseInfo['SHOW_EMP_LV'];
            $empLvName = Cache::getEmpLevelConfig()[$baseInfo['SHOW_EMP_LV']]['LEVEL_NAME'];
        }
        return static::notice([
            'nowTime' => $nowTime,
            'reConsumePool' => Reconsume::getUserReconsumePool(\Yii::$app->user->id),
            'empLv' => $empLv,
            'empLvName' => $empLvName,
        ]);
    }

    /**
     * 近7期奖金
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPeriodBonus(){
        return static::notice(CalcBonus::periodBonus(\Yii::$app->user->id));
    }

    /**
     * 奖金量
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBonusNum(){
        $chartData = ChartData::instance();
        return static::notice($chartData->userBonusData(\Yii::$app->user->id));
    }
}