<?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\Form;
use common\helpers\Log;
use common\models\Ad;
use common\models\AdLocation;
use common\models\forms\AdForm;
use common\models\forms\UploadForm;
use Yii;
use yii\web\UploadedFile;

class AdController extends BaseController
{
    public $modelClass = Ad::class;

    public function actions() {
        return parent::actions(); // TODO: Change the autogenerated stub
    }

    /**
     * 广告位列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionLocation(){
        $condition = '';
        $params = [];
        $data = AdLocation::lists($condition, $params, [
            'select' => 'ADL.*,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME UPDATE_ADMIN_NAME',
            'from' => AdLocation::tableName().' AS ADL',
            'join' => [
                ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'ADMC.ID=ADL.CREATE_ADMIN'],
                ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'ADMU.ID=ADL.UPDATE_ADMIN'],
            ],
            'orderBy' => 'ADL.CREATED_AT ASC',
        ]);
        return static::notice($data);
    }

    /**
     * 列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionList(){
        $lid = Yii::$app->request->get('lid');
        $condition = ' AND AD.LID=:LID';
        $params[':LID']=$lid;
        $data = Ad::lists($condition, $params, [
            'select' => 'AD.*,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME UPDATE_ADMIN_NAME',
            'from' => Ad::tableName().' AS AD',
            'join' => [
                ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'ADMC.ID=AD.CREATE_ADMIN'],
                ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'ADMU.ID=AD.UPDATE_ADMIN'],
            ],
            'orderBy' => 'AD.SORT DESC,AD.CREATED_AT ASC',
        ]);
        $data['allLocation'] = AdLocation::getAllLocation();
        return static::notice($data);
    }

    /**
     * 添加
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionAdd(){
        if(Yii::$app->request->isPost) {
            return parent::edit(AdForm::class, '添加广告成功', null, null, null, function($formModel, $result){
                // 添加操作日志
                // Log::adminHandle('添加广告:'.$result->TITLE);
            });
        }
        // 获取全部分类
        $allLocation = AdLocation::getAllLocation();
        return static::notice(['allLocation'=>$allLocation]);
    }

    /**
     * 编辑
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionEdit(){
        $id = Yii::$app->request->get('id');
        if(Yii::$app->request->isPost) {
            return parent::edit(AdForm::class, '编辑广告成功', null, null, null, function($formModel, $result){
                // 添加操作日志
                // Log::adminHandle('编辑广告:'.$result->TITLE);
            });
        }
        $oneData = Ad::findOneAsArray(['ID'=>$id]);
        // 获取全部分类
        $allLocation = AdLocation::getAllLocation();
        return static::notice(['oneData'=>$oneData, 'allLocation'=>$allLocation]);
    }

    /**
     * 删除
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionAdDelete(){
        $adForm = new AdForm();
        $result = static::delete(Ad::class, function ($selected) use ($adForm) {
            $adForm->beforeDelete($selected);
        }, function ($selected) use ($adForm) {
            $adForm->delete($selected);
        }, true);
        return $result;
    }

    /**
     * 排序
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionSort(){
        if(Yii::$app->request->get('id')){
            $formModel = new AdForm();
            $formModel->scenario = 'sort';
            if($formModel->load(Yii::$app->request->get(), '') && $formModel->sortTo()){
                return static::notice('Success');
            } else {
                return static::notice('Fail', 400);
            }
        }
    }

    /**
     * 状态
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionStatus(){
        if(Yii::$app->request->get('id')){
            $formModel = new AdForm();
            $formModel->scenario = 'status';
            if($formModel->load(Yii::$app->request->get(), '') && $formModel->statusTo()){
                return static::notice('Success');
            } else {
                return static::notice('Fail', 400);
            }
        }
    }

    /**
     * 上传图片
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionUpload(){
        if(\Yii::$app->request->isPost){
            $formModel = new UploadForm();
            $formModel->scenario = 'ad';
            $formModel->file = UploadedFile::getInstanceByName('file');
            $formModel->token = \Yii::$app->request->request('uploadToken');;
            if($formModel->file && $uploader = $formModel->upload()){
                return static::notice($uploader->URL);
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            $token = Cache::setUploadToken();
            return static::notice($token);
        }
    }
}