<?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\CalcBonusBT;
use common\models\CalcBonusFL;
use common\models\DealType;
use common\models\FlowBonus;
use common\models\FlowReconsumePoints;
use common\models\FlowWallet;
use common\models\PerfMonth;
use common\models\Period;
use common\models\ScoreMonth;
use common\models\UserBonus;
use common\models\UserWallet;

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')->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
        if (!$data) {
            $data = [
                'BONUS' => 0,
                'RECONSUME_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' => '会员奖金', 'amount' => Tool::formatPrice($data['BONUS'])];
        $wallet[] = ['walletType' => 'cash', 'walletName' => '会员余额', 'amount' => Tool::formatPrice($data['CASH'])];
        $wallet[] = ['walletType' => 'point', 'walletName' => '会员积分', 'amount' => Tool::formatPrice($data['RECONSUME_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;
//        }
        return static::notice(['wallet' => $wallet]);
    }

    /**
     * 交易记录
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionWalletFlow(){
        $walletType = \Yii::$app->request->get('walletType');
        if(!in_array($walletType,['bonus','point','cash'])) return static::notice('错误的账户类型',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) {
            $condition .= " AND CREATED_AT>:CREATED_START AND CREATED_AT<:CREATED_END";
            $params[':CREATED_START'] = Date::utcToTime($createAt[0]);
            $params[':CREATED_END'] = Date::utcToTime($createAt[1])+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',
            ]);
        }
        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 ? '增加' : '减少';
                    } 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'] = '增加';
                    $dealTypes['2'] = '扣除';
                }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('该期不能查看',400);
        $data = $this->_periodBonus($periodNum);
        if(!$data) return static::notice('当期无奖金记录',400);
        return static::notice($data);
    }

    /**
     * 期数对应的奖金
     * @param $periodNum
     * @return array
     * @throws \yii\db\Exception
     */
    private function _periodBonus($periodNum) {
        $period = Period::instance();
        $yearMonth = $period->getYearMonth($periodNum); // 返回类似202110
        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 [

            ];
        }
        //$t = CalcBonus::find()->yearMonth($yearMonth)->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM',[':USER_ID'=>\Yii::$app->user->id,':PERIOD_NUM'=>$periodNum])->createCommand()->getRawSql();
        $sysConfig = Cache::getSystemConfig();
        // $data[]=['name'=>'期数','value'=>$periodNum];
        // $data[]=['name'=>'级别','value'=>Cache::getDecLevelConfig()[$calcBonus['LAST_DEC_LV']]['LEVEL_NAME']];
        // $data[]=['name'=>'荣誉','value'=>Cache::getEmpLevelConfig()[$calcBonus['LAST_EMP_LV']]['LEVEL_NAME']];
        if($sysConfig['openQY']['VALUE']){
            $data[]=['name'=>'团队奖','value'=>Tool::formatPrice($calcBonus['ORI_BONUS_QY'])];
        }
        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['openFW']['VALUE']) {
            $data[] = ['name' => '服务奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_BD'])];
        }
        if($sysConfig['openTG']['VALUE']) {
            $data[] = ['name' => '推广奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_TG'])];
        }
        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['openGX']['VALUE']) {
            $data[] = ['name' => '共享奖', 'value' => Tool::formatPrice($calcBonus['ORI_BONUS_GX'])];
        }
        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'])];
        //$data[]=['name'=>'管理费','value'=>Tool::formatPrice($calcBonus['MANAGE_TAX'])];
        //$data[]=['name'=>'实发奖金','value'=>Tool::formatPrice($calcBonus['BONUS_REAL'])];
//        $data[]=['name'=>'总奖金','value'=>Tool::formatPrice($calcBonus['BONUS_TOTAL'])];
        //$data[] = ['name' => '复消积分', 'value' => Tool::formatPrice($calcBonus['RECONSUME_POINTS'])];
//        if($sysConfig['openLX']['VALUE']) {
//            $data[] = ['name' => '福利积分二', 'value' => Tool::formatPrice($calcBonus['BONUS_LX'])];
//        }
        // $data[]=['name'=>'一市场新增业绩','value'=>Tool::formatFrontPerf($calcBonus['PV_1L'])];
        // $data[]=['name'=>'二市场新增业绩','value'=>Tool::formatFrontPerf($calcBonus['PV_2L'])];
        // $data[]=['name'=>'三市场新增业绩','value'=>Tool::formatFrontPerf($calcBonus['PV_3L'])];
        // $data[]=['name'=>'一市场结余业绩','value'=>Tool::formatFrontPerf($calcBonus['SURPLUS_1L'])];
        // $data[]=['name'=>'二市场结余业绩','value'=>Tool::formatFrontPerf($calcBonus['SURPLUS_2L'])];
        // $data[]=['name'=>'三市场结余业绩','value'=>Tool::formatFrontPerf($calcBonus['SURPLUS_3L'])];
//        $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])];
        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')->limit($showBonusPeriodNum)->orderBy('PERIOD_NUM DESC')->asArray()->all();
        $sysConfig = Cache::getSystemConfig();
        foreach ($calcBonus as $key => $data) {
            $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['openQY']['VALUE']) {
                $calcBonus[$key]['BONUS_QY'] = ['name' => '团队奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_QY'])];
            }
            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['openFW']['VALUE']) {
                $calcBonus[$key]['BONUS_BD'] = ['name' => '服务奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_BD'])];
            }
            if ($sysConfig['openTG']['VALUE']) {
                $calcBonus[$key]['BONUS_TG'] = ['name' => '推广奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_TG'])];
            }
            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['openGX']['VALUE']) {
                $calcBonus[$key]['BONUS_GX'] = ['name' => '共享奖', 'value' => Tool::formatPrice($calcBonus[$key]['ORI_BONUS_GX'])];
            }
            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'])];
            }
            $calcBonus[$key]['BONUS_TOTAL'] = ['name' => '总奖金', 'value' => Tool::formatPrice($calcBonus[$key]['BONUS_TOTAL'])];
            $calcBonus[$key]['MANAGE_TAX'] = ['name' => '管理费', 'value' => Tool::formatPrice($calcBonus[$key]['MANAGE_TAX'])];
            $calcBonus[$key]['BONUS_REAL'] = ['name' => '实发奖金', 'value' => Tool::formatPrice($calcBonus[$key]['BONUS_REAL'])];
            $calcBonus[$key]['RECONSUME_POINTS'] = ['name' => '复消积分', 'value' => Tool::formatPrice($calcBonus[$key]['RECONSUME_POINTS'])];
        }
        $tableKey[] = 'PERIOD_NUM';
        if ($sysConfig['openQY']['VALUE']) {
            $tableKey[] = 'BONUS_QY';
        }
        if ($sysConfig['openYC']['VALUE']) {
            $tableKey[] = 'BONUS_YC';
        }
        if ($sysConfig['openVIP']['VALUE']) {
            $tableKey[] = 'BONUS_VIP';
        }
        if ($sysConfig['openFW']['VALUE']) {
            $tableKey[] = 'BONUS_BD';
        }
        if ($sysConfig['openTG']['VALUE']) {
            $tableKey[] = 'BONUS_TG';
        }
        if ($sysConfig['openXF']['VALUE']) {
            $tableKey[] = 'BONUS_XF';
        }
        if ($sysConfig['openYJ']['VALUE']) {
            $tableKey[] = 'BONUS_YJ';
        }
        if ($sysConfig['openGX']['VALUE']) {
            $tableKey[] = 'BONUS_GX';
        }
        if ($sysConfig['openGL']['VALUE']) {
            $tableKey[] = 'BONUS_GL';
        }
        if ($sysConfig['openJXS']['VALUE']) {
            $tableKey[] = 'BONUS_STANDARD';
        }
        $tableKey[] = 'BONUS_TOTAL';
        $tableKey[] = 'RECONSUME_POINTS';
        $tableKey[] = 'MANAGE_TAX';
        $tableKey[] = 'BONUS_REAL';

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

    /**
     * 实时业绩
     * @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('该期不能查看',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('提现申请已提交，请等待审核');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            return static::notice('非法请求', 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('非法请求', 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('数据不存在', 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('数据不存在', 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('上传成功');
            } 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('数据不存在', 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('转账成功');
            } 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);
    }
}