<?php
/**
 * Created by PhpStorm.
 * User: Leo
 * Date: 2017/9/3
 * Time: 下午3:05
 */

namespace frontendApi\modules\v1\controllers;

use common\components\ActiveRecord;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\LoggerTool;
use common\helpers\Tool;
use \frontendApi\modules\v1\models\brand\User AS Brand;
use frontendApi\modules\v1\models\User;
use Yii;
use yii\db\Exception;
use yii\web\ForbiddenHttpException;
use yii\web\HttpException;

class BaseController extends \yii\rest\ActiveController {

    /**
     * 不让控制器直接选择model类直接返回数据
     * @return array
     */
    public function actions() {
        return [];
    }

    /**
     * @throws ForbiddenHttpException
     */
    protected function forbiddenQuicklyUser() {
        $isQuickly = User::isQuicklyLogin();
        $requestMethod = Yii::$app->request->getMethod();
        if ($isQuickly == 1 && strtoupper($requestMethod) != 'GET') {
            throw new ForbiddenHttpException(Yii::t('app', 'quickLoginCanNotOperate'));
        }
    }

    /**
     * @throws ForbiddenHttpException
     */
    protected function forbiddenQuicklyBaUser() {
        $isQuickly = Brand::isQuicklyLogin();
        $requestMethod = Yii::$app->request->getMethod();
        if ($isQuickly == 1 && strtoupper($requestMethod) != 'GET') {
            throw new ForbiddenHttpException(Yii::t('app', 'quickLoginCanNotOperate'));
        }
    }

    /**
     * @param $action
     * @return bool
     * @throws ForbiddenHttpException
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action) {
        // 动态返回语言：zh:zh-CN | en:en-US
        if (!Yii::$app->request->isOptions) {
            $language = Yii::$app->request->headers->get('language') ?? 'en';
            Yii::$app->language = Tool::langConvert($language);
//            Yii::$app->sourceLanguage = 'en-US';
        }

        if (!\Yii::$app->getUser()->isGuest) {
            $this->forbiddenQuicklyUser();

            // 增加的判断用户登录后未操作后的超时 和 快速登录的逻辑
            $isQuickly = User::isQuicklyLogin();
            if ($isQuickly != 1 && Yii::$app->getUser()->getUserInfo()) {
                $userId = Yii::$app->getUser()->getUserInfo()['id'];
                $redisKey = 'user:timeOut';

                $lastTime = '';
                if (!Yii::$app->tokenRedis->hget($redisKey, $userId)) {
                    $lastTime = time();
                } else {
                    $lastTime = Yii::$app->tokenRedis->hget($redisKey, $userId);
                }

                $currentTime = time();
                $timeOut = Yii::$app->params['operationTimeOut'];
                if ($currentTime - $lastTime > $timeOut) {
                    return self::notice(Yii::t('app', 'notConnection'), 402);
                } else {
                    Yii::$app->tokenRedis->hset($redisKey, $userId, time());
                }
            }
        } else {
            $this->forbiddenQuicklyBaUser();

            // 增加的判断用户登录后未操作后的超时 和 快速登录的逻辑
            $isQuickly = Brand::isQuicklyLogin();
            if ($isQuickly != 1 && \Yii::$app->getUser()->getId()) {
                $userId = Yii::$app->getUser()->getId();
                $redisKey = 'user:timeOut';

                $lastTime = '';
                if (!Yii::$app->tokenRedis->hget($redisKey, $userId)) {
                    $lastTime = time();
                } else {
                    $lastTime = Yii::$app->tokenRedis->hget($redisKey, $userId);
                }

                $currentTime = time();
                $timeOut = Yii::$app->params['operationTimeOut'];
                if ($currentTime - $lastTime > $timeOut) {
                    return self::notice(Yii::t('app', 'notConnection'), 402);
                } else {
                    Yii::$app->tokenRedis->hset($redisKey, $userId, time());
                }
            }
        }

        return parent::beforeAction($action);
    }

    /**
     * 返回结果集
     * @param $dataOrErrorMessage
     * @param int $code
     * @return mixed
     * @throws HttpException
     */
    public static function notice($dataOrErrorMessage, $code = 0) {
        if ($code === 0) {
            return $dataOrErrorMessage;
        } else {
            throw new HttpException($code, $dataOrErrorMessage, $code);
        }
    }

    /**
     * 编辑方法
     * @param $formModelClass
     * @param $successMsg
     * @param string|null $scenario
     * @param array|null $methodAndParam
     * [
     *      'edit',     // form 调用对象的方法名
     *      'param1',   // form 调用对象的方法的第一个参数
     *      'param2',   // form 调用对象的方法的第二个参数
     *      'param3',   // form 调用对象的方法的第三个参数
     * ]
     * @param callable|null $beforeFun
     * @param callable|null $afterFun
     * @return mixed
     * @throws HttpException
     */
    public static function edit($formModelClass, $successMsg, string $scenario = null, array $methodAndParam = null, callable $beforeFun = null, callable $afterFun = null) {
        $id = Yii::$app->request->get('id', 0);
        $formModel = new $formModelClass();
        $formModel->scenario = 'add';
        if ($id) {
            $formModel->scenario = 'edit';
            $formModel->id = $id;
        }
        if ($scenario !== null) {
            $formModel->scenario = $scenario;
        }
        if ($beforeFun) $beforeFun($formModel);
        if ($methodAndParam === null) {
            $method = 'edit';
            $param = [];
        } else {
            $method = $methodAndParam[0];
            $param = $methodAndParam;
            unset($param[0]);
        }
        if ($formModel->load(Yii::$app->request->post(), '') && $result = call_user_func_array([&$formModel, $method], $param)) {
            if ($afterFun) $afterFun($formModel, $result);
            return static::notice($successMsg);
        } else {
            return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 422);
        }
    }

    /**
     * 删除方法
     * @param $modelClass
     * @param callable|null $beforeFun
     * @param callable|null $afterFun
     * @param bool $isDelData
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public static function delete($modelClass, callable $beforeFun = null, callable $afterFun = null, $isDelData = true) {
        $selected = \Yii::$app->request->get('selected');
        if (!$selected) {
            $selected = \Yii::$app->request->post('selected');
        }
        if (!$selected) {
            return self::notice(Yii::t('app', 'selectAtLeastOne'), 500);
        }

        // 是否存在 DONT_DEL 字段
        if (ActiveRecord::isExistsField($modelClass, 'DONT_DEL')) {
            $isDontDelField = true;
        } else {
            $isDontDelField = false;
        }

        if (is_array($selected)) {
            if ($isDontDelField) {
                $condition = ['AND', ['IN', 'ID', $selected], ['<>', 'DONT_DEL', 1]];
            } else {
                $condition = ['AND', ['IN', 'ID', $selected]];
            }
//            $condition = 'ID IN ('.implode(',', $selected).') AND DONT_DEL<>1';
            $params = [];
        } else {
            if ($isDontDelField) {
                $condition = 'ID=:ID AND DONT_DEL<>1';
            } else {
                $condition = 'ID=:ID';
            }
            //$condition = ['AND', ['ID'=>$selected], ['<>', 'DONT_DEL', 1]];
            $params = [':ID' => $selected];
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            if (!is_array($selected)) {
                $selected = [$selected];
            }
            if ($beforeFun) $beforeFun($selected);
            if ($isDelData) {
                // 真实删除数据
                if (!$modelClass::deleteAll($condition, $params)) {
                    throw new Exception(Yii::t('app', 'deleteFailed'));
                }
            } else {
                // 设置IS_DEL字段为1
                $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
            }
            if ($afterFun) $afterFun($selected);
            $transaction->commit();
            return self::notice(Yii::t('app', 'deleteSuccessfully'));
        } catch (Exception $e) {
            $transaction->rollBack();
            return self::notice($e->getMessage(), 500);
        }
    }

    /**
     * 筛选条件
     * @param array $tableParams
     * [
     *      '筛选提交参数名' => '表名.字段名',
     *      'userIds' => 'USER_INFO.USER_ID',
     *      'userName' => 'USER_INFO.USER_NAME',
     * ]
     *
     * get提交的值
     * [
     *      'userIds' => 'in,asdsa,asdsads',
     *      'userName' => 'like,test',
     *      'createdAt' => '>=,2018-11-26,date'
     * ]
     * @return array
     */
    public function filterCondition(array $tableParams = []) {
        $allGet = Yii::$app->request->get();
        $condition = '';
        $params = [];
        foreach ($tableParams as $getParam => $tableField) {
            if (isset($allGet[$getParam]) && $allGet[$getParam]) {
                $getValue = trim($allGet[$getParam], ", \t\n\r\0\x0B");
                $bindParam = strtoupper($getParam);
                if (strpos($getValue, ',') > 0) {
                    $getValueArr = explode(',', $getValue);
                    $getSymbol = strtoupper($getValueArr[0]);
                    if ($getSymbol == 'IN') {
                        $bindValueArr = $getValueArr;
                        unset($bindValueArr[0]);
                        $bindValue = implode("','", $bindValueArr);
                        $bindValue = "'$bindValue'";
                    } else {
                        $bindValue = $getValueArr[1];
                        if (count($getValueArr) == 3) {
                            if ($getValueArr[2] == 'date') {
                                $bindValue = strtotime($bindValue);
                            }
                        }
                    }
                } else {
                    $getSymbol = '=';
                    $bindValue = $getValue;
                }
                if ($getSymbol == 'LIKE') {
                    $condition .= ' AND INSTR(' . $tableField . ',:' . $bindParam . ')>0';
                } elseif ($getSymbol == 'IN') {
                    $condition .= ' AND ' . $tableField . ' IN (' . $bindValue . ')';
                } else {
                    $condition .= ' AND ' . $tableField . $getSymbol . ':' . $bindParam;
                }
                if ($getSymbol != 'IN') {
                    $params[':' . $bindParam] = $bindValue;
                }
            }
        }
        return [
            'condition' => $condition,
            'params' => $params,
            'request' => $allGet,
        ];
    }

    /**
     * 筛选条件
     * @param string $tableName
     * @param array $otherParams
     * [
     *      '筛选提交参数名' => '表名.字段名',
     *      'userName' => 'USER_INFO.USER_NAME',
     * ]
     * 或者
     * [
     *      '筛选提交参数名' => ['表名.字段名', '符号'],
     *      'userName' => ['USER_INFO.USER_NAME', '<'],
     * ]
     * @return array
     */
    public function filterConditionBak($tableName = '', array $otherParams = []) {
        $dateRange = Yii::$app->request->get('dateRange', '');
        $condition = '';
        $params = [];
        if ($tableName) {
            $tableName = $tableName . '.';
        }
        if ($dateRange) {
            $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
            $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
            $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
        }
        $requestParams = [];
        foreach ($otherParams as $getParam => $field) {
            $getValue = Yii::$app->request->get($getParam, '');
            $requestParams[$getParam] = $getValue;
            if ($getValue === 'all') $getValue = '';
            if ($getValue !== '') {
                if (is_string($field)) {
                    $condition .= " AND $field=:" . strtoupper($getParam);
                    $params[':' . strtoupper($getParam)] = $getValue;
                } elseif (is_array($field)) {
                    if (count($field) == 1) {
                        $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
                        $params[':' . strtoupper($getParam)] = $getValue;
                    } elseif (count($field) == 2) {
                        if (strtolower($field[1]) == 'in') {
                            $getValue = Tool::filterSpecialChar($getValue);
                            if ($getValue) {
                                $getValue = explode(',', $getValue);
                                $getValue = implode("','", $getValue);
                                $getValue = "'$getValue'";
                                $condition .= " AND {$field[0]} IN ({$getValue})";
                            }
                        } else {
                            $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
                            $params[':' . strtoupper($getParam)] = $getValue;
                        }
                    }
                }
            }
        }
        // 请求的参数也一并返回
        $request = array_merge([
            'dateRange' => $dateRange,
        ], $requestParams);
        return [
            'condition' => $condition,
            'params' => $params,
            'request' => $request,
        ];
    }

}