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

namespace home\actions;

use Yii;
use common\models\Common;
use common\models\PermissionScope;

/**
 * 回收站删除
 *
 * 适用于具有逻辑删除的模块
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class TrashDelete extends \yii\base\Action
{
    /**
     * @var object 当前操作所属模型
     */
    public $model;
    /**
     * @var object 回收站模型
     */
    public $trashModel;

    /**
	 * @var array 要跳转的页面
	 */
	public $to = ['index'];
    /**
	 * @var bool 是否开启权限范围控制
	 */
	public $enableScopeAccess = true;
    /**
	 * @var array 范围控制字段,默认有user_id，如果有多个，采用or的关系
     */
    public $scopeAccessFields = ['user_id'];


    public function run()
    {
        $this->model === null && $this->model = $this->controller->model;

        $id = Yii::$app->request->get('id');
        $ids = Yii::$app->request->post('delete');
        $from = Yii::$app->request->get('from');

        $session = Yii::$app->getSession();
        if (empty($id) && empty($ids)) {
            $session->setFlash('error', '要删除的对象不存在');
        } else {
            //权限范围过滤
            if ($this->enableScopeAccess) {
                $permission = Common::getActionPermission($this);
                $scopeUser = PermissionScope::getScopeUser($permission);
            }


			!empty($id) && $ids[] = $id;
            $success = true;
            $canDelete = true;
            foreach ($ids as $id) {
                if (!$model = call_user_func([$this->model, 'findOne'], $id)) {
                    $session->setFlash('error', '要删除的对象不存在');
                    $success = false;
                    break;
                }
                //权限范围判断
                if (isset($scopeUser) && !empty($scopeUser)) {
                    $canDelete = false;
                    foreach($this->scopeAccessFields as $field) {
                        if (false === strpos($model->$field, ',')) {
                            if (in_array($model->$field, $scopeUser)) {
                                $canDelete = true;
                                break;
                            }
                        }
                        else {
                            if (count(array_intersect(explode(',', $model->$field), $scopeUser)) > 0) {
                                $canDelete = true;
                                break;
                            }
                        }
                    }
                    if (!$canDelete) {
                        $session->setFlash('error', '没有权限删除');
                    }
                }

                if ($canDelete) {
                    $attributes = $model->attributes;
                    $trashModel = new $this->trashModel(['scenario' => 'trash']);
                    $trashModel->attributes = $attributes;
                    if (!$trashModel->save()) {
                        $success = false;
                        $session->setFlash('error', 'ID为' . $id . '的对象删除到回收站失败');
                        break;
                    }

                    $model->delete();
                }
            }
            if ($canDelete && $success) {
                $session->setFlash('success', '删除成功');
            }
        }

         if (Yii::$app->request->isAjax) {
            $session = Yii::$app->getSession();
            $flashes = $session->getAllFlashes();
            $msg = '';

            foreach ($flashes as $type => $data) {
                if (in_array($type, ['error', 'success'])) {
                    $data = (array) $data;
                    foreach ($data as $d) {
                        $msg .= $d;
                    }
                    $session->removeFlash($type);
                }
            }
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return ['statue' => isset($flashes['success']) ? 1 : 0, 'info' => $msg];
        }

        if (!empty($from)) {
            return Yii::$app->getResponse()->redirect($from);
        }
        elseif (!empty($this->to)) {
            return $this->controller->redirect($this->to);
        }
        return $this->controller->flash();
    }
}
