<?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\article\IndexList;
use common\helpers\Cache;
use common\helpers\Form;
use common\models\Article;
use common\models\ArticleCategory;
use common\models\Countries;
use common\models\forms\ArticleCategoryForm;
use common\models\forms\ArticleForm;
use common\models\forms\UploadForm;
use Yii;
use yii\web\UploadedFile;

class ArticleController extends BaseController
{
    public $modelClass = Article::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 actionCategory(){
        $data = ArticleCategory::lists('', [], [
            'orderBy' => 'SORT ASC, CREATED_AT DESC',
        ]);
        return static::notice($data);
    }

    /**
     * 添加分类
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionCategoryAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(ArticleCategoryForm::class, Yii::t('ctx', 'successfully'));
        }
    }

    /**
     * 删除文章分类
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionCategoryDelete(){
        $result = static::delete(ArticleCategory::class);
        return $result;
    }

    /**
     * 分类排序
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionCategorySort(){
        if(Yii::$app->request->get('id')){
            $formModel = new ArticleCategoryForm();
            $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 actionIndex()
    {
        // 如果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' => 'ART.TITLE',
            'COUNTRY_ID' => 'ART.COUNTRY_ID',
            'STATUS' => 'ART.STATUS',
        ]);
        $condition = $filter['condition'];
        $params = $filter['params'];

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

        $obj = new IndexList();
        $data = $obj->getList(['condition' => $condition, 'params' => $params]);

        // 全部分类
        $data['allCategory'] = ArticleCategory::getAllCategory();

        return static::notice($data);
    }

    /**
     * 添加文章
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionAdd()
    {
        if (Yii::$app->request->isPost) {
            return parent::edit(ArticleForm::class, Yii::t('ctx', 'successfully'));
        }

        // 获取全部分类
        $allCategory = ArticleCategory::find()->where('STATUS=1')->asArray()->all();

        // 管理员关联国家
        $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([
            'allCategory' => $allCategory,
            'countries' => $countries,
        ]);
    }

    /**
     * 编辑文章
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionEdit(){
        $id = Yii::$app->request->get('id');
        if(Yii::$app->request->isPost){
            return parent::edit(ArticleForm::class, Yii::t('ctx', 'successfully'));
        }
        $oneData = Article::findOneAsArray(['ID'=>$id]);
        $oneData['CONTENT'] = is_resource($oneData['CONTENT']) ? stream_get_contents($oneData['CONTENT']) : '';
        // 国家
        $oneData['COUNTRY'] = Countries::getCountry($oneData['COUNTRY_ID']);
        // 暂时先从文件中取内容
        $path = \Yii::getAlias('@common/runtime/articleContent/').$oneData['ID'];
        if(!file_exists($path)){
            $oneData['CONTENT'] = '';
        } else {
            $oneData['CONTENT'] = file_get_contents($path);
        }
        // 获取全部分类
        $allCategory = ArticleCategory::getAllCategory();
        
        // 管理员关联国家
        $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([
            'oneData' => $oneData, 
            'allCategory' => $allCategory, 
            'countries' => $countries
        ]);
    }

    /**
     * 删除文章
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionArticleDelete(){
        $result = static::delete(Article::class);
        return $result;
    }

    /**
     * 隐藏
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionArticleHide(){
        $adForm = new ArticleForm();
        $result = static::hide(Article::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 actionArticleUnHide(){
        $adForm = new ArticleForm();
        $result = static::hide(Article::class, 'un-hide', function ($selected) use ($adForm) {
        }, function ($selected) use ($adForm) {
        }, true);
        return $result;
    }

    /**
     * 获取文章详细
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDetail()
    {
        $id = \Yii::$app->request->get('id');
        $data = null;
        if($id){
            $data = Article::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=>$id], 'ID,COUNTRY_ID,TITLE,CID,SORT,CREATED_AT');
            // 国家
            $data['COUNTRY'] = Countries::getCountry($data['COUNTRY_ID']);
        }
        if($data){
            // 暂时先从文件中取内容
            $path = \Yii::getAlias('@common/runtime/articleContent/') . $data['ID'];
            if(!file_exists($path)){
                $data['CONTENT'] = '';
            } else {
                $data['CONTENT'] = file_get_contents($path);
            }
            return static::notice($data);
        } else {
            return static::notice('Article not exists!', 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 = 'article';
            $formModel->file = UploadedFile::getInstanceByName('file');
            $formModel->token = \Yii::$app->request->request('uploadToken');;
            if($formModel->file && ($uploader = $formModel->upload()) !== false){
                if (is_object($uploader) && isset($uploader->FILE_NAME)) {
                    return static::notice($uploader->FILE_NAME);
                } else {
                    // 处理非对象返回值的情况
                    return static::notice('Upload successful');
                }
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        } else {
            $token = Cache::setUploadToken();
            return static::notice($token);
        }
    }

    /**
     * 排序
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionSort()
    {
        if (Yii::$app->request->get('id')) {
            $formModel = new ArticleForm();
            $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);
            }
        }
    }

    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);
    }
}
