<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/10/9
 * Time: 下午3:25
 */

namespace common\helpers\user;


use common\helpers\Date;
use common\helpers\Tool;
use common\models\PerfMonth;
use common\models\PerfPeriod;
use common\models\Period;
use common\models\DecOrder;
use common\models\UserNetwork;
use common\models\UserPerf;
use common\models\UserRelation;
use yii\helpers\Json;

class Perf
{
    const CACHE_PERIOD_NEW_PERF_PREFIX = 'periodNewPerf_';
    const CACHE_PERIOD_DEEP_IN_NEW_PERF_PREFIX = 'periodDeepInNewPerf_';

    /**
     * 获取该会员当期新增业绩
     * @param $userId
     * @param null $relationDeep
     * 传推荐网络代数，如果传了此值，则只计算这个代数的所有子会员给的业绩
     * @return array
     */
    public static function getPeriodNewPerf($userId, $periodNum = null, $relationDeep = null){
        $period = Period::instance();
        if(!$periodNum) {
            $periodNum = $period->getNowPeriodNum();
        }
        $redisKey = self::CACHE_PERIOD_NEW_PERF_PREFIX.$userId;
        $perfArr = \Yii::$app->redis->get($redisKey);
        if($perfArr){
            $perfArr = Json::decode($perfArr);
            if($perfArr['periodNum'] == $periodNum){
                return $perfArr['perf'];
            }
        }
        $perf = [
            'PV_TOTAL' => 0,
            'PV_1L' => 0,
            'PV_1L_ZC' => 0,
            'PV_1L_YH' => 0,
            'PV_1L_ZG' => 0,
            'PV_1L_LS' => 0,
            'PV_1L_FX' => 0,
            'PV_2L' => 0,
            'PV_2L_ZC' => 0,
            'PV_2L_YH' => 0,
            'PV_2L_ZG' => 0,
            'PV_2L_LS' => 0,
            'PV_2L_FX' => 0,
            'PV_3L' => 0,
            'PV_3L_ZC' => 0,
            'PV_3L_YH' => 0,
            'PV_3L_ZG' => 0,
            'PV_3L_LS' => 0,
            'PV_3L_FX' => 0,
            'PV_4L' => 0,
            'PV_4L_ZC' => 0,
            'PV_4L_YH' => 0,
            'PV_4L_ZG' => 0,
            'PV_4L_LS' => 0,
            'PV_4L_FX' => 0,
            'PV_5L' => 0,
            'PV_5L_ZC' => 0,
            'PV_5L_YH' => 0,
            'PV_5L_ZG' => 0,
            'PV_5L_LS' => 0,
            'PV_5L_FX' => 0,
            'PV_PCS' => 0,
            'PV_PSS' => 0,
        ];
        if ($period->isSent($periodNum)) {
            if ($perf = PerfPeriod::find()->select('PV_1L,PV_1L_ZC,PV_1L_YH,PV_1L_ZG,PV_1L_LS,PV_1L_FX,PV_2L,PV_2L_ZC,PV_2L_YH,PV_2L_ZG,PV_2L_LS,PV_2L_FX,PV_3L,PV_3L_ZC,PV_3L_YH,PV_3L_ZG,PV_3L_LS,PV_3L_FX,PV_4L,PV_4L_ZC,PV_4L_YH,PV_4L_ZG,PV_4L_LS,PV_4L_FX,PV_5L,PV_5L_ZC,PV_5L_YH,PV_5L_ZG,PV_5L_LS,PV_5L_FX,PV_PCS,PV_PSS')->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID'=>$userId, ':PERIOD_NUM' => $periodNum])->asArray()->one()) {
                $perf['PV_TOTAL'] = $perf['PV_1L'] + $perf['PV_2L'] + $perf['PV_3L'] + $perf['PV_4L'] + $perf['PV_5L'];
            }
        } else {
            foreach ($perf as $k => $item) {
                $perf[$k] = Tool::formatPrice($item);
            }
        }

        // 把业绩加入缓存中5分钟(防止频繁获取)
        \Yii::$app->redis->set($redisKey, Json::encode(['periodNum'=>$periodNum, 'perf'=>$perf]));
        \Yii::$app->redis->expire($redisKey, 5 * 60);
        return $perf;
    }

    /**
     * 获取期数业绩
     * @param $userId
     * @param $periodNum
     * @return array
     */
    public static function getPeriodPerf($userId, $periodNum){
        $period = Period::instance();
        $yearMonth = $period->getYearMonth($periodNum);
        $result = PerfPeriod::findUseSlaves()->yearMonth($yearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID'=>$userId, ':PERIOD_NUM'=>$periodNum])->asArray()->one();
        $userStatus = Status::getStatus($userId, $periodNum);
        if(!$result || $userStatus == \Yii::$app->params['userStatus'][2]['value'] || $userStatus == \Yii::$app->params['userStatus'][9]['value']){
            $result = [
                'PV_PCS' => 0,
                'PV_PCS_ZC' => 0,
                'PV_PCS_YH' => 0,
                'PV_PCS_ZG' => 0,
                'PV_PCS_LS' => 0,
                'PV_PCS_FX' => 0,
                'PV_1L' => 0,
                'PV_1L_ZC' => 0,
                'PV_1L_YH' => 0,
                'PV_1L_ZG' => 0,
                'PV_1L_LS' => 0,
                'PV_1L_FX' => 0,
                'PV_2L' => 0,
                'PV_2L_ZC' => 0,
                'PV_2L_YH' => 0,
                'PV_2L_ZG' => 0,
                'PV_2L_LS' => 0,
                'PV_2L_FX' => 0,
                'PV_3L' => 0,
                'PV_3L_ZC' => 0,
                'PV_3L_YH' => 0,
                'PV_3L_ZG' => 0,
                'PV_3L_LS' => 0,
                'PV_3L_FX' => 0,
                'PV_4L' => 0,
                'PV_4L_ZC' => 0,
                'PV_4L_YH' => 0,
                'PV_4L_ZG' => 0,
                'PV_4L_LS' => 0,
                'PV_4L_FX' => 0,
                'PV_5L' => 0,
                'PV_5L_ZC' => 0,
                'PV_5L_YH' => 0,
                'PV_5L_ZG' => 0,
                'PV_5L_LS' => 0,
                'PV_5L_FX' => 0,
                'PV_LS_TOUCH' => 0,
                'SURPLUS_1L' => 0,
                'SURPLUS_2L' => 0,
                'SURPLUS_3L' => 0,
                'SURPLUS_4L' => 0,
                'SURPLUS_5L' => 0,
                'SURPLUS_LS' => 0,
            ];
        }

        return $result;
    }

    /**
     * 获取指定深度这一代会员给我的业绩
     * @param $userId
     * @param $relationDeep
     * @return int|mixed
     */
    public static function getChildrenDeepInNewPerf($userId, $relationDeep){
        $period = Period::instance();
        $yearMonth = $period->getNowYearMonth();
        $periodNum = $period->getNowPeriodNum();
        $redisKey = self::CACHE_PERIOD_DEEP_IN_NEW_PERF_PREFIX.$relationDeep.'_'.$userId;
        $perfArr = \Yii::$app->redis->get($redisKey);
        if($perfArr){
            $perfArr = Json::decode($perfArr);
            if($perfArr['periodNum'] == $periodNum){
                return $perfArr['perf'];
            }
        }
        static $allData = [];
        if(!$allData){
            $allData = DecOrder::find()->where('PERIOD_NUM=:PERIOD_NUM AND IS_DEL=0', [':PERIOD_NUM'=>$periodNum])->asArray()->all();
        }
        $perf = [
            'PV_ZC' => 0,
            'PV_YH' => 0,
            'PV_ZG' => 0,
            'PV_LS' => 0,
            'PV_FX' => 0,
        ];
        foreach($allData as $data){
            if(UserRelation::deepWithParent($data['TO_USER_ID'], $userId) != $relationDeep){
                continue;
            }
            $perf['PV_'.$data['TYPE']] += $data['DEC_PV'];
        }
        // 把业绩加入缓存中5分钟(防止频繁获取)
        \Yii::$app->redis->set($redisKey, Json::encode(['periodNum'=>$periodNum, 'perf'=>$perf]));
        \Yii::$app->redis->expire($redisKey, 5 * 60);
        return $perf;
    }

    /**
     * 获取月业绩
     * @param $userId
     * @param null $yearMonth
     * @return array
     */
    public static function getMonthPerf($userId, $yearMonth = null){
        $result = [
            'PV_PCS'=>0,//新增个人业绩
            'PV_1L'=>0,//当月新增
            'PV_2L'=>0,
            'PV_3L'=>0,
            'PV_4L'=>0,
            'PV_5L'=>0,
            'PV_1L_TOTAL'=>0,//总业绩
            'PV_2L_TOTAL'=>0,
            'PV_3L_TOTAL'=>0,
            'PV_4L_TOTAL'=>0,
            'PV_5L_TOTAL'=>0,
            'PV_TOTAL' => 0,//当月新增
            'PV_TOTAL_TOTAL' => 0,//总业绩
            'PV_PSS' => 0,//新增团队业绩
            'PV_PSS_TOTAL' => 0,//团队总业绩
        ];
        $userStatus = Status::getStatus($userId);
        if($userStatus == \Yii::$app->params['userStatus'][2]['value'] || $userStatus == \Yii::$app->params['userStatus'][9]['value']){
            return $result;
        }
        // 当月业绩
        if($yearMonth === null){
            $period = Period::instance();
            $yearMonth = $period->getNowYearMonth();
            // 获取本月已挂网的其他期业绩
            // 该月所有已经挂网的期数
            $allSentPeriod = Period::monthSentAllPeriodNum($yearMonth);
            $sentPeriodWhere = '';
            if($allSentPeriod){
                $sentPeriodWhere = implode("','", $allSentPeriod);
                $sentPeriodWhere = " AND PERIOD_NUM IN ('$sentPeriodWhere')";
            }
            $perfPeriodSum = PerfPeriod::find()->yearMonth($yearMonth)->select('SUM(PV_PCS) AS PV_PCS,SUM(PV_1L) AS PV_1L,SUM(PV_2L) AS PV_2L,SUM(PV_3L) AS PV_3L,SUM(PV_4L) AS PV_4L,SUM(PV_5L) AS PV_5L,SUM(PV_PSS) AS PV_PSS')->where('USER_ID=:USER_ID'.$sentPeriodWhere, [':USER_ID'=>$userId])->asArray()->one();
            if($perfPeriodSum){
                $result['PV_PCS'] += $perfPeriodSum['PV_PCS'];
                $result['PV_1L'] += $perfPeriodSum['PV_1L'];
                $result['PV_2L'] += $perfPeriodSum['PV_2L'];
                $result['PV_3L'] += $perfPeriodSum['PV_3L'];
                $result['PV_4L'] += $perfPeriodSum['PV_4L'];
                $result['PV_5L'] += $perfPeriodSum['PV_5L'];
                $result['PV_PSS'] += $perfPeriodSum['PV_PSS'];
                $result['PV_TOTAL'] += ($perfPeriodSum['PV_1L'] + $perfPeriodSum['PV_2L'] + $perfPeriodSum['PV_3L'] + $perfPeriodSum['PV_4L'] + $perfPeriodSum['PV_5L']);
            }
            // 获取本期业绩
            $nowPeriodPerf = self::getPeriodNewPerf($userId);
            if($nowPeriodPerf){
                $result['PV_PCS'] += $nowPeriodPerf['PV_PCS'];
                $result['PV_1L'] += $nowPeriodPerf['PV_1L'];
                $result['PV_2L'] += $nowPeriodPerf['PV_2L'];
                $result['PV_3L'] += $nowPeriodPerf['PV_3L'];
                $result['PV_4L'] += $nowPeriodPerf['PV_4L'];
                $result['PV_5L'] += $nowPeriodPerf['PV_5L'];
                $result['PV_PSS'] += $nowPeriodPerf['PV_PSS'];
                $result['PV_TOTAL'] += ($nowPeriodPerf['PV_1L'] + $nowPeriodPerf['PV_2L'] + $nowPeriodPerf['PV_3L'] + $nowPeriodPerf['PV_4L'] + $nowPeriodPerf['PV_5L']);
            }
            return $result;
        }
        // 往月业绩
        $perfMonth = PerfMonth::find()->yearMonth($yearMonth)->select('PV_PCS,PV_1L,PV_2L,PV_3L,PV_4L,PV_5L,PV_PSS,PV_PSS_TOTAL')->where('USER_ID=:USER_ID AND CALC_MONTH=:CALC_MONTH', [':USER_ID'=>$userId, ':CALC_MONTH' => $yearMonth])->asArray()->one();
        if($perfMonth){
            $result['PV_PCS'] = $result['PV_PCS'] + $perfMonth['PV_PCS'];
            $result['PV_1L_TOTAL'] = $result['PV_1L'] + $perfMonth['PV_1L'];
            $result['PV_2L_TOTAL'] = $result['PV_2L'] + $perfMonth['PV_2L'];
            $result['PV_3L_TOTAL'] = $result['PV_3L'] + $perfMonth['PV_3L'];
            $result['PV_4L_TOTAL'] = $result['PV_4L'] + $perfMonth['PV_4L'];
            $result['PV_5L_TOTAL'] = $result['PV_5L'] + $perfMonth['PV_5L'];
            $result['PV_PSS'] = $result['PV_PSS'] + $perfMonth['PV_PSS'];
            $result['PV_PSS_TOTAL'] = $result['PV_PSS_TOTAL'] + $perfMonth['PV_PSS_TOTAL'];
            $result['PV_TOTAL'] = ($result['PV_1L_TOTAL'] + $result['PV_2L_TOTAL'] + $result['PV_3L_TOTAL'] + $result['PV_4L_TOTAL'] + $result['PV_5L_TOTAL']);
        }
        foreach ($result as $k=>$item) {
            $result[$k] = Tool::formatPrice($item);
        }
        return $result;
    }

    /**
     * 获取到会员的当前的总业绩，含未挂网
     * @param $userId
     * @return array
     */
    public static function getMonthAndNewPeriodPerf($userId){
        $perf = self::getMonthPerf($userId);
        // 当期业绩
        $newPerf = self::getPeriodNewPerf($userId);
        return [
            'PV_1L' => $perf['PV_1L'] + $newPerf['PV_1L'],
            'PV_2L' => $perf['PV_2L'] + $newPerf['PV_2L'],
            'PV_3L' => $perf['PV_3L'] + $newPerf['PV_3L'],
            'PV_4L' => $perf['PV_4L'] + $newPerf['PV_4L'],
            'PV_5L' => $perf['PV_5L'] + $newPerf['PV_5L'],
            'PV_TOTAL' => $perf['PV_TOTAL'] + $newPerf['PV_TOTAL'],
        ];
    }

    /**
     * 所传期数的业绩
     * @param $userId
     * @param $periodNum
     * @return array
     * @throws \yii\db\Exception
     */
    public static function getPeriodTotalPerf($userId, $periodNum){
        // 获取所传期数的上一个结算月
        $period = Period::instance();
        $lastMonthArr = $period->getLastMonth($periodNum);
        $yearMonth = $period->getYearMonth($periodNum);
        $lastYearMonth = $lastMonthArr['yearMonth'];
        // 获取上一个结算月的业绩
        $lastYearMonthPerf = self::getMonthPerf($userId, $lastYearMonth);
        $result = [
            'PV_1L' => $lastYearMonthPerf['PV_1L'],
            'PV_2L' => $lastYearMonthPerf['PV_2L'],
            'PV_3L' => $lastYearMonthPerf['PV_3L'],
            'PV_4L' => $lastYearMonthPerf['PV_4L'],
            'PV_5L' => $lastYearMonthPerf['PV_5L'],
            'PV_TOTAL' => $lastYearMonthPerf['PV_TOTAL'],
        ];
        // 获取所传期数的本月的已结算的全部期数
        $allCalcPeriodNumArr = Period::monthCalcAllPeriodNum($yearMonth);
        foreach($allCalcPeriodNumArr as $calcPeriodNum){
            // 达到所传期数停止
            if($calcPeriodNum > $periodNum) break;
            $periodPerf = self::getPeriodPerf($userId, $periodNum);
            $result['PV_1L'] += $periodPerf['PV_1L'];
            $result['PV_2L'] += $periodPerf['PV_2L'];
            $result['PV_3L'] += $periodPerf['PV_3L'];
            $result['PV_4L'] += $periodPerf['PV_4L'];
            $result['PV_5L'] += $periodPerf['PV_5L'];
            $result['PV_TOTAL'] += ($periodPerf['PV_1L'] + $periodPerf['PV_2L'] + $periodPerf['PV_3L'] + $periodPerf['PV_4L'] + $periodPerf['PV_5L']);
        }
        return $result;
    }

    /**
     * 获取总业绩
     * @param $userId
     * @return array
     */
    public static function getTotalPerf($userId){
        $result = [
            'PV_1L' => 0,
            'PV_2L' => 0,
            'PV_3L' => 0,
            'PV_4L' => 0,
            'PV_5L' => 0,
            'PV_TOTAL' => 0,
        ];
        $userStatus = Status::getStatus($userId);
        if($userStatus == \Yii::$app->params['userStatus'][2]['value'] || $userStatus == \Yii::$app->params['userStatus'][9]['value']){
            return $result;
        }
        // 历史已挂网业绩
        $perf = UserPerf::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId], 'PV_1L,PV_2L,PV_3L,PV_4L,PV_5L');
        if($perf){
            $result['PV_1L'] += $perf['PV_1L'];
            $result['PV_2L'] += $perf['PV_2L'];
            $result['PV_3L'] += $perf['PV_3L'];
            $result['PV_4L'] += $perf['PV_4L'];
            $result['PV_5L'] += $perf['PV_5L'];
            $result['PV_TOTAL'] += ($perf['PV_1L'] + $perf['PV_2L'] + $perf['PV_3L'] + $perf['PV_4L'] + $perf['PV_5L']);
        }
        // 获取本期业绩
        $nowPeriodPerf = self::getPeriodNewPerf($userId);
        if($nowPeriodPerf){
            $result['PV_1L'] += $nowPeriodPerf['PV_1L'];
            $result['PV_2L'] += $nowPeriodPerf['PV_2L'];
            $result['PV_3L'] += $nowPeriodPerf['PV_3L'];
            $result['PV_4L'] += $nowPeriodPerf['PV_4L'];
            $result['PV_5L'] += $nowPeriodPerf['PV_5L'];
            $result['PV_TOTAL'] += ($nowPeriodPerf['PV_1L'] + $nowPeriodPerf['PV_2L'] + $nowPeriodPerf['PV_3L'] + $nowPeriodPerf['PV_4L'] + $nowPeriodPerf['PV_5L']);
        }
        return $result;
    }

    /**
     * 获取用户业绩
     * @param $userId
     * @return array|\yii\db\ActiveRecord
     */
    public static function getUserPerf( $userId ) {
        $data = UserPerf::find()->where('USER_ID=:USER_ID', ['USER_ID'=>$userId])->asArray()->one();
        return $data ?? [];
    }

}