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

namespace backendApi\modules\v1\controllers;

use backendApi\modules\v1\models\Admin;
use backendApi\modules\v1\models\AdminCountry;
use backendApi\modules\v1\models\AdminRole;
use backendApi\modules\v1\models\exportForms\FinanceExportForm;
use backendApi\modules\v1\models\lists\finance\BalanceAuditList;
use backendApi\modules\v1\models\lists\finance\HistoryBonusList;
use backendApi\modules\v1\models\lists\finance\RechargeList;
use backendApi\modules\v1\models\lists\finance\TransferList;
use backendApi\modules\v1\models\lists\finance\WithdrawList;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Excel;
use common\helpers\Log;
use common\helpers\Tool;
use common\helpers\user\Info;
use common\models\BalanceAudit;
use common\models\DealType;
use common\models\forms\ChangeBalanceForm;
use common\models\forms\ChangePerfForm;
use common\models\forms\DealTypeForm;
use common\models\forms\InvoiceAuditForm;
use common\models\forms\InvoiceBalanceAuditForm;
use common\models\forms\RechargeForm;
use common\models\forms\WithdrawForm;
use common\models\HistoryBonus;
use common\models\InvoiceAudit;
use common\models\InvoiceBalanceAudit;
use common\models\InvoiceFlow;
use common\models\OpenBank;
use common\models\PerfAudit;
use common\models\PerfPeriod;
use common\models\Recharge;
use common\models\RegType;
use common\models\DecRole;
use common\models\Region;
use common\models\Transfer;
use common\models\Uploads;
use common\models\User;
use common\models\UserBonus;
use common\models\UserInfo;
use common\models\UserPerf;
use common\models\UserSystem;
use common\models\Withdraw;
use Yii;
use common\helpers\Bonus;
use common\helpers\bonus\BonusCalc;
use common\helpers\Form;
use common\models\FlowBonus;
use common\models\forms\PeriodForm;
use common\models\Period;

class FinanceController extends BaseController {
    public $modelClass = FlowBonus::class;

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

    /**
     * 会员余额变动审核列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBalanceAuditList() {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'userIds' => 'BA.USER_ID',
            'filterStatus' => 'BA.AUDIT_STATUS',
            'LAST_DEC_LV_NAME' => 'BA.LAST_DEC_LV',
            'LAST_DEC_ROLE_NAME' => 'BA.LAST_DEC_ROLE_ID',
            'LAST_EMP_LV_NAME' => 'BA.LAST_EMP_LV',
            'TYPE_NAME' => 'BA.TYPE',
            'DEAL_TYPE_NAME' => 'BA.DEAL_TYPE',
            'AMOUNT' => 'BA.AMOUNT',
            'CREATE_REMARK' => 'BA.CREATE_REMARK',
            'REMARK_IS_SHOW' => 'BA.REMARK_IS_SHOW',
            'CREATED_AT' => 'BA.CREATED_AT',
            'AUDITED_AT' => 'BA.AUDITED_AT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            //4047 国家筛选
            'COUNTRY' => 'U.COUNTRY_ID',
        ]);
        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

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

    /**
     * 会员余额调整列表导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBalanceAuditListExport() {
        $filter = $this->filterCondition([
            'USER_NAME' => 'U.USER_NAME',
            'REAL_NAME' => 'U.REAL_NAME',
            'userIds' => 'BA.USER_ID',
            'filterStatus' => 'BA.AUDIT_STATUS',
            'LAST_DEC_LV_NAME' => 'BA.LAST_DEC_LV',
            'LAST_DEC_ROLE_NAME' => 'BA.LAST_DEC_ROLE_ID',
            'LAST_EMP_LV_NAME' => 'BA.LAST_EMP_LV',
            'TYPE_NAME' => 'BA.TYPE',
            'DEAL_TYPE_NAME' => 'BA.DEAL_TYPE',
            'AMOUNT' => 'BA.AMOUNT',
            'CREATE_REMARK' => 'BA.CREATE_REMARK',
            'REMARK_IS_SHOW' => 'BA.REMARK_IS_SHOW',
            'CREATED_AT' => 'BA.CREATED_AT',
            'AUDITED_AT' => 'BA.AUDITED_AT',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            //4047 国家筛选
            'COUNTRY' => 'U.COUNTRY_ID',
        ]);

        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

        $form = new FinanceExportForm();
        $result = $form->run(['condition' => $condition, 'params' => $params], Yii::t('ctx', 'memberEcoinAdjustmentListFileName')); // 会员余额调整列表
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 调整会员余额
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChangeBalance() {
        if (Yii::$app->request->isPost) { // 申请变动会员余额成功
            return static::edit(ChangeBalanceForm::class, Yii::t('ctx', 'applicationChangeBalanceSucceeded'), 'changeAdd', ['changeAdd'], null, function ($formModel, $result) {
                // $userInfo = User::getBaseInfoFromRedis($result['USER_ID']);
                // $type = BalanceAudit::TYPE[$result['TYPE']]['label'];
                // Log::adminHandle('申请调整会员' . $userInfo['USER_NAME'] . '的' . $type . '余额，金额：' . $result['AMOUNT'], 1, $userInfo['ID'], $userInfo['USER_NAME'], $result['CREATE_REMARK']);
            });
        }
    }

    /**
     * 获取全部类型
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChangeBalanceType(){
        $type = BalanceAudit::getBalanceAuditType();
        $dealTypes = DealType::getTypes();
        return static::notice(['type' => $type, 'dealTypes' => $dealTypes]);
    }

    /**
     * 调整会员余额信息
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBalanceAuditGet() {
        $id = Yii::$app->request->get('id');
        $balanceAudit = BalanceAudit::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$balanceAudit) {
            return static::notice(Yii::t('ctx', 'dataNotExists'), 400);
        }
        $balanceAudit['BASE_INFO'] = Info::baseInfoWithBalance($balanceAudit['USER_ID']);
        return static::notice(['id' => $balanceAudit['ID'], 'baseInfo' => $balanceAudit['BASE_INFO'], 'type' => $balanceAudit['TYPE'], 'dealType' => $balanceAudit['DEAL_TYPE'], 'amount' => Tool::formatPrice($balanceAudit['AMOUNT']), 'remark' => $balanceAudit['CREATE_REMARK'], 'isShow' => $balanceAudit['REMARK_IS_SHOW']]);
    }

    /**
     * 修改调整会员余额数据
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBalanceAuditEdit() {
        $formModel = new ChangeBalanceForm();
        $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', 'modificationAdjustmentMemberBalanceCompleted')); // 修改调整会员余额录入数据完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 审核通过会员余额录入数据
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBalanceAuditPass() {
        $formModel = new ChangeBalanceForm();
        $formModel->scenario = 'pass';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->pass()) {
            $user = User::getBaseInfoFromRedis($result['USER_ID']);
            // Log::adminHandle('审核通过' . $user['USER_NAME'] . '调整会员余额录入数据', 1, $result['USER_ID'], $user['USER_NAME']);
            return static::notice(Yii::t('ctx', 'reviewThroughMemberBalance')); // 审核通过会员余额完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 审核会员余额
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBalanceAudit() {
        $formModel = new ChangeBalanceForm();
        $formModel->scenario = 'changeAudit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->changeAudit()) {
            /*foreach ($result as $value) {
                $userName = Info::getUserNameByUserId($value['userId']);
                // Log::adminHandle('审核调整会员余额录入数据' . $userName . '发放' . $value['type'], 1, $value['userId'], $userName);
            }*/
            return static::notice(Yii::t('ctx', 'batchAuditMemberBalanceCompleted')); // 批量审核/审核拒绝会员余额完成
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 删除审核会员余额信息
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBalanceAuditDelete() {
        $changeBalanceForm = new ChangeBalanceForm();
        $result = static::delete(BalanceAudit::class, function ($selected) use ($changeBalanceForm) {
            $changeBalanceForm->beforeDelete($selected);
            // Log::adminHandle('删除审核会员余额信息');
        }, function ($selected) use ($changeBalanceForm) {
            $changeBalanceForm->delete($selected);
            // Log::adminHandle('删除审核会员余额信息');
        }, true);
        return $result;
    }

    /**
     * 转账列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionTransferList() {
        $filter = $this->filterCondition([
            'TRANSFER_SN' => 'TRANSFER_SN',
            'LAST_OUT_USER_NAME' => 'LAST_OUT_USER_NAME',
            'LAST_OUT_REAL_NAME' => 'LAST_OUT_REAL_NAME',
            'LAST_OUT_DEC_LV_NAME' => 'LAST_OUT_DEC_LV',
//            'LAST_OUT_DEC_ROLE_NAME' => 'LAST_OUT_DEC_ROLE_ID',
//            'OUT_WALLET' => 'OUT_WALLET',
//            'LAST_OUT_SYSTEM_NAME' => 'LAST_OUT_SYSTEM_ID',
            'LAST_IN_USER_NAME' => 'LAST_IN_USER_NAME',
            'LAST_IN_REAL_NAME' => 'LAST_IN_REAL_NAME',
            'LAST_IN_DEC_LV_NAME' => 'LAST_IN_DEC_LV',
//            'IN_WALLET' => 'IN_WALLET',
//            'LAST_IN_SYSTEM_NAME' => 'LAST_IN_SYSTEM_ID',
            'ORI_AMOUNT' => 'ORI_AMOUNT',
            'FEE' => 'FEE',
            'AMOUNT' => 'AMOUNT',
            'CREATED_AT' => 'CREATED_AT',
            'PERIOD_NUM' => 'PERIOD_NUM',
            'REMARK' => 'REMARK',
            //4047 国家筛选
            'COUNTRY' => 'U.COUNTRY_ID',
        ]);
        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

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

    /**
     * 转账列表导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionTransferListExport() {
        $filter = $this->filterCondition([
            'TRANSFER_SN' => 'TRANSFER_SN',
            'LAST_OUT_USER_NAME' => 'LAST_OUT_USER_NAME',
            'LAST_OUT_REAL_NAME' => 'LAST_OUT_REAL_NAME',
            'LAST_OUT_DEC_LV_NAME' => 'LAST_OUT_DEC_LV',
//            'LAST_OUT_DEC_ROLE_NAME' => 'LAST_OUT_DEC_ROLE_ID',
//            'OUT_WALLET' => 'OUT_WALLET',
//            'LAST_OUT_SYSTEM_NAME' => 'LAST_OUT_SYSTEM_ID',
            'LAST_IN_USER_NAME' => 'LAST_IN_USER_NAME',
            'LAST_IN_REAL_NAME' => 'LAST_IN_REAL_NAME',
            'LAST_IN_DEC_LV_NAME' => 'LAST_IN_DEC_LV',
//            'IN_WALLET' => 'IN_WALLET',
//            'LAST_IN_SYSTEM_NAME' => 'LAST_IN_SYSTEM_ID',
            'ORI_AMOUNT' => 'ORI_AMOUNT',
            'FEE' => 'FEE',
            'AMOUNT' => 'AMOUNT',
            'CREATED_AT' => 'CREATED_AT',
            'PERIOD_NUM' => 'PERIOD_NUM',
            'REMARK' => 'REMARK',
            //4047 国家筛选
            'COUNTRY' => 'U.COUNTRY_ID',
        ]);

        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

        $form = new FinanceExportForm();
        $result = $form->run(['condition' => $condition, 'params' => $params], Yii::t('ctx', 'financeControllerTransferListExport')); // 转账列表
        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 actionWithdraw() {
        $filter = $this->filterCondition([
            'SN' => 'W.SN',
            'WITHDRAW_PERIOD_NUM' => 'W.WITHDRAW_PERIOD_NUM',
            'filterStatus' => 'W.AUDIT_STATUS',
            'CREATED_AT' => 'W.CREATED_AT',
            'PAID_AT' => 'W.PAID_AT',
            'USER_NAME' => 'U.USER_NAME',
            'REAL_AMOUNT' => 'W.REAL_AMOUNT',
            //4047新增 “会员姓名”、“国家”、“提现银行”、“手机号"
            'USER_REAL_NAME' => 'U.REAL_NAME',
            'COUNTRY_NAME' => 'U.COUNTRY_ID',
            'OPEN_BANK' => 'U.OPEN_BANK',
            'MOBILE' => 'U.MOBILE',
        ]);
        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

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

        return static::notice($data);
    }

    /**
     * 后台新增提现
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawAdd() {
        if (Yii::$app->request->isPost) {// 新增会员提现成功
            return parent::edit(WithdrawForm::class, Yii::t('ctx', 'addedMemberSuccessfullyWithdrewCash'), 'addByAdmin', ['add'], null, function ($form, $result) {
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('申请为' . $user['USER_NAME'] . '提现' . $result['WITHDRAW_AMOUNT'], 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
        // 获取全部注册类型
        $regTypes = RegType::getTypes();
        return static::notice(['regTypes' => $regTypes]);
    }

    /**
     * 提现数据获取
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawGet() {
        $id = Yii::$app->request->get('id');
        $withdraw = Withdraw::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$withdraw) {
            return static::notice(Yii::t('ctx', 'dataDoesNotExists'), 400); // 数据不存在
        }
        $withdraw['BASE_INFO'] = Info::baseInfoZh($withdraw['USER_ID']);
        $withdraw['PLAN_PAID_AT'] = $withdraw['PLAN_PAID_AT'] ? Date::convert($withdraw['PLAN_PAID_AT']) : null;
        return static::notice(['id' => $withdraw['ID'], 'baseInfo' => $withdraw['BASE_INFO'], 'amount' => Tool::formatPrice($withdraw['AMOUNT']), 'planPaidAt' => $withdraw['PLAN_PAID_AT'], 'remark' => $withdraw['REMARK']]);
    }

    /**
     * 修改提现
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            $formModel = new WithdrawForm();
            $formModel->scenario = 'editByAdmin';
            $formModel->id = $id;
            if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->editByAdmin()) {
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('修改提现信息，ID为：' . $result['ID'], 1, $result['USER_ID'], $user['USER_NAME']);
                return static::notice(Yii::t('ctx', 'withdrawalInformationModifiedSuccessfully')); // 修改提现信息成功
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        return static::notice('Illegal request', 400); // 非法请求
    }

    /**
     * 改变状态
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawStatus() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            $formModel = new WithdrawForm();
            $formModel->scenario = 'statusByAdmin';
            $formModel->id = $id;
            if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->changeStatus()) {
                foreach ($result['logs'] as $k => $value) {
                    $userName = Info::getUserNameByUserId($k);
                    // Log::adminHandle('为会员' . $userName . '的提现流水号为' . $value . '改变提现状态至' . Withdraw::STATUS_NAME[$result['status']], 1, $k, $userName);
                }
                return static::notice(Yii::t('ctx', 'statusSettingSucceeded')); // 状态设置成功
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        return static::notice(Yii::t('ctx', 'illegalRequest'), 400); // 非法请求
    }

    /**
     * 提现明细导出到excel
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawExport() {
        $filter = $this->filterCondition([
            'SN' => 'W.SN',
            'WITHDRAW_PERIOD_NUM' => 'W.WITHDRAW_PERIOD_NUM',
            'filterStatus' => 'W.AUDIT_STATUS',
            'CREATED_AT' => 'W.CREATED_AT',
            'PAID_AT' => 'W.PAID_AT',
            'USER_NAME' => 'U.USER_NAME',
            'REAL_AMOUNT' => 'W.REAL_AMOUNT',
            //4047新增 “会员姓名”、“国家”、“提现银行”、“手机号"
            'USER_REAL_NAME' => 'U.REAL_NAME',
            'COUNTRY_NAME' => 'U.COUNTRY_ID',
            'OPEN_BANK' => 'U.OPEN_BANK',
            'MOBILE' => 'U.MOBILE',
        ]);
//        $selectedIds = \Yii::$app->request->get('selectedIds', []);
//        if ($selectedIds) {
//            $filter['condition'] .= " AND W.ID IN (" . implode(',', $selectedIds) . ")";
//        }
        if (isset($filter['request']['filterStatus'])) {
            $status = explode(',',$filter['request']['filterStatus']);
            $status = end($status);
            if (is_numeric($status)) {
                $filter['condition'] .= " AND W.AUDIT_STATUS = $status";
            }
        }
        if (isset($filter['request']['WITHDRAW_PERIOD_NUM'])) {
            
            $period = explode(',',$filter['request']['WITHDRAW_PERIOD_NUM']);
            $periodNum = isset($period[1]) ? $period[1] : '';
            if (is_numeric($periodNum)) {
                 $filter['condition'] .= " AND W.WITHDRAW_PERIOD_NUM = $periodNum";
            }
        }

        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

        $form = new FinanceExportForm();
        $result = $form->run(['condition' => $condition, 'params' => $params], Yii::t('ctx', 'exportWithdrawApplyExcelName')); // 提现申请
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 分页导入excel文件到待导入数据的表中
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionImportWithdrawsToExcelTable() {
        // 先上传到服务器文件
        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 Excel();
                $result = $excel->pageImportDataFromExcel('withdrawPaidFalse', $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('Error:' . $errorMsg, 400);
            }
        }
    }

    /**
     * 分页把待导入表中的数据导入到真正的数据中
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionImportWithdrawsPaidFalse() {
        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 Excel();
                $result = $excel->pageImportDataFromExcelTable('withdrawPaidFalse', $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('error:' . $errorMsg, 400);
            }
        }
    }

    /**
     * 发票管理
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceAudit() {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'createdAt' => 'IA.CREATED_AT',
            'regType' => 'IA.REG_TYPE',
            'filterStatus' => 'IA.AUDIT_STATUS',
            'INVOICE_CODE' => 'IA.INVOICE_CODE',
            'INVOICE_NUM' => 'IA.INVOICE_NUM',
            'INVOICE_DATE' => 'IA.INVOICE_DATE',
            'AMOUNT' => 'IA.AMOUNT',
            'SN' => 'W.SN',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $data = InvoiceAudit::lists($condition, $params, [
            'select' => 'IA.*,W.SN WITHDRAW_SN,U.URL INVOICE_URL',
            'orderBy' => 'IA.CREATED_AT DESC',
            'from' => InvoiceAudit::tableName() . ' AS IA',
            'join' => [
                ['LEFT JOIN', UserInfo::tableName() . ' AS UI', 'IA.USER_ID=UI.USER_ID'],
                ['LEFT JOIN', Uploads::tableName() . ' AS U', 'IA.UPLOAD_ID=U.ID'],
                ['LEFT JOIN', Withdraw::tableName() . ' AS W', 'IA.WITHDRAW_ID=W.ID'],
            ],
        ]);
        $auditStatus = array_column(Tool::paramConvert(\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 \yii\web\HttpException
     */
    public function actionInvoiceAuditAdd() {
        if (Yii::$app->request->isPost) {
            return parent::edit(InvoiceAuditForm::class, Yii::t('ctx', 'invoiceEnteredSuccessfully'), 'addByAdmin', ['addByAdmin'], null, function ($form, $result) {
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('申请为' . $user['USER_NAME'] . '发票录入', 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
        // 获取全部注册类型
        $regTypes = RegType::getTypes();
        return static::notice(['regTypes' => $regTypes]);
    }

    /**
     * 发票信息获取
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceAuditGet() {
        $id = Yii::$app->request->get('id');
        $invoiceAudit = InvoiceAudit::findOneAsArray('ID=:ID AND AUDIT_STATUS=:AUDIT_STATUS', [':ID' => $id, ':AUDIT_STATUS' => \Yii::$app->params['auditStatus']['un']['value']]);
        if (!$invoiceAudit) {
            return static::notice(['id' => null, 'withdrawId' => null, 'withdrawSn' => null, 'invoiceCode' => null, 'invoiceNum' => null, 'invoiceDate' => null, 'amount' => null, 'taxRate' => null, 'purchaserName' => null, 'purchaserRegisterNum' => null, 'purchaserAddress' => null, 'purchaserBank' => null, 'sellerName' => null, 'sellerRegisterNum' => null, 'sellerAddress' => null, 'sellerBank' => null, 'itemName' => null, 'invoiceRemark' => null, 'createRemark' => null]);
        }
        $invoiceAudit['BASE_INFO'] = Info::baseInfoZh($invoiceAudit['USER_ID']);
        $invoiceAudit['INVOICE_DATE'] = $invoiceAudit['INVOICE_DATE'] ? (Date::validator(str_replace(['年', '月', '日'], ['-', '-', ''], $invoiceAudit['INVOICE_DATE']))?Date::convert(str_replace(['年', '月', '日'], ['-', '-', ''], $invoiceAudit['INVOICE_DATE'])):null) : null;
        $withdraw = Withdraw::findOneAsArray('ID=:ID', [':ID' => $invoiceAudit['WITHDRAW_ID']], 'ID,SN');
        return static::notice(['id' => $invoiceAudit['ID'], 'withdrawId' => $withdraw['ID'], 'withdrawSn' => $withdraw['SN'], 'invoiceCode' => $invoiceAudit['INVOICE_CODE'], 'invoiceNum' => $invoiceAudit['INVOICE_NUM'], 'invoiceDate' => $invoiceAudit['INVOICE_DATE'], 'amount' => Tool::formatPrice($invoiceAudit['AMOUNT']), 'taxRate' => $invoiceAudit['TAX_RATE'], 'purchaserName' => $invoiceAudit['PURCHASER_NAME'], 'purchaserRegisterNum' => $invoiceAudit['PURCHASER_REGISTER_NUM'], 'purchaserAddress' => $invoiceAudit['PURCHASER_ADDRESS'], 'purchaserBank' => $invoiceAudit['PURCHASER_BANK'], 'sellerName' => $invoiceAudit['SELLER_NAME'], 'sellerRegisterNum' => $invoiceAudit['SELLER_REGISTER_NUM'], 'sellerAddress' => $invoiceAudit['SELLER_ADDRESS'], 'sellerBank' => $invoiceAudit['SELLER_BANK'], 'itemName' => $invoiceAudit['ITEM_NAME'], 'invoiceRemark' => $invoiceAudit['INVOICE_REMARK'], 'createRemark' => $invoiceAudit['CREATE_REMARK']]);
    }

    /**
     * 发票信息修改
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceAuditEdit() {
        $formModel = new InvoiceAuditForm();
        $formModel->scenario = 'editByAdmin';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->editByAdmin()) {
            $user = User::getBaseInfoFromRedis($result['USER_ID']);
            // Log::adminHandle('修改' . $user['USER_NAME'] . '发票录入数据', 1, $result['USER_ID'], $user['USER_NAME']);
            return static::notice(Yii::t('ctx', 'modifyInvoiceEntryCompleted'));
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 发票信息审核
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceAuditAudit() {
        $formModel = new InvoiceAuditForm();
        $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', 'reviewInvoiceDataCompleted'));
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 发票信息删除
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceAuditDelete() {
        $result = static::delete(InvoiceAudit::class, null, function ($selected) {
            InvoiceAuditForm::delete($selected);
            // Log::adminHandle('删除发票信息');
        }, true);
        return $result;
    }

    /**
     * 调整会员业绩审核列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPerfAuditList() {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'filterStatus' => 'PA.AUDIT_STATUS',
            'SYSTEM_NAME' => 'UI.SYSTEM_ID',
            'PV_1L' => 'PA.PV_1L',
            'SURPLUS_1L' => 'PA.SURPLUS_1L',
            'PV_2L' => 'PA.PV_2L',
            'SURPLUS_2L' => 'PA.SURPLUS_2L',
            'PV_3L' => 'PA.PV_3L',
            'SURPLUS_3L' => 'PA.SURPLUS_3L',
            'PV_4L' => 'PA.PV_4L',
            'SURPLUS_4L' => 'PA.SURPLUS_4L',
            'PV_5L' => 'PA.PV_5L',
            'SURPLUS_5L' => 'PA.SURPLUS_5L',
            'SURPLUS_LS' => 'PA.SURPLUS_LS',
            'PERF_TYPE_NAME' => 'PA.PERF_TYPE',
            'PERF_LOCATION_NAME' => 'PA.PERF_LOCATION',
            'PERF_BEFORE' => 'PA.PERF_BEFORE',
            'AMOUNT' => 'PA.AMOUNT',
            'PERF_AFTER' => 'PA.PERF_AFTER',
            'CREATED_AT' => 'PA.CREATED_AT',
            'AUDITED_AT' => 'PA.AUDITED_AT',
            'REMARK' => 'PA.REMARK',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new PerfAuditList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 会员业绩调整列表导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPerfAuditListExport() {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'filterStatus' => 'PA.AUDIT_STATUS',
            'SYSTEM_NAME' => 'UI.SYSTEM_ID',
            'PV_1L' => 'PA.PV_1L',
            'SURPLUS_1L' => 'PA.SURPLUS_1L',
            'PV_2L' => 'PA.PV_2L',
            'SURPLUS_2L' => 'PA.SURPLUS_2L',
            'PV_3L' => 'PA.PV_3L',
            'SURPLUS_3L' => 'PA.SURPLUS_3L',
            'PV_4L' => 'PA.PV_4L',
            'SURPLUS_4L' => 'PA.SURPLUS_4L',
            'PV_5L' => 'PA.PV_5L',
            'SURPLUS_5L' => 'PA.SURPLUS_5L',
            'SURPLUS_LS' => 'PA.SURPLUS_LS',
            'PERF_TYPE_NAME' => 'PA.PERF_TYPE',
            'PERF_LOCATION_NAME' => 'PA.PERF_LOCATION',
            'PERF_BEFORE' => 'PA.PERF_BEFORE',
            'AMOUNT' => 'PA.AMOUNT',
            'PERF_AFTER' => 'PA.PERF_AFTER',
            'CREATED_AT' => 'PA.CREATED_AT',
            'AUDITED_AT' => 'PA.AUDITED_AT',
            'REMARK' => 'PA.REMARK',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
        ]);
        $form = new FinanceExportForm();
        $result = $form->run($filter, Yii::t('ctx', 'memberPerformanceAdjustmentList'));
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 申请调整会员业绩
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionPerfApply() {
        if (\Yii::$app->request->isPost) { // 申请调整会员业绩成功
            return static::edit(ChangePerfForm::class, Yii::t('ctx', 'applicationAdjustMemberPerfSuccess'), 'add', ['add'], null, function ($formModel, $result) {
                // 添加操作日志
                // Log::adminHandle('申请调整会员' . $formModel->userName . '的' . $formModel->location . '区业绩，调整额度为：' . $formModel->amount);
            });
        }
        $periodNum = Period::sentMaxPeriodNum();
        return static::notice(['periodNum' => $periodNum]);
    }

    /**
     * 获取调整会员的业绩
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionPerfApplyGet() {
        $periodNum = Period::sentMaxPeriodNum();
        if (Period::find()->where('IS_SENT=:IS_SENT AND PERIOD_NUM>=:START_PERIOD_NUM AND PERIOD_NUM<=:END_PERIOD_NUM', [':IS_SENT' => Period::SEND_FINISH, ':START_PERIOD_NUM' => $periodNum + 1, ':END_PERIOD_NUM' => $periodNum + 1])->count() == 1) {
//            return static::notice('下一期【' . ($periodNum + 1) . '】已挂网，该期无法调整', 400);
            return static::notice(Yii::t('ctx', 'nextPeriodConnectedNetCannotAdjusted',[
                'periodNum' => $periodNum + 1
            ]), 400);
        }
        $userName = \Yii::$app->request->get('userName');
        if (!$userId = Info::getUserIdByUserName($userName)) {
            return static::notice(Yii::t('ctx', 'memberDoesNotExist'), 400); // 会员不存在
        }
        $perf = PerfAudit::getUserPerfAndPerfPeriod($userId, $periodNum);
        return static::notice(array_merge(['REAL_NAME' => Info::getUserRealNameByUserId($userId)], $perf));
    }

    /**
     * 获取会员业绩审核信息
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionPerfAuditGet() {
        $id = Yii::$app->request->get('id');
        $perfAudit = PerfAudit::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$perfAudit) {
            return static::notice(Yii::t('ctx', 'dataDoesNotExists'), 400); // 数据不存在
        }
        $perf = PerfAudit::getUserPerfAndPerfPeriod($perfAudit['USER_ID'], $perfAudit['PERIOD_NUM']);
        return static::notice(['userInfo'=>array_merge(['USER_NAME' => Info::getUserNameByUserId($perfAudit['USER_ID']),'REAL_NAME' => Info::getUserRealNameByUserId($perfAudit['USER_ID'])], $perf),'perfAudit'=>['periodNum'=>$perfAudit['PERIOD_NUM'],'perfType'=>$perfAudit['PERF_TYPE'],'location'=>$perfAudit['PERF_LOCATION'],'amount'=>Tool::formatPrice($perfAudit['AMOUNT']),'remark'=>$perfAudit['REMARK'],'id'=>$perfAudit['ID']]]);
    }

    /**
     * 审核通过会员业绩录入数据
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPerfAuditPass() {
        $formModel = new ChangePerfForm();
        $formModel->scenario = 'pass';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->pass()) {
            $user = User::getBaseInfoFromRedis($result['USER_ID']);
            // Log::adminHandle('审核通过' . $user['USER_NAME'] . '调整会员业绩录入数据', 1, $result['USER_ID'], $user['USER_NAME']);
            return static::notice(Yii::t('ctx', 'passReviewAdjustPerfSuccess'));
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 审核会员业绩
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPerfAudit() {
        $formModel = new ChangePerfForm();
        $formModel->scenario = 'changeAudit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->changeAudit()) {
            foreach ($result as $value) {
                $userName = Info::getUserNameByUserId($value['userId']);
                // Log::adminHandle('审核调整会员业绩录入数据' . $userName, 1, $value['userId'], $userName);
            }
            return static::notice(Yii::t('ctx', 'batchReviewMemberPerfCompletion'));
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 删除审核会员业绩信息
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPerfAuditDelete() {
        $changePerfForm = new ChangePerfForm();
        $result = static::delete(PerfAudit::class, function ($selected) use ($changePerfForm) {
            $changePerfForm->beforeDelete($selected);
            // Log::adminHandle('删除审核会员余额信息');
        }, function ($selected) use ($changePerfForm) {
            $changePerfForm->delete($selected);
            // Log::adminHandle('删除审核会员余额信息');
        }, true);
        return $result;
    }
    /**
     * 交易类型管理
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDealType() {
        $condition = '';
        $params = [];
        $data = DealType::lists($condition, $params, [
            'orderBy' => 'DT.IS_PRESET ASC,DT.SORT_ORDER DESC',
            'from' => DealType::tableName() . ' AS DT',
        ]);
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['CREATE_ADMIN_NAME'] = Admin::getAdminNameById($value['CREATE_ADMIN']);
            $data['list'][$key]['UPDATE_ADMIN_NAME'] = Admin::getAdminNameById($value['UPDATE_ADMIN']);
        }
        return static::notice($data);
    }

    /**
     * 交易类型录入
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDealTypeAdd() {
        if (Yii::$app->request->isPost) {
            return parent::edit(DealTypeForm::class, Yii::t('ctx', 'transactionTypeAddSuccess'), 'add', ['add'], null, function ($form, $result) {
                // Log::adminHandle('交易类型录入');
            });
        }
    }

    /**
     * 交易类型获取
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDealTypeGet() {
        $id = Yii::$app->request->get('id');
        $dealType = DealType::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$dealType) {
            return static::notice(Yii::t('ctx', 'dataDoesNotExists'), 400); // 数据不存在
        }
        return static::notice(['id' => $dealType['ID'], 'typeName' => $dealType['TYPE_NAME'], 'isEnable' => $dealType['IS_ENABLE'] ? true : false, 'isPreset' => $dealType['IS_PRESET'] ? true : false, 'createRemark' => $dealType['CREATE_REMARK'], 'sort' => $dealType['SORT_ORDER']]);
    }

    /**
     * 交易类型修改
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionDealTypeEdit() {
        $formModel = new DealTypeForm();
        $formModel->scenario = 'edit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->edit()) {
            // Log::adminHandle('修改交易类型');
            return static::notice(Yii::t('ctx', 'modifyTransactionTypeCompleted'));
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 交易类型删除
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionDealTypeDelete() {
        return static::notice(Yii::t('ctx', 'unableDelete'), 400);
        $result = static::delete(DealType::class, null, function ($selected) {
            DealTypeForm::delete($selected);
            // Log::adminHandle('删除交易类型');
        }, true);
        return $result;
    }

    /**
     * 分页导入excel文件到待导入数据的表中
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionImportChangeBalanceToExcelTable() {
        // 先上传到服务器文件
        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 Excel();
                $result = $excel->pageImportDataFromExcel('changeBalance', $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 \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionImportChangeBalance() {
        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 Excel();
                $result = $excel->pageImportDataFromExcelTable('changeBalance', $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($errorMsg, 400);
            }
        }
    }

    /**
     * 历史奖金余额
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionHistoryBonus() {
        $filter = $this->filterCondition([
            'USER_NAME' => 'USER_NAME',
            'REAL_NAME' => 'REAL_NAME',
            'DEC_LV_NAME' => 'DEC_LV',
            'EMP_LV_NAME' => 'EMP_LV',
            'IS_DEC' => 'IS_DEC',
//            'DEC_ROLE_NAME' => 'DEC_ROLE_ID',
            'SYSTEM_NAME' => 'SYSTEM_NAME',
            'BONUS' => 'BONUS',
//            'CF' => 'CF',
//            'LX' => 'LX',
            'WITHDRAW' => 'WITHDRAW',
//            'WITHDRAW_TAX' => 'WITHDRAW_TAX',
//            'WITHDRAW_DEDUCT' => 'WITHDRAW_DEDUCT',
            'WITHDRAW_REAL' => 'WITHDRAW_REAL',
            'WITHDRAW_FAIL' => 'WITHDRAW_FAIL',
            'USER_STATUS_NAME' => 'USER_STATUS',
            'USER_STATUS_AT' => 'USER_STATUS_AT',
//            'HIGHEST_EMP_LV_NAME' => 'HIGHEST_EMP_LV',
            'PERIOD_AT' => 'PERIOD_AT',
//            'DEC_DEC_ROLE_NAME' => 'DEC_DEC_ROLE_ID',
            'DEC_USER_NAME' => 'DEC_USER_NAME',
            'DEC_REAL_NAME' => 'DEC_REAL_NAME',
            'MOBILE' => 'MOBILE',
            'TEL' => 'TEL',
            'AREA' => [
                'FIELD' => ['PROVINCE', 'CITY', 'COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
//            'SUB_COM_NAME' => 'SUB_COM_ID',
//            'IS_DIRECT_SELLER' => 'IS_DIRECT_SELLER',
            'BACKUP_AT' => 'BACKUP_AT',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new HistoryBonusList();
        $data = $listObj->getList(['condition' => $condition, 'params' => $params]);
        return static::notice($data);
    }

    /**
     * 历史奖金余额导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionHistoryBonusExport() {
        $filter = $this->filterCondition([
            'USER_NAME' => 'USER_NAME',
            'REAL_NAME' => 'REAL_NAME',
            'DEC_LV_NAME' => 'DEC_LV',
            'EMP_LV_NAME' => 'EMP_LV',
            'IS_DEC' => 'IS_DEC',
            'DEC_ROLE_NAME' => 'DEC_ROLE_ID',
            'SYSTEM_NAME' => 'SYSTEM_NAME',
            'BONUS' => 'BONUS',
            'CF' => 'CF',
            'LX' => 'LX',
            'WITHDRAW' => 'WITHDRAW',
            'WITHDRAW_TAX' => 'WITHDRAW_TAX',
            'WITHDRAW_DEDUCT' => 'WITHDRAW_DEDUCT',
            'WITHDRAW_REAL' => 'WITHDRAW_REAL',
            'WITHDRAW_FAIL' => 'WITHDRAW_FAIL',
            'USER_STATUS_NAME' => 'USER_STATUS',
            'USER_STATUS_AT' => 'USER_STATUS_AT',
            'HIGHEST_EMP_LV_NAME' => 'HIGHEST_EMP_LV',
            'PERIOD_AT' => 'PERIOD_AT',
            'DEC_DEC_ROLE_NAME' => 'DEC_DEC_ROLE_ID',
            'DEC_USER_NAME' => 'DEC_USER_NAME',
            'DEC_REAL_NAME' => 'DEC_REAL_NAME',
            'MOBILE' => 'MOBILE',
            'TEL' => 'TEL',
            'AREA' => [
                'FIELD' => ['PROVINCE', 'CITY', 'COUNTY'],
                'BIND' => ['PROVINCE', 'CITY', 'COUNTY'],
            ],
            'SUB_COM_NAME' => 'SUB_COM_ID',
            'IS_DIRECT_SELLER' => 'IS_DIRECT_SELLER',
            'BACKUP_AT' => 'BACKUP_AT',
        ]);
        $form = new FinanceExportForm();
        $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\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRecharge()
    {
        $filter = $this->filterCondition([
            'SN' => 'R.SN',
            'USER_NAME' => 'UI.USER_NAME',
            'AMOUNT' => 'R.AMOUNT',
            'AUDIT_STATUS' => 'R.AUDIT_STATUS',
            'BANK_NO' => 'R.BANK_NO',
            'CREATED_AT' => 'R.CREATED_AT',
            'PAY_DATE' => 'R.PAY_DATE',
            //4047 国家筛选
            'COUNTRY_NAME' => 'U.COUNTRY_ID',
        ]);
        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

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

    /**
     * 提交充值申请
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRechargeType() {
        if (\Yii::$app->request->isPost) {
            $formModel = new RechargeForm();
            $formModel->scenario = 'updateByAdmin';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->updateType()) {
                return static::notice(Yii::t('app', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        return static::notice(['type'=>['Cash', 'Credit Card', 'Direct Banking']]);
    }

    /**
     * 充值导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRechargeExport() {
        $filter = $this->filterCondition([
            'SN' => 'R.SN',
            'USER_NAME' => 'UI.USER_NAME',
            'AMOUNT' => 'R.AMOUNT',
            'AUDIT_STATUS' => 'R.AUDIT_STATUS',
            'BANK_NO' => 'R.BANK_NO',
            'CREATED_AT' => 'R.CREATED_AT',
            'PAY_DATE' => 'R.PAY_DATE',
            //4047 国家筛选
            'COUNTRY_NAME' => 'U.COUNTRY_ID',
        ]);

        $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 U.COUNTRY_ID IN (" . implode(',', $quotedAdminCountry) . ")";
        }

        $form = new FinanceExportForm();
        $result = $form->run(['condition' => $condition, 'params' => $params], 'Recharge'); // 充值申请
        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\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRechargeStatus() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            $formModel = new RechargeForm();
            $formModel->scenario = 'statusByAdmin';
            //$formModel->id = $id;
            if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->changeStatus()) {
                foreach ($result['logs'] as $k => $value) {
                    $userName = Info::getUserNameByUserId($k);
                    // Log::adminHandle('为会员' . $userName . '的充值流水号为' . $value . '改变充值状态至' . Recharge::STATUS_NAME[$result['status']], 1, $k, $userName);
                }
                return static::notice(Yii::t('ctx', 'statusSettingSucceeded')); // 状态设置成功
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        // 所有开户行
        $statusArray = [
            2=>Yii::t('ctx', 'backendApiControllersFinaceRechargeStatusApprove'),
            3=>Yii::t('ctx', 'backendApiControllersFinaceRechargeStatusReject'),
        ]; // 2=>'审核通过',3=>'审核拒绝'
        return static::notice(['statusArray' => $statusArray]);
    }

    /**
     * 连点操作校验码获取
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionMultPoint() {
        $verifyCode = $this->_random(8,1);
        $adminId = \Yii::$app->user->id;
        if (\Yii::$app->request->isPost) {
            $opType = Yii::$app->request->post('opType');
            if($opType==1){
                $redisName = 'balanceCode';
            }elseif ($opType==2){
                $redisName = 'withdrawAudit';
            }
        }
        \Yii::$app->redis->set($redisName.'_'.$adminId,$verifyCode);
        return static::notice([$redisName => $verifyCode]);
    }

    /**
     * 生成随机数
     * @param $length
     * @param int $numeric
     * @return string
     */
    private function _random($length, $numeric = 0) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        $hash = '';
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed[mt_rand(0, $max)];
        }
        return $hash;
    }
}