<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */
namespace backendApi\modules\v1\controllers;

use backendApi\modules\v1\models\AdminCountry;
use backendApi\modules\v1\models\AdminRole;
use common\helpers\LoggerTool;
use common\helpers\snowflake\PageSnowFake;
use common\helpers\Tool;
use common\models\CurrencyConversions;
use common\models\DealType;
use common\models\Period;
use common\models\RegType;
use common\models\DecRole;
use common\models\OpenBank;
use common\models\UserSystem;
use Yii;
use backendApi\modules\v1\models\User;
use common\helpers\Cache;

class SiteController extends BaseController
{
    public $modelClass = User::class;
    public function behaviors() {
        return parent::behaviors();
    }


    public function actions()
    {
        $actions = parent::actions();
        $actions['captcha'] = [
            'class' => 'common\helpers\CaptchaAction',
            'width' => 120,
            'height' => 40,
            'padding' => 0,
            'minLength' => 4,
            'maxLength' => 4,
            'offset'=>8,        //设置字符偏移量 有效果
            'testLimit'=>1,
        ];

        return $actions;
    }

    /**
     * 请求服务器时间差
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDaysDiff(){
        return static::notice(['daysDiff'=>Yii::$app->params['daysDiff']]);
    }

    /**
     * 请求页面数据
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionPageData() {
        $pageId = PageSnowFake::instance()->generateId();
        return static::notice(['pageId'=>$pageId]);
    }

    public function actionBaseInfo(){
        // 会员级别
        $decLevels = Cache::getDecLevelConfig();
        // 荣衔级别
        $empLevels = Cache::getEmpLevelConfig();
        // Elite级别
        $eliteLevels = Cache::getEliteLevelConfig();
        // 注册类型
        $regTypes = Cache::getRegType();
        // 交易类型
        $dealTypes = Cache::getDealType();
        // 体系
        $systems = [];
        // 菜单
        $menu = require Yii::getAlias('@backendApi/config/menu.php');
        $menu = $this->_childMenu($menu);
        // 管理员角色
        $adminRoles = Cache::getAdminRole();
        // 超级管理员角色ID
        $superAdminRoleId = Yii::$app->params['superAdminRoleId'];
        // 时间差
        $daysDiff = Yii::$app->params['daysDiff'];
        // 钱包
        $shopWalletType = Tool::paramConvert(Yii::$app->params['shopWalletType']);
        // 报单中心角色
        $decRoles = Cache::getDecRoleConfig();
        // 子公司
        $subCompanies = [];
        // 会员状态
        $allStatus = Tool::paramConvert(Yii::$app->params['userStatus']);
        // 全部银行
        $allOpenBank = OpenBank::find()->where('1=1 AND STATUS=1')->select('BANK_NAME,BANK_CODE')->indexBy('BANK_CODE')->asArray()->all();
        // 民族
        $allNation = Yii::$app->params['nation'];
        // 期数
        $period = Period::instance();
        $periodNum = $period->getNowPeriodNum();
        // 汇率
        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
        $isSuperAdmin = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);

        return [
            'decLevels' => $decLevels,
            'empLevels' => $empLevels,
            'eliteLevels' => $eliteLevels,
            'regTypes' => $regTypes,
            'dealTypes' => $dealTypes,
            'systems' => $systems,
            'menu' => $menu,
            'adminRoles' => $adminRoles,
            'superAdminRoleId' => $superAdminRoleId,
            'daysDiff' => $daysDiff,
            'shopWalletType' => $shopWalletType,
            'decRoles' => $decRoles,
            'subCompanies' => $subCompanies,
            'allStatus' => $allStatus,
            'allOpenBank' => $allOpenBank,
            'allNation' => $allNation,
            'nowPeriodNum' => $periodNum,
            'exchangeRate' => $exchangeRate,
            'isSuperAdmin' => $isSuperAdmin,
        ];
    }

    private function _childMenu($parentArray){
        $menuResult = [];
        foreach($parentArray as $key => $parentMenu){
            // 菜单是否显示
            if(isset($parentMenu['show']) && !$parentMenu['show']){
                continue;
            }
            // 查看是否有该控制器的权限
            if(isset($parentMenu['controller']) && $parentMenu['controller']){
                if(!Yii::$app->user->validateAdminController($parentMenu['controller'])) continue;
            }
            // 查看是否有权限
            if(isset($parentMenu['action']) && $parentMenu['action']){
                if(!Yii::$app->user->validateAdminAction($parentMenu['controller'], $parentMenu['action'])) continue;
            }
            // 子菜单同样设置
            if(isset($parentMenu['child']) && !empty($parentMenu['child'])){
                $parentMenu['child'] = $this->_childMenu($parentMenu['child']);
            }
            // 如果在白名单的不显示菜单
            if(isset($parentMenu['controller']) && $parentMenu['controller']){
                if(Yii::$app->user->noCheckAdminController($parentMenu['controller'])) continue;
            }
            $menuResult[] = $parentMenu;
        }
        return $menuResult;
    }

    /**
     * 发送钉钉测试信息
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionSendNotice()
    {
        $data = [
            'code' => 400,
            'message' => 'autoSendDingTalk',
        ];
        return static::notice(['data' => $data['bug监控正常运行，没有发现异常.']]);
    }

    public function actionSendNotify()
    {
        $message = Yii::$app->request->get('message', '收到信息了');
        $data = ['message' => $message];

        return static::notice($data);
    }

    public function actionCountries()
    {
        // 国家
        $countries = Cache::getCountries();

//        $filter = \Yii::$app->request->get('filter', 0);
        $isSuperAdmin = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuperAdmin) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);

            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
            $countries = array_values($countries);
        }

        // 货币
        $currencies = Cache::getCurrencies();
        $currencies = array_column($currencies, NULL, 'ID');
        // 货币汇率
        $currenciesConversions = CurrencyConversions::getFromCache();
        $currenciesConversions = array_column($currenciesConversions, NULL, 'TO_CURRENCY_ID');

        $countries = array_map(function ($country) use ($currencies, $currenciesConversions) {
            return array_merge(
                $country,
                [
                    'LOCAL_CURRENCY_NAME' => $currencies[$country['LOCAL_CURRENCY_ID']]['NAME'] ?? '',
                    'CURRENCY_PRODUCT_RATE' => $currenciesConversions[$country['LOCAL_CURRENCY_ID']]['PRODUCT_RATE'] ?? 0
                ]
            );
        }, $countries);

        return static::notice(['data' => $countries]);
    }

    public function actionLanguages()
    {
        // 语言列表
        $data = Cache::getLanguages();

        return static::notice(['data' => $data]);
    }

    public function actionBanks()
    {
        // 默认国家
        $countryId = \Yii::$app->request->get('countryId');
        if (!$countryId) {
            return static::notice(Yii::t('app', 'countryDoesNotSelect'), 400);
        }

        $data = OpenBank::find()
            ->where('STATUS=:STATUS AND COUNTRY_ID=:COUNTRY_ID', [':STATUS' => 1, ':COUNTRY_ID' => $countryId])
            ->orderBy('BANK_NAME ASC')
            ->asArray()
            ->all();

        return static::notice(['data' => $data]);
    }
}