<?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\lists\ad\AdIndexList;
use common\helpers\Cache;
use common\helpers\Form;
use common\helpers\LoggerTool;
use common\models\Ad;
use common\models\AdLocation;
use common\models\Article;
use common\models\Countries;
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()
    {
        // 获取位置ID
        $lid = Yii::$app->request->get('lid', 0);
        if (empty($lid)) {
            throw new \yii\web\HttpException(400, Yii::t('ctx', 'paramError'));
        }

        // 如果admin不是超管,只允许查询自己关联的国家
        $admin = Admin::findOne(Yii::$app->user->id);
        $roleId = $admin->ROLE_ID;
        if ($roleId == \Yii::$app->params['superAdminRoleId']) {
            $countries = Countries::find()->asArray()->all();
        } else {
            // 关联国家
            $countries = Countries::find()
                ->select('COU.ID, COU.CODE, COU.NAME')
                ->from(['COU' => Countries::tableName()])
                ->join('INNER JOIN', AdminCountry::tableName() . ' AS ADL', 'ADL.COUNTRY_ID = COU.ID')
                ->where(['ADL.ADMIN_ID' => $admin->ID])
                ->asArray()
                ->all();
        }

        $filter = $this->filterCondition([
            'TITLE' => 'AD.TITLE',
            'COUNTRY_ID' => 'AD.COUNTRY_ID',
            'STATUS' => 'AD.STATUS',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];

        $condition .= ' AND AD.LID=:LID';
        $params[':LID'] = $lid;

        $countryIds = array_column($countries, 'ID');
        if (!empty($countryIds)) {
            $placeholders = [];
            foreach ($countryIds as $key => $id) {
                $paramName = ':countryId_' . $key;
                $placeholders[] = $paramName;
                $params[$paramName] = $id;
            }
            $condition .= ' AND AD.COUNTRY_ID IN (' . implode(',', $placeholders) . ')';
        }

        $obj = new AdIndexList();
        // 直接获取完整的数据，包括columnsShow和filterTypes
        $data = $obj->getList(['condition' => $condition, 'params' => $params]);

        // 添加额外数据
        $data['allLocation'] = AdLocation::getAllLocation();
        $data['countries'] = $countries;
        $data['allArticle'] = Article::find()
            ->from(['ART' => Article::tableName()])
            ->select('ART.ID,ART.TITLE')
            ->andFilterWhere(['ART.COUNTRY_ID' => array_column($countries, 'ID')])
            ->asArray()
            ->all();

        return static::notice($data);
    }

    /**
     * 添加
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionAdd(){
        if(Yii::$app->request->isPost) {
            return parent::edit(AdForm::class, Yii::t('ctx', 'AdAddedSuccessfully'), null, null, null, function($formModel, $result){
                // 添加操作日志
                // Log::adminHandle('添加广告:'.$result->TITLE);
            });
        }
        // 获取全部分类
        $allLocation = AdLocation::getAllLocation();
        
        // 管理员关联国家的文章
        $admin = Admin::findOne(Yii::$app->user->id);
        $roleId = $admin->ROLE_ID;
        if ($roleId == \Yii::$app->params['superAdminRoleId']) {
            $countries = Countries::find()->asArray()->all();
        } else {
            // 关联国家
            $countries = Countries::find()
                ->select('COU.ID, COU.CODE, COU.NAME')
                ->from(['COU' => Countries::tableName()])
                ->join('INNER JOIN', AdminCountry::tableName() . ' AS ADL', 'ADL.COUNTRY_ID = COU.ID')
                ->where(['ADL.ADMIN_ID' => $admin->ID])
                ->asArray()
                ->all();
        }

        // 关联文章，关联国家表
        $allArticle = Article::find()
            ->from(['ART' => Article::tableName()])
            ->leftJoin(['COU' => Countries::tableName()], 'COU.ID = ART.COUNTRY_ID')
            ->select('ART.ID,ART.TITLE,ART.COUNTRY_ID,COU.NAME AS COUNTRY_NAME')
            ->andFilterWhere(['ART.COUNTRY_ID' => array_column($countries, 'ID')])
            ->asArray()
            ->all();

        return static::notice([
            'allLocation'=>$allLocation, 
            'allArticle' => $allArticle,
            'countries' => $countries,
        ]);
    }

    /**
     * 编辑
     * @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, Yii::t('ctx', 'EditAdSuccessfully'), null, null, null, function($formModel, $result){
                // 添加操作日志
                // Log::adminHandle('编辑广告:'.$result->TITLE);
            });
        }
        $oneData = Ad::findOneAsArray(['ID'=>$id]);
        // 获取全部分类
        $allLocation = AdLocation::getAllLocation();

        // 管理员关联国家的文章
        $admin = Admin::findOne(Yii::$app->user->id);
        $roleId = $admin->ROLE_ID;
        if ($roleId == \Yii::$app->params['superAdminRoleId']) {
            $countries = Countries::find()->asArray()->all();
        } else {
            // 关联国家
            $countries = Countries::find()
                ->select('COU.ID, COU.CODE, COU.NAME')
                ->from(['COU' => Countries::tableName()])
                ->join('INNER JOIN', AdminCountry::tableName() . ' AS ADL', 'ADL.COUNTRY_ID = COU.ID')
                ->where(['ADL.ADMIN_ID' => $admin->ID])
                ->asArray()
                ->all();
        }

        // 关联文章，关联国家表
        $allArticle = Article::find()
            ->from(['ART' => Article::tableName()])
            ->leftJoin(['COU' => Countries::tableName()], 'COU.ID = ART.COUNTRY_ID')
            ->select('ART.ID,ART.TITLE,ART.COUNTRY_ID,COU.NAME AS COUNTRY_NAME')
            ->andFilterWhere(['ART.COUNTRY_ID' => array_column($countries, 'ID')])
            ->asArray()
            ->all();

        return static::notice([
            'oneData' => $oneData, 
            'allLocation' => $allLocation, 
            'allArticle' => $allArticle,
            'countries' => $countries,
        ]);
    }

    /**
     * 删除
     * @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\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionAdHide(){
        $adForm = new AdForm();
        $result = static::hide(Ad::class, 'hide', function ($selected) use ($adForm) {
        }, function ($selected) use ($adForm) {
        }, true);
        return $result;
    }

    /**
     * 取消隐藏
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionAdUnHide(){
        $adForm = new AdForm();
        $result = static::hide(Ad::class, 'un-hide', function ($selected) use ($adForm) {
        }, function ($selected) use ($adForm) {
        }, 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(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Yii::t('ctx', 'failed'), 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(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Yii::t('ctx', 'failed'), 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);
        }
    }

    public function actionCountry()
    {
        $admin = Admin::findOne(Yii::$app->user->id);
        $roleId = $admin->ROLE_ID;
        if ($roleId == \Yii::$app->params['superAdminRoleId']) {
            $countries = Countries::find()->asArray()->all();
        } else {
            // 关联国家
            $countries = Countries::find()
                ->select('COU.ID, COU.CODE, COU.NAME')
                ->from(['COU' => Countries::tableName()])
                ->join('INNER JOIN', AdminCountry::tableName() . ' AS ADL', 'ADL.COUNTRY_ID = COU.ID')
                ->where(['ADL.ADMIN_ID' => $admin->ID])
                ->asArray()
                ->all();
        }

        return static::notice($countries);
    }
}
