<?php
/**
 * 测试专用控制器
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/3/9
 * Time: 上午11:56
 */
namespace console\controllers;

use common\helpers\Cache;
use common\helpers\DataBak;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\ocr\OcrApi;
use common\helpers\Tool;
use common\libs\api\sms\SmsApi;
use common\libs\swoole\RPCApi;
use common\models\CalcBonus;
use common\models\CalcBonusFX;
use common\models\CalcBonusQY;
use common\models\CalcBonusYC;
use common\models\FlowBonus;
use common\models\forms\ClearDataForm;
use common\models\forms\DeclarationLoopForm;
use common\models\forms\UserForm;
use common\models\PerfMonth;
use common\models\PerfOrder;
use common\models\PerfPeriod;
use common\models\ReconsumePool;
use common\models\ReconsumePoolFlow;
use common\models\DecOrder;
use common\models\User;
use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;
use yii\base\Exception;
use yii\db\Expression;
use yii\db\Query;

class ToolController extends BaseController
{

    /**
     * 显示系统的当前时间
     */
    public function actionTime(){
        echo(Date::nowTime().PHP_EOL);
    }

    /**
     * 显示系统的当前时间
     * @param null $time
     */
    public function actionDateTime($time = null){
        if($time === null){
            $time = Date::nowTime();
        }
        echo(date('Y-m-d H:i:s', $time).PHP_EOL);
    }

    /**
     * 格式化传入的时间
     * @param $dateTime
     */
    public function actionDateToTime($dateTime){
        echo(strtotime($dateTime).PHP_EOL);
    }

    /**
     * 重新生成表缓存
     * @throws Exception
     * @throws \yii\base\InvalidConfigException
     */
    public function actionTable(){
        $percent = 0;
        $dir = \Yii::getAlias('@common/runtime/tableSchema');
        Tool::clearDir($dir);
        $percent += 10;
        $this->_percentHandle($percent);
        $dbArr = ['db'];
        foreach($dbArr as $key=>$dbName){
            $db = \Yii::$app->get($dbName, false);
            $dbTables = $db->getSchema()->getTableNames();
            $tableCount = count($dbTables);
            foreach($dbTables as $tableName){
                $db->getSchema()->generateTableSchema($tableName);
                $percent += 1/$tableCount * 100;
                $this->_percentHandle($percent);
            }
        }
        $this->_percentHandle($percent, true);
        echo ' 生成表缓存完成'.PHP_EOL;
    }

    /**
     * 生成百分比箭头文字
     * @param $percent
     * @param bool $isDone
     */
    private function _percentHandle($percent, $isDone = false){
        $percent = intval($percent);
        if($percent >= 100) $percent = 100;
        $beforeStr = str_repeat('=', intval($percent/2));
        $afterStr = str_repeat(' ', 50 - intval($percent/2));
        if($percent >= 100){
            $echoString = "\r[=".$beforeStr.$afterStr.'] '.$percent.'%  ';
        } else {
            $echoString = "\r[".$beforeStr.'>'.$afterStr.'] '.$percent.'%  ';
        }
        echo $echoString;
        flush();
        if($percent >= 100 && $isDone){
            echo PHP_EOL;
        }
    }

    /**
     * 清空缓存
     */
    public function actionClearCache() {
        \Yii::$app->tokenRedis->flushdb();
        \Yii::$app->redis->flushdb();
        \Yii::$app->cache->flush();
        echo '清空成功'.PHP_EOL;
    }


    /**
     * 重置接点和推荐数量
     */
    public function actionResetConNum(){
        // 先清空会员表内的所有con_num数据
        UserInfo::updateAll(['CON_NUM'=>0, 'REC_NUM'=>0], '1=1');
        // 循环所有会员，给他的上级数量增加1
        $this->_loopUserAddConNum();
        echo ' 重置接点推荐数量完成'.PHP_EOL;
    }

    /**
     * 循环为上级增加数量
     * @param int $offset
     */
    public function _loopUserAddConNum($offset = 0){
        $userData = UserInfo::find()->select('USER_ID,CON_UID,REC_UID')->where('1=1')->orderBy('CREATED_AT ASC')->offset($offset)->limit(100)->asArray()->all();
        $totalNum = UserInfo::find()->count();
        $startNum = $offset;
        if($userData){
            foreach($userData as $user){
                if($user['CON_UID']){
                    UserInfo::updateAll(['CON_NUM'=>new Expression('CON_NUM+1')], 'USER_ID=:USER_ID', [':USER_ID'=>$user['CON_UID']]);
                }
                if($user['REC_UID']){
                    UserInfo::updateAll(['REC_NUM'=>new Expression('REC_NUM+1')], 'USER_ID=:USER_ID', [':USER_ID'=>$user['REC_UID']]);
                }
                $this->_percentHandle($startNum + 1/$totalNum*100);
            }
            $this->_loopUserAddConNum($offset + 100);
        }
    }

    /**
     * 清网络缓存
     */
    public function actionClearNet(){
        \Yii::$app->redis->del(Cache::USER_NETWORK_PARENTS);
        \Yii::$app->redis->del(Cache::USER_RELATION_PARENTS);
    }

}