<?php
/**
 * 修改用户信息
 * @author yzxh24
 */
class UpdateAction extends BaseAction
{
    public function run()
    {
        $obj = new Manager('update');
        $uid = intval($_GET['id']);
        $model = $obj->find('id=:id',array(':id'=>$uid));

        if (Yii::app()->request->isPostRequest)
        {
            $model->attributes = $_POST['Manager'];
            if ($model->save())
            {
                // 删掉原来的部门信息，重新生成
                DepartmentUser::model()->deleteAll('user_id=:id',array(':id'=>$uid));
                if (!empty($_POST['departments']))
                {
                    foreach ($_POST['departments'] as $value)
                    {
                        $department = new DepartmentUser();
                        $department->user_id = $uid;
                        $department->department_id = $value;
                        $department->save();
                    }
                }
                $this->getController()->redirect(array('list'));
            }
        }
        
        // 获取部门列表
        $departments = Department::model()->findAll();

        // 获取但前用户的部门列表
        $userDepartments = array();
        $userDepartment = DepartmentUser::model()->findAll('user_id=:id',array(':id'=>$uid));
        if (!empty($userDepartment))
        {
            foreach ($userDepartment as $user)
            {
                $userDepartments[] = $user->department_id;
            }
        }
        $this->getController()->render('update', array(
                'model' => $model,
                'departments' => $departments,
                'userDepartments' => $userDepartments,
            )
        );
    }
}