<?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\exportForms\ReconsumeExportForm;
use backendApi\modules\v1\models\lists\reconsume\FlowList;
use backendApi\modules\v1\models\lists\reconsume\PoolList;
use backendApi\modules\v1\models\lists\reconsume\ReconsumeAuditList;
use common\helpers\Cache;
use common\helpers\Form;
use common\helpers\Log;
use common\helpers\Tool;
use common\helpers\user\Reconsume;
use common\helpers\user\Info;
use common\libs\export\module\ReconsumeExport;
use common\models\forms\ReconsumeForm;
use common\models\Period;
use common\models\ReconsumeAudit;
use common\models\ReconsumePool;
use common\models\ReconsumePoolFlow;
use common\models\User;
use common\models\UserInfo;
use Yii;

class ReconsumeController extends BaseController {
    public $modelClass = ReconsumePool::class;

    /**
     * 复销池余额列表
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPoolList() {
        $filter = $this->filterCondition([
            'userIds' => 'USER_ID',
            'UNUSED_PV' => 'UNUSED_PV',
            'UNUSED_MONTH' => 'UNUSED_MONTH',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new PoolList();
        $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
        return static::notice($data);
    }

    /**
     * 复销池余额列表导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPoolListExport() {
        $filter = $this->filterCondition([
            'userIds' => 'USER_ID',
            'UNUSED_PV' => 'UNUSED_PV',
            'UNUSED_MONTH' => 'UNUSED_MONTH',
        ]);
        $form = new ReconsumeExportForm();
        $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 actionChangeAuditList() {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'filterStatus' => 'RA.AUDIT_STATUS',
            'TYPE_NAME' => 'RA.TYPE',
            'CHANGE_PV' => 'RA.CHANGE_PV',
            'CHANGE_MONTH' => 'RA.CHANGE_MONTH',
            'REMARK_IS_SHOW' => 'RA.REMARK_IS_SHOW',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'AUDIT_ADMIN_NAME' => 'ADMA.ADMIN_NAME',
            'CREATED_AT' => 'RA.CREATED_AT',
            'AUDITED_AT' => 'RA.AUDITED_AT',
            'CREATE_REMARK' => 'RA.CREATE_REMARK',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new ReconsumeAuditList();
        $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
        return static::notice($data);
    }

    /**
     * 复销余额调整审核列表导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionChangeAuditListExport() {
        $filter = $this->filterCondition([
            'userIds' => 'UI.USER_ID',
            'filterStatus' => 'RA.AUDIT_STATUS',
            'TYPE_NAME' => 'RA.TYPE',
            'CHANGE_PV' => 'RA.CHANGE_PV',
            'CHANGE_MONTH' => 'RA.CHANGE_MONTH',
            'REMARK_IS_SHOW' => 'RA.REMARK_IS_SHOW',
            'CREATE_ADMIN_NAME' => 'ADMC.ADMIN_NAME',
            'AUDIT_ADMIN_NAME' => 'ADMU.ADMIN_NAME',
            'CREATED_AT' => 'RA.CREATED_AT',
            'AUDITED_AT' => 'RA.AUDITED_AT',
            'CREATE_REMARK' => 'RA.CREATE_REMARK',
        ]);
        $form = new ReconsumeExportForm();
        $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\httpclient\Exception
     * @throws \yii\web\HttpException
     *
     */
    public function actionChangeAuditAdd() {
        $userName = Yii::$app->request->get('userName');
        if (Yii::$app->request->isPost) {
            return parent::edit(ReconsumeForm::class, '申请调整复销余额成功', 'changeAdd', ['changeAdd'], null, function ($form, $result) {
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('申请为' . $user['USER_NAME'] . '调整复销余额', 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
        if (!$userName) {
            return static::notice('会员不正确');
        }
        // 获取复销的可用余额和剩余次数
        $reConsumePool = Reconsume::getUserReconsumePoolByUserName($userName);
        return static::notice($reConsumePool);
    }

    /**
     * 复销变动信息
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionChangeAuditGet() {
        $id = Yii::$app->request->get('id');
        $reconsumAudit = ReconsumeAudit::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$reconsumAudit) {
            return static::notice('The data does not exist', 400); // 数据不存在
        }
        $reconsumAudit['BASE_INFO'] = Info::baseInfoZh($reconsumAudit['USER_ID']);
        $reConsumePool = Reconsume::getUserReconsumePool($reconsumAudit['USER_ID']);
        return static::notice(['id' => $reconsumAudit['ID'], 'baseInfo' => $reconsumAudit['BASE_INFO'], 'balance' => $reConsumePool, 'type' => $reconsumAudit['CHANGE_PV'] != 0 ? ReconsumeForm::TYPE_BALANCE : ReconsumeForm::TYPE_MONTH, 'changePv' => Tool::formatPrice($reconsumAudit['CHANGE_PV']), 'changeMonth' => $reconsumAudit['CHANGE_MONTH'], 'remark' => $reconsumAudit['CREATE_REMARK'], 'isShow' => $reconsumAudit['REMARK_IS_SHOW']]);
    }

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

    /**
     * 审核通过复销月录入数据
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionChangeAuditPass() {
        $formModel = new ReconsumeForm();
        $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('审核通过调整复销池余额完成');
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

    /**
     * 审核
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     * @throws \yii\httpclient\Exception
     * @throws \yii\web\HttpException
     */
    public function actionChangeAudit() {
        $formModel = new ReconsumeForm();
        $formModel->scenario = 'changeAudit';
        if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->changeAudit()) {
            return static::notice('批量审核/拒绝调整复销池余额完成');
        }
        return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
    }

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

    /**
     * 扣除复销审核列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDeductAuditList() {
        $filter = $this->filterCondition([
            'userIds' => 'RA.USER_ID',
            'filterStatus' => 'RA.AUDIT_STATUS',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $condition .= ' AND RA.TYPE=:TYPE ';
        $params[':TYPE'] = ReconsumeAudit::TYPE_RECONSUME;
        $data = ReconsumeAudit::lists($condition, $params, [
            'from' => ReconsumeAudit::tableName() . ' AS RA',
            'orderBy' => 'RA.CREATED_AT DESC',
        ]);
        $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\base\InvalidConfigException
     * @throws \yii\db\Exception
     * @throws \yii\httpclient\Exception
     * @throws \yii\web\HttpException
     */
    public function actionDeductAuditAdd() {
        $userName = Yii::$app->request->get('userName');
        if (Yii::$app->request->isPost) {
            return parent::edit(ReconsumeForm::class, '扣除月复销成功', 'deductReConsumeAdd', ['deductReConsumeAdd'], null, function ($form, $result) {
                //$user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('为' . $user['USER_NAME'] . '扣除月复销', 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
        if ($userName) {
            // 获取复销的可用余额和剩余次数
            $reConsumePool = Reconsume::getUserReconsumePoolByUserName($userName);
            $sysConfig = Cache::getSystemConfig();
            $deductPv = $sysConfig['reConsumePerf']['VALUE'];
            return static::notice(['balance'=>$reConsumePool,'deductPv'=>$deductPv]);
        }else{
            $period = Period::instance();
            $year = $period->getNowYear();
            $sentMaxPeriodNum = Period::sentMaxPeriodNum();
            $month = $period->getMonth($sentMaxPeriodNum);
            return static::notice(['year'=>$year,'month'=>$month]);
        }
    }

    /**
     * 扣除月复销审核
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDeductAudit() {
        $id = Yii::$app->request->get('id', 0);
        if (Yii::$app->request->isPost) {
            return parent::edit(ReconsumeForm::class, '审核完成', 'deductReConsumeAudit', ['deductReConsumeAudit'], function ($formModel) use ($id) {
                $formModel->id = $id;
            }, function ($form, $result) {
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('审核为' . $user['USER_NAME'] . '扣除月复销', 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
    }

    /**
     * 扣复销(合格不合格)
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDeduct() {
        if (Yii::$app->request->isPost) {
            return parent::edit(ReconsumeForm::class, '扣除成功', 'deductReConsume', ['deductReConsume'], null, function ($form, $result) {
                if ($form->isPass) {
                    $handle = '合格';
                } else {
                    $handle = '不合格';
                }
                $user = User::getBaseInfoFromRedis($result['USER_ID']);
                // Log::adminHandle('为' . $user['USER_NAME'] . '扣除月复销' . $handle, 1, $result['USER_ID'], $user['USER_NAME']);
            });
        }
    }

    /**
     * 复销流水
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionFlowList() {
        $filter = $this->filterCondition([
            'userIds' => 'USER_ID',
            'filterStatus' => 'RECONSUME_POOL_TYPE',
            'RECONSUME_POOL_SN' => 'RECONSUME_POOL_SN',
            'LAST_DEC_LV_NAME' => 'LAST_DEC_LV',
            'LAST_EMP_LV_NAME' => 'LAST_EMP_LV',
            'LAST_STATUS_NAME' => 'LAST_STATUS',
            'DEAL_TYPE_NAME' => 'DEAL_TYPE',
            'DEDUCT_PV' => 'DEDUCT_PV',
            'UNUSED_PV' => 'UNUSED_PV',
            'DEDUCT_MONTH' => 'DEDUCT_MONTH',
            'UNUSED_MONTH' => 'UNUSED_MONTH',
            'CALC_MONTH' => 'CALC_MONTH',
            'CREATED_AT' => 'CREATED_AT',
            'REMARK' => 'REMARK',
            'ADMIN_NAME' => 'ADMIN_NAME',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];
        $listObj = new FlowList();
        $data = $listObj->getList(['condition'=>$condition, 'params'=>$params]);
        return static::notice($data);
    }

    /**
     * 复销流水导出
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionFlowListExport() {
        $filter = $this->filterCondition([
            'userIds' => 'USER_ID',
            'filterStatus' => 'RECONSUME_POOL_TYPE',
            'RECONSUME_POOL_SN' => 'RECONSUME_POOL_SN',
            'LAST_DEC_LV_NAME' => 'LAST_DEC_LV',
            'LAST_EMP_LV_NAME' => 'LAST_EMP_LV',
            'LAST_STATUS_NAME' => 'LAST_STATUS',
            'DEAL_TYPE_NAME' => 'DEAL_TYPE',
            'DEDUCT_PV' => 'DEDUCT_PV',
            'UNUSED_PV' => 'UNUSED_PV',
            'DEDUCT_MONTH' => 'DEDUCT_MONTH',
            'UNUSED_MONTH' => 'UNUSED_MONTH',
            'CALC_MONTH' => 'CALC_MONTH',
            'CREATED_AT' => 'CREATED_AT',
            'REMARK' => 'REMARK',
            'ADMIN_NAME' => 'ADMIN_NAME',
        ]);
        $form = new ReconsumeExportForm();
        $result = $form->run($filter, '复销流水列表');
        if (!$result) {
            return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
        }
        return static::notice(Yii::t('ctx', 'startExporting')); // 导出开始，请到文件管理-导出文件查看
    }

    /**
     * 不能扣除复销的月份
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionCantDeductMonth(){
        $userName = Yii::$app->request->get('userName');
        $year = Yii::$app->request->get('year');
        $userId = Info::getUserIdByUserName($userName);
        return Reconsume::cantDeductMonth($userId, $year);
    }

    /**
     * 流水交易类型
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionGetFlowDealType(){
        return static::notice(['dealTypes'=>Reconsume::TYPE]);
    }
}