<?php
namespace frontend\widgets;

use Yii;
use yii\base\Widget;
use common\models\Ad;
use common\components\CHelper;
use yii\helpers\Html;
class AdWidget extends Widget
{
    public $limit;
    public $alias;
    
    public function init()
    {
        parent::init();
        $this->limit = $this->limit?$this->limit:4;
    }
    
    public function run()
    {
        $category = \common\models\AdCategory::find()->asArray()->andWhere(['alias'=>$this->alias])->one();
        $limit = $this->limit>$category['max']?$category['max']:$this->limit;
    	$list = Ad::find()->asArray()->andWhere(['display'=>1,'categoryid'=>$category['id']])->andWhere(['<','addtime',time()])->andWhere(['>','deadline',time()])->orWhere(['deadline'=>0])->limit($limit)->orderBy('ordid desc,id desc')->all();
        $list = $this->_format_list($list);
        $return['list'] = $list;
        $return['category'] = $category;
    	return json_encode($return);
    }
    private function _format_list($list){
        foreach ($list as $key => $value) {
        	$list[$key]['title'] = Html::encode(CHelper::cutStr($value['title'],15));
            $list[$key]['img'] = CHelper::attach($value['img'],'ad');
        }
        return $list;
    }
}