<?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 common\helpers\Cache;
use common\helpers\Excel;
use common\helpers\http\RemoteUploadApi;
use common\helpers\Tool;
use common\models\ExcelImport;
use common\models\Export;
use common\models\ExportFile;
use common\models\forms\UploadForm;
use common\models\forms\WithdrawForm;
use common\models\Uploads;
use common\models\UserInfo;
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;
use yii\web\UploadedFile;

class FileController extends BaseController
{
    public $modelClass = Uploads::class;
    public function behaviors() {
        $behaviors = parent::behaviors();
        //$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    /**
     * 导出文件管理
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionExport(){
        $filter = $this->filterCondition([
            'moduleName' => 'MODULE_NAME',
            'createdAt' => 'CREATED_AT',
            'EXPORT_NAME' => 'EXPORT_NAME',
            'STARTED_AT' => 'STARTED_AT',
            'ENDED_AT' => 'ENDED_AT',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];

        $roleId = Yii::$app->user->userInfo['roleId'];
        if ( $roleId !== Yii::$app->params['superAdminRoleId'] ) {
            $condition .= ' AND ADMIN_ID=:ADMIN_ID';
            $params['ADMIN_ID'] = Yii::$app->user->id;
        }

        $data = Export::lists($condition, $params, [
            'useSlaves' => true,
            'orderBy' => 'CREATED_AT DESC',
        ]);
        if($data){
            foreach($data['list'] as $key => $value){
                $data['list'][$key]['ADMIN_NAME'] = Admin::getAdminNameById($value['ADMIN_ID']);
            }
        }
        // 全部模块
        //$data['allModuleName'] = Yii::$app->params['exportModule'];
        $data['allModuleName'] = $this->returnAllModuleNameTranslate(Tool::paramConvert(\Yii::$app->params['exportModule']));
        return static::notice($data);
    }

    /**
     *  多语言
     */
    public function returnAllModuleNameTranslate($allModuleName = []){
        foreach($allModuleName as $k=>$v){
            switch ($k)
            {
                case 'shop':
                    $allModuleName[$k]['label'] = \Yii::t('ctx', 'mallManagement');
                    break;
                case 'user':
                    $allModuleName[$k]['label'] = Yii::t('ctx', 'memberManagement');
                    break;
                case 'atlas':
                    $allModuleName[$k]['label'] = Yii::t('ctx', 'networkChart');
                    break;
                case 'reconsume':
                    $allModuleName[$k]['label'] = Yii::t('ctx', 'resaleManagement');
                    break;
                case 'bonus':
                    $allModuleName[$k]['label'] = Yii::t('ctx', 'bonusManagement');
                    break;
                case 'finance':
                    $allModuleName[$k]['label'] = Yii::t('ctx', 'financialManagement');
                    break;
            }
        }
        return $allModuleName;
    }

    /**
     * 删除已导出文件
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionExportDelete() {
        return false;
        return static::delete(Export::class, function ($selected) {
            // 通过Id查找文件并删除他们
            foreach ($selected as $id) {
                if ($fileData = Export::findOneAsArray('ID=:ID', [':ID' => $id])) {
                    if ($fileData['REMOTE_URL']) {
                        $remoteUploadApi = RemoteUploadApi::instance();
                        $remoteUploadApi->delete($fileData['REMOTE_URL']);
                    }
                    if ($fileData['FILE_NAME']) {
                        $file=$fileData['FILE_NAME'];
                        $basePath = \Yii::getAlias('@backendApi') . __DS__ . 'web' . __DS__ . 'upload' . __DS__ . \Yii::$app->params['excelLocalDir'];
                        if(strpos($file, $basePath) === false){
                            $file = $basePath . __DS__ . ltrim($file , __DS__);
                        }
                        if(file_exists($file)) unlink($file);
                    }
                }
            }
        }, null, true);
    }

    /**
     * 获取上传token
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionToken(){
        $token = Cache::setUploadToken();
        return static::notice($token);
    }

    /**
     * 上传excel文件
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionUploadExcel(){
        if(\Yii::$app->request->isPost){
            $formModel = new UploadForm();
            $formModel->scenario = 'excel';
            $formModel->file = UploadedFile::getInstanceByName('file');
            //$formModel->token = \Yii::$app->request->post('uploadToken');
            $formModel->token = \Yii::$app->request->request('uploadToken');
            $formModel->excelOption = \Yii::$app->request->request('excelOption');
            if($formModel->file && $uploads = $formModel->upload()){
                // 通过upload的id获取excelImport的Id
                $excelImport = ExcelImport::findOneAsArray('UPLOAD_ID=:UPLOAD_ID', [':UPLOAD_ID'=>$uploads['ID']], 'ID');
                return static::notice([
                    'fileName'=>$uploads['FILE_NAME'],
                    'excelImportId' => $excelImport['ID'],
                ]);
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

}
