<?php


namespace api\modules\v1\controllers;


use api\common\controllers\Controller;
use common\modules\config\models\Config;
use common\models\Policy;
use yii\helpers\ArrayHelper;
use api\common\behaviors\QueryParamAuth;

use Yii;
use yii\base\Exception;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;

class PolicyController extends Controller {

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

  
    
    public function actionIndex()
    {
        
        $params = request()->get();
        $query = Policy::find()->select('id,title,author,created_at,summary');
        //过滤查询的政策
        $query->andWhere(new \yii\db\Expression('FIND_IN_SET("'. Policy::TYPE_SEARCH .'", type)'));
        
        if(!empty($params)){
            $arr = [];
       
            foreach ($params as $key=>$value) {
                if($key == 'page' || $key == 'page_no'){
                    continue;
                }
    		    if($value){
    		         $fd = $key.'_' . $value;
    		         $query->orWhere(new \yii\db\Expression('FIND_IN_SET("'.$fd.'", filter)'));
    		    }
    		}
        }
        
        
        return new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageParam' => 'page_no',
                'pageSizeParam' => 'page_size',
            ],
            'sort' => [
                'defaultOrder' => [
                    'created_at' => SORT_ASC,
                ]
            ]
        ]);
    }
    
    public function actionCategory()
    {
        $lists = Config::find()->select(['name','value','extra','description','type'])->where(['group' => 'policy'])->asArray()->all();
        foreach ($lists as &$value) {
            
            $arr = [];
            $val = explode("\r\n",$value['value']);
			$extra = explode("\r\n",$value['extra']);
			
			foreach($extra as $k => $v){
			    $arr[] = [
			        'name'=>$v,
			        'value'=>$val[$k]
			     ];
			}
			
            $value['data'] = $arr;
			unset($value['extra'],$value['value'],$value['type']);
        }

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

 
    public function actionDetails($id)
    {
        $model = Policy::find()->where(['id' => $id])->select('id,content,author,created_at,title')->one();

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


}