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

namespace backendApi\modules\v1\controllers;

use common\helpers\Date;
use common\helpers\Tool;
use common\models\UserInfo;
use common\models\UserSystem;
use \Yii;
use common\components\ActiveRecord;
use common\helpers\Form;
use yii\db\Exception;
use yii\web\HttpException;

class BaseController extends \yii\rest\ActiveController {

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

    /**
     * 校验管理员权限
     * @param $action
     * @return bool|mixed
     * @throws HttpException
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action) {
        $parentBeforeAction = parent::beforeAction($action);
        // 校验用户权限
        if (!Yii::$app->user->validateAdminAction($this->id, $this->action->id)) {
            return self::notice('权限不足', 403);
        }
        return $parentBeforeAction;
    }

    /**
     * 返回结果集
     * @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('必须选择一条删除数据', 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('删除失败');
                }
            } else {
                // 设置IS_DEL字段为1
                $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
            }
            if ($afterFun) $afterFun($selected);
            $transaction->commit();
            return self::notice('删除成功');
        } 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) {
                    $condition .= ' AND (';
                    $chidValueArr = explode('|', $getValue);
                    foreach ($chidValueArr as $k => $value) {
                        if ($k == 0) {
                            $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, '');
                        } else {
                            $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, 'OR');
                        }
                        $condition .= $result['condition'];
                        $params += $result['params'];
                    }
                    $condition .= ')';
                } else {
                    $result = $this->_getConditionAndParams($getValue, $tableField, $bindParam);
                    $condition .= $result['condition'];
                    $params += $result['params'];
                }
            }
        }
        return [
            'condition' => $condition,
            'params' => $params,
            'request' => $allGet,
        ];
    }

    /**
     * 获取条件
     * @param $getValue
     * @param $tableField
     * @param $bindParam
     * @param string $relation
     * @return array
     */
    private function _getConditionAndParams($getValue, $tableField, $bindParam, $relation = 'AND') {
        $condition = '';
        $params = [];
        $isDate = false;
        $filterModel = '';
        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];
                $filterModel = end($getValueArr);
                reset($getValueArr);
                if($filterModel == 'date'){
                    if( $getSymbol !== '>=' && $getSymbol !== '<=' && $getSymbol !== '>' && $getSymbol !== '<' ) {
                        throw new \Exception("日期筛选格式不对");
                    }
                    $bindValue = strtotime($getValueArr[1]);
                    $isDate = true;
                    $relation = $relation ? 'AND' : '';
                }
                elseif($filterModel == 'area'){
                    $bindValue = array_slice($getValueArr, 1, 3);
                }
            }
        } else {
            $getSymbol = '=';
            $bindValue = $getValue;
        }
        if ($getSymbol == 'LIKE') {
            $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')>0';
        } elseif ($getSymbol == strtoupper('notLike')) {
            $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')=0';
        } elseif ($getSymbol == 'IN') {
            $condition .= ' ' . $relation . ' ' . $tableField . ' IN (' . $bindValue . ')';
        } else {
            if ($isDate && $getSymbol == '=') {
                $condition .= ' ' . $relation . ' ' . $tableField . '>=:' . $bindParam . 's';
                $condition .= ' AND ' . $tableField . '<=:' . $bindParam . 'e';
            }
            elseif($filterModel == 'area'){
                if($bindValue[0]){
                    $condition .= ' AND '.$tableField['FIELD'][0].'=:'.$tableField['BIND'][0];
                    if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
                        $condition .= ' AND '.$tableField['FIELD'][1].'=:'.$tableField['BIND'][1];
                        if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
                            $condition .= ' AND '.$tableField['FIELD'][2].'=:'.$tableField['BIND'][2];
                        }
                    }
                }
            }
            else {
                if($getSymbol!=='=' && $relation=='OR'){
                    $relation = 'AND';
                }
                $condition .= ' ' . $relation . ' ' . $tableField . $getSymbol . ':' . $bindParam;
            }
        }
        if ($getSymbol != 'IN') {
            if ($isDate && $getSymbol == '=') {
                $params[':' . $bindParam . 's'] = $bindValue;
                $params[':' . $bindParam . 'e'] = $bindValue + 86399;
            }
            if ($filterModel == 'area') {
                if($bindValue[0]){
                    $params[':'.$tableField['BIND'][0]] = $bindValue[0];
                    if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
                        $params[':'.$tableField['BIND'][1]] = $bindValue[1];
                        if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
                            $params[':'.$tableField['BIND'][2]] = $bindValue[2];
                        }
                    }
                }
            }
            else {
                $params[':' . $bindParam] = $bindValue;
            }
        }
        return ['condition' => $condition, 'params' => $params];
    }

    /**
     * 筛选条件
     * @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,
        ];
    }
}