<?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 yii\db\Query;
use common\models\Common;
use common\models\PermissionScope;
use home\modules\reimbursement\models\Reimbursement;
use home\modules\reimbursement\models\Category;
use home\modules\reimbursement\models\Verify;
use yii\data\ActiveDataProvider;
use common\components\Tool;
use home\models\Announcement;
use home\behaviors\TaskAccessControlFilter;
use yii\helpers\ArrayHelper;

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

    /**
     * 控制器的行为事件
     *
     * @key taskAccess 任务权限过滤器
     */
    public function behaviors()
    {
        $request = Yii::$app->request;
        return [
            'taskAccess' => [
                'class' => TaskAccessControlFilter::className(),
                'only' => ['create'],
                'permissions' => ['task/task/create-reimbursement'],
                'id' =>  ($request->isGet) ? $request->get('link_id') : ArrayHelper::getValue($request->post('Reimbursement'), 'link_id'),
                'taskField' => 'task_no',
                'enableFilter' => function($request) {
                    if ($request->isGet) {
                        $linkId = $request->get('link_id');
                        $linkType = $request->get('link_type');
                    }
                    else {
                        $post = $request->post('Reimbursement');
                        $linkId = ArrayHelper::getValue($post, 'link_id');
                        $linkType = ArrayHelper::getValue($post, 'link_type');
                    }
                    return !empty($linkId) && $linkType == 'task';
                },
            ],
            'access' => [
                'class' => \home\behaviors\ReimbursementFilter::className(),
                'only' => ['update','delete','view','verify','set-status','set-isclearing'],
            ],
        ];
    }

	public function actionIndex()
    {
    	$id = Yii::$app->user->id;
        $selectTime = false; //是否显示报表导出选项
        $monthTime = time() - 60 * 60 * 24 * date("t");

        $request = Yii::$app->request;
        $beginTime = $request->get('begin_time');
        if ($beginTime === null) {
            $beginTime = mktime(0, 0, 0, date('m', $monthTime), 1, date('Y', $monthTime));
        }
        $endTime = $request->get('end_time');
        if ($endTime === null) {
            $endTime = time();
        }

        $showVerify = false; //是否显示审核选项
        //权限判断
        $permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);
        $viewUser = PermissionScope::getScopeUser('reimbursement/reimbursement/view');
        $deleteUser = PermissionScope::getScopeUser('reimbursement/reimbursement/delete');

        (empty($scopeUser) || Reimbursement::readAccess('reimbursement/reimbursement/verify')) && $showVerify = true;

        (!empty($beginTime) && !empty($endTime)) && $selectTime = true;

        //若选择显示全部报销，则报表导出置灰
        $request->get('type') == 'all' && $selectTime = false;

        return $this->render('index', [
                'get' =>$request->get(),
                'beginTime' => $beginTime,
                'endTime' => $endTime,
                'selectTime' => $selectTime,
                'model' => new Reimbursement(),
                'showVerify' => $showVerify,
        ]);
    }

    /**
     * 报销列表(iframe)
     */
    public function actionIndexIframe()
    {
        $id = Yii::$app->user->id;
        $selectTime = false; //是否显示报表导出选项
        $monthTime = time() - 60 * 60 * 24 * date("t");

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

        $ids = $request->get('ids');
        $beginTime = $request->get('begin_time');
        if ($beginTime === null) {
            $beginTime = mktime(0, 0, 0, date('m', $monthTime), 1, date('Y', $monthTime));
        }
        $endTime = $request->get('end_time');
        if ($endTime === null) {
            $endTime = time();
        }
        $map = $request->get('map');
        $type = $request->get('type');
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $status = $request->get('status_id');
        $isclearing = $request->get('isclearing');
        $category = $request->get('category_id');

        $query = Reimbursement::find();

        $showVerify = false; //是否显示审核选项
        //权限判断
        /*$permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);*/
        $scopeUser = PermissionScope::getScopeUser('reimbursement/reimbursement/index');
        $viewUser = PermissionScope::getScopeUser('reimbursement/reimbursement/view');
        $deleteUser = PermissionScope::getScopeUser('reimbursement/reimbursement/delete');
        if (empty($scopeUser)) {
            //若当前用户拥有超级权限，则显示所有报销，并且编辑和报销选项均显示
            $query->orderBy([
                Reimbursement::isverifyOrderBy('verify') => SORT_ASC,
                //'reim_id' => SORT_DESC,
                'reim_time' => SORT_DESC,
            ]);
            if ($type == 'reim') {
                $query->where(['user_id' => $id]);
            } elseif ($type == 'verify') {
                $query->where("FIND_IN_SET(:verify_id,verify_ids)", [':verify_id' => $id]);
            }
            empty($gets) && $query->andWhere(['isverify' => Yii::$app->cache->get('reimbursement_config')['reimbursement_verify_show']]);
        } else {
            if (Reimbursement::readAccess('reimbursement/reimbursement/verify')) {
                //若当前用户有审核权限，则显示属于报销人的报销和自己申请的，并且编辑和报销选项均显示
                $query->orderBy([
                    Reimbursement::isverifyOrderBy('verify') => SORT_ASC,
                    //'reim_id' => SORT_DESC,
                    'reim_time' => SORT_DESC,
                ]);

                if ($type == 'reim') {
                    $query->where(['user_id' => $id]);
                } elseif ($type == 'verify') {
                    $query->where("FIND_IN_SET(:verify_id,verify_ids)", [':verify_id' => $id]);
                } else {
                    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);
                        //$query->where(array_merge(['or'], $findArr));
                    }/* else {
                        $query->where("user_id = :id or FIND_IN_SET(:verify_id,verify_ids)", [':id' => $id, ':verify_id' => $id]);
                    }*/
                }
                //根据后台配置显示列表
                empty($gets) && $query->andWhere(['isverify' => Yii::$app->cache->get('reimbursement_config')['reimbursement_verify_show']]);
                //$showVerify = true;
            } else {
                //若当前用户没有审核权限，则只显示当前用户申请的报销，并且只显示编辑选项
                $query->orderBy([
                    Reimbursement::isverifyOrderBy() => SORT_ASC,
                    //'reim_id' => SORT_DESC,
                    'reim_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('reimbursement_config')['reimbursement_reim_show']]);
                //$query->where(['user_id' => $id]);
            }
        }

        Reimbursement::readAccess('reimbursement/reimbursement/verify') && $showVerify = true;
        
        //$query->where("user_id = :id or FIND_IN_SET(:verify_id,verify_ids)", [':id' => $id, ':verify_id' => $id]);

        //搜索
        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', $field, $keywords]);
        }
        if ($status != '') {
            $query->andWhere(['isverify' => (int)$status]);
        }
        if ($isclearing != '') {
            $query->andWhere(['isclearing' => (int)$isclearing]);
        }
        if ($category != '') {
            $query->andwhere(['category_id' => (int)$category]);
        }

        if ($map == 'month') {
            //本月报销
            $begin_time = mktime(0, 0, 0, date('m'), 1, date('Y'));
            $end_time = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
            $query->andWhere(['between', 'reim_time', $begin_time, $end_time]);
        } elseif ($map == 'week') {
            //本周报销
            $begin_time = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
            $end_time = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y'));
            $query->andWhere(['between', 'reim_time', $begin_time, $end_time]);
        } elseif (!empty($beginTime) && !empty($endTime)) {
            //自定义时间搜索，当用户通过自定义时间段搜索时，显示报表导出选项
            $beginTime = (strtotime($beginTime) == false) ? $beginTime : strtotime($beginTime);
            $endTime = (strtotime($endTime) == false) ? $endTime : strtotime($endTime) + 86399;
            $query->andWhere(['between', 'reim_time', $beginTime, $endTime]);

            $selectTime = true;
        }

        //显示全部报销时去除搜索条件
        $type == 'all' && $query->where = $query->where[1];
        if ($ids != '') {
            //$beginTime = $endTime = null;
            $query->andWhere("FIND_IN_SET(user_id,:ids)", [':ids' => $ids]);
        }

        Yii::$app->cache->set('reim_list', $query);
        
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

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

    /**
     * 报销统计
     */
    public function actionStatistics()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        
        return $this->render('statistics',['id' => $id]);
    }

    /**
     * 报销统计(iframe)
     */
    public function actionStatisticsIframe() {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $beginTime = $request->get('begin_time');
        $endTime = $request->get('end_time');
        $map = $request->get('map');
        $type = $request->get('type');

        $category = Category::findOne(['cat_id' => $id]);
        $childs = $category['child_ids'];
        $childArr =  explode(',', $childs);
        $category = [];

        foreach ($childArr as $key => $value) {
            $child = Category::findOne(['cat_id' => $value]);
            $reim = Reimbursement::getReimByCategory($value, $map, $type, $beginTime, $endTime);
            $category[$key]['name'] = $child['name'];
            $category[$key]['count'] = empty($reim[0]['count(reim_id)']) ? '0' : $reim[0]['count(reim_id)'];
            $category[$key]['money'] = empty($reim[0]['sum(reim_money)']) ? '0' : $reim[0]['sum(reim_money)'];
            $category[$key]['bill'] = empty($reim[0]['sum(bill_amount)']) ? '0' : $reim[0]['sum(bill_amount)'];
            $category[$key]['wait'] = $reim[0]['wait'];
            $category[$key]['enable'] = $reim[0]['enable'];
            $category[$key]['disable'] = $reim[0]['disable'];
        }

        Yii::$app->cache->set('categoryId', $id);

        return $this->renderPartial('statistics-iframe',[
            'categorys' => $category,
            'id' => $id,
            'get' =>$request->get(),
            'begin_time' => $beginTime,
            'end_time' => $endTime,
        ]);
    }

    /**
     * 详情
     */
    public function actionDetail()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $user_id = Yii::$app->user->id;

        $model = Reimbursement::findOne(['reim_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/reimbursement/view');
        $deleteUser = PermissionScope::getScopeUser('reimbursement/reimbursement/delete');
        $verify_ids = explode(',', $model['verify_ids']);
        if (!empty($scopeUser) && !in_array($model['user_id'], $scopeUser) && !in_array($user_id, $verify_ids)) {
            Yii::$app->getSession()->setFlash('error', '当前没有浏览该报销详情的权限');
            return $this->flash();
        }

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

	/**
     * 报销审批
     */
    public function actionVerify()
    {
        $model = new Reimbursement();
        $request = Yii::$app->request;
        if ($request->isPost) {
            //审核表单提交操作
            $id = (int) $request->post('id');

            /*if ($request->post('verify_id') != '') {
	            $verify = Verify::findOne($request->post('verify_id'));
	        } else {*/
	        	$verify = new Verify();
	        	$verify->link_type = 'reim';
	        	$verify->link_id = $id;
	        /*}*/
	        $verify->status = $request->post('verify_status');
	        $verify->remark = $request->post('Reimbursement')['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便于显示数据
            $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' => 'reim', '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' => 'reim', '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' => 'reim',
            'link_id' => $id,
            'verify_user_id' => Yii::$app->user->id,
        ];
        $verifyResult = Verify::findOne($map);
        /*if (!empty($verifyResult)) {
            $verify = $verifyResult;
        } else {*/
            $verify = new Verify();
            $verify->link_type = 'reim';
            $verify->link_id = $id;
        /*}*/
        $verify->status = $status;
        ($remark != '') && $verify->remark = $remark;
        //更新报销审核表
        if (Reimbursement::readAccess('reimbursement/reimbursement/verify')) {
            if ($verify->save()) {
                $data = ['status' => 1, 'info' => '审核成功'];
            } else {
                $data = ['status' => 0, 'info' => '审核出错，请稍后再试'];
            }
        } else {
            $data = ['status' => 0, 'info' => '当前没有审核权限'];
        }

        return $data;
    }

    /**
     * ajax更改报销结算状态
     */
    public function actionSetIsclearing()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $isclearing = (int) $request->get('isclearing');

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

        if (empty($id)) {
            $data = ['status' => 0, 'info' => '数据错误'];
            return $data;
        }
        $reim = Reimbursement::find()
            ->where(['reim_id' => $id])
            ->one();

        if (!$reim) {
            $data = ['status' => 0, 'info' => '报销数据错误'];
            return $data;
        } elseif (!Yii::$app->session->get('isSuperAdmin') && !Reimbursement::readAccess('reimbursement/reimbursement/verify')) {
            //如果不是负责人或没有修改权限则不能修改
            $data = ['status' => 0, 'info' => '当前无权操作此报销'];
            return $data;
        }

        $command = Yii::$app->db->createCommand();
        $result = $command->update('{{%reimbursement}}', ['isclearing' => $isclearing], 'reim_id = :reim_id', [':reim_id' => $reim->reim_id])->execute();

        if (0 !== $result) {
            $data = ['status' => 1, 'info' => '结算状态修改成功'];
        } else {
            $data = ['status' => 0, 'info' => '设置失败'];
        }

        return $data;
    }

    /**
     * 报销金额检测
     */
    public function actionGetCheckMoney()
    {
        $category_id = Yii::$app->request->get('cat_id');
        $category = Category::findOne(['cat_id' => $category_id]);
        if (isset($category)) {
            $json['data'] = $category->check_money;
        } else {
            $json['data'] = 1;
        }

        return \Yii::createObject([
                'class' => 'yii\web\Response',
                'format' => \yii\web\Response::FORMAT_JSON,
                'data' => $json,
            ]);
    }

    /**
     * 报销类别树生成
     * @return [type] [description]
     */
    public function actionGetCategory()
    {
        $category = Category::getData([], ['sort' => SORT_DESC,'cat_id' => SORT_DESC], 'cat_id,parent_id,name', 'cat_id');

        $json['data'] = [];
        foreach ($category as $key => $value) {
            $value['open'] = true;
            $json['data'][] = $value;
        }

        return \Yii::createObject([
                'class' => 'yii\web\Response',
                'format' => \yii\web\Response::FORMAT_JSON,
                'data' => $json,
            ]);
    }

    /**
     * 报销报表导出
     */
    public function actionExport()
    {
        $request = Yii::$app->request;
        $beginTime = $request->get('beginTime');
        $endTime = $request->get('endTime');

        Reimbursement::pointExport('导出--报销明细', Yii::$app->cache->get('reim_list'), $beginTime, $endTime);
    }

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