<?php
/**
 * Created by PhpStorm.
 * User:  NODELOG
 * Date: 16-1-28
 * Time: 下午6:40
 */

namespace api\modules\v1\controllers;


use api\common\controllers\Controller;
use api\modules\v1\models\Article;
use common\enums\CodeEnum;
use common\models\ArticleModule;
use common\models\Footprint;
use common\models\SearchRecord;
use Yii;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
use api\common\behaviors\QueryParamAuth;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;

class ArticleController extends Controller
{
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => QueryParamAuth::className(),
                'tokenParam' => 'token',
                'optional' => []
            ]
        ]);
    }

    /**
     * @param $cid
     * @param $chain
     * @param $keyword
     * @return ActiveDataProvider
     * @author jiang
     */
    public function actionIndex($cid = null, $chain = null, $keyword = null)
    {

        $query = Article::find()->published()
            ->andFilterWhere(['category_id' => $cid]);
        //产业链
        if (!empty($chain) && $chain != '全部') {
            $query->andWhere([
                'or',
                ['like', 'chain', $chain],
                ['like', 'title', $chain],
                ['like', 'company', $chain],
                ['like', 'description', $chain],
                ['like', 'intro', $chain],
                ['like', 'address', $chain],
                ['like', 'city', $chain],
                ['like', 'tel', $chain],
                ['like', 'principal', $chain],
                ['like', 'position', $chain],
            ]);
        }
        //搜索关键字
        if (!empty($keyword)) {
            $query->andWhere([
                'or',
                ['like', 'chain', $keyword],
                ['like', 'title', $keyword],
                ['like', 'company', $keyword],
                ['like', 'description', $keyword],
                ['like', 'intro', $keyword],
                ['like', 'address', $keyword],
                ['like', 'city', $keyword],
                ['like', 'tel', $keyword],
                ['like', 'principal', $keyword],
                ['like', 'position', $keyword],
            ]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
//                'validatePage' => true,
                'pageParam' => 'page_no',
                'pageSizeParam' => 'page_size',
            ],
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_ASC
                ]
            ]
        ]);

        //记录搜索关键词
        self::recordKeyword($keyword);

        return $dataProvider;
    }

    /**
     * 详情
     * @param $id
     * @return array
     * @throws NotFoundHttpException
     * @author jiang
     */
    public function actionView($id)
    {
//        request()->setQueryParams(['expand' => 'data']);
        $model = Article::find()->published()->where(['id' => $id])->one();
        if ($model === null) {
            throw new NotFoundHttpException('not found');
        }
        $model->addView();
        //添加足迹记录
        Footprint::add(\common\models\Article::className(), $id);

        return ['data' => $model];
    }

    /**
     * 看板统计
     * @return array
     * @throws NotFoundHttpException
     * @author jiang
     */
    public function actionCount()
    {

        $list = Article::find()->select(['module', 'count(module) as count'])->published()->groupBy('module')->orderBy(['count' => SORT_DESC])->asArray()->all();
        $citylist = Article::find()->select(['city', 'count(city) as count'])->where(['!=', 'city', ''])->published()->groupBy('city')->having(['>', 'count', 5])->orderBy(['count' => SORT_DESC])->asArray()->all();
        $data = [];
        foreach ($list as $item) {
            $data['normal'][] = [
                'name' => array_get(\common\models\ArticleModule::getTypeEnum(), $item['module']),
                'centerText' => $item['count'],
                'value' => (int)$item['count']
            ];
        }
        foreach ($citylist as $item) {
            $size = 10;
            if ($item['count'] >= 100) {
                $size = 50;
            }
            if ($item['count'] >= 50 && $item['count'] < 100) {
                $size = 40;
            }
            if ($item['count'] >= 40 && $item['count'] < 50) {
                $size = 30;
            }
            if ($item['count'] >= 30 && $item['count'] < 40) {
                $size = 25;
            }
            if ($item['count'] >= 20 && $item['count'] < 30) {
                $size = 20;
            }
            if ($item['count'] >= 10 && $item['count'] < 20) {
                $size = 15;
            }
//            if ($item['count'] < 10) {
//                $size = 10;
//            }
            $data['word'][] = [
                'name' => $item['city'],
                'textSize' => $size
            ];
        }

        return ['data' => $data];
    }

    /**
     * 浏览足迹
     * @return ActiveDataProvider
     * @author jiang
     */
    public function actionFootprint()
    {
        $ids = Footprint::find()->where(['entity' => \common\models\Article::className()])->my()->active()->select('entity_id')->orderBy(['id' => SORT_DESC])->column();
        $query = Article::find()->where(['in', 'id', $ids])->published();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageParam' => 'page_no',
                'pageSizeParam' => 'page_size',
            ],
//            'sort' => [
//                'defaultOrder' => [
//                    'created_at' => SORT_DESC,
//                ]
//            ]
        ]);

        return $dataProvider;
    }

    /**
     * 数据模型列表
     * @return array
     * @author jiang
     */
    public function actionModule()
    {
        $data = ArticleModule::find()->select(['name', 'title'])->all();
        return ['data' => $data];
    }

    /**
     * 企业反馈
     * @return array|string[]
     * @throws \yii\db\Exception
     * @author jiang
     */
    public function actionCreate()
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {

            $model = new \common\models\Article();
            $model->load(request()->post(), '');
            $model->status = \common\models\Article::STATUS_PENDING;//待审核
            $model->save();

            if ($model->hasErrors()) {
                throw new Exception(current($model->getErrors())[0]);
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['errcode' => CodeEnum::CODE_ERROR, 'errmsg' => '提交失败：' . $e->getMessage()];
        }

        return ['errmsg' => '提交成功'];
    }

    /**
     * 历史搜索
     * @return array
     * @author jiang
     */
    public function actionHistorySearch()
    {
        $where = [
            'del' => 0,
            'user_id' => \Yii::$app->user->id
        ];
        $order = [
            'count' => SORT_DESC,
            'updated_at' => SORT_DESC,
            'id' => SORT_DESC
        ];
        $data = SearchRecord::find()->where($where)->orderBy($order)->limit(50)->select('keyword')->column();

        return ['data' => $data];
    }

    /**
     * @author jiang
     */
    public function actionClearSearch()
    {
        $where = [
            'del' => 0,
            'user_id' => \Yii::$app->user->id
        ];
        $data = [
            'del' => 1,
        ];
        SearchRecord::updateAll($data, $where);

        return ['errmsg' => '清空成功'];
    }

    /**
     * 记录关键词
     */
    public static function recordKeyword($keyword)
    {
        if (empty($keyword)) {
            return false;
        }
        $where = [
            'del' => 0,
            'user_id' => \Yii::$app->user->id,
            'keyword' => $keyword
        ];
        $record = SearchRecord::find()->where($where)->one();
        if ($record) {
            // 有该关键词记录, 更新
            $data = [
                'count' => 1,
            ];
            SearchRecord::updateAllCounters($data, $where);
            return true;
        }

        $record = new SearchRecord();
        $record->load($where, '');
        $record->count = 1;
        $record->save();

        return true;
    }
}