<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */

namespace backendApi\modules\v1\controllers;

use backendApi\modules\v1\components\UserAuth;
use backendApi\modules\v1\models\Admin;
use backendApi\modules\v1\models\AdminCountry;
use backendApi\modules\v1\models\AdminRole;
use backendApi\modules\v1\models\exportForms\BaUserExportForm;
use backendApi\modules\v1\models\exportForms\UserExportForm;
use backendApi\modules\v1\models\lists\shop\BaUserList;
use backendApi\modules\v1\models\lists\user\BindList;
use backendApi\modules\v1\models\lists\user\ChangeHighestEmpLevelList;
use backendApi\modules\v1\models\lists\user\DecLevelList;
use backendApi\modules\v1\models\lists\user\GroupList;
use backendApi\modules\v1\models\lists\user\IndexList;
use backendApi\modules\v1\models\lists\user\MoveList;
use backendApi\modules\v1\models\lists\user\StatusAuditList;
use backendApi\modules\v1\models\lists\user\SystemList;
use backendApi\modules\v1\models\lists\user\TeamworkList;
use backendApi\modules\v1\models\lists\user\YearHighestEmpLvList;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\http\BackendToFrontendApi;
use common\helpers\Log;
use common\helpers\LoggerTool;
use common\helpers\NetPoint;
use common\helpers\Tool;
use common\helpers\user\Balance;
use common\helpers\user\Cash;
use common\helpers\user\Info;
use common\helpers\user\Status;
use common\models\BaUser;
use common\models\CompanyBank;
use common\models\Countries;
use common\models\CurrencyConversions;
use common\models\FlowBonus;
use common\models\forms\AdminAddUserForm;
use common\models\forms\BaUserBasicForm;
use common\models\forms\ChangeShowEmpLvForm;
use common\models\forms\CloseDecForm;
use common\models\forms\CloseLoginForm;
use common\models\forms\DecLevelLogForm;
use common\models\forms\DecRoleLogForm;
use common\models\forms\HighestEmpLevelLogForm;
use common\models\forms\ImmigrantForm;
use common\models\forms\NetMoveForm;
use common\models\forms\RechargeForm;
use common\models\forms\ReconsumeForm;
use common\models\forms\RegInfoAuditForm;
use common\models\forms\UploadForm;
use common\models\forms\UserBasicForm;
use common\models\forms\UserBindForm;
use common\models\forms\UserCloseForm;
use common\models\forms\UserDecForm;
use common\models\forms\UserForm;
use common\models\forms\UserGroupForm;
use common\models\forms\UserStatusForm;
use common\models\forms\UserSystemForm;
use common\models\forms\UserTeamworkForm;
use common\models\forms\UserTransferPropForm;
use common\models\Instalment;
use common\models\Language;
use common\models\Period;
use common\models\ReconsumeAudit;
use common\models\ReconsumePool;
use common\models\RegInfoAudit;
use common\models\Region;
use common\models\RegType;
use common\models\DecOrder;
use common\models\DecRole;
use common\models\EmployLevel;
use common\models\OpenBank;
use common\models\UserBind;
use common\models\UserClose;
use common\models\UserImmigrant;
use common\models\UserMove;
use common\models\UserNetwork;
use common\models\UserRelation;
use common\models\UserStatusAudit;
use common\models\UserSystem;
use common\models\YearHighestEmpLv;
use SebastianBergmann\CodeCoverage\Report\PHP;
use sunmoon\phpspreadsheet\Excel;
use Yii;
use common\helpers\Cache;
use common\models\User;
use common\models\UserInfo;
use common\models\UserTeamwork;
use yii\base\Exception;
use yii\web\HttpException;
use yii\web\UploadedFile;

class UserController extends BaseController
{
    public $modelClass = User::class;

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        //$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    /**
     * 会员列表
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionIndex()
    {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'STATUS' => 'U.STATUS',
            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
            'CREATED_AT' => 'U.CREATED_AT',
            'PERIOD_AT' => 'U.PERIOD_AT',
            'DEC_LV_NAME' => 'U.DEC_LV',
            'COUNTRY' => 'U.COUNTRY_ID',
            'DEC_LV_UPDATED_AT' => 'U.DEC_LV_UPDATED_AT',
            'LAST_DEC_LV_NAME' => 'U.LAST_DEC_LV',
            'EMP_LV_NAME' => 'U.EMP_LV',
            'LAST_EMP_LV_NAME' => 'U.LAST_EMP_LV',
            'ELITE_LV_NAME' => 'U.ELITE_LV',
            'LAST_ELITE_LV_NAME' => 'U.LAST_ELITE_LV',
            'REC_USER_NAME' => 'RU.USER_NAME',
            'CON_USER_NAME' => 'CU.USER_NAME',
            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
            'MOBILE' => 'U.MOBILE',
            'TEL' => 'U.TEL',
            'DEC_USER_NAME' => 'DU.USER_NAME',
            'IS_DEC' => 'U.IS_DEC',
            'IS_STUDIO' => 'U.IS_STUDIO',
            'DEC_ROLE_NAME' => 'U.DEC_ROLE_ID',
            'AREA' => [
                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
            'ADDRESS' => 'U.ADDRESS',
        ]);

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);
            $quotedAdminCountry = array_map(function($item) {
                return "'" . addslashes($item) . "'";
            }, $adminCountry);

            $condition = $filter['condition'] ?? '';
            $filter['condition'] = $condition . " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";

            $condition = $filter['condition'];
            $params = $filter['params'];
            $condition .= " AND U.DELETED=0 AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        } else {
            $condition = $filter['condition'] . ' AND U.DELETED=0' ?? ' AND U.DELETED=0';
            $params = $filter['params'];
        }

        $listObj = new IndexList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 导出会员列表
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionIndexExport()
    {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'STATUS' => 'U.STATUS',
            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
            'CREATED_AT' => 'U.CREATED_AT',
            'PERIOD_AT' => 'U.PERIOD_AT',
            'DEC_LV_NAME' => 'U.DEC_LV',
            'DEC_LV_UPDATED_AT' => 'U.DEC_LV_UPDATED_AT',
            'LAST_DEC_LV_NAME' => 'U.LAST_DEC_LV',
            'EMP_LV_NAME' => 'U.EMP_LV',
            'REC_USER_NAME' => 'RU.USER_NAME',
            'CON_USER_NAME' => 'CU.USER_NAME',
            'ID_CARD' => 'U.ID_CARD',
            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
            'SPOUSE_IDCARD' => 'U.SPOUSE_IDCARD',
            'SYSTEM_NAME' => 'U.SYSTEM_ID',
            'MOBILE' => 'U.MOBILE',
            'TEL' => 'U.TEL',
            'DEC_USER_NAME' => 'DU.USER_NAME',
            'IS_DEC' => 'U.IS_DEC',
            'IS_STUDIO' => 'U.IS_STUDIO',
            'DEC_ROLE_NAME' => 'U.DEC_ROLE_ID',
            'OPEN_BANK_NAME' => 'U.OPEN_BANK',
            'BANK_AREA' => [
                'FIELD' => ['U.BANK_PROVINCE', 'U.BANK_CITY', 'U.BANK_COUNTY'],
                'BIND' => ['BANK_PROVINCE', 'BANK_CITY', 'BANK_COUNTY'],
            ],
            'BANK_ADDRESS' => 'U.BANK_ADDRESS',
            'BANK_NO' => 'U.BANK_NO',
            'SEX' => 'U.SEX',
            'NATION_NAME' => 'U.NATION',
            'AREA' => [
                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
            'ADDRESS' => 'U.ADDRESS',
            'VERIFIED' => 'U.VERIFIED',
            'VERIFIED_AT' => 'U.VERIFIED_AT',
            'ALLOW_TRANSFER' => 'UI.ALLOW_TRANSFER',
        ]);

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);
            $quotedAdminCountry = array_map(function($item) {
                return "'" . addslashes($item) . "'";
            }, $adminCountry);

            $condition = $filter['condition'] ?? '';
            $filter['condition'] = $condition . " AND U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        } else {
            $condition = $filter['condition'] ?? '';
            $filter['condition'] = $condition;
        }

        $form = new UserExportForm();
        $result = $form->run($filter, 'Member_List');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 空单会员列表
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionEmptyList()
    {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'STATUS' => 'U.STATUS',
            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
            'CREATED_AT' => 'U.CREATED_AT',
            'PERIOD_AT' => 'U.PERIOD_AT',
            'DEC_LV_NAME' => 'U.DEC_LV',
            'DEC_LV_UPDATED_AT' => 'U.DEC_LV_UPDATED_AT',
            'LAST_DEC_LV_NAME' => 'U.LAST_DEC_LV',
            'EMP_LV_NAME' => 'U.EMP_LV',
//            'HIGHEST_EMP_LV_NAME' => 'UI.HIGHEST_EMP_LV',
//            'HIGHEST_EMP_LV_PERIOD' => 'UI.HIGHEST_EMP_LV_PERIOD',
            'REC_USER_NAME' => 'RU.USER_NAME',
            'CON_USER_NAME' => 'CU.USER_NAME',
            'ID_CARD' => 'U.ID_CARD',
            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
            'SPOUSE_IDCARD' => 'U.SPOUSE_IDCARD',
            'SYSTEM_NAME' => 'U.SYSTEM_ID',
            'MOBILE' => 'U.MOBILE',
            'TEL' => 'U.TEL',
            'DEC_USER_NAME' => 'DU.USER_NAME',
            'IS_DEC' => 'U.IS_DEC',
            'DEC_ROLE_NAME' => 'U.DEC_ROLE_ID',
            'OPEN_BANK_NAME' => 'U.OPEN_BANK',
            'BANK_AREA' => [
                'FIELD' => ['U.BANK_PROVINCE', 'U.BANK_CITY', 'U.BANK_COUNTY'],
                'BIND' => ['BANK_PROVINCE', 'BANK_CITY', 'BANK_COUNTY'],
            ],
            'BANK_ADDRESS' => 'U.BANK_ADDRESS',
            'BANK_NO' => 'U.BANK_NO',
            'SEX' => 'U.SEX',
            'NATION_NAME' => 'U.NATION',
            'AREA' => [
                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
            'ADDRESS' => 'U.ADDRESS',
//            'IS_AUTO_WITHDRAW' => 'UI.IS_AUTO_WITHDRAW',
            'VERIFIED' => 'U.VERIFIED',
            'VERIFIED_AT' => 'U.VERIFIED_AT',
//            'IS_DIRECT_SELLER' => 'U.IS_DIRECT_SELLER',
//            'IS_SYSTEM_LEADER' => 'UI.IS_SYSTEM_LEADER',
//            'IS_GROUP_LEADER' => 'UI.IS_GROUP_LEADER',
            'ALLOW_TRANSFER' => 'UI.ALLOW_TRANSFER',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $condition .= ' AND UI.DELETED=0 AND U.REG_FROM=0';
        $listObj = new IndexList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 点位绑定
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionBind()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'MAIN_USER_NAME' => 'MUI.USER_NAME',
            'HIGHEST_EMP_LV' => 'UI.HIGHEST_EMP_LV',
            'CREATED_AT' => 'UB.CREATED_AT',
            'UPDATED_AT' => 'UB.UPDATED_AT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $condition .= ' AND UB.IS_DEL=0';
        $listObj = new BindList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 点位绑定导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionBindExport()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'MAIN_USER_NAME' => 'MUI.USER_NAME',
            'HIGHEST_EMP_LV' => 'UI.HIGHEST_EMP_LV',
            'CREATED_AT' => 'UB.CREATED_AT',
            'UPDATED_AT' => 'UB.UPDATED_AT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
        ]);
        $filter['condition'] .= ' AND UB.IS_DEL=0';
        $form = new UserExportForm();
        $result = $form->run($filter, '点位绑定');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 添加点位绑定
     * @return mixed
     * @throws HttpException
     */
    public function actionBindAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserBindForm::class, Yii::t('ctx', 'successfully'), 'add', ['add'], null, function ($form, $result) {
                // Log::adminHandle('为' . $form->userName . '添加点位绑定，主点位：' . $form->mainUserName);
            });
        }
    }

    /**
     * 编辑点位绑定
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionBindEdit()
    {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return parent::edit(UserBindForm::class, Yii::t('ctx', 'successfully'), 'edit', ['edit'], null, function ($form, $result) {
                //$userBaseInfo = Info::baseInfo($result->USER_ID);
                // Log::adminHandle('为' . $userBaseInfo['USER_NAME'] . '更改点位绑定关系');
            });
        }
        // 获得当前会员的用户名等信息
        $userBind = UserBind::findOneAsArray('ID=:ID AND IS_DEL=0', [':ID' => $id]);
        $userBinds = UserBind::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userBind['MAIN_UID']]);
        foreach ($userBinds as $key => $value) {
            $userBinds[$key]['BASE_INFO'] = Info::baseInfoZh($value['USER_ID']);
        }
        return static::notice(['userBinds' => $userBinds, 'mainUid' => $userBind['MAIN_UID']]);
    }

    /**
     * 删除点位绑定
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionBindDelete()
    {
        $userBindForm = new UserBindForm();
        $result = static::delete(UserBind::class, function ($selected) use ($userBindForm) {
            $userBindForm->beforeDelete($selected);
        }, function ($selected) use ($userBindForm) {
            $userBindForm->delete($selected);
        }, false);
        return self::notice(Yii::t('ctx', 'successfully'));
    }

    /**
     * 生成点位合作的用户名
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws HttpException
     */
    public function actionGenerateUserName()
    {
        // 获取用户名
        if (!$userName = Info::generateUserName('hz')) {
            return static::notice(Yii::t('ctx', 'failed'), 400);
        }
        return static::notice(['userName' => $userName]);
    }

    /**
     * 点位合作
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionTeamwork()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'MAIN_USER_NAME' => 'MUI.USER_NAME',
            'DIVIDE_PERCENT' => 'UT.DIVIDE_PERCENT',
            'CREATE_REMARK' => 'UT.CREATE_REMARK',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'CREATED_AT' => 'UT.CREATED_AT',
            'PERIOD_NUM' => 'UT.PERIOD_NUM',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            'UPDATED_AT' => 'UT.UPDATED_AT',
            'UPDATED_PERIOD' => 'UT.PERIOD_NUM',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $condition .= ' AND UT.IS_DEL=0';
        $listObj = new TeamworkList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 点位合作导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionTeamworkExport()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'MAIN_USER_NAME' => 'MUI.USER_NAME',
            'DIVIDE_PERCENT' => 'UT.DIVIDE_PERCENT',
            'CREATE_REMARK' => 'UT.CREATE_REMARK',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'CREATED_AT' => 'UT.CREATED_AT',
            'PERIOD_NUM' => 'UT.PERIOD_NUM',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            'UPDATED_AT' => 'UT.UPDATED_AT',
            'UPDATED_PERIOD' => 'UT.PERIOD_NUM',
        ]);
        $filter['condition'] .= ' AND UT.IS_DEL=0';
        $form = new UserExportForm();
        $result = $form->run($filter, '点位合作');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 添加点位合作
     * @return mixed
     * @throws HttpException
     */
    public function actionTeamworkAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserTeamworkForm::class, Yii::t('ctx', 'successfully'), 'add', ['add'], null, function ($form, $result) {
                // Log::adminHandle('为' . $form->mainUserName . '添加合作点位，姓名：' . $form->userName, 0, $result->USER_ID, $form->userName);
            });
        }
        // 所有民族
        $allNation = Yii::$app->params['nation'];
        // 所有开户行
        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
        return static::notice(['allNation' => $allNation, 'allOpenBank' => $allOpenBank]);
    }

    /**
     * 编辑点位合作
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionTeamworkEdit()
    {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return parent::edit(UserTeamworkForm::class, Yii::t('ctx', 'successfully'), 'changeDivide', ['changeDivide'], null, function ($form, $result) {
                foreach ($result['logs'] as $k => $value) {
                    $userName = Info::getUserNameByUserId($k);
                    // Log::adminHandle('为' . $userName . '编辑合作点位分成比例为' . $value , 1, $k, $userName);
                }
            });
        }
        // 获得当前会员的用户名等信息
        if (!$userTeamwork = UserTeamwork::findOneAsArray('ID=:ID AND IS_DEL=0', [':ID' => $id], 'MAIN_UID')) {
            return static::notice('点位合作不存在', 404);
        }
        $teamwork = UserTeamwork::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userTeamwork['MAIN_UID']], 'ID,USER_ID,MAIN_UID,DIVIDE_PERCENT');
        foreach ($teamwork as $key => $value) {
            $userInfo = Info::baseInfo($value['USER_ID']);
            $teamwork[$key]['USER_NAME'] = $userInfo['USER_NAME'];
            $teamwork[$key]['REAL_NAME'] = $userInfo['REAL_NAME'];
        }
        unset($userInfo);
        return static::notice($teamwork);
    }

    /**
     * 删除方法
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionTeamworkDelete()
    {
        return static::notice('无法删除', 400);
        $result = static::delete(UserTeamwork::class, null, function ($selected) {
            UserTeamworkForm::delete($selected);
            // Log::adminHandle('删除合作点位');
        }, false);
        return $result;
    }

    /**
     * 会员体系
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionSystem()
    {
        $filter = $this->filterCondition([
            'userIds' => 'US.LEADER_UID',
            'SYSTEM_NAME' => 'US.SYSTEM_NAME',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'PERIOD_NUM' => 'US.PERIOD_NUM',
            'CREATED_AT' => 'US.CREATED_AT',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            'UPDATE_PERIOD_NUM' => 'US.UPDATE_PERIOD_NUM',
            'UPDATED_AT' => 'US.UPDATED_AT',
            'IS_DEL' => 'US.IS_DEL',
            'CREATE_REMARK' => 'US.CREATE_REMARK',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new SystemList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 体系管理导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionSystemExport()
    {
        $filter = $this->filterCondition([
            'userIds' => 'US.LEADER_UID',
            'SYSTEM_NAME' => 'US.SYSTEM_NAME',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'PERIOD_NUM' => 'US.PERIOD_NUM',
            'CREATED_AT' => 'US.CREATED_AT',
            'UPDATE_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            'UPDATE_PERIOD_NUM' => 'US.UPDATE_PERIOD_NUM',
            'UPDATED_AT' => 'US.UPDATED_AT',
            'IS_DEL' => 'US.IS_DEL',
            'CREATE_REMARK' => 'US.CREATE_REMARK',
        ]);
        $form = new UserExportForm();
        $result = $form->run($filter, '体系管理');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 添加体系
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     * @throws \yii\httpclient\Exception
     * @throws HttpException
     */
    public function actionSystemAdd()
    {
        if (Yii::$app->request->post()) {
            $formModel = new UserSystemForm();
            $formModel->scenario = 'add';
            if ($formModel->load(Yii::$app->request->post(), '') && $formModel->edit()) {
                // Log::adminHandle('添加体系' . Yii::$app->request->post('systemName'));
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 编辑体系
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\httpclient\Exception
     * @throws HttpException
     */
    public function actionSystemEdit()
    {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return parent::edit(UserSystemForm::class, Yii::t('ctx', 'successfully'), 'edit', ['edit'], null, function ($form, $result) {
                // Log::adminHandle('编辑体系' . $result['SYSTEM_NAME']);
            });
        }
        if (!$oneData = UserSystem::find()->select('US.*, UI.USER_NAME AS LEADER_NAME')->where('US.ID=:ID AND US.IS_DEL=0', [':ID' => $id])->from(UserSystem::tableName() . ' AS US')->join('LEFT JOIN', UserInfo::tableName() . ' AS UI', 'US.LEADER_UID=UI.USER_ID')->asArray()->one()) {
            return static::notice('体系已撤销或不存在', 400);
        }
        return static::notice(['oneData' => $oneData]);
    }

    /**
     * 恢复体系
     * @return mixed
     * @throws HttpException
     */
    public function actionSystemRenew()
    {
        return parent::edit(UserSystemForm::class, Yii::t('ctx', 'successfully'), 'renewSystem', [
            'renewSystem',
        ], null, function ($form, $result) {
            // Log::adminHandle('编辑体系' . $result['SYSTEM_NAME']);
        });
    }

    /**
     * 删除方法
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionSystemDelete()
    {
        $userSystemForm = new UserSystemForm();
        $result = static::delete(UserSystem::class, function ($selected) use ($userSystemForm) {
            $userSystemForm->beforeDelete($selected);
        }, function ($selected) use ($userSystemForm) {
            $userSystemForm->delete($selected);
        }, false);
        return self::notice(Yii::t('ctx', 'successfully'));
    }

    /**
     * 团队领导人列表
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionGroup()
    {
        $filter = $this->filterCondition([
            'userName' => 'UI.USER_NAME',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $condition .= ' AND PUI.IS_GROUP_LEADER=1';
        $listObj = new GroupList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 团队领导人列表导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionGroupExport()
    {
        $filter = $this->filterCondition([
            'userName' => 'UI.USER_NAME',
        ]);
        $filter['condition'] .= ' AND PUI.IS_GROUP_LEADER=1';
        $form = new UserExportForm();
        $result = $form->run($filter, '团队领导人列表');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 会员移网记录
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionMove()
    {
        $filter = $this->filterCondition([
            'filterStatus' => 'UM.AUDIT_STATUS',
            'MOVE_USER_NAME' => 'CU.USER_NAME',
            'MOVE_REAL_NAME' => 'CU.REAL_NAME',
            'MOVE_PERCENT_SHOW' => 'UM.MOVE_PERCENT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'PERIOD_NUM' => 'UM.PERIOD_NUM',
            'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            'MOVE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'AUDITED_AT' => 'UM.AUDITED_AT',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);
            $quotedAdminCountry = array_map(function($item) {
                return "'" . addslashes($item) . "'";
            }, $adminCountry);

            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

        $listObj = new MoveList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 移网管理导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionMoveExport()
    {
        $filter = $this->filterCondition([
            //'userIds' => 'UM.USER_ID',
            'filterStatus' => 'UM.AUDIT_STATUS',
            'moveType' => 'UM.TYPE',
            'FROM_USER_NAME' => 'FUI.USER_NAME',
            'TO_USER_NAME' => 'TUI.USER_NAME',
            //'MOVE_PERCENT_SHOW' => 'UM.MOVE_PERCENT',
            //'STARTED_AT' => 'UM.STARTED_AT',
            //'ENDED_AT' => 'UM.ENDED_AT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'PERIOD_NUM' => 'UM.PERIOD_NUM',
            'CREATED_AT' => 'UM.CREATED_AT',
            'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            //'AUDIT_PERIOD_NUM' => 'UM.AUDIT_PERIOD_NUM',
            'AUDITED_AT' => 'UM.AUDITED_AT',
            //'CREATE_REMARK' => 'UM.CREATE_REMARK',
        ]);
        $form = new UserExportForm();
        $result = $form->run($filter, 'Move_Network'); // 移网管理
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 申请移网
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\httpclient\Exception
     * @throws HttpException
     */
    public function actionMoveAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(NetMoveForm::class, Yii::t('ctx', 'successfully'), 'add', ['add'], null, function ($form, $result) {   // 移网申请成功
//                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('申请为' . $user['USER_NAME'] . '移网', 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
    }

    /**
     * 获取全部移网类型
     * @return mixed
     * @throws HttpException
     */
    public function actionMoveNetType()
    {
        return static::notice(['netType' => UserMove::getNetWork()]);
    }

    /**
     * 获取移网数据
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionMoveGet()
    {
        $id = Yii::$app->request->get('id');
        $userMove = UserMove::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        if (!$userMove) {
            return static::notice('Data not exists', 400);
        }
        $userMove['BASE_INFO'] = Info::baseInfoWithNet($userMove['USER_ID']);
        $toUserInfo = Info::baseInfoZh($userMove['TO_UID']);
        return static::notice(['moveId' => $userMove['ID'], 'moveUserName' => $userMove['BASE_INFO']['USER_NAME'], 'baseInfo' => $userMove['BASE_INFO'], 'type' => $userMove['TYPE'], 'toConUserName' => $toUserInfo['USER_NAME'], 'toConRealName' => $toUserInfo['REAL_NAME'], 'location' => $userMove['LOCATION'], 'remark' => $userMove['CREATE_REMARK']]);
    }

    /**
     * 修改移网数据
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionMoveEdit()
    {
        $formModel = new NetMoveForm();
        $formModel->scenario = 'edit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->edit()) {
            $user = Info::baseInfoZh($result['USER_ID']);
            // Log::adminHandle('修改' . $user['USER_NAME'] . '移网录入数据', 1, $result['USER_ID'], $user['USER_NAME']);
            return static::notice(Yii::t('ctx', 'successfully')); // 修改移网录入数据完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 审核通过移网数据(实际的移网动作在这里，异步操作)
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionMovePass()
    {
        $formModel = new NetMoveForm();
        $formModel->scenario = 'pass';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->pass()) {
            $user = Info::baseInfoZh($result['USER_ID']);
            // Log::adminHandle('审核通过移网数据', 1, $result['USER_ID'], $user['USER_NAME']);
            return static::notice("It's on the move. Please wait"); // 正在移动中，请稍候
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 审核移网数据
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     * @throws \yii\httpclient\Exception
     * @throws HttpException
     */
    public function actionMoveAudit()
    {
        $formModel = new NetMoveForm();
        $formModel->scenario = 'changeAudit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->changeAudit()) {
            // Log::adminHandle('审核移网数据');
            return static::notice(Yii::t('ctx', 'successfully')); // 审核移网数据完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 删除移网数据
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionMoveDelete()
    {
        $netMoveForm = new NetMoveForm();
        $result = static::delete(UserMove::class, function ($selected) use ($netMoveForm) {
            $netMoveForm->beforeDelete($selected);
        }, function ($selected) use ($netMoveForm) {
            $netMoveForm->delete($selected);
        }, true);
        return $result;
    }

    /**
     * 会员的基础用户信息
     * @return mixed
     * @throws HttpException
     */
    public function actionFullInfo()
    {
        $userName = Yii::$app->request->get('userName');
        $userInfo = Info::getBaseUserByUserName($userName);

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);

            if (!in_array($userInfo['COUNTRY_ID'], $adminCountry)) {
                return static::notice('Member number does not exist', 400);
            }
        }

        if($userInfo){
            $decLevelConfig = Cache::getDecLevelConfig();
            $userInfo['LEVEL_NAME'] = isset($decLevelConfig[$userInfo['DEC_LV']])?$decLevelConfig[$userInfo['DEC_LV']]['LEVEL_NAME'] : '';
            $userInfo['BONUS'] = Balance::getAvailableBalance($userInfo['ID']);
            $userInfo['CASH'] = Cash::getAvailableBalance($userInfo['ID']);
            $userInfo['RECONSUME_POINTS'] = Balance::getBalanceReconsumePoints($userInfo['ID']);
            $userInfo['EXCHANGE_POINTS'] = Balance::getBalanceExchangePoints($userInfo['ID']);
            $userInfo['country'] = Countries::getNameById($userInfo['COUNTRY_ID']);
            $userInfo['countryCode'] = Countries::getCodeById($userInfo['COUNTRY_ID']);

            return static::notice($userInfo);
        }else{
            return static::notice('Member number does not exist', 400);//会员编号不存在
        }
    }

    /**
     * 会员的基本信息编号名称
     * @return mixed
     * @throws HttpException
     */
    public function actionBaseInfo()
    {
        $userName = Yii::$app->request->get('userName');
        $baseUser = Info::getBaseUserByUserName($userName);
        return static::notice($baseUser);
    }

    /**
     * 点位合作主点位分成比例
     * @return mixed
     * @throws HttpException
     */
    public function actionMainDivide()
    {
        $userId = Yii::$app->request->get('userId');
        $divide = 100;
        if ($teamwork = UserTeamwork::findOneAsArray('USER_ID=:USER_ID AND MAIN_UID=:USER_ID AND IS_DEL=0', [':USER_ID' => $userId], 'DIVIDE_PERCENT')) {
            $divide = $teamwork['DIVIDE_PERCENT'];
        }
        return static::notice($divide);
    }

    /**
     * 获取子公司
     * @return mixed
     * @throws HttpException
     */
    public function actionGetSubCom()
    {
        $areaSelected = Yii::$app->request->get('areaSelected');
        $location = [];
        return static::notice($location);
    }

    /**
     * 判断是否在同一推荐网络
     * @return mixed
     * @throws HttpException
     */
    public function actionChkRelation()
    {
        $userName = Yii::$app->request->get('userName');
        $toUserName = Yii::$app->request->get('toUserName');
        $userId = Info::getUserIdByUserName($userName);
        $toUserId = Info::getUserIdByUserName($toUserName);
        $is = 0;
        if (UserRelation::isParentUser($userId, $toUserId)) {
            $is = 1;
        }
        $toUser = Info::baseInfoWithNetAndBalance($toUserId);
        $real_name = $toUser ? $toUser['REAL_NAME'] : '';
        return static::notice(['is' => $is, 'real_name' => $real_name]);
    }

    /**
     * 获取当前期数
     * @return mixed
     * @throws HttpException
     */
    public function actionGetPeriodNum()
    {
        $period = Period::instance();
        $periodNum = $period->getNowPeriodNum();
        //上期是否挂网
        $lastPeriodNum = $periodNum - 1;
        $periodArr = [$periodNum];
        if ($period->isSent($lastPeriodNum)) {
            $periodArr[] = $periodNum + 1;
        } else {
            $periodArr[] = $lastPeriodNum;
        }
        return static::notice($periodArr);
    }

    /**
     * 关停列表
     * @return mixed
     * @throws HttpException
     */
//    public function actionClose()
//    {
//        $filter = $this->filterCondition([
//            'userIds' => 'UC.USER_ID',
//            'filterStatus' => 'UC.AUDIT_STATUS',
//        ]);
//        $condition = $filter['condition'];
//        $params = $filter['params'];
//        $data = UserClose::lists($condition, $params, [
//            'from' => UserClose::tableName() . ' AS UC',
//            'orderBy' => 'UC.CREATED_AT DESC',
//        ]);
//        // 获取全部移网类型
//        $data['type'] = [
//            UserClose::TYPE_GT => '关停',
//            UserClose::TYPE_TF => '停发',
//        ];
//        $auditStatus = array_column(\Yii::$app->params['auditStatus'], null, 'value');
//        foreach ($data['list'] as $key => $value) {
//            $data['list'][$key]['BASE_INFO'] = Info::baseInfoZh($value['USER_ID']);
//            $data['list'][$key]['CREATE_ADMIN_NAME'] = Admin::getAdminNameById($value['ADMIN_ID']);
//            $data['list'][$key]['AUDIT_ADMIN_NAME'] = Admin::getAdminNameById($value['AUDIT_ADMIN_ID']);
//            $data['list'][$key]['STATUS_NAME'] = $auditStatus[$value['AUDIT_STATUS']]['label'];
//        }
//        return static::notice($data);
//
//    }

    /**
     * 申请关停或停发
     * @return mixed
     * @throws HttpException
     */
//    public function actionCloseAdd()
//    {
//        if (Yii::$app->request->isPost) {
//            return parent::edit(UserCloseForm::class, '申请成功', null, null, null, function ($form, $result) {
//                $user = User::getBaseInfoFromRedis($result['USER_ID']);
//                $type = '';
//                switch ($result['TYPE']) {
//                    case UserClose::TYPE_GT:
//                        $type = '关停';
//                        break;
//                    case UserClose::TYPE_TF:
//                        $type = '停发';
//                        break;
//                }
//                // Log::adminHandle('申请' . $user['USER_NAME'] . $type, 1, $result['USER_ID'], $user['USER_NAME']);
//            });
//        }
//        // 获取全部移网类型
//        $type = [
//            UserClose::TYPE_GT => '关停',
//            UserClose::TYPE_TF => '停发',
//        ];
//        return static::notice(['type' => $type]);
//    }

    /**
     * 审核关停或停发
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
//    public function actionCloseAudit()
//    {
//        $formModel = new UserCloseForm();
//        $formModel->scenario = 'audit';
//        if ($formModel->load(Yii::$app->request->get(), '') && $result = $formModel->audit()) {
//            $user = User::getBaseInfoFromRedis($result['USER_ID']);
//            $type = '';
//            switch ($result['TYPE']) {
//                case UserClose::TYPE_GT:
//                    $type = '关停';
//                    break;
//                case UserClose::TYPE_TF:
//                    $type = '停发';
//                    break;
//            }
//            // Log::adminHandle('审核' . $user['USER_NAME'] . $type, 1, $result['USER_ID'], $user['USER_NAME']);
//            return static::notice('操作成功');
//        }
//        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
//    }

    /**
     * 添加会员
     * @return mixed
     * @throws HttpException
     */
    public function actionUserAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(AdminAddUserForm::class, Yii::t('ctx', 'successfully'), null, null, null, function ($form, $result) {//添加成功
                // Log::adminHandle('后台添加会员:' . $result['USER_NAME'], 1, $result['ID'], $result['USER_NAME']);
            });
        }

        $countryId = \Yii::$app->request->get('countryId');

        // 获取所有报单中心级别
        $allDecRole = DecRole::getAllData();
        // 所有民族
        $allNation = Yii::$app->params['nation'];
        // 行政区划
        $regions = Region::getByCountryId($countryId);
        // 银行开户行
        $allOpenBank = OpenBank::findAllAsArray('STATUS=:STATUS AND COUNTRY_ID=:COUNTRY_ID', [':STATUS' => 1, ':COUNTRY_ID' => $countryId]);
        // 生成用户名
        if (!$userName = Info::generateWebName($countryId)) {
            return static::notice('Failed to generate member number', 400);//会员编号生成失败
        }
        return static::notice(
            [
                'allDecRole' => $allDecRole,
                'allNation' => $allNation,
                'allOpenBank' => $allOpenBank,
                'userName' => $userName,
                'region' => $regions,
            ]);
    }

    /**
     * 分页导入excel文件到待导入数据的表中
     * @return mixed
     * @throws HttpException
     */
    public function actionImportUsersToExcelTable()
    {
        // 先上传到服务器文件
        if (\Yii::$app->request->isPost) {
            $excelImportId = Yii::$app->request->post('excelImportId');
            $rowCount = Yii::$app->request->post('rowCount');
            $startRow = Yii::$app->request->post('startRow');
            $limit = Yii::$app->request->post('limit', 1000);
            $errorMsg = '';
            try {
                $excel = new \common\helpers\Excel();
                $result = $excel->pageImportDataFromExcel('addUser', $excelImportId, $rowCount, $startRow, $limit);
            } catch (Exception $e) {
                $result = false;
                $errorMsg = $e->getMessage();
            }
            // 还有数据
            if ($result === 1) {
                return static::notice(['finish' => false]);
            } elseif ($result === 0) {
                return static::notice(['finish' => true]);
            } else {
                return static::notice('An error occurred：' . $errorMsg, 400);//发生错误
            }
        }
    }

    public function actionModifyPassword() {
        $form = new UserBasicForm();
        $form->scenario = 'modifyPassword';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->edit()){
            return static::notice(Yii::t('ctx', 'successfully')); // 密码修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    /**
     * 个人资料获取
     * @return mixed
     * @throws HttpException
     */
    public function actionProfileGet() {
        $id = Yii::$app->request->get('id');
        $userInfo = User::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$userInfo) {
            return static::notice('Data does not exist', 400);//数据不存在
        }

        $data['allNation'] = \Yii::$app->params['nation'];
        $data['region'] = Region::getByCountryId($userInfo['COUNTRY_ID']);
        $data['language'] = Language::getFromCache();
        $data['allOpenBank'] = OpenBank::find()
            ->where('STATUS=:STATUS AND COUNTRY_ID=:COUNTRY_ID', [':STATUS' => 1, ':COUNTRY_ID' => $userInfo['COUNTRY_ID']])
            ->orderBy('BANK_NAME ASC')
            ->asArray()
            ->all();

        $countries = Countries::getFromCache();

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $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);
        }

        $data['country'] = array_values($countries);

        $data['userInfo'] = [
            'userId' => $userInfo['ID'],
            'nation' => \Yii::$app->params['nation'][$userInfo['NATION']]['name']??'',
            'realName' => $userInfo['REAL_NAME'],
            'idCard' => $userInfo['ID_CARD'],
            'mobile' => $userInfo['MOBILE'],
            'openBank' => $userInfo['OPEN_BANK'],
            'bankAddress' => $userInfo['BANK_ADDRESS'],
            'bankNo' => $userInfo['BANK_NO'],
            'language' => $userInfo['LANGUAGE_ID'],
            'country' => $userInfo['COUNTRY_ID'],
        ];

        return static::notice($data);
    }

    public function actionModifyProfile() {
        $form = new UserBasicForm();
        $form->scenario = 'modifyProfile';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->modifyProfile()){
            return static::notice(Yii::t('ctx', 'successfully'));//个人资料修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    public function actionModifyStatus() {
        $form = new UserBasicForm();
        $form->scenario = 'modifyStatus';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->modifyStatus()){
            return static::notice(Yii::t('ctx', 'successfully'));//会员状态修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    /**
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionIsModifyPasswordStatus() {
        $form = new UserBasicForm();
        $form->scenario = 'isModifyPasswordStatus';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->isModifyPasswordStatus()){
            return static::notice(Yii::t('ctx', 'successfully'));//状态修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    /**
     * 分页把待导入表中的数据导入到真正的数据中
     * @return mixed
     * @throws HttpException
     */
    public function actionImportUsersAdd()
    {
        if (\Yii::$app->request->isPost) {
            $excelImportId = Yii::$app->request->post('excelImportId');
            $offset = Yii::$app->request->post('offset');
            $limit = Yii::$app->request->post('limit', 1000);
            $errorMsg = '';
            try {
                $excel = new \common\helpers\Excel();
                $result = $excel->pageImportDataFromExcelTable('addUser', $excelImportId, $offset, $limit);
            } catch (Exception $e) {
                $result = false;
                $errorMsg = $e->getMessage();
            }
            // 还有数据
            if ($result === 1) {
                return static::notice(['finish' => false]);
            } elseif ($result === 0) {
                return static::notice(['finish' => true]);
            } else {
                return static::notice('An error occurred：' . $errorMsg, 400);//发生错误
            }
        }
    }

    /**
     * 判断是否满足删除条件
     * @return mixed
     * @throws HttpException
     */
    public function actionChkDelUser()
    {
        $userName = Yii::$app->request->get('userName');
        if (!$uid = Info::getUserIdByUserName($userName)) {
            return static::notice('user does not exist' . $userName, 400);//用户不存在
        }
        if (UserInfo::findOneAsArray('REC_UID=:REC_UID AND DELETED=0', [':REC_UID' => $uid], 'USER_ID')) {
            return static::notice('This member has developed other members and cannot be deleted', 400);//此会员已开拓其它会员不可以删除
        }
        if (UserInfo::findOneAsArray('CON_UID=:CON_UID AND DELETED=0', [':CON_UID' => $uid], 'USER_ID')) {
            return static::notice('This member has been placed with other members and cannot be deleted', 400);//此会员已安置其它会员不可以删除
        }
        if (User::findOneAsArray('DEC_ID=:DEC_ID AND DELETED=0', [':DEC_ID' => $uid], 'ID')) {
            return static::notice('This member has submitted a bill and other members cannot delete it', 400);//此会员已报单其它会员不可以删除
        }
        if (DecOrder::findOneAsArray('USER_ID=:TO_USER_ID OR TO_USER_ID=:TO_USER_ID', [':TO_USER_ID' => $uid], 'ID')) {
            return static::notice('This member has submitted a bill and cannot be deleted', 400);//此会员已报单不可以删除
        }
        $info = Info::baseInfoWithNet($uid);
        if ($info['REG_FROM'] == 1) {
            return static::notice('This member is not empty and cannot be deleted', 400);//此会员不是空单无法删除
        }
        $sentMaxPeriodNum = Period::sentMaxPeriodNum();
        if ($info['PERIOD_AT'] <= $sentMaxPeriodNum) {
            return static::notice('The number of enrollment periods of this member is less than or equal to the number of online periods', 400);//此会员加入期数小于等于已挂网期数
        }
        if (User::find()->where('ID=:ID AND VERIFIED=1', [':ID' => $uid])->exists()) {
            return static::notice('This member has been authenticated by real name and cannot be deleted', 400);//此会员已实名认证无法删除
        }
        if (User::find()->where('ID=:ID AND SUB_COM_LEADER=1', [':ID' => $uid])->exists()) {
            return static::notice('This member is a branch leader and cannot be deleted', 400);//此会员是分公司领导人无法删除
        }
        if (UserInfo::find()->where('USER_ID=:USER_ID AND (IS_GROUP_LEADER=1 OR IS_SYSTEM_LEADER=1 OR IS_BIND=1 OR IS_TEAM=1)', [':USER_ID' => $uid])->exists()) {
            return static::notice('This member cannot be deleted due to the following conditions: Team Leader / system leader / point binding / point cooperation', 400);//此会员存在以下情况无法删除，团队领导人/体系领导人/点位绑定/点位合作
        }
        if (FlowBonus::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $uid], 'ID')) {
            return static::notice('This member has generated a balance flow, which cannot be deleted', 400);//该会员产生过余额流水无法删除
        }
        if (UserMove::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $uid], 'ID')) {
            return static::notice('The member cannot be deleted due to network migration', 400);//该会员发生过移网无法删除
        }
        return static::notice($info);
    }

    /**
     * 删除空单会员
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionUserDel()
    {
        $formModel = new AdminAddUserForm();
        $formModel->scenario = 'userDel';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->userDel()) {
            $user = User::getBaseInfoFromRedis($result);
            //// Log::adminHandle('删除空单会员' . $user['USER_NAME'], 1, $result, $user['USER_NAME']);
            // Log::adminHandle('删除空单会员' . $user['USER_NAME'], 1);
            return static::notice(Yii::t('ctx', 'successfully'));//删除空单会员完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 复销列表
     * @return mixed
     * @throws HttpException
     */
    public function actionReConsumeList()
    {
//        $filter = $this->filterCondition(ReconsumePool::tableName(), [
//            'userName' => ['UI.USER_NAME', '='],
//        ]);
        $condition = '';
        $params = [];
        $data = ReconsumePool::lists($condition, $params, [
            'select' => 'RP.USER_ID,RP.UNUSED_PV,RP.UNUSED_MONTH',
            'from' => ReconsumePool::tableName() . ' AS RP',
            'join' => [
                ['LEFT JOIN', UserInfo::tableName() . ' AS UI', 'UI.USER_ID=RP.USER_ID']
            ],
            'orderBy' => 'RP.USER_ID ASC'
        ]);
        foreach ($data['list'] as $key => $value) {
            $userBaseInfo = Cache::getUserBaseInfo($value['USER_ID']);
            $data['list'][$key]['USER_NAME'] = $userBaseInfo['USER_NAME'];
            $data['list'][$key]['REAL_NAME'] = $userBaseInfo['REAL_NAME'];
            $data['list'][$key]['DEC_LV'] = Info::getDecLv($value['USER_ID']);
            $data['list'][$key]['EMP_LV'] = Info::getEmpLv($value['USER_ID']);
        }
        return static::notice($data);
    }

    /**
     * 筛选用户
     * 前端传过来的get参数类似于
     * [
     *      'USER_NAME' => 'like,test',
     *      'CREATED_AT' => '>=,2018-11-10,date'
     * ]
     * @return mixed
     * @throws HttpException
     */
    public function actionFilterUser()
    {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'STATUS' => 'U.STATUS',
            'STATUS_AT' => 'U.STATUS_AT',
            'STATUS_NAME' => 'U.STATUS',
            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
            'CREATED_AT' => 'U.CREATED_AT',
            'USER_CREATED_AT' => 'U.CREATED_AT',
            'PERIOD_AT' => 'U.PERIOD_AT',
            'DEC_LV' => 'U.DEC_LV',
            'DEC_LV_NAME' => 'U.DEC_LV',
            'DEC_LV_UPDATED_AT' => 'U.DEC_LV_UPDATED_AT',
            'LAST_DEC_LV' => 'U.LAST_DEC_LV',
            'LAST_DEC_LV_NAME' => 'U.LAST_DEC_LV',
            'EMP_LV' => 'U.EMP_LV',
            'EMP_LV_NAME' => 'U.EMP_LV',
            //'ID_TYPE' => 'U.ID_TYPE',
            'ID_CARD' => 'U.ID_CARD',
            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
            'SPOUSE_IDCARD' => 'U.SPOUSE_IDCARD',
            'SUB_COM_ID' => 'U.SUB_COM_ID',
            'SUB_COM_NAME' => 'U.SUB_COM_ID',
            'MOBILE' => 'U.MOBILE',
            'TEL' => 'U.TEL',
            'DEC_DEC_ROLE_ID' => 'UD.DEC_ROLE_ID',
            'DEC_DEC_ROLE_NAME' => 'UD.DEC_ROLE_ID',
            'DEC_USER_NAME' => 'UD.USER_NAME',
            'IS_DEC' => 'U.IS_DEC',
            'DEC_ROLE_ID' => 'U.DEC_ROLE_ID',
            'DEC_ROLE_NAME' => 'U.DEC_ROLE_ID',
            'OPEN_BANK' => 'U.OPEN_BANK',
            'OPEN_BANK_NAME' => 'U.OPEN_BANK',
            'BANK_AREA' => [
                'FIELD' => ['U.BANK_PROVINCE', 'U.BANK_CITY', 'U.BANK_COUNTY'],
                'BIND' => ['BANK_PROVINCE', 'BANK_CITY', 'BANK_COUNTY'],
            ],
            'BANK_ADDRESS' => 'U.BANK_ADDRESS',
            'BANK_NO' => 'U.BANK_NO',
            'SEX' => 'U.SEX',
            'NATION' => 'U.NATION',
            'NATION_NAME' => 'U.NATION',
            'AREA' => [
                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
            'ADDRESS' => 'U.ADDRESS',
            'VERIFIED' => 'U.VERIFIED',
            'VERIFIED_AT' => 'U.VERIFIED_AT',
            'IS_DIRECT_SELLER' => 'U.IS_DIRECT_SELLER',
            'PART_FUNC_CLOSED' => 'U.PART_FUNC_CLOSED',
            //'BIRTHDAY' => 'U.BIRTHDAY',
            'DEC_CLOSED' => 'U.DEC_CLOSED',
            'NOT_OPERATING' => 'U.NOT_OPERATING',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $data = User::lists($condition, $params, [
            'select' => 'U.*, UD.USER_NAME AS UD_USER_NAME',
            'from' => User::tableName() . ' AS U',
            'join' => [
                ['LEFT JOIN', User::tableName() . ' AS UD', 'U.DEC_ID=UD.ID'],
            ],
            'orderBy' => 'U.CREATED_AT DESC',
        ]);
        return static::notice($data);
    }

    /**
     * 会员级别变动记录
     * @return mixed
     * @throws \yii\base\Exception
     * @throws HttpException
     */
    public function actionDecLevelList()
    {
        $filter = $this->filterCondition([
            'USER_NAME' => 'CU.USER_NAME',
            'CREATED_AT' => 'LL.CREATED_AT',
            'ADMIN_NAME' => 'ADM.ADMIN_NAME',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);
            $quotedAdminCountry = array_map(function($item) {
                return "'" . addslashes($item) . "'";
            }, $adminCountry);

            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

        $listObj = new DecLevelList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);

        return static::notice($data);
    }
    /**
     * 调整会员级别报单级别
     * @return mixed
     * @throws HttpException
     */
    public function actionChangeUserDecLevel()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(DecLevelLogForm::class, Yii::t('ctx', 'successfully'), 'adminChange', [ // 修改会员级别成功
                'adminChange',
            ], null, function ($form, $result) {
                //$userName = Info::getUserNameByUserId($result['ID']);
                // Log::adminHandle('后台调整会员级别级别:'.$userName, 1, $result['ID'], $userName);
            });
        }
    }

    /**
     * 调整会员级别报单级别
     * @return mixed
     * @throws HttpException
     */
    public function actionChangeUserDecRole()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(DecRoleLogForm::class, Yii::t('ctx', 'successfully'), 'adminChange', [//修改报单中心级别成功
                'adminChange',
            ], null, function ($form, $result) {
                //$userName = Info::getUserNameByUserId($result['ID']);
                // Log::adminHandle('后台调整会员级别级别:'.$userName, 1, $result['ID'], $userName);
            });
        }
    }

    /**
     * 修改会员前台显示聘级
     * @return mixed
     * @throws HttpException
     */
    public function actionChangeShowEmpLevel()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(ChangeShowEmpLvForm::class, Yii::t('ctx', 'successfully'), 'adminChange', [//修改会员前台显示聘级成功
                'adminChange',
            ], null, function ($form, $result) {
                //$userName = Info::getUserNameByUserId($result['ID']);
                // Log::adminHandle('后台调整会员级别级别:'.$userName, 1, $result['ID'], $userName);
            });
        }
    }

    /**
     * 注册信息管理
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionRegInfo()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'regType' => 'UI.REG_TYPE',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $condition .= ' AND UI.DELETED=0';
        $data = UserInfo::lists($condition, $params, [
            'orderBy' => 'UI.CREATED_AT DESC',
            'from' => UserInfo::tableName() . ' AS UI',
        ]);
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['BASE_INFO'] = Info::baseInfoZh($value['USER_ID']);
            $data['list'][$key]['AUDIT_INFO'] = RegInfoAudit::find()->from(RegInfoAudit::tableName() . ' AS RIA')->select('RIA.*,ADM.ADMIN_NAME CREATE_ADMIN_NAME,ADMA.ADMIN_NAME AUDIT_ADMIN_NAME')->where('USER_ID=:USER_ID AND AUDIT_STATUS=:AUDIT_STATUS', [':USER_ID' => $value['USER_ID'], ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['true']['value']])->join('LEFT JOIN', Admin::tableName() . ' AS ADM', 'ADM.ID=RIA.CREATE_ADMIN')->join('LEFT JOIN', Admin::tableName() . ' AS ADMA', 'ADMA.ID=RIA.AUDIT_ADMIN')->orderBy('AUDITED_AT DESC')->asArray()->one();
        }

        return static::notice($data);
    }

    /**
     * 注册信息管理中提交修改注册信息
     * @return mixed
     * @throws HttpException
     */
    public function actionRegInfoEdit()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(RegInfoAuditForm::class, 'The registration information modification has been submitted successfully and will take effect after approval', 'editRegInfo', ['editRegInfo'], null, function ($form, $result) {//注册信息修改提交成功，审核后生效
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('申请为' . $user['USER_NAME'] . '注册信息修改', 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
        return static::notice(['allOpenBank' => $allOpenBank]);
    }

    /**
     * 会员注册信息审核
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionRegInfoAudit()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'createdAt' => 'RIA.CREATED_AT',
            'regType' => 'RIA.REG_TYPE',
            'filterStatus' => 'RIA.AUDIT_STATUS',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $data = RegInfoAudit::lists($condition, $params, [
            'orderBy' => 'RIA.CREATED_AT DESC',
            'from' => RegInfoAudit::tableName() . ' AS RIA',
            'join' => [
                ['LEFT JOIN', UserInfo::tableName() . ' AS UI', 'RIA.USER_ID=UI.USER_ID'],
            ],
        ]);
        $auditStatus = array_column(\Yii::$app->params['auditStatus'], null, 'value');
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['BASE_INFO'] = Info::baseInfoZh($value['USER_ID']);
            $data['list'][$key]['CREATE_ADMIN_NAME'] = Admin::getAdminNameById($value['CREATE_ADMIN']);
            $data['list'][$key]['AUDIT_ADMIN_NAME'] = Admin::getAdminNameById($value['AUDIT_ADMIN']);
            $data['list'][$key]['STATUS_NAME'] = $auditStatus[$value['AUDIT_STATUS']]['label'];
        }
        return static::notice($data);
    }

    /**
     * 会员注册信息添加
     * @return mixed
     * @throws HttpException
     */
    public function actionRegInfoAuditAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(RegInfoAuditForm::class, Yii::t('ctx', 'successfully'), 'add', ['add'], null, function ($form, $result) {//注册信息录入成功
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('申请为' . $user['USER_NAME'] . '注册信息录入', 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
    }

    /**
     * 会员注册信息添加获取
     * @return mixed
     * @throws HttpException
     */
    public function actionRegInfoAuditAddOpt()
    {
        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
        return static::notice(['allOpenBank' => $allOpenBank]);
    }

    /**
     * 会员注册信息获取
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionRegInfoAuditGet()
    {
        $id = Yii::$app->request->get('id');
        $regInfo = RegInfoAudit::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$regInfo) {
            return static::notice('Data does not exist', 400);//数据不存在
        }
        $regInfo['BASE_INFO'] = Info::baseInfoZh($regInfo['USER_ID']);
        $regInfo['REG_EXPIRES'] = Date::convert($regInfo['REG_EXPIRES']);
        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
        $companyBank = CompanyBank::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $regInfo['USER_ID']]);
        $bank = ['openBank' => null, 'bankAreaSelected' => [], 'bankAddress' => null, 'openName' => null, 'bankNo' => null];
        if ($companyBank) $bank = ['openBank' => $companyBank['OPEN_BANK'], 'bankAreaSelected' => [$companyBank['BANK_PROVINCE'], $companyBank['BANK_CITY'], $companyBank['BANK_COUNTY']], 'bankAddress' => $companyBank['BANK_ADDRESS'], 'openName' => $companyBank['OPEN_NAME'], 'bankNo' => $companyBank['BANK_NO']];
        return static::notice(['form' => ['id' => $regInfo['ID'], 'userId' => $regInfo['USER_ID'], 'baseInfo' => $regInfo['BASE_INFO'], 'type' => $regInfo['REG_TYPE'], 'regName' => $regInfo['REG_NAME'], 'creditCode' => $regInfo['CREDIT_CODE'], 'premises' => $regInfo['PREMISES'], 'legalPerson' => $regInfo['LEGAL_PERSON'], 'regExpires' => $regInfo['REG_EXPIRES'], 'createRemark' => $regInfo['CREATE_REMARK'], 'companyBank' => $bank], 'allOpenBank' => $allOpenBank]);
    }

    /**
     * 会员注册信息修改
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionRegInfoAuditEdit()
    {
        $formModel = new RegInfoAuditForm();
        $formModel->scenario = 'edit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->edit()) {
            $user = User::getBaseInfoFromRedis($result['USER_ID']);
            // Log::adminHandle('修改' . $user['USER_NAME'] . '注册信息录入数据', 1, $result['USER_ID'], $user['USER_NAME']);
            return static::notice(Yii::t('ctx', 'successfully'));//修改注册信息录入数据完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 会员注册信息审核
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionRegInfoAuditAudit()
    {
        $formModel = new RegInfoAuditForm();
        $formModel->scenario = 'audit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->audit()) {
            $user = User::getBaseInfoFromRedis($result['USER_ID']);
            // Log::adminHandle('审核' . $user['USER_NAME'] . '注册信息', 1, $result['USER_ID'], $user['USER_NAME']);
            return static::notice(Yii::t('ctx', 'successfully'));//审核注册信息完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 分页导入excel文件到待导入数据的表中
     * @return mixed
     * @throws HttpException
     */
    public function actionImportRegInfoToExcelTable()
    {
        // 先上传到服务器文件
        if (\Yii::$app->request->isPost) {
            $excelImportId = Yii::$app->request->post('excelImportId');
            $rowCount = Yii::$app->request->post('rowCount');
            $startRow = Yii::$app->request->post('startRow');
            $limit = Yii::$app->request->post('limit', 1000);
            $errorMsg = '';
            try {
                $excel = new \common\helpers\Excel();
                $result = $excel->pageImportDataFromExcel('regInfo', $excelImportId, $rowCount, $startRow, $limit);
            } catch (Exception $e) {
                $result = false;
                $errorMsg = $e->getMessage();
            }
            // 还有数据
            if ($result === 1) {
                return static::notice(['finish' => false]);
            } elseif ($result === 0) {
                return static::notice(['finish' => true]);
            } else {
                return static::notice('发生错误：' . $errorMsg, 400);
            }
        }
    }

    /**
     * 分页把待导入表中的数据导入到真正的数据中
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionImportRegInfo()
    {
        if (\Yii::$app->request->isPost) {
            $excelImportId = Yii::$app->request->post('excelImportId');
            $offset = Yii::$app->request->post('offset');
            $limit = Yii::$app->request->post('limit', 1000);
            $errorMsg = '';
            $excel = new \common\helpers\Excel();
            $result = $excel->pageImportDataFromExcelTable('regInfo', $excelImportId, $offset, $limit);
            // 还有数据
            if ($result === 1) {
                return static::notice(['finish' => false]);
            } elseif ($result === 0) {
                return static::notice(['finish' => true]);
            } else {
                return static::notice('发生错误：' . $errorMsg, 400);
            }
        }
    }

    /**
     * 会员注册信息删除
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionRegInfoAuditDelete()
    {
        $result = static::delete(RegInfoAudit::class, null, function ($selected) {
            RegInfoAuditForm::delete($selected);
            // Log::adminHandle('删除注册信息');
        }, true);
        return $result;
    }

    /**
     * 禁止登录
     * @return mixed
     * @throws HttpException
     */
    public function actionCloseLogin()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(CloseLoginForm::class, Yii::t('ctx', 'successfully'), 'single', ['single'], null, function ($form, $result) {
//                $appStr = CloseLoginForm::$apps[$form->shopOrBonus];
//                $closeStr = CloseLoginForm::$closeSwitch[$form->isClose];
//                $typeStr = CloseLoginForm::$types[$form->type];
//                $remark = $form->remark;
                // Log::adminHandle('为会员' . $form->userName . $typeStr . $closeStr . $appStr, 1, $result, $form->userName, $remark);
            });
        }
    }

    /**
     * 禁止登陆类型获取
     * @return mixed
     * @throws HttpException
     */
    public function actionCloseLoginGet()
    {
        return static::notice(['types' => CloseLoginForm::$types, 'closeSwitch' => CloseLoginForm::$closeSwitch]);
    }

    /**
     * 关闭地区登录
     * @return mixed
     * @throws HttpException
     */
    public function actionCloseAreaLogin()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(CloseLoginForm::class, Yii::t('ctx', 'successfully'), 'area', ['area'], null, function ($form, $result) {
//                $appStr = CloseLoginForm::$apps[$form->shopOrBonus];
//                $closeStr = CloseLoginForm::$closeSwitch[$form->isClose];
//                $province = $form->areaSelected[0] ?? '';
//                $city = $form->areaSelected[1] ?? '';
//                $county = $form->areaSelected[2] ?? '';
//                $remark = $form->remark;
                // Log::adminHandle('区域'.$appStr.$closeStr.'：' . $province . $city . $county, 1, null, null, $remark);
            });
        }
        return static::notice(['types' => CloseLoginForm::$types, 'closeSwitch' => CloseLoginForm::$closeSwitch]);
    }

    /**
     * 批量登录管理
     * @return mixed
     * @throws HttpException
     */
    public function actionBatchCloseLogin()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(CloseLoginForm::class, Yii::t('ctx', 'successfully'), 'batch', ['batch'], null, function ($form, $result) {
                /*$appStr = CloseLoginForm::$apps[$form->shopOrBonus];
                $closeStr = CloseLoginForm::$closeSwitch[$form->isClose];
                $remark = $form->remark;
                if (is_array($result)) {
                    foreach ($result as $value) {
                        // 获取其中一个人的会员编号
                        $userName = Info::getUserNameByUserId($value);
                        // Log::adminHandle('为会员' . $userName . $closeStr . $appStr, 1, $value, $userName, $remark);
                    }
                }*/
            });
        }
        return static::notice(['types' => CloseLoginForm::$types, 'closeSwitch' => CloseLoginForm::$closeSwitch]);
    }

    /**
     * 关闭报单信息获取
     * @return mixed
     * @throws HttpException
     */
    public function actionCloseDecGet()
    {
        return static::notice(['types' => CloseDecForm::$types, 'closeSwitch' => CloseDecForm::$closeSwitch]);
    }

    /**
     * 关闭报单
     * @return mixed
     * @throws HttpException
     */
    public function actionCloseDec()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(CloseDecForm::class, Yii::t('ctx', 'successfully'), 'single', ['single'], null, function ($form, $result) {
//                $closeStr = CloseDecForm::$closeSwitch[$form->isClose];
//                $typeStr = CloseDecForm::$types[$form->type];
//                $remark = $form->remark;
                // Log::adminHandle('为会员' . $form->userName . $typeStr . $closeStr, 1, $result, $form->userName, $remark);
            });
        }
    }

    /**
     * 批量关闭报单
     * @return mixed
     * @throws HttpException
     */
    public function actionBatchCloseDec()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(CloseDecForm::class, Yii::t('ctx', 'successfully'), 'batch', ['batch'], null, function ($form, $result) {
                /*$closeStr = CloseDecForm::$closeSwitch[$form->isClose];
                $remark = $form->remark;
                if (is_array($result)) {
                    foreach ($result as $value) {
                        // 获取其中一个人的会员编号
                        $userName = Info::getUserNameByUserId($value);
                        // Log::adminHandle('为会员' . $userName . $closeStr, 1, $value, $userName, $remark);
                    }
                }*/
            });
        }
        return static::notice(['types' => CloseDecForm::$types, 'closeSwitch' => CloseDecForm::$closeSwitch]);
    }

    /**
     * 按地区关闭报单
     * @return mixed
     * @throws HttpException
     */
    public function actionCloseAreaDec()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(CloseDecForm::class, Yii::t('ctx', 'successfully'), 'area', ['area'], null, function ($form, $result) {
//                $closeStr = CloseDecForm::$closeSwitch[$form->isClose];
//                $province = $form->areaSelected[0] ?? '';
//                $city = $form->areaSelected[1] ?? '';
//                $county = $form->areaSelected[2] ?? '';
//                $remark = $form->remark;
                // Log::adminHandle('区域'.$closeStr.'：' . $province . $city . $county, 1, null, null, $remark);
            });
        }
        return static::notice(['types' => CloseDecForm::$types, 'closeSwitch' => CloseDecForm::$closeSwitch]);
    }

    /**
     * 会员状态管理
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
//    public function actionStatusAuditList()
//    {
//        $filter = $this->filterCondition([
//            'userIds' => 'UI.USER_ID',
//            'filterStatus' => 'USA.AUDIT_STATUS',
//            'SYSTEM_NAME' => 'UI.SYSTEM_ID',
//            'ORI_STATUS_NAME' => 'USA.ORI_VALUE',
//            'STATUS_NAME' => 'USA.STATUS_VALUE',
//            'PERIOD_NUM' => 'USA.PERIOD_NUM',
//            'CREATE_REMARK' => 'USA.CREATE_REMARK',
//            'IS_PERIOD_ADD_T' => 'USA.IS_PERIOD_ADD_T',
//            'ADD_T_PERIOD_NUM' => 'USA.ADD_T_PERIOD_NUM',
//            'IS_PERIOD_OPEN' => 'USA.IS_PERIOD_OPEN',
//            'OPEN_PERIOD_NUM' => 'USA.OPEN_PERIOD_NUM',
//            'CREATE_ADMIN_NAME' => 'ADM.ADMIN_NAME',
//            'CREATED_AT' => 'ADM.CREATED_AT',
//            'AUDIT_ADMIN_NAME' => 'ADMA.ADMIN_NAME',
//            'AUDITED_AT' => 'ADM.AUDITED_AT',
//        ]);
//        $condition = $filter['condition'];
//        $params = $filter['params'];
//        $listObj = new StatusAuditList();
//        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
//        return static::notice($data);
//    }

    /**
     * 会员状态管理导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionStatusAuditExport()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'filterStatus' => 'USA.AUDIT_STATUS',
            'SYSTEM_NAME' => 'UI.SYSTEM_ID',
            'ORI_STATUS_NAME' => 'USA.ORI_VALUE',
            'STATUS_NAME' => 'USA.STATUS_VALUE',
            'PERIOD_NUM' => 'USA.PERIOD_NUM',
            'CREATE_REMARK' => 'USA.CREATE_REMARK',
            'IS_PERIOD_ADD_T' => 'USA.IS_PERIOD_ADD_T',
            'ADD_T_PERIOD_NUM' => 'USA.ADD_T_PERIOD_NUM',
            'IS_PERIOD_OPEN' => 'USA.IS_PERIOD_OPEN',
            'OPEN_PERIOD_NUM' => 'USA.OPEN_PERIOD_NUM',
            'CREATE_ADMIN_NAME' => 'ADM.ADMIN_NAME',
            'CREATED_AT' => 'ADM.CREATED_AT',
            'AUDIT_ADMIN_NAME' => 'ADMA.ADMIN_NAME',
            'AUDITED_AT' => 'ADM.AUDITED_AT',
        ]);
        $form = new UserExportForm();
        $result = $form->run($filter, '会员状态管理');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 申请修改会员状态
     * @return mixed
     * @throws HttpException
     */
    public function actionStatusAuditAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserStatusForm::class, Yii::t('ctx', 'successfully'), 'add', ['add'], null, function ($form, $result) {
                $userInfo = Info::baseInfo($result->USER_ID);
                // Log::adminHandle('申请修改' . $userInfo['USER_NAME'] . '状态为' . Yii::$app->params['userStatus'][$result->STATUS_VALUE]['label'], 1, $result->USER_ID, $userInfo['USER_NAME']);
            });
        }

    }

    /**
     * 获取全部移网类型
     * @return mixed
     * @throws HttpException
     */
    public function actionStatusAuditGetStatuses()
    {
        $statuses = Tool::paramConvert(Yii::$app->params['userStatus']);
        return static::notice(['statuses' => $statuses]);
    }

    /**
     * 获取会员状态数据
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionStatusAuditGet()
    {
        $id = Yii::$app->request->get('id');
        $userStatusAudit = UserStatusAudit::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$userStatusAudit) {
            return static::notice('The data does not exist', 400); // 数据不存在
        }
        $userStatusAudit['BASE_INFO'] = Info::baseInfoZh($userStatusAudit['USER_ID']);
        $statuses = Tool::paramConvert(Yii::$app->params['userStatus']);
        return static::notice([
            'id' => $userStatusAudit['ID'],
            'baseInfo' => $userStatusAudit['BASE_INFO'],
            'statusValue' => $userStatusAudit['STATUS_VALUE'],
            'isPeriodAddT' => $userStatusAudit['IS_PERIOD_ADD_T'] ? true : false,
            'addTPeriodNum' => $userStatusAudit['ADD_T_PERIOD_NUM'],
            'isPeriodOpen' => $userStatusAudit['IS_PERIOD_OPEN'] ? true : false,
            'openPeriodNum' => $userStatusAudit['OPEN_PERIOD_NUM'],
            'remark' => $userStatusAudit['CREATE_REMARK'],
        ]);
    }

    /**
     * 审核修改会员状态
     * @return mixed
     * @throws Exception
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionStatusAudit()
    {
        $formModel = new UserStatusForm();
        $formModel->scenario = 'audit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->audit()) {
            $userInfo = Info::baseInfo($result->USER_ID);
            // Log::adminHandle('审核修改' . $userInfo['USER_NAME'] . '状态为' . Yii::$app->params['userStatus'][$result->STATUS_VALUE]['label'], 1, $result->USER_ID, $userInfo['USER_NAME']);
            return static::notice(Yii::t('ctx', 'successfully'));
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 删除审核修改会员状态
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionStatusAuditDelete()
    {
        $userStatusForm = new UserStatusForm();
        $result = static::delete(UserStatusAudit::class, function ($selected) use ($userStatusForm) {
            $userStatusForm->beforeDelete($selected);
            // Log::adminHandle('删除审核修改会员状态信息');
        }, function ($selected) use ($userStatusForm) {
            $userStatusForm->delete($selected);
            // Log::adminHandle('删除审核修改会员状态信息');
        }, true);
        return $result;
    }

    /**
     * 设置是否运作
     * @return mixed
     * @throws HttpException
     */
    public function actionIsOperating()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserStatusForm::class, Yii::t('ctx', 'successfully'), 'operating', ['operating'], null, function ($form, $result) {
                /*$isOperating = $form->isOperating ? '运作' : '不运作';
                if(is_array($result)){
                    foreach ($result as $value){
                        // 获取其中一个人的会员编号
                        $userName = Info::getUserNameByUserId($value);
                        // Log::adminHandle('为会员' . $userName . '会员设置为' . $isOperating, 1, $value, $userName);
                    }
                }*/
            });
        }
    }

    /**
     * 团队领导人
     * @return mixed
     * @throws HttpException
     */
    public function actionIsGroup()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserGroupForm::class, Yii::t('ctx', 'successfully'), 'group', ['group'], null, function ($form, $result) {
                $isGroup = $form->isGroup ? '设为团队领导人' : '取消团队领导人';
                if (is_array($result)) {
                    foreach ($result as $value) {
                        // 获取其中一个人的会员编号
                        $userName = Info::getUserNameByUserId($value);
                        // Log::adminHandle('为会员' . $userName . $isGroup, 1, $value, $userName);
                    }
                }
            });
        }
    }

    /**
     * 报单中心
     * @return mixed
     * @throws HttpException
     */
    public function actionIsDec()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserDecForm::class, Yii::t('ctx', 'successfully'), 'isDec', ['isDec'], null, null);
        }
    }

    /**
     * 工作室
     * @return mixed
     * @throws HttpException
     */
    public function actionIsStudio()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserDecForm::class, Yii::t('ctx', 'successfully'), 'isStudio', ['isStudio'], null, null);
        }
    }

    /**
     * 网络图谱
     * @return mixed
     * @throws HttpException
     */
    public function actionIsAtlas()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserDecForm::class, Yii::t('ctx', 'successfully'), 'isAtlas', ['isAtlas'], null, null);
        }
    }

    /**
     * 会员充值管理显隐设置
     * @return mixed
     * @throws HttpException
     */
    public function actionIsRecharge()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserDecForm::class, Yii::t('ctx', 'successfully'), 'isRecharge', ['isRecharge'], null, null);
        }
    }

    /**
     * 获取企业银行信息
     * @return mixed
     * @throws HttpException
     */
    public function actionCompanyBankGet()
    {
        $id = Yii::$app->request->get('id');
        $userName = Yii::$app->request->get('userName');
        $companyBank = [];
        if ($id) {
            $companyBank = CompanyBank::findOneAsArray('ID=:ID', [':ID' => $id]);
        }
        if ($userName) {
            $userId = Info::getUserIdByUserName($userName);
            if ($userId) $companyBank = CompanyBank::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId]);
        }
        if ($companyBank) return static::notice(['openBank' => $companyBank['OPEN_BANK'], 'bankAreaSelected' => [$companyBank['BANK_PROVINCE'], $companyBank['BANK_CITY'], $companyBank['BANK_COUNTY']], 'bankAddress' => $companyBank['BANK_ADDRESS'], 'openName' => $companyBank['OPEN_NAME'], 'bankNo' => $companyBank['BANK_NO']]);
        return static::notice(['openBank' => null, 'bankAreaSelected' => [], 'bankAddress' => null, 'openName' => null, 'bankNo' => null]);
    }

    /**
     * 调整会员转账/提现比例
     * @return mixed
     * @throws HttpException
     */
    public function actionChangeTransferProp()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(UserTransferPropForm::class, Yii::t('ctx', 'successfully'), 'change', ['change'], null, function ($form, $result) {
                /*$remark = $form->remark;
                if (is_array($result)) {
                    foreach ($result as $value) {
                        // 获取其中一个人的会员编号
                        $userName = Info::getUserNameByUserId($value);
                        // Log::adminHandle('调整会员'.$userName.'转账/提现比例成功', 1, $value, $userName, $remark);
                    }
                }*/
            });
        }
    }

    public function actionStatusCloseGet()
    {
        $users = Status::getCloseUser();
        return $users;
    }

    /**
     * 清空关停会员钱包
     * @return mixed
     * @throws Exception
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionClearWallet()
    {
        $formModel = new UserStatusForm();
        $formModel->scenario = 'clearWallet';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->clearWallet()) {
            /*if (is_array($result)) {
                foreach ($result as $value) {
                    // 获取其中一个人的会员编号
                    $userName = Info::getUserNameByUserId($value);
                    Log::adminHandle('清空关停会员' . $userName . '钱包', 1, $value, $userName);
                }
            }*/
            return static::notice('清空关停会员钱包，影响会员【' . count($result) . '】人');
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 会员历史年度最高聘级表
     * @return mixed
     * @throws Exception
     * @throws HttpException
     */
    public function actionYearHighestEmpLv()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'YEAR' => 'YHEL.YEAR',
            'HIGHEST_EMP_LV_NAME' => 'YHEL.HIGHEST_EMP_LV',
            'HIGHEST_EMP_LV_PERIOD' => 'YHEL.HIGHEST_EMP_LV_PERIOD',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new YearHighestEmpLvList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 会员历史年度最高聘级表导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionYearHighestEmpLvExport()
    {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'YEAR' => 'YHEL.YEAR',
            'HIGHEST_EMP_LV_NAME' => 'YHEL.HIGHEST_EMP_LV',
            'HIGHEST_EMP_LV_PERIOD' => 'YHEL.HIGHEST_EMP_LV_PERIOD',
        ]);
        $form = new UserExportForm();
        $result = $form->run($filter, '会员历史年度最高聘级表');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 会员现金充值
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionRechargeToUser()
    {
        $formModel = new RechargeForm();
        $formModel->scenario = 'addByAdmin';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->recharge()) {
            return static::notice(Yii::t('ctx', 'successfully'));
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 会员修改密码
     * @return mixed
     * @throws HttpException
     */
    public function actionBaModifyPassword()
    {
        $form = new BaUserBasicForm();
        $form->scenario = 'modifyPassword';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->edit()){
            return static::notice(Yii::t('ctx', 'successfully')); // 密码修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    /**
     * 个人资料获取
     * @return mixed
     * @throws HttpException
     */
    public function actionBaProfileGet() {
        $id = Yii::$app->request->get('id');
        $userInfo = BaUser::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$userInfo) {
            return static::notice('Data does not exist', 400);//数据不存在
        }
        $data['userInfo'] = [
            'userId' => $userInfo['ID'],
            'realName' => $userInfo['REAL_NAME'],
            'mobile' => $userInfo['MOBILE'],
        ];

        return static::notice($data);
    }

    public function actionBaModifyProfile() {
        $form = new BaUserBasicForm();
        $form->scenario = 'modifyProfile';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->modifyProfile()){
            return static::notice(Yii::t('ctx', 'successfully'));//个人资料修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    public function actionBaModifyStatus() {
        $form = new BaUserBasicForm();
        $form->scenario = 'modifyStatus';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->modifyStatus()){
            return static::notice(Yii::t('ctx', 'successfully'));//会员状态修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    /**
     * @return mixed
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionBaIsModifyPasswordStatus() {
        $form = new BaUserBasicForm();
        $form->scenario = 'isModifyPasswordStatus';
        if(Yii::$app->request->isPost && $form->load(Yii::$app->request->post(), '') && $result = $form->isModifyPasswordStatus()){
            return static::notice(Yii::t('ctx', 'successfully'));//状态修改成功
        } else {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
    }

    /**
     * BA会员列表
     * @return mixed
     * @throws Exception
     * @throws \yii\web\HttpException
     */
    public function actionBaUserList() {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'STATUS' => 'U.STATUS',
            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
            'CREATED_AT' => 'U.CREATED_AT',
            'PERIOD_AT' => 'U.PERIOD_AT',
            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
            'MOBILE' => 'U.MOBILE',
            'TEL' => 'U.TEL',
            'SEX' => 'U.SEX',
            'AREA' => [
                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
            'ADDRESS' => 'U.ADDRESS',
            'ALLOW_TRANSFER' => 'UI.ALLOW_TRANSFER',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $condition .= ' AND UI.DELETED=0 ';
        $listObj = new BaUserList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionBaUserListExport() {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'STATUS' => 'U.STATUS',
            'ALLOW_LOGIN' => 'U.ALLOW_LOGIN',
            'CREATED_AT' => 'U.CREATED_AT',
            'PERIOD_AT' => 'U.PERIOD_AT',
            'REC_USER_NAME' => 'RU.USER_NAME',
            'CON_USER_NAME' => 'CU.USER_NAME',
            'SPOUSE_NAME' => 'U.SPOUSE_NAME',
            'SYSTEM_NAME' => 'U.SYSTEM_ID',
            'MOBILE' => 'U.MOBILE',
            'TEL' => 'U.TEL',
            'SEX' => 'U.SEX',
            'AREA' => [
                'FIELD' => ['U.PROVINCE', 'U.CITY', 'U.COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
            'ADDRESS' => 'U.ADDRESS',
            'ALLOW_TRANSFER' => 'UI.ALLOW_TRANSFER',
        ]);
        $form = new BaUserExportForm();
        $result = $form->run($filter, 'Brand_Ambassador_List');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 会员最高聘级变动记录.
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionChangeHighestEmpLevelList()
    {
        $filter = $this->filterCondition([
            'USER_NAME' => 'CU.USER_NAME',
            'CREATED_AT' => 'LL.CREATED_AT',
            'ADMIN_NAME' => 'ADM.ADMIN_NAME',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);
            $quotedAdminCountry = array_map(function($item) {
                return "'" . addslashes($item) . "'";
            }, $adminCountry);

            $condition .= " AND CU.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

        $listObj = new ChangeHighestEmpLevelList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);

        return static::notice($data);
    }
    /**
     * 调整会员最高聘级.
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChangeHighestEmpLevel()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(HighestEmpLevelLogForm::class, Yii::t('ctx', 'successfully'), 'adminChange', ['adminChange',], null, function ($form, $result) {

            });
        }
        return static::notice('无效请求', 400);
    }

    /**
     * 移民记录.
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionImmigrantList()
    {
        $filter = $this->filterCondition([
            'USER_NAME' => 'CU.USER_NAME',
            'CREATED_AT' => 'UU.CREATED_AT',
            'ADMIN_NAME' => 'ADM.ADMIN_NAME',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new UserImmigrant();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);

        return static::notice($data);
    }

    /**
     * 移民.
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionImmigrant()
    {
        // 移民条件检查
        if (Yii::$app->request->isGet) {
            // 会员
            $userId = Info::getUserIdByUserName(Yii::$app->request->get('userName'));
            // 1.是否有进行中的分期订单
            $instalmentOrder = Instalment::findOne(['USER_ID' => $userId]);
            // 订单分期总期数配置
            if ($instalmentOrder) {
                // 分期的总期数
                $instalment = intval(Cache::getSystemConfig()['instalment']['VALUE'] ?? 3);
                // 分期商品的期数不能大于总分期数限制
                if (intval($instalmentOrder['STAGE']) < $instalment) {
                    return static::notice(Yii::t('app', 'instalmentOrderInProcess'), 400);
                }
            }
        }

        // 移民
        if (Yii::$app->request->isPost) {
            return parent::edit(ImmigrantForm::class, Yii::t('ctx', 'successfully'), 'userImmigrant', ['userImmigrant'], null, function ($form, $result) {});
        }

        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }
}