<?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\EliteLevel;
use common\models\FlowBonus;
use common\models\Period;
use common\models\ReconsumePool;
use common\models\RemainPv;
use common\models\Order;
use common\models\User;
use Yii;

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('CREATED_AT DESC')
            ->asArray()
            ->all();

        $where = ' CID=:CID AND STATUS=1 AND COUNTRY_ID=:COUNTRY_ID';
        foreach ($news as &$value){
            $params = [
                ':CID' => $value['ID'],
                ':COUNTRY_ID' => $baseInfo['COUNTRY_ID'],
            ];
            $value['LISTS'] = Article::find()
                ->select('ID,TITLE,CID,CREATED_AT')
                ->where($where, $params)
                ->orderBy('SORT DESC, 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();

        // 会员Elite级别
        $user = User::findOneAsArray('ID=:ID', [':ID' => \Yii::$app->user->id]);
        $eliteLv = $user['LAST_ELITE_LV'] ?: EliteLevel::getDefaultLevelId();
        $eliteLvName = EliteLevel::getNameById($eliteLv);

        $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();

        $wkrd = '';
        foreach ($plist as $k=>$v){
            if($v['PERIOD_NUM']==$periodNum){
                $wkrd =$k+1;break;
            }
        }
        if($wkrd==1){
            $wkrd.='st';
        }else{
            $wkrd.='nd';
        }

        $monthArray = [
            1 => 'Jan',
            2 => 'Feb',
            3 => 'Mar',
            4 => 'Apr',
            5 => 'May',
            6 => 'Jun',
            7 => 'Jul',
            8 => 'Aug',
            9 => 'Sep',
            10 => 'Oct',
            11 => 'Nov',
            12 => 'Dec',
        ];

        //剩余分期PV显示
        $myRemainPv = RemainPv::findOne(['USER_ID'=>$baseInfo['ID']])->REMAIN_PV ?? 0;
        // 找到当月的所有订单，计算总PV及总REMAIN_PV
        $myOrders = Order::fetchOrderCurrentMonth($periodNum, $baseInfo['ID']);
        $myCurrentOrders = Order::fetchOrderCurrentPeriod($periodNum, $baseInfo['ID']);
        $currentPv = $myOrders->SUM('PV');
        $currentRemainPv = $myCurrentOrders->SUM('REMAIN_PV');

        $totalRemainPv = $myRemainPv + $currentRemainPv;
        $remainMonth = $totalRemainPv / 30;

        if($currentPv >= 30){ // 如果当月合格，则活跃资格延后一个月
            $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));

        $sliders = Ad::findUseSlaves()
            ->select('ID,IMAGE,LID,TITLE,CONTENT,TYPE')
            ->where('LID=:LID AND STATUS=1 AND COUNTRY_ID=:COUNTRY_ID', [':LID'=>'7EFF6260A16C3CC7E053693418AC03E4', ':COUNTRY_ID'=>$baseInfo['COUNTRY_ID']])
            ->orderBy('SORT DESC, CREATED_AT DESC')
            ->asArray()
            ->all();

        return static::notice([
            'nowTime' => $nowTime,
            'empLv'=>$empLv,
            'empLvName'=>$empLvName,
            'decLv'=>$decLv,
            'decLvName'=>$decLvName,
            'eliteLv'=>$eliteLv,
            'eliteLvName'=>$eliteLvName,
            'slides'=> $sliders,
            'news'=>$news,
            'periodNum'=>$periodNum . ', ' . $wkrd . ' '. Yii::t('app', 'pcOf') . ' '. $monthArray[$curYM['CALC_MONTH']],
            '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));
    }

    /**
     * 控制台首页
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBaIndex(){
        $nowTime = Date::nowTime();
        $news = ArticleCategory::find()->select('ID,CATE_NAME')->orderBy('SORT ASC')->asArray()->all();
        $where = ' CID=:CID AND STATUS=1';
        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();
        }

        //期数显示
        $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();

        $wkrd = '';
        foreach ($plist as $k=>$v) {
            if($v['PERIOD_NUM'] == $periodNum){
                $wkrd = $k + 1;
                break;
            }
        }
        if ($wkrd == 1) {
            $wkrd .= 'st';
        } else {
            $wkrd .= 'nd';
        }

        $monthArray = [
            1 => 'Jan',
            2 => 'Feb',
            3 => 'Mar',
            4 => 'Apr',
            5 => 'May',
            6 => 'Jun',
            7 => 'Jul',
            8 => 'Aug',
            9 => 'Sep',
            10 => 'Oct',
            11 => 'Nov',
            12 => 'Dec',
        ];


        return static::notice([
            'nowTime' => $nowTime,
            '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 . ' ，' . $wkrd . ' PC of '. $monthArray[$curYM['CALC_MONTH']],
        ]);
    }
}
