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

namespace home\modules\reimbursement\controllers;

use Yii;
use yii\helpers\Url;
use home\controllers\Controller;
use common\models\Common;
use common\models\PermissionScope;
use home\modules\reimbursement\models\Application;
use home\modules\reimbursement\models\Verify;
use common\components\Tool;
use yii\data\ActiveDataProvider;
use home\models\Announcement;

/**
 * 报销申请控制器
 * 
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class ApplicationController extends Controller
{
	public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        $actions['view']['layout'] = '//modal';
        $actions['create']['layout'] = '//modal';
        $actions['update']['layout'] = '//modal';
        $actions['delete']['to'] = ['index-iframe'];
        return $actions;
	}

    /**
     * 控制器的行为事件
     *
     * @key appliAccess 权限过滤器
     */
    public function behaviors()
    {
        $request = Yii::$app->request;
        return [
            'access' => [
                'class' => \home\behaviors\ApplicationFilter::className(),
                'only' => ['update','delete','view','verify','set-status'],
            ],
        ];
    }

	public function actionIndex()
    {
    	$id = Yii::$app->user->id;
        $request = Yii::$app->request;
        $showVerify = false; //是否显示审核选项
        //权限判断
        $permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);
        $viewUser = PermissionScope::getScopeUser('reimbursement/application/view');
        $deleteUser = PermissionScope::getScopeUser('reimbursement/application/delete');
        (empty($scopeUser) || Application::readAccess('reimbursement/application/verify')) && $showVerify = true;

        return $this->render('index', [
                'get' =>$request->get(),
                'showVerify' => $showVerify,
                'viewUser' => $viewUser,
                'deleteUser' => $deleteUser,
                'model' => new Application(),
        ]);
    }

    /**
     * 申请单列表(iframe)
     */
    public function actionIndexIframe()
    {
        $id = Yii::$app->user->id;

        $request = Yii::$app->request;
        $gets = $request->get();
        unset($gets['r']);
        unset($gets['nav_id']);

        $query = Application::find();
        $query->orderBy([
            Application::isverifyOrderBy() => SORT_ASC,
            'appli_id' => SORT_DESC,
            'create_time' => SORT_DESC,
            ]);

        $showVerify = false; //是否显示审核选项
        //权限判断
        $scopeUser = PermissionScope::getScopeUser('reimbursement/application/index');
        $viewUser = PermissionScope::getScopeUser('reimbursement/application/view');
        $deleteUser = PermissionScope::getScopeUser('reimbursement/application/delete');
        if (empty($scopeUser)) {
            //若当前用户拥有超级权限，则显示所有申请单，并且编辑和审核选项均显示
            $query->orderBy([
                Application::isverifyOrderBy('verify') => SORT_ASC,
                'appli_id' => SORT_DESC,
                'create_time' => SORT_DESC,
            ]);
            empty($gets) && $query->andWhere(['isverify' => Yii::$app->cache->get('application_config')['application_verify_show']]);
            //$query->where("user_id = :id or FIND_IN_SET(:verify_id,verify_ids)", [':id' => $id, ':verify_id' => $id]);
            $showVerify = true;
        } else {
            if (Application::readAccess('reimbursement/application/verify')) {
                //若当前用户有审核权限，则显示当前用户申请的申请单以及显示属于报销人的申请单，并且编辑和审核选项均显示
                $query->orderBy([
                    Application::isverifyOrderBy('verify') => SORT_ASC,
                    'appli_id' => SORT_DESC,
                    'create_time' => SORT_DESC,
                ]);

                if (!empty($scopeUser)) {
                    $findArr = [];
                    foreach($scopeUser as $u) {
                        $findArr[] = 'user_id = ' . (int) $u;
                    }
                    $findArr[] = 'FIND_IN_SET(' . $id . ', verify_ids)';
                    $findStr = implode(' or ', $findArr);
                    $query->where($findStr);
                }
                empty($gets) && $query->andWhere(['isverify' => Yii::$app->cache->get('application_config')['application_verify_show']]);
                $showVerify = true;
                //$query->where(['user_id' => $id]);
            } else {
                //若当前用户没有审核权限，则只显示当前用户申请的申请单，并且只显示编辑选项
                $query->orderBy([
                    Application::isverifyOrderBy() => SORT_ASC,
                    'appli_id' => SORT_DESC,
                    'create_time' => SORT_DESC,
                ]);

                if (!empty($scopeUser)) {
                    $findArr = [];
                    foreach($scopeUser as $u) {
                        $findArr[] = 'user_id = ' . (int) $u;
                    }
                    $findStr = implode(' or ', $findArr);
                    $query->where($findStr);
                }
                empty($gets) && $query->andWhere(['isverify' => Yii::$app->cache->get('application_config')['application_reim_show']]);
                //$query->where(['user_id' => $id]);
            }
        }

        //搜索
        /*$request = Yii::$app->request;
        $query->where("user_id = :id or FIND_IN_SET(:verify_id,verify_ids)", [':id' => $id, ':verify_id' => $id]);*/
        
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $status = $request->get('status');
        $isUsed = $request->get('isused');
        $type = $request->get('type');
        $ids = $request->get('ids');

        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', $field, $keywords]);
        }
        if ($status != '') {
            $query->andWhere(['isverify' => (int)$status]);
        }
        if ($isUsed != '') {
            $query->andwhere(['isUsed' => (int)$isUsed]);
        }
        
        //$type == 'all' && $query->where = $query->where[1];
        if ($ids != '') {
            $query->andWhere("FIND_IN_SET(user_id,:ids)", [':ids' => $ids]);
        }
       
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return $this->renderPartial('index-iframe', [
                'get' =>$request->get(),
                'model' => new Application(),
                'models' => $provider->models,
                'showVerify' => $showVerify,
                'viewUser' => $viewUser,
                'deleteUser' => $deleteUser,
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 详情
     */
    public function actionDetail()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $model = Application::findOne(['appli_id' => $id]);
        if (empty($model)) {
            Yii::$app->getSession()->setFlash('error', '申请单不存在或已被删除');
            return $this->flash();
        }

        //权限检测
        $permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);
        $viewUser = PermissionScope::getScopeUser('reimbursement/application/view');
        $deleteUser = PermissionScope::getScopeUser('reimbursement/application/delete');
        if (!empty($scopeUser) && !in_array($model['user_id'], $scopeUser)) {
            Yii::$app->getSession()->setFlash('error', '当前没有浏览该申请单详情的权限');
            return $this->flash();
        }

        $verifys = Verify::getList(['link_type' => 'appli', 'link_id' => $id]);
        return $this->render('detail', [
            'model' => $model,
            'verify' => new Verify(),
            'verifys' => $verifys,
            'viewUser' => $viewUser,
            'deleteUser' => $deleteUser,
        ]);
    }

	/**
     * 报销审批
     */
    public function actionVerify()
    {
        $model = new Application();

        $request = Yii::$app->request;
        if ($request->isPost) {
            $id = (int) $request->post('id');
            //if (!empty($request->post('verify_id'))) {
            /*if ($request->post('verify_id') != '') {
	            $verify = Verify::findOne($request->post('verify_id'));
	        } else {*/
	        	$verify = new Verify();
	        	$verify->link_type = 'appli';
	        	$verify->link_id = $id;
	        /*}*/
	        $verify->status = $request->post('verify_status');
	        $verify->remark = $request->post('Application')['verify_remark'];
	        if ($verify->save()) {
                Yii::$app->getSession()->setFlash('success', '更新成功');
            } elseif ($verify->hasErrors()) {
                $firstError = reset($verify->getFirstErrors());
                Yii::$app->getSession()->setFlash('error', $firstError);
            }
        } else {
            $id = (int) $request->get('id');
        }
        if (empty($id) || !$model = call_user_func([$model, 'findOne'], $id)) {
            Yii::$app->getSession()->setFlash('error', '要更新的对象不存在');
            return $this->flash();
        }

        //检测当前用户是否有权限进行审核
        if (in_array(Yii::$app->user->id, explode(',', $model->verify_ids)) && $model->isverify == 0) {
            $curVerify = Verify::find()->where(['link_type' => 'appli', 'link_id' => $id, 'verify_user_id' => Yii::$app->user->id])->orderBy(['verify_time' => SORT_DESC])->one();
            if (isset($curVerify)) {
                $model->verify_id = $curVerify->verify_id;
                $model->verify_status = $curVerify->status;
                $model->verify_remark = $curVerify->remark;
            } else {
                $model->verify_status = 0;
                $model->verify_remark = '';
            }
        } else {
            $model->isShow = false;
        }
        
        $verifys = Verify::getList(['link_type' => 'appli', 'link_id' => $id]);

        $this->layout = '//modal';
        return $this->render('create', [
                'model' => $model,
                'verify' => new Verify(),
                'verifys' => $verifys,
                'form_name' => '_verify',
                'action' => [$this->id . '/verify']
        ]);
    }

    /**
     * 快捷操作审核申请
     */
    public function actionSetStatus()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $status = (int) $request->get('status');
        $remark = $request->get('remark');

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $map = [
            'link_type' => 'appli',
            'link_id' => $id,
            'verify_user_id' => Yii::$app->user->id,
        ];
        $verifyAppli = Verify::findOne($map);
        /*if (!empty($verifyAppli)) {
            $verify = $verifyAppli;
        } else {*/
            $verify = new Verify();
            $verify->link_type = 'appli';
            $verify->link_id = $id;
        /*}*/
        $verify->status = $status;
        ($remark != '') && $verify->remark = $remark;
        //更新报销审核表
        if (Application::readAccess('reimbursement/application/verify')) {
            if ($verify->save()) {
                $data = ['status' => 1, 'info' => '审核成功'];
            } else {
                $data = ['status' => 0, 'info' => '审核出错，请稍后再试'];
            }
        } else {
            $data = ['status' => 0, 'info' => '当前没有审核权限'];
        }

        return $data;
    }

    /**
     * 快捷操作更改使用状态
     */
    public function actionSetIsused()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $isused = (int) $request->get('isused');

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $appli = Application::findOne(['appli_id' => $id]);
        if (!$appli) {
            $data = ['status' => 0, 'info' => '该申请单不存在'];
            return $data;
        }

        //更新报销审核表
        if (Application::readAccess('reimbursement/application/change-isused')) {
            $command = Yii::$app->db->createCommand();
            $result = $command->update('{{%reimbursement_application}}', ['isused' => $isused], 'appli_id = :appli_id', [':appli_id' => $id])->execute();
            if (0 !== $result) {
                $data = ['status' => 1, 'info' => '使用状态修改成功'];
            } else {
                $data = ['status' => 0, 'info' => '修改出错，请稍后再试'];
            }
        } else {
            $data = ['status' => 0, 'info' => '当前没有权限'];
        }

        return $data;
    }

    /**
     * 左侧树形列表数据
     */
    public function actionGetTreedata()
    {
        $data = \qcbase\models\UserDepartment::obtainDepartmentTree('reimbursement/application/index');
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $data;
    }
}