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

use common\helpers\bonus\CalcCache;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Email;
use common\helpers\LoggerTool;
use common\helpers\Tool;
use common\helpers\user\Balance;
use common\models\CalcBonusBS;
use common\models\CalcBonusQY;
use common\models\DealType;
use common\models\EmployLevel;
use common\models\Period;
use common\models\Region;
use common\models\User;
use common\models\UserInfo;
use Yii;
use yii\base\Exception;
use yii\db\Expression;

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 actionClearConfigCache() {
        \Yii::$app->cache->delete(Cache::SYSTEM_CONFIG_KEY);
        echo '清空成功: ' . Cache::SYSTEM_CONFIG_KEY . 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);
    }

    /**
     * 自动送钉钉提醒
     */
    public function actionAutoSendDingTalkFrontend() {
        $ip = 'https://ng-frontend-api.elken.com';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $ip . '/v1/site/send-notice');
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($curl);
        if ($res) {
            curl_close($curl);
        } else {
            $error = curl_errno($curl);
            curl_close($curl);
        }
    }

    /**
     * 自动送钉钉提醒
     */
    public function actionAutoSendDingTalkBackend() {
        $ip = 'https://ng-backend-api.elken.com';    // Prod
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $ip . '/v1/site/send-notice');
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $res = curl_exec($curl);
        if ($res) {
            curl_close($curl);
        } else {
            $error = curl_errno($curl);
            curl_close($curl);
        }
    }

    public function actionSendEmail()
    {
        Email::sendRegistrationEmail('18511880790@163.com', 'zhangl', 'test123');
    }

    public function actionOrderInvoiceRemark()
    {
        try {
            $formModel = new \common\models\forms\OrderInvoiceRemarkForm();
            // 设置测试用的订单号
            $formModel->orderSn = 'OS202402015553509710';
            $formModel->invoiceRemark = "这是一个测试发票备注。<span style='color:red;'>这是一个测试发票备注。</span>";

            // 调用remarkOrderInvoice方法
            $result = $formModel->remarkOrderInvoice();

            if ($result) {
                echo "成功：订单发票备注已更新\n";
            } else {
                echo "失败：" . json_encode($formModel->getErrors()) . "\n";
            }
        } catch (Exception $e) {
            echo "异常：" . $e->getMessage() . "\n";
        }
    }

    public function actionUpdatePercent() {
        $percent = 100;
        $periodNum = 134;
        $period = Period::findOneAsArray('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $periodNum]);

        // 把数据写入数据库中
        Period::updateAll(['SENT_PERCENT' => $percent], 'PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $periodNum]);
        \Yii::$app->swooleAsyncTimer->pushAsyncPercentToAdmin($percent, ['MODEL' => 'PERIOD', 'ID' => $period['ID'], 'FIELD' => 'SENT_PERCENT']);
    }

    public function actionUpdateEmpLevel()
    {
        $periodNum = 134;

        $empLv = EmployLevel::getIdConvertLevelSortCache();
        $allData = CalcBonusBS::find()
            ->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM' => $periodNum])
            ->orderBy('CREATED_AT DESC')
            ->limit(10000)
            ->all();

        $defaultEmpLv = EmployLevel::getDefaultLevelId();
        if ($allData) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                foreach ($allData as $data) {
                    // 蓝星奖计算的最新聘级
                    $latestEmpLv = $data['LEVEL_ID'];    // 本期计算最新管理级别
                    $latestEmpLvSort = $empLv[$latestEmpLv]; // 当前蓝星计算的聘级 级别值
                    if ($defaultEmpLv == $latestEmpLv) {
                        continue;
                    }
                    // 用户存储的最高聘级
                    $user = CalcCache::getUserInfo($data['USER_ID'], $periodNum);
                    $highestEmpLv = $user['EMP_LV']; // 用户的历史最高聘级
                    $highestEmpLvSort = $empLv[$highestEmpLv]; // 历史最高聘级的 级别值
                    // 如果当前期的聘级高于用户表的最高聘级,则进行更新
                    if ($latestEmpLvSort > $highestEmpLvSort) {
                        User::updateAll(['EMP_LV' => $latestEmpLv], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);
                        User::deleteBaseInfoFromRedis($data['USER_ID']);

                        LoggerTool::info('sendBonus' . sprintf('actionUpdateEmpLevel-1: %s', json_encode([$latestEmpLv, $data['USER_ID']])));
                    }
                    // 更新最新用户表级别
                    User::updateAll([
                        'LAST_EMP_LV' => $latestEmpLv,
                        'LAST_EMP_LV_UPDATED_AT' => time(),
                        'LAST_EMP_LV_UPDATED_PERIOD' => $periodNum
                    ], 'ID=:USER_ID', [':USER_ID' => $data['USER_ID']]);

                    LoggerTool::info('sendBonus' . sprintf('actionUpdateEmpLevel-2: %s', json_encode([$latestEmpLv, $data['USER_ID']])));

                    User::deleteBaseInfoFromRedis($data['USER_ID']);
                    unset($data);
                }
                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();
                return false;
            }
            unset($transaction, $allData, $defaultEmpLv);
        }

        unset($allData);

        // 刷新会员EmpLv为0
        User::updateAll([
            'LAST_EMP_LV' => '',
            'LAST_EMP_LV_UPDATED_AT' => time(),
            'LAST_EMP_LV_UPDATED_PERIOD' => $periodNum,
        ], 'LAST_EMP_LV_UPDATED_PERIOD < :PERIOD_NUM AND LAST_EMP_LV <> ""', [':PERIOD_NUM' => $periodNum]);

        User::deleteAllBaseInfoFromRedis();
    }

    /**
     * 构建行政区划js文件到cdn,刷新Redis数据
     */
    public function actionRegionBuild()
    {
        // 所有行政区划
        $regions = Region::getAllData();

        $regionData = [];
        foreach ($regions as $region) {
            $regionData[$region['COUNTRY_ID']][] = [$region['REGION_CODE'] => $region['REGION_NAME']];
        }

        // 1.生成js文件
        $ar_region_data = json_encode($regionData,JSON_UNESCAPED_UNICODE);
        $str = (string)$ar_region_data;
        $str = "const AR_REGION_DATA = " . $str;

        file_put_contents(\Yii::$app->params['cdnPath'] . "jsdata/ar_region_data.js", $str);

        // 2.刷新缓存
        Region::updateToCache();
    }
}