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

namespace frontendApi\modules\v1\controllers;

use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\user\Balance;
use common\helpers\user\Cash;
use common\helpers\user\Info;
use common\helpers\user\Reconsume;
use common\models\forms\RechargeForm;
use common\models\forms\TransferBonusForm;
use common\models\forms\TransferForm;
use common\models\forms\UploadForm;
use common\models\forms\WithdrawForm;
use common\models\InvoiceAudit;
use common\models\OpenBank;
use common\models\PerfPeriod;
use common\models\Period;
use common\models\Recharge;
use common\models\ReconsumePoolFlow;
use common\models\Region;
use common\models\RegType;
use common\models\Transfer;
use common\models\Uploads;
use common\models\UserInfo;
use common\models\Withdraw;
use yii\helpers\Json;
use yii\web\UploadedFile;

class FinanceController extends BaseController {
    public $modelClass = Withdraw::class;
    /**
     * 会员复销池余额流水
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReconsumePoolFlow() {
        $showReconsumePoolFlowMonth = Cache::getSystemConfig()['showReconsumePoolFlowMonth']['VALUE'];
        $condition = ' AND USER_ID=:USER_ID AND CREATED_AT>:CREATED_AT AND DEAL_TYPE!=:DEAL_TYPE';
        $params[':USER_ID'] = \Yii::$app->user->id;
        $params[':CREATED_AT'] = Date::nowTime() - $showReconsumePoolFlowMonth * 30 * 86400;
        $params[':DEAL_TYPE'] = Reconsume::TYPE_AUDIT_MONTH;
        $data = ReconsumePoolFlow::lists($condition, $params, [
            'SELECT' => 'DEAL_TYPE,DEDUCT_PV,CREATED_AT,REMARK,REMARK_IS_SHOW',
            'orderBy' => 'CREATED_AT DESC',
        ]);
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['DEAL_TYPE_NAME'] = Reconsume::TYPE[$value['DEAL_TYPE']]['label'];
            if ($value['REMARK_IS_SHOW'] == 0) $data['list'][$key]['REMARK'] = '';
        }
        return static::notice($data);
    }

    /**
     * 提现列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdraw() {
        $yearMonth = \Yii::$app->request->get('yearMonth');
        if ($yearMonth) {
            if (!Date::isYearMonth($yearMonth)) {
                return static::notice('无效参数', 400);
            }
        } else {
            $period = Period::instance();
            $yearMonth = $period->getNowYearMonth();
        }
        $showWithdrawPeriodNum = Cache::getSystemConfig()['showWithdrawPeriodNum']['VALUE'];
        $periodArr = Period::getNearlyPeriodNum($showWithdrawPeriodNum);
        $condition = ' AND W.USER_ID=:USER_ID AND (W.AUDIT_STATUS!=:AUDIT_STATUS OR (W.AUDIT_STATUS=:AUDIT_STATUS AND W.WITHDRAW_PERIOD_NUM>=:PERIOD_NUM_MIN AND W.WITHDRAW_PERIOD_NUM<=:PERIOD_NUM_MAX))';
        $params = [':USER_ID' => \Yii::$app->user->id,':AUDIT_STATUS'=>Withdraw::STATUS_PAID,':PERIOD_NUM_MIN' => min($periodArr), ':PERIOD_NUM_MAX'=> max($periodArr)];
        $data = Withdraw::lists($condition, $params, [
            'useSlaves' => true,
            'select' => 'W.ID,W.USER_ID,W.IS_AUTO_WITHDRAW,W.AMOUNT,W.FEES,W.REAL_AMOUNT,W.AUDIT_STATUS,W.CREATED_AT,W.PAID_AT,W.PAY_TYPE,W.PAID_FAIL_REMARK,W.REMARK,W.BACK_REMARK,W.INVOICE_ID,IA.AMOUNT INVOICE_AMOUNT,IA.AUDIT_STATUS INVOICE_AUDIT_STATUS,IA.UPLOAD_ID',
            'from' => Withdraw::tableName() . ' AS W',
            'join' => [
                ['LEFT JOIN', InvoiceAudit::tableName() . ' AS IA', 'W.ID=IA.WITHDRAW_ID'],
            ],
            'yearMonth' => $yearMonth,
            'orderBy' => 'W.CREATED_AT DESC',
            //'with' => 'openBank',
        ]);
        $auditStatus = array_column(\Yii::$app->params['auditStatus'], null, 'value');
        foreach ($data['list'] as $key => $value) {
            $baseInfo = Info::baseInfo($value['USER_ID']);
            $data['list'][$key]['USER_NAME'] = $baseInfo['USER_NAME'];
            $data['list'][$key]['REAL_NAME'] = $baseInfo['REAL_NAME'];
            $data['list'][$key]['STATUS_NAME'] = Withdraw::STATUS_NAME[$value['AUDIT_STATUS']];
            $data['list'][$key]['INVOICE_STATUS_NAME'] = isset($value['INVOICE_AUDIT_STATUS'])?$auditStatus[$value['INVOICE_AUDIT_STATUS']]['label']:'未传发票';
        }
        return static::notice($data);
    }

    /**
     * 提交提现申请
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawAdd() {
        if (\Yii::$app->request->isPost) {
            $formModel = new WithdrawForm();
            $formModel->scenario = 'addByUser';
            $checkStatus = $formModel->checkHasIdCardInfo();
            switch ($checkStatus) {
                case 0:
                    if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->add()) {
                        $rtn =  static::notice('提现申请已提交，请等待审核');
                    } else {
                        $rtn = static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
                    }
                    break;
                case -1:
                    $rtn = static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
                    break;
                case -2:
                    $rtn = static::notice(Form::formatErrorsForApi($formModel->getErrors()), 424);
                    break;
                default:
                    $rtn = static::notice('状态错误', 400);
                    break;
            }

            return $rtn;

        } else {
            return static::notice('非法请求', 400);
        }
    }

    /**
     * 提现连点校验
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionWdMultPoint() {
        $formModel = new WithdrawForm();
        $withdrawCode = $formModel->wdcode(8,1);
        $uid = \Yii::$app->user->id;
        \Yii::$app->redis->set('withdrawCode_'.$uid,$withdrawCode);
        return static::notice(['withdrawCode' => $withdrawCode]);
    }

    /**
     * 提现退回
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawBack() {
        return static::notice('非法请求', 400);
        if (\Yii::$app->request->isPost) {
            $formModel = new WithdrawForm();
            $formModel->scenario = 'backByUser';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->backByUser()) {
                return static::notice('提现已退回');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            return static::notice('非法请求', 400);
        }
    }

    /**
     * 判断并获取提现的会员信息
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChkWithdrawUser() {
        $uid = \Yii::$app->user->id;
        if (!Info::isVerified($uid)) {
            return static::notice('未实名验证无法提现', 400);
        }
        $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $uid], 'IS_BIND,IS_BIND_MAIN,IS_AUTO_WITHDRAW,REG_TYPE,TRANSFER_PROP');
//        if ($userInfo['IS_BIND'] == 1 && $userInfo['IS_BIND_MAIN'] == 0) {
//            return static::notice('附属会员无法提现', 400);
//        }
//        if (!Withdraw::allowWithdraw()) {
//            return static::notice('未到提现日期，请在每月挂网后第一周申请提现', 400);
//        }
//        if (Withdraw::hasThisMonthWithdraw($uid)) {
//            return static::notice('提现失败，每月只可以提现一次', 400);
//        }
//        if (Withdraw::existWaitAudit($uid)) {
//            return static::notice('提现失败，您存在未审核的提现记录', 400);
//        }
        //是否显示服务协议
        $regType = RegType::findOneAsArray('ID=:ID', [':ID' => $userInfo['REG_TYPE']], 'IS_PACT');
        $path = \Yii::getAlias('@common/runtime/datas/pact.php');
        if (!file_exists($path)) {
            $oneData = [];
        } else {
            $oneData = include $path;
        }
//        $isCanTransferProp = Cache::getSystemConfig()['isCanTransferProp']['VALUE'];
//        if ($isCanTransferProp == 0) {
//            $userInfo['WITHDRAW_PROP'] = 100;
//        } else {
//            $userInfo['WITHDRAW_PROP'] = 100 - $userInfo['TRANSFER_PROP'];
//        }
        $minAmount = Cache::getSystemConfig()['manualWithdrawMinAmount']['VALUE'] ?? 0;
        $fee = Cache::getSystemConfig()['withdrawFee']['VALUE'] ?? 0;
        return static::notice(['userInfo' => $userInfo, 'isPact' => $regType['IS_PACT'], 'content' => $oneData['CONTENT'] ?? '', 'withdrawFee'=>$fee]);
    }

    /**
     * 归集附属会员奖金
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionCollectBind() {
        $transferBonusForm = new TransferBonusForm();
        if ($totals=$transferBonusForm->collectBind(\Yii::$app->user->id)) {
            return static::notice('归集完成，归集金额'.$totals);
        } else {
            if($totals==0){
                return static::notice('归集完成，归集金额'.$totals);
            }else{
                return static::notice(Form::formatErrorsForApi($transferBonusForm->getErrors()), 400);
            }
        }
    }

    /**
     * 上传发票之前
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceBeforeAdd() {
        $id = \Yii::$app->request->get('id');
        $withdraw = Withdraw::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$withdraw) {
            return static::notice('数据不存在', 400);
        }
        $uploadInvoiceTip = Cache::getSystemConfig()['uploadInvoiceTip']['VALUE'];
        if ($withdraw['AUDIT_STATUS'] == Withdraw::STATUS_APPLIED) {
            return static::notice(['addInvoiceTips' => $uploadInvoiceTip]);
        } else {
            return static::notice('该提现记录无法上传发票', 400);
        }
    }

    /**
     * 上传发票
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceAdd() {
        $id = \Yii::$app->request->get('id');
        $withdraw = Withdraw::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$withdraw) {
            return static::notice('数据不存在', 400);
        }
        if (\Yii::$app->request->isPost) {
            $formModel = new UploadForm();
            $formModel->scenario = 'invoiceFront';
            $formModel->file = UploadedFile::getInstanceByName('file');
            $formModel->withdrawId = $withdraw['ID'];
            $formModel->remark = '提现'.$withdraw['SN'].'发票';
            //$formModel->token = \Yii::$app->request->post('uploadToken');
            $formModel->token = \Yii::$app->request->request('uploadToken');
            if ($formModel->file && $formModel->upload()) {
                return static::notice('上传成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 显示上传的发票
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionInvoiceShow() {
        $id = \Yii::$app->request->get('id');
        $uploads = Uploads::findOneAsArray('ID=:ID', [':ID' => $id],'URL');
        if (!$uploads) {
            return static::notice('数据不存在', 400);
        }
        return static::notice($uploads['URL']);
    }

    /**
     * 获取可用余额
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionAvailableBalance() {
        $data['bonus'] = Balance::getAvailableBalance(\Yii::$app->user->id);
        $data['cash'] = Cash::getAvailableBalance(\Yii::$app->user->id);
        $data['point'] = Balance::getBalanceReconsumePoints(\Yii::$app->user->id);
        return static::notice($data);
    }

    /**
     * 查看业绩
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionPerf() {
        $yearMonth = \Yii::$app->request->get('yearMonth');
        if ($yearMonth) {
            if (!Date::isYearMonth($yearMonth)) {
                return static::notice('无效参数', 400);
            }
        } else {
            $period = Period::instance();
            $yearMonth = $period->getNowYearMonth();
        }
        $data = PerfPeriod::lists('AND P.USER_ID=:USER_ID AND PN.IS_SENT=1', [':USER_ID' => \Yii::$app->user->id], [
            'select' => 'P.*',
            'yearMonth' => $yearMonth,
            'from' => PerfPeriod::tableName() . ' AS P',
            'join' => [
                ['LEFT JOIN', Period::tableName() . ' AS PN', 'P.PERIOD_NUM=PN.PERIOD_NUM']
            ],
            'orderBy' => 'P.PERIOD_NUM DESC',
        ]);
        $data['request']['yearMonth'] = $yearMonth;
        return static::notice($data);
    }

    /**
     * 转账列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionTransferList() {
//        $filter = $this->filterCondition([
//            'OUT_WALLET' => 'OUT_WALLET',
//            'userName' => 'LAST_IN_USER_NAME',
//            'LAST_IN_REAL_NAME' => 'LAST_IN_REAL_NAME',
//            'IN_WALLET' => 'IN_WALLET',
//            'CREATED_AT' => 'CREATED_AT',
//        ]);
//        $condition = $filter['condition'];
//        $params = $filter['params'];
        $condition = ' AND OUT_UID=:OUT_UID AND PERIOD_NUM>=:PERIOD_NUM_MIN AND PERIOD_NUM<=:PERIOD_NUM_MAX';

        $LAST_IN_USER_NAME = \Yii::$app->request->get('userName');
        if($LAST_IN_USER_NAME){
            $condition.= ' AND LAST_IN_USER_NAME=:LAST_IN_USER_NAME';
            $params[':LAST_IN_USER_NAME'] = $LAST_IN_USER_NAME;
        }
        $LAST_IN_REAL_NAME = \Yii::$app->request->get('realName');
        if($LAST_IN_REAL_NAME){
            $condition.= ' AND LAST_IN_REAL_NAME=:LAST_IN_REAL_NAME';
            $params[':LAST_IN_REAL_NAME'] = $LAST_IN_REAL_NAME;
        }
        $IN_WALLET = \Yii::$app->request->get('inWallet');
        if($IN_WALLET){
            $condition.= ' AND IN_WALLET=:IN_WALLET';
            $params[':IN_WALLET'] = $IN_WALLET;
        }
        $OUT_WALLET = \Yii::$app->request->get('outWallet');
        if($OUT_WALLET){
            $condition.= ' AND OUT_WALLET=:OUT_WALLET';
            $params[':OUT_WALLET'] = $OUT_WALLET;
        }
        $dateRange = \Yii::$app->request->get('dateRange', '');
        if ($dateRange) {
            $condition .= " AND CREATED_AT>:CREATED_START AND CREATED_AT<:CREATED_END";
            $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
            $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
        }


        //获取可以查看几期流水
        $showTransferPeriodNum = Cache::getSystemConfig()['showTransferPeriodNum']['VALUE'];
        $periodArr = Period::getNearlyPeriodNum($showTransferPeriodNum);


        $params[':OUT_UID'] = \Yii::$app->user->id;
        $params[':PERIOD_NUM_MIN'] = min($periodArr);
        $params[':PERIOD_NUM_MAX']= max($periodArr);
        //$params = [':OUT_UID' => \Yii::$app->user->id,':PERIOD_NUM_MIN' => min($periodArr), ':PERIOD_NUM_MAX'=> max($periodArr)];

        $data = Transfer::lists($condition, $params, [
            'select' => 'OUT_WALLET,LAST_IN_USER_NAME,LAST_IN_REAL_NAME,IN_WALLET,ORI_AMOUNT,FEE,AMOUNT,CREATED_AT,REMARK',
            'from' => Transfer::tableName(),
        ]);
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['OUT_WALLET_NAME'] = Transfer::WALLET_NAME[$data['list'][$key]['OUT_WALLET']];
            $data['list'][$key]['IN_WALLET_NAME'] = Transfer::WALLET_NAME[$data['list'][$key]['IN_WALLET']];
        }
        //是否显示手续费
        $transferConfig = Json::decode(Cache::getSystemConfig()['allowWallet']['VALUE']);
        $showFee = false;
        foreach ($transferConfig as $value){
            if($value['fee']!=0){
                $showFee=true;
                break;
            }
        }
        $data['showFee'] = $showFee;
        return static::notice($data);
    }

    /**
     * 转账
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionTransferAdd() {
        if (\Yii::$app->request->isPost) {
            $formModel = new TransferForm();
            $formModel->scenario = 'transfer';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->transfer()) {
                return static::notice('转账成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }

    }

    /**
     * 转账连点校验
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionMultPoint() {
        $formModel = new TransferForm();
        $transferCode = $formModel->random(8,1);
        $uid = \Yii::$app->user->id;
        \Yii::$app->redis->set('transferCode_'.$uid,$transferCode);
        return static::notice(['transferCode' => $transferCode]);
    }

    /**
     * 检查转账资格
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionChkTransferUser() {
        $uid = \Yii::$app->user->id;
        if (!Info::isVerified($uid)) {
            return static::notice('未实名验证无法转账', 400);
        }
        $sysConfig = Cache::getSystemConfig();
        if(!$sysConfig['transferOpen']['VALUE']){
            return static::notice('转账功能未启用', 400);
        }
        $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $uid], 'ALLOW_TRANSFER,TRANSFER_PROP');
        if($userInfo['ALLOW_TRANSFER']==0){
            return static::notice('您不允许转账', 400);
        }
        $isCanTransferProp = Cache::getSystemConfig()['isCanTransferProp']['VALUE'];
        if($isCanTransferProp==0){
            $userInfo['TRANSFER_PROP']=100;
        }
        //获取转账的设置
        $transferConfig = Json::decode($sysConfig['allowWallet']['VALUE']);
        $arr = [];
        foreach ($transferConfig as $key=>$value){
            if($value['isOpen']==0) continue;
            $arr[]=['typeId'=>$key+1,'out'=>$value['out'],'in'=>$value['in'],'fee'=>$value['fee'],'outName'=>Transfer::WALLET_NAME[$value['out']],'inName'=>Transfer::WALLET_NAME[$value['in']]];
        }
        if(count($arr)==0){
            return static::notice('没有可用的转账类型', 400);
        }
        return static::notice(['userInfo' => $userInfo, 'transferConfig'=>$arr]);
    }

    /**
     * 充值列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRecharge() {
        $condition = ' AND USER_ID=:USER_ID';
        $params = [':USER_ID' => \Yii::$app->user->id];
        $data = Recharge::lists($condition, $params, [
            'from' => Recharge::tableName(),
            'orderBy' => 'CREATED_AT DESC',
        ]);
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['OPEN_BANK_NAME'] = $value['OPEN_BANK'] ? OpenBank::getCnName($value['OPEN_BANK']) : '';
            //$data['list'][$key]['BANK_PROVINCE_NAME'] = $value['BANK_PROVINCE'] ? Region::getCnName($value['BANK_PROVINCE']) : '';
            //$data['list'][$key]['BANK_CITY_NAME'] = $value['BANK_CITY'] ? Region::getCnName($value['BANK_CITY']) : '';
            //$data['list'][$key]['BANK_COUNTY_NAME'] = $value['BANK_COUNTY'] ? Region::getCnName($value['BANK_COUNTY']) : '';
            $data['list'][$key]['STATUS_NAME'] = Recharge::STATUS_NAME[$value['AUDIT_STATUS']];
        }
        return static::notice($data);
    }

    /**
     * 提交充值申请
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionRechargeAdd() {
        if (\Yii::$app->request->isPost) {
            $formModel = new RechargeForm();
            $formModel->scenario = 'addByUser';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->add()) {
                return static::notice('充值申请已提交，请等待审核');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        // 所有开户行
        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
        return static::notice(['allOpenBank' => $allOpenBank]);
    }

    /**
     * 上传充值凭证
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionProveAdd() {
        $id = \Yii::$app->request->get('id');
        if (\Yii::$app->request->isPost) {
            $formModel = new UploadForm();
            $formModel->scenario = 'proveFront';
            $formModel->file = UploadedFile::getInstanceByName('file');
            $formModel->token = \Yii::$app->request->request('uploadToken');
            $formModel->rechargeId = $id;
            if ($formModel->file && $formModel->upload()) {
                return static::notice('上传成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            $token = Cache::setUploadToken();
            return static::notice($token);
        }
    }

}