<?php

namespace common\components;

use common\services\AdminLogService;
use common\util\ActiveRecordHelper;
use frontend\modules\api\components\BaseAdminController;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;

class BaseAjaxController extends Controller
{
    use ActiveRecordHelper;

    public $enableCsrfValidation = false;

    public function runAction($id, $params = [])
    {
        $params = ArrayHelper::merge(Yii::$app->request->post(), $params);
        if ($this instanceof BaseAdminController) {
            //update
            $url = substr(Yii::$app->controller->getRoute() . "/" . $id, strlen($this->module->id));
            $adminLog = AdminLogService::saveLog($this->userInfo, $url, $params);
            if (in_array($url, AdminLogService::$staffTitle)) {
                if ($adminLog) {
                    $_GET['adminLogId'] = $adminLog->id;
                    $_GET['adminLogModel'] = $adminLog;
                }
            }
        }
        return parent::runAction($id, $params);
    }

    public function asJson($data = [], $r = 0, $msg = "成功")
    {
        if ($r !== 0) {
            $resultData['r'] = 1;
        } else {
            $resultData['r'] = 0;
        }
        if ($msg !== "成功") {
            $resultData['msg'] = $msg;
        } else {
            $resultData['msg'] = "成功";
        }
        $resultData['data'] = $data;
        return parent::asJson($resultData);
    }

    /**
     * 从Get参数里增加检索条件
     */
    public function addJoinConditionToQuery($name, $getName, $notEqual, ActiveQuery $query, $isLike = true)
    {
        if (isset($_GET[$getName]) && $_GET[$getName] != $notEqual) {
            if ($isLike) {
                $query = $query->andWhere(["like", $name, $_GET[$getName]]);
            } else {
                $query = $query->andWhere([$name => $_GET[$getName]]);
            }
        }
        return $query;
    }

    public function addArrayConditionToQuery($name, ActiveQuery $query, $unionArray = [])
    {
        if ($unionArray != []) {
            $query = $query->andWhere([$name => $unionArray]);
        }
        return $query;
    }

    /**
     * @param $name
     * @param ActiveQuery $query
     * @param bool $isLike
     * @return ActiveQuery
     */
    public function addConditionToQuery($name, ActiveQuery $query, bool $isLike = false): ActiveQuery
    {
        $paramsValue = $this->getParams($name);
        if ($paramsValue === null || $paramsValue === "") {
            return $query;
        }
        if ($isLike) {
            $query = $query->andWhere(["like", $name, $paramsValue]);
        } else {
            $query = $query->andWhere([$name => $paramsValue]);
        }
        return $query;
    }

    /**
     * @param $name
     * @param ActiveQuery $query
     * @param bool $isLike
     * @return ActiveQuery
     * @throws InvalidConfigException
     */
    public function addConditionToQueryNew($name, $paramName, ActiveQuery $query, bool $isLike = false): ActiveQuery
    {
        $paramsValue = $this->getParams($paramName);
        if ($paramsValue === null || $paramsValue === "") {
            return $query;
        }
        if ($isLike) {
            $query = $query->andWhere(["like", $name, $paramsValue]);
        } else {
            $query = $query->andWhere([$name => $paramsValue]);
        }
        return $query;
    }

    /**
     * 从Get和Post参数里增加检索条件
     * @param $name
     * @param ActiveQuery $query
     * @param bool $timestamp
     * @param array $values
     * @return ActiveQuery
     * @throws InvalidConfigException
     */
    public function addStartEndConditionToQueryNew($name, $paramName, ActiveQuery $query, bool $timestamp = false, array $values = []): ActiveQuery
    {
        $exist = true;
        $array = [];
        if ($values === []) {
            $values = $this->getParams($paramName);
        }
        if (isset($values[0]) && isset($values[1])) {
            $array = $values;
        } else {
            $exist = false;
        }
        if ($exist) {
            if ($timestamp === true) {
                $array[0] = strtotime($array[0]);
                $array[1] = strtotime($array[1]);//替换掉
            }
            $query = $query->andWhere([">=", $name, $array[0]])->andWhere(["<=", $name, $array[1]]);
        }
        return $query;
    }

    /**
     * 从Get和Post参数里增加检索条件
     * @param $name
     * @param ActiveQuery $query
     * @param bool $timestamp
     * @param array $values
     * @return ActiveQuery
     */
    public function addStartEndConditionToQuery($name, ActiveQuery $query, bool $timestamp = false, array $values = []): ActiveQuery
    {
        $exist = true;
        $array = [];
        if ($values === []) {
            $values = $this->getParams($name);
        }
        if (isset($values[0]) && isset($values[1])) {
            $array = $values;
        } else {
            $exist = false;
        }
        if ($exist) {
            if ($timestamp === true) {
                $array[0] = strtotime($array[0]);
                $array[1] = strtotime($array[1]);//替换掉
            }
            $query = $query->andWhere([">=", $name, $array[0]])->andWhere(["<=", $name, $array[1]]);
        }
        return $query;
    }

    public function log($info)
    {
        Yii::info($info, get_class($this));
    }

    public function returnError($msg, $r = -1)
    {
        return parent::asJson(['r' => $r, 'msg' => $msg, 'data' => []]);
    }

    /**
     * 生成唯一字符串
     * @return string
     */
    function uniqueNum(): string
    {
        return strtoupper(dechex(date('m'))) . date(
                'd'
            ) . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d',
                rand(111, 999)
            );
    }

    /**
     * 从Get参数里增加更新内容(单一)
     */
    public function addUpdateToModel(ActiveRecord $model, $name): void
    {
        $value = $this->getParams($name);
        if ($value && $model->hasAttribute($name)) {
            $model->setAttribute($name, $value);
        }
    }

    /**
     * @return string
     */
    public function getImageBasePath()
    {
        $http = $this->is_ssl() ? 'https://' : 'http://';

        if (YII_ENV_DEV) {
            $host = $_SERVER['HTTP_HOST'];
        } else {
            //案例库存储服务器
            $host = "172.20.41.109:8080";
        }
        return $http . $host;
    }

    /**
     * 判断是否SSL协议
     * @return bool
     */
    public function is_ssl()
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] = "https") {
            return true;
        } else if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
            return true;
        } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
            return true;
        }
        return false;
    }

    /**
     * @param ActiveQuery $query
     * @param string $orderBy
     * @param string $sequenceKey
     * @return void
     */
    public function initSequence(ActiveQuery $query, string $orderBy = "id desc", string $sequenceKey = "sequence"): void
    {
        $sequenceRaw = $this->getParams($sequenceKey);
        if (!$sequenceRaw) {
            $query->orderBy($orderBy);
            return;
        }
        $sequence = is_array($sequenceRaw) ? $sequenceRaw : json_decode($sequenceRaw, true);
        if (!is_null($sequence['prop'])) {
            if (isset($sequence['order']) && $sequence['order'] == 'descending') {
                $sort = 'desc';
            } else {
                $sort = 'asc';
            }
            if ($sequence['prop'] === "start_time" && $sort === "desc") {
                $query->orderBy("start_time desc,id desc");
            } else {
                $query->orderBy("{$sequence['prop']} {$sort}");
            }
        } else {
            if ($orderBy === "start_time desc") {
                $orderBy = "start_time desc,id desc";
            }
            $query->orderBy($orderBy);
        }
    }
}
