<?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\Date;
use common\helpers\Tool;
use common\helpers\user\Info;
use common\helpers\user\Perf;
use common\models\CalcBonus;
use common\models\CalcBonusBSDefault;
use common\models\CalcBonusBT;
use common\models\CalcBonusFL;
use common\models\DealType;
use common\models\FlowBonus;
use common\models\FlowCF;
use common\models\FlowGaragePoints;
use common\models\FlowLX;
use common\models\FlowReconsumePoints;
use common\models\FlowTourismPoints;
use common\models\FlowVillaPoints;
use common\models\FlowWallet;
use common\models\PerfMonth;
use common\models\PerfPeriod;
use common\models\Period;
use common\models\DecRole;
use common\models\EmployLevel;
use common\models\FlowExchangePoints;
use common\models\ScoreMonth;
use common\models\UserBonus;
use common\models\UserWallet;
use common\models\UserRelation;
use frontendApi\modules\v1\models\User;

class BonusController extends BaseController {
    public $modelClass = CalcBonus::class;

    /**
     * 我的账户
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionIndex() {
        $userId = \Yii::$app->user->id;
        $data = UserBonus::findUseSlaves()->select('BONUS,RECONSUME_POINTS,EXCHANGE_POINTS,TOURISM_POINTS,GARAGE_POINTS,VILLA_POINTS')->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
        if (!$data) {
            $data = [
                'BONUS' => 0,
//                'RECONSUME_POINTS' => 0,
                'EXCHANGE_POINTS' => 0,
                'TOURISM_POINTS' => 0,
                'GARAGE_POINTS' => 0,
                'VILLA_POINTS' => 0,
            ];
        }
        $data['CASH'] = 0;
        $cashWallet = UserWallet::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId], 'CASH');
        if($cashWallet){
            $data['CASH'] = $cashWallet['CASH'];
        }
        //是否显示车房领袖
//        $showCFLX = true;
//        if ($data['CF'] <= 0 && $data['LX'] <= 0) {
//            $showCFLX = false;
//            //查看历史最高聘级是否到过五钻
//            if (EmployLevel::getSortById(Info::getHighEmpLv($userId)) >= 7) {
//                $showCFLX = true;
//            }
//        }
        $wallet[] = ['walletType' => 'bonus', 'walletName' => 'Member Bonus', 'amount' => Tool::formatPrice($data['BONUS'])];//会员奖金
        $wallet[] = ['walletType' => 'cash', 'walletName' => 'Member Ecoin', 'amount' => Tool::formatPrice($data['CASH'])];//会员余额
//        $wallet[] = ['walletType' => 'point', 'walletName' => '会员积分', 'amount' => Tool::formatPrice($data['RECONSUME_POINTS'])];
//        $wallet[] = ['walletType' => 'exchange', 'walletName' => 'Exchange points', 'amount' => Tool::formatPrice($data['EXCHANGE_POINTS'])];//兑换点数
//        $wallet[] = ['walletType' => 'tourism_points', 'walletName' => 'Travel points', 'amount' => Tool::formatPrice($data['TOURISM_POINTS'])];//旅游积分
        $wallet[] = ['walletType' => 'garage_points', 'walletName' => 'Car Points', 'amount' => Tool::formatPrice($data['GARAGE_POINTS'])];//车奖积分
        $wallet[] = ['walletType' => 'villa_points', 'walletName' => 'Villa Points', 'amount' => Tool::formatPrice($data['VILLA_POINTS'])];//房奖积分
//        if ($showCFLX) {
//            $wallet[] = ['walletType' => 'cf', 'walletName' => '福利积分一', 'amount' => Tool::formatPrice($data['CF'])];
//            $wallet[] = ['walletType' => 'lx', 'walletName' => '福利积分二', 'amount' => Tool::formatPrice($data['LX'])];
//        }
        //是否显示报单中心
//        $showBt = true;
//        $showFl = true;
//        $userInfo = User::getEnCodeInfo(\Yii::$app->user->id);
//        if ($userInfo['IS_DEC'] != 1) {
//            $showBt = false;
//            $showFl = false;
//        }else{
//            $sysConfig = Cache::getSystemConfig();
//            if(!$sysConfig['openBT']['VALUE']&&!$sysConfig['openPROD']['VALUE']) $showBt = false;
//            if(!$sysConfig['openFL']['VALUE']) $showFl = false;
//            $decRole = DecRole::find()->where('1=1')->indexBy('ID')->asArray()->all()[$userInfo['DEC_ROLE_ID']];
//            if ($decRole['GOODS_SUBSIDY'] <= 0) $showFl = false;
//        }

        $dealSwitch = isset(Cache::getSystemConfig()['dealSwitch']) ? Cache::getSystemConfig()['dealSwitch']['VALUE'] : '';

        return static::notice(['wallet' => $wallet,'dealSwitch'=>$dealSwitch]);
    }

    /**
     * 团队查询
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionTeams() {
        $userId = \Yii::$app->user->id;
        $period = Period::instance();
        $periodNum = $period->getNowPeriodNum();
        $month = $period->getNowYearMonth();
        // 判断此业绩期是否已经完成生成了预计算业绩单,生成完毕才能看到
        $isPerfed = Period::checkPerf($periodNum);
        if (!$isPerfed) {
            return static::notice(['user' => [],'team'=>[]]);
        }
        // 判断当前时间，是否临近封期，否则隐藏
        $nowTs = time();
        $currentPeriodEnd = Period::getEndTime($periodNum);
        if ($nowTs + 432000 <= $currentPeriodEnd || $currentPeriodEnd < $nowTs || ($periodNum % 2)) {
            return static::notice(['user' => [],'team'=>[]]);
        }
        $userInfo = User::getEnCodeInfo($userId);
        $data = PerfMonth::fetchMonthPerf($month, $userId);
        $user[0] = [
            'number' => $userInfo['USER_NAME'],
            'name' => $userInfo['REAL_NAME'],
            'user_perf' => 0, // 个人业绩
            'team_perf' => 0, // 团队新增累计业绩
            'total_perf' => 0, // 合计业绩
            'perf_status' => '0', // 0  未达标  1为已达标
            'perf_status_name' => 'Fail',
        ];
        if (!empty($data)) {
            $userCheck = PerfMonth::checkStatus($data['PV_PCS']+$data['PV_PSS']);
            $user[0]['user_perf'] = $data['PV_PCS'];
            $user[0]['team_perf'] = $data['PV_PSS'];
            $user[0]['total_perf'] = $data['PV_PCS']+$data['PV_PSS'];
            $user[0]['perf_status'] = $userCheck ? '1' : $user[0]['perf_status'];
            $user[0]['perf_status_name'] = $userCheck ? 'Pass' : $user[0]['perf_status_name'];
        }
        $teamInfo = [];
        $calcAt = PerfMonth::find()->select(['CREATED_AT'])->where('CALC_MONTH=:CALC_MONTH', ['CALC_MONTH'=>$month])->asArray()->one();

        if(!$calcAt){
            $periodStartTime = $period->nowPeriodArr['START_TIME'];
            return static::notice(['user' => $user,'team'=>[],'calcAt' => $periodStartTime]);
        }
        // 查询此用户的推荐(开拓)团队一级信息
        $relation = UserRelation::getChildrenWithDeepAndLayer($userId, 1, 1, $periodNum);
        $userStatusFlag = false;
        if ($relation) {
            // 循环一级开拓用户
            foreach($relation as $k=>$v) {
                // 获取此用户预计算月业绩
                $relationPerf = PerfMonth::fetchMonthPerf($month, $v['USER_ID']);
                if (empty($relationPerf)) {
                    $relationPerf['PV_PCS'] = 0;
                    $relationPerf['PV_PSS'] = 0;
                }
                $relationCheck = PerfMonth::checkStatus($relationPerf['PV_PCS']+$relationPerf['PV_PSS']);
                $teamInfo[]['perf_status'] = $relationCheck ? '1' : '0';
                if ($relationCheck) {
                    $userStatusFlag = true; // 只要有一个达标,则个人就达标
                    $teamInfo[$k]['number'] = $v['USER_NAME'];
                    $teamInfo[$k]['name'] = $v['REAL_NAME'];
                    $teamInfo[$k]['user_perf'] = $relationPerf['PV_PCS'];
                    $teamInfo[$k]['team_perf'] = $relationPerf['PV_PSS'];
                    $teamInfo[$k]['total_perf'] = $relationPerf['PV_PCS']+$relationPerf['PV_PSS'];
                    $teamInfo[$k]['perf_status'] = '1';
                    $teamInfo[$k]['perf_status_name'] = 'Pass';
                } else {
                    $teamInfo[$k]['number'] = $v['USER_NAME'];
                    $teamInfo[$k]['name'] = $v['REAL_NAME'];
                    $teamInfo[$k]['user_perf'] = $relationPerf['PV_PCS'];
                    $teamInfo[$k]['team_perf'] = $relationPerf['PV_PSS'];
                    $teamInfo[$k]['total_perf'] = $relationPerf['PV_PCS']+$relationPerf['PV_PSS'];
                    $teamInfo[$k]['perf_status'] = '0';
                    $teamInfo[$k]['perf_status_name'] = 'Fail';
                }
            }
        }
        if ($userStatusFlag === true) {
            $user[0]['perf_status'] = '1';
            $user[0]['perf_status_name'] = 'Pass';
        }

        return static::notice(['user' => $user,'team'=>$teamInfo,'calcAt' => $calcAt['CREATED_AT']]);
    }

    /**
     * 交易记录
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionWalletFlow(){
        $walletType = \Yii::$app->request->get('walletType');
        if(!in_array($walletType,['bonus', 'cash', 'exchange', 'tourism_points', 'garage_points', 'villa_points'])) return static::notice('walletType error',400);
        $dealType = \Yii::$app->request->get('dealType');
        $createAt = \Yii::$app->request->get('createAt');
        $remark = \Yii::$app->request->get('remark');

        //获取可以查看几期流水
        $showFlowPeriodNum = Cache::getSystemConfig()['showFlowPeriodNum']['VALUE'];
        $periodArr = Period::getNearlyPeriodNum($showFlowPeriodNum);
        $condition = ' AND USER_ID=:USER_ID AND PERIOD_NUM>=:PERIOD_NUM_MIN AND PERIOD_NUM<=:PERIOD_NUM_MAX';
        $params = [':USER_ID' => \Yii::$app->user->id,':PERIOD_NUM_MIN' => min($periodArr), ':PERIOD_NUM_MAX'=> max($periodArr)];
        if($dealType){
            if($dealType==1){//增加
                $condition.=' AND IS_INCR=1 AND DEAL_TYPE_IS_PRESET=0';
            }elseif ($dealType==2){//扣除
                $condition.=' AND IS_INCR=0 AND DEAL_TYPE_IS_PRESET=0';
            }else{
                $condition.=' AND DEAL_TYPE_ID=:DEAL_TYPE';
                $params[':DEAL_TYPE'] = $dealType;
            }
        }
        if ($createAt) {
            $createAtStart = $createAt[0] ?? '';
            $createAtEnd = $createAt[1] ?? '';
            if ($createAtStart) {
                $condition .= " AND CREATED_AT>:CREATED_START";
                $params[':CREATED_START'] = Date::utcToTime($createAtStart);
            }
            if ($createAtEnd) {
                $condition .= " AND CREATED_AT<:CREATED_END";
                $params[':CREATED_END'] = Date::utcToTime($createAtEnd)+86399;
            }
        }
        if($remark){
            $condition .= " AND REMARK LIKE :REMARK";
            $params[':REMARK'] = '%'.$remark.'%';
        }
        $data = [];
        $dealLists=[];
        $dealTypes=[];
        if($walletType == 'bonus') {
            $dealLists = FlowBonus::find()->groupBy('DEAL_TYPE_ID')->select('DEAL_TYPE_ID')->where('USER_ID=:USER_ID',[':USER_ID'=>\Yii::$app->user->id])->asArray()->all();
            $data = FlowBonus::lists($condition, $params, [
                'useSlaves' => true,
                'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,REMARK_IS_SHOW,PERIOD_NUM,CALC_MONTH,CREATED_AT,DEAL_TYPE_ID,DEAL_TYPE_IS_PRESET',
                'orderBy' => 'CREATED_AT DESC,SORT DESC',
            ]);
//        }elseif ($walletType == 'point'){
//            $dealLists = FlowReconsumePoints::find()->groupBy('DEAL_TYPE_ID')->select('DEAL_TYPE_ID')->where('USER_ID=:USER_ID',[':USER_ID'=>\Yii::$app->user->id])->asArray()->all();
//            $data = FlowReconsumePoints::lists($condition, $params, [
//                'useSlaves' => true,
//                'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,REMARK_IS_SHOW,PERIOD_NUM,CALC_MONTH,CREATED_AT,DEAL_TYPE_ID,DEAL_TYPE_IS_PRESET',
//                'orderBy' => 'CREATED_AT DESC',
//            ]);
        }elseif ($walletType == 'cash'){
            $data = FlowWallet::lists($condition, $params, [
                'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,PERIOD_NUM,CALC_MONTH,CREATED_AT',
                'orderBy' => 'CREATED_AT DESC',
            ]);
        }else if ($walletType == 'exchange') {
            $dealLists = FlowExchangePoints::find()->groupBy('DEAL_TYPE_ID')->select('DEAL_TYPE_ID')->where('USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->user->id])->asArray()->all();
            $data = FlowExchangePoints::lists($condition, $params, [
                'useSlaves' => true,
                'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,REMARK_IS_SHOW,PERIOD_NUM,CALC_MONTH,CREATED_AT,DEAL_TYPE_ID,DEAL_TYPE_IS_PRESET',
                'orderBy' => 'CREATED_AT DESC',
            ]);
        } else if ($walletType == 'tourism_points') {
                $dealLists = FlowTourismPoints::find()->groupBy('DEAL_TYPE_ID')->select('DEAL_TYPE_ID')->where('USER_ID=:USER_ID',[':USER_ID'=>\Yii::$app->user->id])->asArray()->all();
                $data = FlowTourismPoints::lists($condition, $params, [
                    'useSlaves' => true,
                    'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,REMARK_IS_SHOW,PERIOD_NUM,CALC_MONTH,CREATED_AT,DEAL_TYPE_ID,DEAL_TYPE_IS_PRESET',
                    'orderBy' => 'CREATED_AT DESC',
                ]);
        } else if ($walletType == 'garage_points') {
            $dealLists = FlowGaragePoints::find()->groupBy('DEAL_TYPE_ID')->select('DEAL_TYPE_ID')->where('USER_ID=:USER_ID',[':USER_ID'=>\Yii::$app->user->id])->asArray()->all();
            $data = FlowGaragePoints::lists($condition, $params, [
                'useSlaves' => true,
                'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,REMARK_IS_SHOW,PERIOD_NUM,CALC_MONTH,CREATED_AT,DEAL_TYPE_ID,DEAL_TYPE_IS_PRESET',
                'orderBy' => 'CREATED_AT DESC',
            ]);
        } else if ($walletType == 'villa_points') {
            $dealLists = FlowVillaPoints::find()->groupBy('DEAL_TYPE_ID')->select('DEAL_TYPE_ID')->where('USER_ID=:USER_ID',[':USER_ID'=>\Yii::$app->user->id])->asArray()->all();
            $data = FlowVillaPoints::lists($condition, $params, [
                'useSlaves' => true,
                'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,REMARK_IS_SHOW,PERIOD_NUM,CALC_MONTH,CREATED_AT,DEAL_TYPE_ID,DEAL_TYPE_IS_PRESET',
                'orderBy' => 'CREATED_AT DESC',
            ]);
        } else {
            return static::notice('walletType error',400);
        }

        if($data) {
            if($walletType != 'cash') {
                foreach ($data['list'] as $key => $value) {
                    if ($value['DEAL_TYPE_IS_PRESET'] == 0) {
                        $data['list'][$key]['DEAL_TYPE_NAME'] = $value['AMOUNT'] > 0 ? 'increase' : 'reduce'; // 增加 减少
                    } else {
                        $data['list'][$key]['DEAL_TYPE_NAME'] = DealType::getAllTypesForShow()[$value['DEAL_TYPE_ID']]['TYPE_NAME'] ?? '';
                    }
                    if ($value['REMARK_IS_SHOW'] == 0) $data['list'][$key]['REMARK'] = '';
                    $data['list'][$key]['REMARK'] = str_replace("车房养老奖", "福利积分一", $data['list'][$key]['REMARK']);
                    $data['list'][$key]['REMARK'] = str_replace("领袖分红奖", "福利积分二", $data['list'][$key]['REMARK']);
                    $data['list'][$key]['REMARK'] = str_replace("车房养老", "福利积分一", $data['list'][$key]['REMARK']);
                    $data['list'][$key]['REMARK'] = str_replace("领袖分红", "福利积分二", $data['list'][$key]['REMARK']);
                }
            }
        }
        if($dealLists){
            foreach ($dealLists as $key=>$value){
                if(!$value['DEAL_TYPE_ID']) continue;
                $dealType = DealType::getAllTypesForShow()[$value['DEAL_TYPE_ID']];
                if($dealType['IS_PRESET']==0){
                    $dealTypes['1'] = 'increase';// 增加
                    $dealTypes['2'] = 'reduce';// 扣除
                }else{
                    $dealLists[$key]['DEAL_TYPE_NAME'] = $dealType['TYPE_NAME']??'';
                    $dealTypes[$value['DEAL_TYPE_ID']] = $dealLists[$key]['DEAL_TYPE_NAME'];
                }
            }
        }
        $data['dealTypes'] = $dealTypes;
        unset($dealTypes);
        return static::notice($data);
    }

    /**
     * 最新奖金
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionNew(){
        if(!$periodNum = \Yii::$app->request->get('periodNum')) {
            $periodNum = Period::sentMaxPeriodNum();
        }
        //是否近期期数
        $showFlowPeriodNum = Cache::getSystemConfig()['showFlowPeriodNum']['VALUE'];
        $periodArr = Period::getNearlySendPeriodNum($showFlowPeriodNum);
        if(!in_array($periodNum,$periodArr)) return static::notice('Cannot view this period',400); // 该期不能查看
        //增加明细开关控制(0 只显示总奖金 1 全部显示)
        $flowBonusSwitch = Cache::getSystemConfig()['flowBonusSwitch']['VALUE'];
        $data = $this->_periodBonus($periodNum,$flowBonusSwitch);
        if(!$data) return static::notice('当期无奖金记录',400);
        return static::notice($data);
    }

    /**
     * 期数对应的奖金
     * @param $periodNum
     * @param $detailSwitch
     * @return array
     * @throws \yii\db\Exception
     */
    private function _periodBonus($periodNum,$detailSwitch=1) {
        $period = Period::instance();
        $yearMonth = $period->getYearMonth($periodNum);
        if(!$calcBonus = CalcBonus::find()->yearMonth($yearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',[':USER_ID'=>\Yii::$app->user->id,':PERIOD_NUM'=>$periodNum])->asArray()->one()){
            return [

            ];
        }
        $sysConfig = Cache::getSystemConfig();

        if($detailSwitch) {
            $data['USER_NAME'] = ['name' => '编号', 'value' => Info::getUserNameByUserId(\Yii::$app->user->id)];
            $data['PERIOD_NUM'] = ['name' => '期数', 'value' => $periodNum];
            $data['LAST_DEC_LV'] = ['name' => '级别', 'value' => Cache::getDecLevelConfig()[$calcBonus['LAST_DEC_LV']]['LEVEL_NAME']];
            $data['LAST_EMP_LV'] = ['name' => '管理星级', 'value' => Cache::getEmpLevelConfig()[$calcBonus['LAST_EMP_LV']]['LEVEL_NAME']];
            $data['LAST_CROWN_LV'] = ['name' => '皇冠星级', 'value' => Cache::getStarCrownLevelConfig()[$calcBonus['LAST_CROWN_LV']]['LEVEL_NAME']];
            if ($sysConfig['openTG']['VALUE']) {
                // 销售奖金 就是 原来的推广奖
                $data['ORI_BONUS_TG'] = ['name' => '销售奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_TG'])];
            }
            $data['ORI_BONUS_TG_SWITCH'] = intval($sysConfig['openTG']['VALUE']);

            if ($sysConfig['openQY']['VALUE']) {
                // 业绩奖金  就是原来的团队奖 并将业绩奖金改成绩效奖金
                // $data[] = ['name' => '团队奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_QY'])];
                $data['ORI_BONUS_QY'] = ['name' => '业绩奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_QY'])];
            }
            $data['ORI_BONUS_QY_SWITCH'] = intval($sysConfig['openQY']['VALUE']);

            //服务奖
            if ($sysConfig['openFW']['VALUE']) {
                $data['BONUS_BD'] = ['name' => '服务奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BD'])];
            }
            $data['BONUS_BD_SWITCH'] = intval($sysConfig['openFW']['VALUE']);

            // 管理奖金 就是新的蓝星奖
//            $data[] = ['name' => '管理奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BS'])];
//            if ($sysConfig['openGX']['VALUE']) {
//                $data[] = ['name' => '共享奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_GX'])];
//            }
//            if ($sysConfig['openFW']['VALUE']) {
//                $data[] = ['name' => '服务奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BD'])];
//            }
            // 管理奖金 就是新的蓝星奖
            $data['ORI_BONUS_BS'] = ['name' => '管理奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BS'])];
            $data['ORI_BONUS_BS_MNT'] = ['name' => '管理奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BS_MNT'])];
            $data['ORI_BONUS_BS_ABBR'] = ['name' => '绩效奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BS_ABBR'])];

            $data['ORI_BONUS_QUARTER'] = ['name' => '季度奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_QUARTER'] ?? 0.00)];
            $data['BONUS_TOURISM'] = ['name' => '旅游奖', 'value' => Tool::formatPrice($calcBonus['BONUS_TOURISM'])];
            $data['BONUS_GARAGE'] = ['name' => '车房奖', 'value' => Tool::formatPrice($calcBonus['BONUS_GARAGE'])];
            $data['BONUS_TOTAL'] = ['name' => '合计', 'value' => Tool::formatPrice($calcBonus['BONUS_TOTAL'])];
//            $data[] = ['name' => '管理费', 'value' => Tool::formatPrice($calcBonus['MANAGE_TAX'])];
            $data['BONUS_REAL'] = ['name' => '实发奖金', 'value' => Tool::formatPrice($calcBonus['BONUS_REAL'])];
//            $data[] = ['name' => '复消积分', 'value' => Tool::formatPrice($calcBonus['RECONSUME_POINTS'])];
//            $data[] = ['name' => '兑换积分', 'value' => Tool::formatPrice($calcBonus['EXCHANGE_POINTS'])];
            $data['PV_1L'] = ['name' => '一市场新增业绩', 'value' => Tool::formatFrontPerf($calcBonus['PV_1L'])];
            $data['PV_2L'] = ['name' => '二市场新增业绩', 'value' => Tool::formatFrontPerf($calcBonus['PV_2L'])];
//            $data['PV_3L'] = ['name' => '三市场新增业绩', 'value' => Tool::formatFrontPerf($calcBonus['PV_3L'])];
            $data['SURPLUS_1L'] = ['name' => '一市场结余业绩', 'value' => Tool::formatFrontPerf($calcBonus['SURPLUS_1L'])];
            $data['SURPLUS_2L'] = ['name' => '二市场结余业绩', 'value' => Tool::formatFrontPerf($calcBonus['SURPLUS_2L'])];
//            $data['SURPLUS_3L'] = ['name' => '三市场结余业绩', 'value' => Tool::formatFrontPerf($calcBonus['SURPLUS_3L'])];

            // 是否活跃
            $perfPeriod = PerfPeriod::find()->where('USER_ID=:USER_ID AND PERIOD_NUM = :PERIOD_NUM', [':USER_ID' => \Yii::$app->user->id, ':PERIOD_NUM' => $periodNum])->asArray()->one();
            $data['IS_ACTIVE'] = ['name' => '是否活跃', 'value' => ($perfPeriod['IS_ACTIVE'] ? intval($perfPeriod['IS_ACTIVE']) : 0)];
            // 管理奖个人小组业绩
            $calcBonusBS = CalcBonusBSDefault::findOneAsArray('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => \Yii::$app->user->id, ':PERIOD_NUM' => $periodNum], 'GPV10');
            $data['DIRECTOR_BONUS_PGS'] = ['name' => '个人小组业绩', 'value' => ($calcBonusBS['GPV10'] ?? 0)];

            // if ($sysConfig['openYC']['VALUE']) {
            //     $data[] = ['name' => '荣衔奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_YC'])];
            // }
            // if ($sysConfig['openVIP']['VALUE']) {
            //     $data[] = ['name' => 'VIP奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_VIP'])];
            // }


            // if ($sysConfig['openXF']['VALUE']) {
            //     $data[] = ['name' => '消费奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_XF'])];
            // }
            // if ($sysConfig['openYJ']['VALUE']) {
            //     $data[] = ['name' => '业绩奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_YJ'])];
            // }

            // if ($sysConfig['openGL']['VALUE']) {
            //     $data[] = ['name' => '管理奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_GL'])];
            // }

            // if ($sysConfig['openJXS']['VALUE']) {
            //     $data[] = ['name' => '团队成长奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_STANDARD'])];
            // }
//        if($sysConfig['openLS']['VALUE']) {
//            $data[] = ['name' => '零售奖', 'value' => Tool::formatPrice($calcBonus['BONUS_LS'])];
//        }
//        $data[]=['name'=>'责任业绩扣除','value'=>Tool::formatPrice($calcBonus['DEDUCT_ZR'])];


//        $data[]=['name'=>'总奖金','value'=>Tool::formatPrice($calcBonus['BONUS_TOTAL'])];

//        if($sysConfig['openLX']['VALUE']) {
//            $data[] = ['name' => '福利积分二', 'value' => Tool::formatPrice($calcBonus['BONUS_LX'])];
//        }

//        $data[]=['name'=>'四市场新增业绩','value'=>Tool::formatFrontPerf($calcBonus['PV_4L'])];
//        $data[]=['name'=>'五市场新增业绩','value'=>Tool::formatFrontPerf($calcBonus['PV_5L'])];
//        $data[]=['name'=>'虚拟市场新增业绩','value'=>Tool::formatFrontPerf($calcBonus['PV_LS_TOUCH'])];
            //查看剩余区域是哪个区
//        $surplusArr=[$calcBonus['SURPLUS_1L'],$calcBonus['SURPLUS_2L'],$calcBonus['SURPLUS_3L']];
//        $bigLocation = array_search(max($surplusArr), $surplusArr);
//        $bigLocationName = ['一市场','二市场','三市场'][$bigLocation];
//        $data[]=['name'=>'剩余业绩市场','value'=>$bigLocationName];
//        $data[]=['name'=>'剩余业绩','value'=>Tool::formatFrontPerf($surplusArr[$bigLocation])];

        }else{
            $data[] = ['name' => '总奖金', 'value' => Tool::formatPrice($calcBonus['BONUS_TOTAL'])];
        }
        return $data;
    }

    /**
     * 往期奖金
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionOther(){
        //获取可以查看几期奖金
        $showBonusPeriodNum = Cache::getSystemConfig()['showBonusPeriodNum']['VALUE'];
        $calcBonus = CalcBonus::find()->where('USER_ID=:USER_ID AND IS_SENT=1', [':USER_ID' => \Yii::$app->user->id])
        ->select('PERIOD_NUM,ORI_BONUS_QY,ORI_BONUS_YC,ORI_BONUS_VIP,ORI_BONUS_STANDARD,ORI_BONUS_BD,ORI_BONUS_TG,
        ORI_BONUS_XF,BONUS_TOTAL,MANAGE_TAX,BONUS_REAL,BONUS_INCOME,ORI_BONUS_YJ,ORI_BONUS_GX,ORI_BONUS_GL,RECONSUME_POINTS,
        LAST_DEC_LV,LAST_EMP_LV,EXCHANGE_POINTS,ORI_BONUS_BS,ORI_BONUS_BS_MNT,ORI_BONUS_BS_ABBR,ORI_BONUS_QUARTER,BONUS_TOURISM,BONUS_GARAGE')
        ->limit($showBonusPeriodNum)
        ->orderBy('PERIOD_NUM DESC')
        ->asArray()
        ->all();
        $sysConfig = Cache::getSystemConfig();

        //增加明细开关控制(0 只显示总奖金 1 全部显示)
        $flowBonusSwitch = Cache::getSystemConfig()['flowBonusSwitch']['VALUE'];

        $bonusSwitch = [
            'welcomeBonusSwitch' => intval($sysConfig['openTG']['VALUE']),
            'teamBonusSwitch' => intval($sysConfig['openQY']['VALUE']),
            'stockistCommissionSwitch' => intval($sysConfig['openFW']['VALUE']),
        ];

        foreach ($calcBonus as $key => $data) {
            if($flowBonusSwitch) {
                $calcBonus[$key]['PERIOD_NUM'] = ['name' => '期数', 'value' => $calcBonus[$key]['PERIOD_NUM']];
                $calcBonus[$key]['LAST_DEC_NAME'] = ['name' => '级别', 'value' => Cache::getDecLevelConfig()[$calcBonus[$key]['LAST_DEC_LV']]['LEVEL_NAME']];
                $calcBonus[$key]['LAST_EMP_NAME'] = ['name' => '聘级', 'value' => Cache::getEmpLevelConfig()[$calcBonus[$key]['LAST_EMP_LV']]['LEVEL_NAME']];

                // 销售奖金,就是原来的推广奖金
                if ($sysConfig['openTG']['VALUE']) {
                    $calcBonus[$key]['BONUS_TG'] = ['name' => '销售奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_TG'])];
                }
                // 业绩奖金,就是原来的团队奖  并将业绩奖金改成绩效奖金
                if ($sysConfig['openQY']['VALUE']) {
                    $calcBonus[$key]['ORI_BONUS_QY'] = ['name' => '业绩奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_QY'])];
                }

                // 管理奖金 就是新的蓝星奖金
//                $calcBonus[$key]['BONUS_BS'] = ['name' => '管理奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_BS'])];
                //共享奖
//                if ($sysConfig['openGX']['VALUE']) {
//                    $calcBonus[$key]['BONUS_GX'] = ['name' => '共享奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_GX'])];
//                }
                //服务奖
                if ($sysConfig['openFW']['VALUE']) {
                    $calcBonus[$key]['BONUS_BD'] = ['name' => '服务奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_BD'])];
                }

                // 管理奖金 就是新的蓝星奖
                $calcBonus[$key]['ORI_BONUS_BS'] = ['name' => '管理奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_BS'])];
                $calcBonus[$key]['ORI_BONUS_BS_MNT'] = ['name' => '管理奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_BS_MNT'])];
                $calcBonus[$key]['ORI_BONUS_BS_ABBR'] = ['name' => '绩效奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_BS_ABBR'])];

                $calcBonus[$key]['ORI_BONUS_QUARTER'] = ['name' => '季度奖金', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_QUARTER'] ?? 0)];
                $calcBonus[$key]['BONUS_TOURISM'] = ['name' => '旅游奖', 'value' => Tool::formatPrice($calcBonus[$key]['BONUS_TOURISM'])];
                $calcBonus[$key]['BONUS_GARAGE'] = ['name' => '车房奖', 'value' => Tool::formatPrice($calcBonus[$key]['BONUS_GARAGE'])];
                // 总奖金
                $calcBonus[$key]['BONUS_TOTAL'] = ['name' => '合计', 'value' => Tool::formatPrice($calcBonus[$key]['BONUS_TOTAL'])];
//                $calcBonus[$key]['RECONSUME_POINTS'] = ['name' => '复销积分', 'value' => Tool::formatPrice($calcBonus[$key]['RECONSUME_POINTS'])];
//                $calcBonus[$key]['EXCHANGE_POINTS'] = ['name' => '兑换积分', 'value' => Tool::formatPrice($calcBonus[$key]['EXCHANGE_POINTS'])];
//                $calcBonus[$key]['MANAGE_TAX'] = ['name' => '管理费', 'value' => Tool::formatPrice($calcBonus[$key]['MANAGE_TAX'])];
                $calcBonus[$key]['BONUS_REAL'] = ['name' => '实发奖金', 'value' => Tool::formatPrice($calcBonus[$key]['BONUS_REAL'])];
                // if ($sysConfig['openYC']['VALUE']) {
                //     $calcBonus[$key]['BONUS_YC'] = ['name' => '荣衔奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_YC'])];
                // }
                // if ($sysConfig['openVIP']['VALUE']) {
                //     $calcBonus[$key]['BONUS_VIP'] = ['name' => 'VIP奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_VIP'])];
                // }
                // if ($sysConfig['openXF']['VALUE']) {
                //     $calcBonus[$key]['BONUS_XF'] = ['name' => '消费奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_XF'])];
                // }
                // if ($sysConfig['openYJ']['VALUE']) {
                //     $calcBonus[$key]['BONUS_YJ'] = ['name' => '业绩奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_YJ'])];
                // }
                // if ($sysConfig['openGL']['VALUE']) {
                //     $calcBonus[$key]['BONUS_GL'] = ['name' => '管理奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_GL'])];
                // }
                // if ($sysConfig['openJXS']['VALUE']) {
                //     $calcBonus[$key]['BONUS_STANDARD'] = ['name' => '团队成长奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_STANDARD'])];
                // }
            }else{

                $calcBonus[$key]['BONUS_TOTAL'] = ['name' => '总奖金', 'value' => Tool::formatPrice($calcBonus[$key]['BONUS_TOTAL'])];

            }
        }

//        if($flowBonusSwitch) {
//            $tableKey[] = 'PERIOD_NUM';
//            if ($sysConfig['openTG']['VALUE']) {
//                $tableKey[] = 'BONUS_TG';
//            }
//            if ($sysConfig['openQY']['VALUE']) {
//                $tableKey[] = 'BONUS_QY';
//            }
//            $tableKey[] = 'BONUS_BS';
//            if ($sysConfig['openGX']['VALUE']) {
//                $tableKey[] = 'BONUS_GX';
//            }
//            // if ($sysConfig['openYC']['VALUE']) {
//            //     $tableKey[] = 'BONUS_YC';
//            // }
//            // if ($sysConfig['openVIP']['VALUE']) {
//            //     $tableKey[] = 'BONUS_VIP';
//            // }
//            if ($sysConfig['openFW']['VALUE']) {
//                $tableKey[] = 'BONUS_BD';
//            }
//
//            // if ($sysConfig['openXF']['VALUE']) {
//            //     $tableKey[] = 'BONUS_XF';
//            // }
//            // if ($sysConfig['openYJ']['VALUE']) {
//            //     $tableKey[] = 'BONUS_YJ';
//            // }
//
//            // if ($sysConfig['openGL']['VALUE']) {
//            //     $tableKey[] = 'BONUS_GL';
//            // }
//            // if ($sysConfig['openJXS']['VALUE']) {
//            //     $tableKey[] = 'BONUS_STANDARD';
//            // }
//
//            $tableKey[] = 'BONUS_TOTAL';
//            $tableKey[] = 'RECONSUME_POINTS';
//            $tableKey[] = 'EXCHANGE_POINTS';
//            $tableKey[] = 'MANAGE_TAX';
//            $tableKey[] = 'BONUS_REAL';
//        }else{
//            $tableKey[] = 'BONUS_TOTAL';
//        }

        return static::notice(['tableData' => $calcBonus, 'tableKey' => '', 'bonusSwitch' => $bonusSwitch]);
    }

    /**
     * 历史累积奖金
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionHistoricalCumulativeBonus()
    {
        $calcBonus = CalcBonus::find()->where('USER_ID=:USER_ID AND IS_SENT=1', [':USER_ID' => \Yii::$app->user->id])
            ->select([
                'SUM(ORI_BONUS_TG) AS ORI_BONUS_TG',
                'SUM(ORI_BONUS_QY) AS ORI_BONUS_QY',
                'SUM(ORI_BONUS_BD) AS ORI_BONUS_BD',
                'SUM(ORI_BONUS_BS) AS ORI_BONUS_BS',
                'SUM(ORI_BONUS_QUARTER) AS ORI_BONUS_QUARTER',
                'SUM(BONUS_TOTAL) AS BONUS_TOTAL'
            ])
            ->asArray()
            ->one();

        // 增加明细开关控制(0 只显示总奖金 1 全部显示)
        $flowBonusSwitch = Cache::getSystemConfig()['flowBonusSwitch']['VALUE'];

        $sysConfig = Cache::getSystemConfig();
        $bonusSwitch = [
            'welcomeBonusSwitch' => intval($sysConfig['openTG']['VALUE']),
            'teamBonusSwitch' => intval($sysConfig['openQY']['VALUE']),
            'stockistCommissionSwitch' => intval($sysConfig['openFW']['VALUE']),
        ];

        if ($calcBonus) {
            if ($flowBonusSwitch) {
                if ($sysConfig['openTG']['VALUE']) {
                    $calcBonus['BONUS_TG'] = ['name' => '销售奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_TG'])];
                }
                if ($sysConfig['openQY']['VALUE']) {
                    $calcBonus['ORI_BONUS_QY'] = ['name' => '业绩奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_QY'])];
                }
                if ($sysConfig['openFW']['VALUE']) {
                    $calcBonus['BONUS_BD'] = ['name' => '服务奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BD'])];
                }

                $calcBonus['ORI_BONUS_BS'] = ['name' => '蓝星奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BS'])];
                $calcBonus['ORI_BONUS_QUARTER'] = ['name' => '季度奖金', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_QUARTER'])];
            }

            $calcBonus['BONUS_TOTAL'] = ['name' => '总奖金', 'value' => Tool::formatPrice($calcBonus['BONUS_TOTAL'])];
        }

        return static::notice(['tableData' => [$calcBonus], 'bonusSwitch' => $bonusSwitch]);
    }

    /**
     * 实时业绩
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRealTimePerf() {
        $userId = \Yii::$app->user->id;
        $period = Period::instance();
        $newPerf = Perf::getPeriodNewPerf($userId);
        $weekData = [['PV_1L' => Tool::formatFrontPerf($newPerf['PV_1L']), 'PV_2L' => Tool::formatFrontPerf($newPerf['PV_2L']), 'PV_3L' => Tool::formatFrontPerf($newPerf['PV_3L'])]];
        $monthPerf = Perf::getMonthPerf($userId);
        $monthData = [['PV_1L' => Tool::formatFrontPerf($monthPerf['PV_1L']), 'PV_2L' => Tool::formatFrontPerf($monthPerf['PV_2L']), 'PV_3L' => Tool::formatFrontPerf($monthPerf['PV_3L'])]];
        $lastMonth = PerfMonth::getMonthPerf($period->getLastMonth()['yearMonth'], $userId);
        $lastData = [['PV_1L' => Tool::formatFrontPerf($lastMonth['PV_1L_TOTAL']), 'PV_2L' => Tool::formatFrontPerf($lastMonth['PV_2L_TOTAL']), 'PV_3L' => Tool::formatFrontPerf($lastMonth['PV_3L_TOTAL'])]];
        //是否合格
//        $lastChkStatus = '';
//        $lastMonthPerfChk = Cache::getSystemConfig()['lastMonthPerfChk']['VALUE'];
//        $lastArr = [$lastMonth['PV_1L_TOTAL'], $lastMonth['PV_2L_TOTAL'], $lastMonth['PV_3L_TOTAL'], $lastMonth['PV_4L_TOTAL'], $lastMonth['PV_5L_TOTAL']];
//        if (array_sum($lastArr) >= $lastMonthPerfChk) {
//            $lastChkStatus = '已合格';
//        }
        //判断大区
//        $bigLocation = array_search(max($lastArr), $lastArr) + 1;
        return static::notice(['weekData' => $weekData, 'monthData' => $monthData, 'lastData' => $lastData]);
    }

    /**
     * 近十期已挂网的期数
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecPeriod() {
        $showDecPeriodNum = Cache::getSystemConfig()['showDecPeriodNum']['VALUE'];
        $data = Period::find()->where('IS_SENT=:IS_SENT',[':IS_SENT' => Period::SEND_FINISH])->select('PERIOD_NUM,END_TIME')->limit($showDecPeriodNum)->orderBy('PERIOD_NUM DESC')->asArray()->all();
        return static::notice($data);
    }

    /**
     * 报单中心补助明细
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionFlowBt() {
        $periodNum = \Yii::$app->request->get('periodNum');
        $condition = '';
        $params = [];
        if (!$periodNum) {
            return static::notice('请选择期数',400);
        }
        if ($periodNum) {
            $showDecPeriodNum = Cache::getSystemConfig()['showDecPeriodNum']['VALUE'];
            $periodNums = Period::find()->where('IS_SENT=:IS_SENT',[':IS_SENT' => Period::SEND_FINISH])->select('PERIOD_NUM')->limit($showDecPeriodNum)->orderBy('PERIOD_NUM DESC')->asArray()->all();
            if(!in_array($periodNum,array_column($periodNums,'PERIOD_NUM'))){
                return static::notice('该期无法查看',400);
            }
            $condition .= ' AND PERIOD_NUM=:PERIOD_NUM';
            $params[':PERIOD_NUM'] = $periodNum;
        }
        $condition .= ' AND USER_ID=:USER_ID';
        $params[':USER_ID'] = \Yii::$app->user->id;
        $data = CalcBonusBT::lists($condition, $params, [
            'select' => 'BT_TYPE,FROM_ORDER_SN,ORDER_TIME,PAY_PV,DELIVERY_AT,TRANSFER_AMOUNT,TRANSFER_AT,AMOUNT',
            'from' => CalcBonusBT::tableName(),
            'orderBy' => 'CREATED_AT DESC',
        ]);
        if ($data['list']) {
            foreach ($data['list'] as $key => $value) {
                $data['list'][$key]['BT_TYPE_NAME'] = CalcBonusBT::TYPE_NAME[$value['BT_TYPE']];
                foreach ($value as $k=>$item){
                    if($item==0) $data['list'][$key][$k] ='';
                }
            }
        }

        return static::notice($data);
    }

    /**
     * 报单中心货补追溯
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionTraceFl() {
        $periodNum = \Yii::$app->request->get('periodNum');
        $condition = '';
        $params = [];
        if (!$periodNum) {
            return static::notice('请选择期数',400);
        }
        if ($periodNum) {
            $showDecPeriodNum = Cache::getSystemConfig()['showDecPeriodNum']['VALUE'];
            $periodNums = Period::find()->where('IS_SENT=:IS_SENT',[':IS_SENT' => Period::SEND_FINISH])->select('PERIOD_NUM')->limit($showDecPeriodNum)->orderBy('PERIOD_NUM DESC')->asArray()->all();
            if(!in_array($periodNum,array_column($periodNums,'PERIOD_NUM'))){
                return static::notice('该期无法查看',400);
            }
            $condition .= ' AND PERIOD_NUM=:PERIOD_NUM';
            $params[':PERIOD_NUM'] = $periodNum;
        }
        $condition .= ' AND USER_ID=:USER_ID';
        $params[':USER_ID'] = \Yii::$app->user->id;
        $data = CalcBonusFL::lists($condition, $params, [
            'select' => 'DEC_SN,DEC_AT,DEC_PV,AMOUNT',
            'from' => CalcBonusFL::tableName(),
            'orderBy' => 'CREATED_AT DESC',
        ]);

        return static::notice($data);
    }




    /**
     * 查看所传期数的各项奖金
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBonusDetail() {
        $periodNum = \Yii::$app->request->get('periodNum');
        $period = Period::instance();
        $periodInfo = $period->setPeriodNum($periodNum);
        $yearMonth = $period->getYearMonth($periodNum);
        if (!$period->isSent($periodNum)) {
            return static::notice('Cannot view this period',400); // 该期不能查看
        }
        $data = CalcBonus::findUseSlaves()->yearMonth($yearMonth)->select('BONUS_QY,BONUS_YC,BONUS_FX,BONUS_LS,BONUS_CF,BONUS_LX,BONUS_FL')->where('PERIOD_NUM=:PERIOD_NUM AND USER_ID=:USER_ID', [':PERIOD_NUM' => $periodNum, ':USER_ID' => \Yii::$app->user->id])->asArray()->one();
        return static::notice(['period' => $periodInfo, 'bonus' => $data]);
    }

    /**
     * 奖金流水
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionFlowBonus() {
        $yearMonth = \Yii::$app->request->get('yearMonth');
        if ($yearMonth) {
            if (!Date::isYearMonth($yearMonth)) {
                return static::notice('无效参数', 400);
            }
        } else {
            $period = Period::instance();
            $yearMonth = $period->getNowYearMonth();
        }
        $data = FlowBonus::lists(' AND USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->user->id], [
            'useSlaves' => true,
            'select' => 'AMOUNT,TOTAL,IS_INCR,REMARK,REMARK_IS_SHOW,PERIOD_NUM,CALC_MONTH,CREATED_AT',
            'yearMonth' => $yearMonth,
            'orderBy' => 'CREATED_AT DESC',
        ]);
        foreach ($data['list'] as $key => $value) {
            if($value['REMARK_IS_SHOW']==0) $data['list'][$key]['REMARK'] = '';
        }
        return static::notice($data);
    }

    /**
     * 提现列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdraw() {
        $yearMonth = \Yii::$app->request->get('yearMonth');
        if ($yearMonth) {
            if (!Date::isYearMonth($yearMonth)) {
                return static::notice('无效参数', 400);
            }
        } else {
            $period = Period::instance();
            $yearMonth = $period->getNowYearMonth();
        }
        $data = Withdraw::lists('AND W.USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->user->id], [
            'useSlaves' => true,
            'select' => 'W.ID,W.USER_ID,W.IS_AUTO_WITHDRAW,W.AMOUNT,W.AUDIT_STATUS,W.CREATED_AT,W.PAID_AT,W.PAY_TYPE,W.PAID_FAIL_REMARK,W.INVOICE_ID,IA.AMOUNT INVOICE_AMOUNT,IA.AUDIT_STATUS INVOICE_AUDIT_STATUS,IA.UPLOAD_ID',
            'from' => Withdraw::tableName() . ' AS W',
            'join' => [
                ['LEFT JOIN', InvoiceAudit::tableName() . ' AS IA', 'W.ID=IA.WITHDRAW_ID'],
            ],
            'yearMonth' => $yearMonth,
            'orderBy' => 'W.CREATED_AT DESC',
            //'with' => 'openBank',
        ]);
        $auditStatus = array_column(\Yii::$app->params['auditStatus'], null, 'value');
        foreach ($data['list'] as $key => $value) {
            $baseInfo = Info::baseInfo($value['USER_ID']);
            $data['list'][$key]['USER_NAME'] = $baseInfo['USER_NAME'];
            $data['list'][$key]['REAL_NAME'] = $baseInfo['REAL_NAME'];
            $data['list'][$key]['STATUS_NAME'] = Withdraw::STATUS_NAME[$value['AUDIT_STATUS']];
            $data['list'][$key]['INVOICE_STATUS_NAME'] = isset($value['INVOICE_AUDIT_STATUS'])?$auditStatus[$value['INVOICE_AUDIT_STATUS']]['label']:'未传发票';
        }
        return static::notice($data);
    }

    /**
     * 提交提现申请
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawAdd() {
        if (\Yii::$app->request->isPost) {
            $formModel = new WithdrawForm();
            $formModel->scenario = 'addByUser';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->add()) {
                return static::notice('Withdrawal application has been submitted, please wait for review.'); // 提现申请已提交，请等待审核
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            return static::notice('Illegal request', 400); // 非法请求
        }
    }

    /**
     * 提现退回
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawBack() {
        if (\Yii::$app->request->isPost) {
            $formModel = new WithdrawForm();
            $formModel->scenario = 'backByUser';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->backByUser()) {
                return static::notice('提现已退回');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            return static::notice('Illegal request', 400); // 非法请求
        }
    }

    /**
     * 判断并获取提现的会员信息
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChkWithdrawUser() {
        $uid = \Yii::$app->user->id;
        if (!Info::isVerified($uid)) {
            return static::notice('未实名验证无法提现', 400);
        }
        $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $uid], 'IS_BIND,IS_BIND_MAIN,IS_AUTO_WITHDRAW,REG_TYPE,TRANSFER_PROP');
        if ($userInfo['IS_BIND'] == 1 && $userInfo['IS_BIND_MAIN'] == 0) {
            return static::notice('附属会员无法提现', 400);
        }
        if ($userInfo['IS_AUTO_WITHDRAW'] == 1) {
            return static::notice('已开启自动提现，如需手动提现请关闭自动提现', 400);
        }
        if (!Withdraw::allowWithdraw()) {
            return static::notice('未到提现日期，请在每月挂网后第一周申请提现', 400);
        }
        if (Withdraw::hasThisMonthWithdraw($uid)) {
            return static::notice('提现失败，每月只可以提现一次', 400);
        }
        if (Withdraw::existWaitAudit($uid)) {
            return static::notice('提现失败，您存在未审核的提现记录', 400);
        }
        //是否显示服务协议
        $regType = RegType::findOneAsArray('ID=:ID', [':ID' => $userInfo['REG_TYPE']], 'IS_PACT');
        $path = \Yii::getAlias('@common/runtime/datas/pact.php');
        if (!file_exists($path)) {
            $oneData = '';
        } else {
            $oneData = include $path;
        }
        $isCanTransferProp = Cache::getSystemConfig()['isCanTransferProp']['VALUE'];
        if ($isCanTransferProp == 0) {
            $userInfo['WITHDRAW_PROP'] = 100;
        } else {
            $userInfo['WITHDRAW_PROP'] = 100 - $userInfo['TRANSFER_PROP'];
        }
        return static::notice(['userInfo' => $userInfo, 'isPact' => $regType['IS_PACT'], 'content' => $oneData['CONTENT']]);
    }

    /**
     * 归集附属会员奖金
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionCollectBind() {
        $transferBonusForm = new TransferBonusForm();
        if ($totals=$transferBonusForm->collectBind(\Yii::$app->user->id)) {
            return static::notice('归集完成，归集金额'.$totals);
        } else {
            if($totals==0){
                return static::notice('归集完成，归集金额'.$totals);
            }else{
                return static::notice(Form::formatErrorsForApi($transferBonusForm->getErrors()), 400);
            }
        }
    }

    /**
     * 上传发票之前
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceBeforeAdd() {
        $id = \Yii::$app->request->get('id');
        $withdraw = Withdraw::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$withdraw) {
            return static::notice('The data does not exist', 400); // 数据不存在
        }
        $uploadInvoiceTip = Cache::getSystemConfig()['uploadInvoiceTip']['VALUE'];
        if ($withdraw['AUDIT_STATUS'] == Withdraw::STATUS_APPLIED) {
            return static::notice(['addInvoiceTips' => $uploadInvoiceTip]);
        } else {
            return static::notice('该提现记录无法上传发票', 400);
        }
    }

    /**
     * 上传发票
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceAdd() {
        $id = \Yii::$app->request->get('id');
        $withdraw = Withdraw::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$withdraw) {
            return static::notice('The data does not exist', 400); // 数据不存在
        }
        if (\Yii::$app->request->isPost) {
            $formModel = new UploadForm();
            $formModel->scenario = 'invoiceFront';
            $formModel->file = UploadedFile::getInstanceByName('file');
            $formModel->withdrawId = $withdraw['ID'];
            $formModel->remark = '提现'.$withdraw['SN'].'发票';
            //$formModel->token = \Yii::$app->request->post('uploadToken');
            $formModel->token = \Yii::$app->request->request('uploadToken');
            if ($formModel->file && $formModel->upload()) {
                return static::notice('Successful');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 显示上传的发票
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceShow() {
        $id = \Yii::$app->request->get('id');
        $uploads = Uploads::findOneAsArray('ID=:ID', [':ID' => $id],'URL');
        if (!$uploads) {
            return static::notice('The data does not exist', 400); // 数据不存在
        }
        return static::notice($uploads['URL']);
    }

    /**
     * 获取可用余额
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionAvailableBalance() {
        return static::notice(Balance::getAvailableBalance(\Yii::$app->user->id));
    }

    /**
     * 查看业绩
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionPerf() {
        $yearMonth = \Yii::$app->request->get('yearMonth');
        if ($yearMonth) {
            if (!Date::isYearMonth($yearMonth)) {
                return static::notice('无效参数', 400);
            }
        } else {
            $period = Period::instance();
            $yearMonth = $period->getNowYearMonth();
        }
        $data = PerfPeriod::lists('AND P.USER_ID=:USER_ID AND PN.IS_SENT=1', [':USER_ID' => \Yii::$app->user->id], [
            'select' => 'P.*',
            'yearMonth' => $yearMonth,
            'from' => PerfPeriod::tableName() . ' AS P',
            'join' => [
                ['LEFT JOIN', Period::tableName() . ' AS PN', 'P.PERIOD_NUM=PN.PERIOD_NUM']
            ],
            'orderBy' => 'P.PERIOD_NUM DESC',
        ]);
        $data['request']['yearMonth'] = $yearMonth;
        return static::notice($data);
    }

    /**
     * 转账列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionTransferList() {
        $type = \Yii::$app->request->get('type', 'out');
        if ($type == 'out') {
            $condition = ' AND T.FROM_UID=:USER_ID';
        } else {
            $condition = ' AND T.TO_UID=:USER_ID';
        }
        $params = [
            ':USER_ID' => \Yii::$app->user->id,
        ];
        $data = Transfer::lists($condition, $params, [
            'select' => 'FUI.USER_NAME AS FROM_USER_NAME, TUI.USER_NAME AS TO_USER_NAME, T.AMOUNT, T.PERIOD_NUM, T.CREATED_AT',
            'from' => Transfer::tableName() . ' AS T',
            'join' => [
                ['LEFT JOIN', UserInfo::tableName() . ' AS FUI', 'FUI.USER_ID=T.FROM_UID'],
                ['LEFT JOIN', UserInfo::tableName() . ' AS TUI', 'TUI.USER_ID=T.TO_UID'],
            ],
        ]);
        return static::notice($data);
    }

    /**
     * 转账
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionTransferAdd() {
        if (\Yii::$app->request->isPost) {
            $formModel = new TransferForm();
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->transfer()) {
                return static::notice('Transfer success'); // 转账成功
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 检查转账资格
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChkTransferUser() {
        $uid = \Yii::$app->user->id;
        if (!Info::isVerified($uid)) {
            return static::notice('未实名验证无法转账', 400);
        }
        $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $uid], 'ALLOW_TRANSFER,TRANSFER_PROP');
        if($userInfo['ALLOW_TRANSFER']==0){
            return static::notice('您不允许转账', 400);
        }
        $isCanTransferProp = Cache::getSystemConfig()['isCanTransferProp']['VALUE'];
        if($isCanTransferProp==0){
            $userInfo['TRANSFER_PROP']=100;
        }
        return static::notice(['userInfo' => $userInfo]);
    }

    /**
     * 房产积分列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionFcPoint() {
        $condition = ' AND USER_ID=:USER_ID';
        $params = [':USER_ID' => \Yii::$app->user->id];

        $yearMonth = \Yii::$app->request->get('yearMonth');
        if ($yearMonth) {
            if (!Date::isYearMonth($yearMonth)) {
                return static::notice('无效参数', 400);
            }
            $condition .= ' AND CALC_MONTH=:CALC_MONTH';
            $params['CALC_MONTH'] = $yearMonth;
        }

        $data = ScoreMonth::lists($condition, $params, [
            'from' => ScoreMonth::tableName(),
            'orderBy' => 'ID DESC',
        ]);
        return static::notice($data);
    }
}
