<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\controllers;

use Yii;
use home\models\UserPortlet;

/**
 * 用户组件控制器
 *
 * 用于工作台组件的添加删除等
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class UserPortletController extends Controller
{
	public function actions()
    {
		$acitons = parent::actions();
		$acitons['create']['layout'] = 'modal';
		$acitons['view']['layout'] = 'modal';
		$acitons['update']['layout'] = 'modal';
		return $acitons;
	}

    /**
     * 修改组件位置
     */
    public function actionModifyPosition()
    {
        $positions = Yii::$app->request->get('positions');
        $positions = substr($positions, 1);
        $positions = explode('|', $positions);

        foreach ($positions as $position) {
            list($portlet, $x, $y) = explode(',', $position);
            $where = ['user_id' => Yii::$app->user->id, 'portlet' => $portlet];

            $userPortlet = UserPortlet::find()->where($where)->one();
            if ($userPortlet !== null) {
                Yii::$app->db->createCommand()->update('{{%user_portlet}}', [
                    'x' => (int) $x, 
                    'y' => (int) $y,
                ], $where)->execute();
            }
        }
    }

    /**
     * 删除组件
     */
    public function actionRemovePortlet()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $portlet = Yii::$app->request->get('portlet');
        $userPortlet = UserPortlet::find()->where(['user_id' => Yii::$app->user->id, 'portlet' => $portlet])->one();

        if ($userPortlet !== null && ($userPortlet->delete() > 0)) {
            return ['status' => 1, 'info' => '删除组件成功'];
        }
        else {
            return ['status' => 0, 'info' => '删除组件失败！'];
        }
    }
}
