<?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\Form;
use common\helpers\LoggerTool;
use common\helpers\Tool;
use common\helpers\user\Balance;
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\Countries;
use common\models\Currency;
use common\models\DealType;
use common\models\DeclarationLevel;
use common\models\EliteLevel;
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\forms\TransferForm;
use common\models\forms\UploadForm;
use common\models\forms\WithdrawForm;
use common\models\InvoiceAudit;
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\RegType;
use common\models\ScoreMonth;
use common\models\Transfer;
use common\models\Uploads;
use common\models\UserBonus;
use common\models\UserInfo;
use common\models\UserPerformance;
use common\models\UserWallet;
use common\models\UserRelation;
use common\models\Withdraw;
use frontendApi\modules\v1\models\User;
use Yii;
use yii\web\HttpException;
use yii\web\UploadedFile;

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')->where('USER_ID=:USER_ID', [':USER_ID' => $userId])->asArray()->one();
        if (!$data) {
            $data = [
                'BONUS' => 0,
            ];
        }
        $data['CASH'] = 0;
        $cashWallet = UserWallet::findOneAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId], 'CASH');
        if($cashWallet){
            $data['CASH'] = $cashWallet['CASH'];
        }

        $user = User::getEnCodeInfo($userId);
        // 账户币种
        $country = Countries::getById($user['COUNTRY_ID']);
        $currency = Currency::getById($country['LOCAL_CURRENCY_ID']);

        // 绩效奖金
        $userPerformance = UserPerformance::getAmountByUserId($userId);
        $data['userPerformanceBonus'] = $userPerformance['AMOUNTS'] ?? 0;

        $wallet[] = ['walletType' => 'bonus', 'walletName' => Yii::t('app', 'memberBonus'), 'amount' => Tool::formatPrice($data['BONUS'])];//会员奖金
        $wallet[] = ['walletType' => 'cash', 'walletName' => Yii::t('app', 'memberEcoin'), 'amount' => Tool::formatPrice($data['CASH']), 'coin' => $currency['CODE']];//会员余额
        $wallet[] = ['walletType' => 'userPerformanceBonus', 'walletName' => Yii::t('app', 'userPerformanceBonus'), 'amount' => Tool::formatPrice($data['userPerformanceBonus']), 'coin' => $currency['CODE']];//绩效奖金

        $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->getTeamsPeriodNum();
        $month = $period->getTeamsYearMonth($periodNum);
        $periodData = Period::getInfoByPeriodNum($periodNum);

        // 判断此业绩期是否已经计算完成
        if ($periodData['IS_PREPARE'] != 4) {
            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', 'userPerformanceBonus'])) {
            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 if ($walletType != 'cash') {
                $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 == '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 == 'userPerformanceBonus') {
            $condition = ' AND USER_ID=:USER_ID AND STATUS_ID<20 AND AMOUNTS>0';
            $params = [':USER_ID' => \Yii::$app->user->id];
            $data = UserPerformance::lists($condition, $params, [
                'select' => 'ID,USER_ID,AMOUNTS,ORIGINAL,EXPIRED_AT',
                'orderBy' => 'EXPIRED_AT ASC, CREATED_AT ASC',
            ]);
        } else {
            return static::notice('walletType error',400);
        }

        if($data && $walletType == 'bonus') {
            foreach ($data['list'] as $key => $value) {
                if ($value['DEAL_TYPE_IS_PRESET'] == 0) {
                    $data['list'][$key]['DEAL_TYPE_NAME'] = $value['AMOUNT'] > 0 ? Yii::t('app', 'increase') : Yii::t('app', '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'] = '';
            }
        }

        if ($dealLists  && $walletType != 'userPerformanceBonus') {
            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'] = Yii::t('app', 'increase');// 增加
                    $dealTypes['2'] = Yii::t('app', '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(Yii::t('app', 'cannotViewThisPeriod'), 400);
        }

        // 查询奖金
        $data = User::find()
            ->from(User::tableName().' AS U')
            ->join('LEFT JOIN', CalcBonus::tableName() . ' AS B','B.USER_ID = U.ID')
            ->select('U.ID AS USER_ID, U.USER_NAME, U.LAST_DEC_LV, B.LAST_EMP_LV, B.LAST_ELITE_LV, B.IS_ACTIVE, B.BONUS_E, B.BONUS_PE, B.BONUS_SE, B.BONUS_LB, B.BONUS_ST, B.BONUS_WB, B.BONUS_CAR, B.BONUS_TOTAL, B.BONUS_PB')
            ->where('USER_ID=:USER_ID AND PERIOD_NUM=:PERIOD_NUM', [':USER_ID' => \Yii::$app->user->id,':PERIOD_NUM'=>$periodNum])
            ->asArray()
            ->one();

        $result = [
            'userName' => $data['USER_NAME'],
            'period' => $periodNum,
            'decLevel' => Cache::getDecLevelConfig()[($data['LAST_DEC_LV'] ?: DeclarationLevel::getDefaultLevelId())]['LEVEL_NAME'],
            'empLevel' => Cache::getEmpLevelConfig()[($data['LAST_EMP_LV'] ?: EmployLevel::getDefaultLevelId())]['LEVEL_NAME'],
            'eliteLevel' => Cache::getEliteLevelConfig()[($data['LAST_ELITE_LV'] ?: EliteLevel::getDefaultLevelId())]['LEVEL_NAME'],
            'isActive' => $data['IS_ACTIVE'] ?? 0,
            'eliteBonus' => Tool::formatPrice($data['BONUS_E']),
            'proEliteBonus' => Tool::formatPrice($data['BONUS_PE']),
            'superEliteBonus' => Tool::formatPrice($data['BONUS_SE']),
            'leaderShipBonus' => Tool::formatPrice($data['BONUS_LB']),
            'stockistBonus' => Tool::formatPrice($data['BONUS_ST']),
            'welcomeBonus' => Tool::formatPrice($data['BONUS_WB']),
            'carBonus' => Tool::formatPrice($data['BONUS_CAR']),
            'totalBonus' => Tool::formatPrice($data['BONUS_TOTAL']),
            'userPerformanceBonus' => Tool::formatPrice($data['BONUS_PB']),
        ];

        return static::notice($result);
    }

    /**
     * 往期奖金
     * @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,CALC_MONTH,LAST_DEC_LV,LAST_EMP_LV,LAST_ELITE_LV,BONUS_TOTAL,BONUS_E,BONUS_PE,BONUS_SE,BONUS_LB,BONUS_ST,BONUS_WB,BONUS_CAR,BONUS_PB')
            ->limit($showBonusPeriodNum)
            ->orderBy('PERIOD_NUM DESC')
            ->asArray()
            ->all();


        $result = [];
        foreach ($calcBonus as $data) {
            $result[] = [
                'period' => $data['PERIOD_NUM'],
                'eliteBonus' => Tool::formatPrice($data['BONUS_E']),
                'proEliteBonus' => Tool::formatPrice($data['BONUS_PE']),
                'superEliteBonus' => Tool::formatPrice($data['BONUS_SE']),
                'leaderShipBonus' => Tool::formatPrice($data['BONUS_LB']),
                'stockistBonus' => Tool::formatPrice($data['BONUS_ST']),
                'welcomeBonus' => Tool::formatPrice($data['BONUS_WB']),
                'carBonus' => Tool::formatPrice($data['BONUS_CAR']),
                'totalBonus' => Tool::formatPrice($data['BONUS_TOTAL']),
                'userPerformanceBonus' => Tool::formatPrice($data['BONUS_PB']),
            ];
        }

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

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

    /**
     * 历史累积奖金
     * @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([
                'IFNULL(SUM(BONUS_E), 0.00) AS BONUS_E',
                'IFNULL(SUM(BONUS_PE), 0.00) AS BONUS_PE',
                'IFNULL(SUM(BONUS_SE), 0.00) AS BONUS_SE',
                'IFNULL(SUM(BONUS_ST), 0.00) AS BONUS_ST',
                'IFNULL(SUM(BONUS_LB), 0.00) AS BONUS_LB',
                'IFNULL(SUM(BONUS_WB), 0.00) AS BONUS_WB',
                'IFNULL(SUM(BONUS_CAR), 0.00) AS BONUS_CAR',
                'IFNULL(SUM(BONUS_PB), 0.00) AS BONUS_PB',
            ])
            ->asArray()
            ->one();

        $data = [
            ['name' => 'eliteBonus', 'bonus' => $calcBonus['BONUS_E'] ?? '0'],
            ['name' => 'proEliteBonus', 'bonus' => $calcBonus['BONUS_PE'] ?? '0'],
            ['name' => 'superEliteBonus', 'bonus' => $calcBonus['BONUS_SE'] ?? '0'],
            ['name' => 'stockistBonus', 'bonus' => $calcBonus['BONUS_ST'] ?? '0'],
            ['name' => 'leaderShipBonus', 'bonus' => $calcBonus['BONUS_LB'] ?? '0'],
            ['name' => 'welcomeBonus', 'bonus' => $calcBonus['BONUS_WB'] ?? '0'],
            ['name' => 'carBonus', 'bonus' => $calcBonus['BONUS_CAR'] ?? '0'],
            ['name' => 'userPerformanceBonus', 'bonus' => $calcBonus['BONUS_PB'] ?? '0'],
        ];


        return static::notice(['tableData' => $data]);
    }

    /**
     * 实时业绩
     * @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'];
        $calcBonus = 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($calcBonus);
    }

    /**
     * 报单中心补助明细
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionFlowBt() {
        $periodNum = \Yii::$app->request->get('periodNum');
        $condition = '';
        $params = [];
        if (!$periodNum) {
            return static::notice(Yii::t('app', 'pleaseSelectThePeriod'), 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(Yii::t('app', 'cannotViewThisPeriod'), 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(Yii::t('app', 'pleaseSelectThePeriod'), 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(Yii::t('app', 'cannotViewThisPeriod'), 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(Yii::t('app', 'cannotViewThisPeriod'), 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(Yii::t('app', 'invalidParameter'), 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(Yii::t('app', 'invalidParameter'), 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(Yii::t('app', 'withdrawalApplicationHasBeenSubmitted'), 400);
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            return static::notice(Yii::t('app', 'illegalRequest'), 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(Yii::t('app', 'withdrawHasBeenBacked'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            return static::notice(Yii::t('app', 'illegalRequest'), 400);
        }
    }

    /**
     * 判断并获取提现的会员信息
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChkWithdrawUser() {
        $uid = \Yii::$app->user->id;
        if (!Info::isVerified($uid)) {
            return static::notice(Yii::t('app', 'withdrawDoesNotAllowedOfAuthentication'), 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(Yii::t('app', 'withdrawDoesNotAllowedOfSubsidiaryMember'), 400);
        }
        if ($userInfo['IS_AUTO_WITHDRAW'] == 1) {
            return static::notice(Yii::t('app', 'autoWithdrawHasBeenOpened'), 400);
        }
        if (!Withdraw::allowWithdraw()) {
            return static::notice(Yii::t('app', 'withdrawNotAllowOfDate'), 400);
        }
        if (Withdraw::hasThisMonthWithdraw($uid)) {
            return static::notice(Yii::t('app', 'withdrawAllowOnceOfMonth'), 400);
        }
        if (Withdraw::existWaitAudit($uid)) {
            return static::notice(Yii::t('app', 'withdrawRecordHasNotVerify'), 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(Yii::t('app', 'notionalPoolingAmountFinished') . $totals);
        } else {
            if($totals==0){
                return static::notice(Yii::t('app', 'notionalPoolingAmountFinished') . $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(Yii::t('app', 'dataDoesNotExists'), 400);
        }
        $uploadInvoiceTip = Cache::getSystemConfig()['uploadInvoiceTip']['VALUE'];
        if ($withdraw['AUDIT_STATUS'] == Withdraw::STATUS_APPLIED) {
            return static::notice(['addInvoiceTips' => $uploadInvoiceTip]);
        } else {
            return static::notice(Yii::t('app', 'withdrawDoesNotUploadInvoice'), 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(Yii::t('app', 'dataDoesNotExists'), 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(Yii::t('app', 'successfully'));
            } 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(Yii::t('app', 'dataDoesNotExists'), 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(Yii::t('app', 'invalidParameter'), 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(Yii::t('app', 'successfully'));
            } 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(Yii::t('app', 'transferDoesNotAllowedOfAuthentication'), 400);
        }
        $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $uid], 'ALLOW_TRANSFER,TRANSFER_PROP');
        if($userInfo['ALLOW_TRANSFER']==0){
            return static::notice(Yii::t('app', 'transferDoesNotAllowed'), 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(Yii::t('app', 'invalidParameter'), 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);
    }

    /**
     * 查询可用期数
     * @return mixed
     * @throws HttpException
     */
    public function actionPeriod() {
        $nowTs = time();
        // 当前期
        $currentPeriod = Period::find()->where('START_TIME<:NOW_TIME', ['NOW_TIME' => $nowTs])->where('END_TIME>=:NOW_TIME', ['NOW_TIME' => $nowTs - 6])->asArray()->one();
        $data[] = $currentPeriod['PERIOD_NUM'];
        // 上一期是否封期
        $prevPeriodNum = $currentPeriod['PERIOD_NUM'] - 1;
        $prevPeriod = Period::find()->where('PERIOD_NUM=:PERIOD_NUM AND IS_SENT=0', [':PERIOD_NUM' => $prevPeriodNum])->asArray()->one();
        if ($prevPeriod) {
            $data[] = $prevPeriod['PERIOD_NUM'];
        }

        return static::notice(['data' => $data]);
    }

    function actionSentUserPerformance()
    {
        if (\Yii::$app->request->isPost) {
            $param = \Yii::$app->request->post();
            foreach ($param as $value){
                UserPerformance::sentUserPerformanceApi($value['user_id'], $value['amount'], $value['period']);
            }
            return static::notice(Yii::t('app', 'successfully'));
        } else {
            return static::notice(Yii::t('app', 'illegalRequest'), 400);
        }
    }
}
