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

namespace wap\controllers;

use Yii;
use wap\controllers\Controller;
use wap\models\Reimbursement;
use yii\db\Query;
use common\models\Common;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\data\ActiveDataProvider;
use yii\helpers\StringHelper;
use yii\helpers\Url;
use common\models\PermissionScope;
use home\modules\reimbursement\models\Verify;

/**
 * 报销控制器
 *
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class ReimbursementController extends Controller
{
    /**
     * 首页
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $category = $request->get('category', 'category');

        if ($request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $keywords = $request->get('keywords');

//            $scopeUser = PermissionScope::getScopeUser('reimbursement/reimbursement/index');
            $query = Reimbursement::find()->with('category');
//            if (empty($scopeUser)) {
//                //若当前用户拥有超级权限，则显示所有报销，并且编辑和报销选项均显示
//                $query->orderBy([
//                    Reimbursement::isverifyOrderBy('verify') => SORT_ASC,
//                    'reim_id' => SORT_DESC,
//                    'create_time' => SORT_DESC,
//                ]);
//                $showVerify = true;
//            } else {
//                if (Reimbursement::readAccess('reimbursement/reimbursement/verify')) {
//                    //若当前用户有审核权限，则显示属于报销人的报销和自己申请的，并且编辑和报销选项均显示
//                    $query->orderBy([
//                        Reimbursement::isverifyOrderBy('verify') => SORT_ASC,
//                        'reim_id' => SORT_DESC,
//                        'create_time' => SORT_DESC,
//                    ]);
//
//                    $findArr = [];
//                    foreach ($scopeUser as $u) {
//                        $findArr[] = 'user_id = ' . (int) $u;
//                    }
//                    $findArr[] = 'FIND_IN_SET(' . $userId . ', verify_ids)';
//                    $findStr = implode(' or ', $findArr);
//                    $query->where($findStr);
//
//                    $showVerify = true;
//                } else {
                    //若当前用户没有审核权限，则只显示当前用户申请的报销，并且只显示编辑选项
                    $query->orderBy([
                        Reimbursement::isverifyOrderBy() => SORT_ASC,
                        'reim_id' => SORT_DESC,
                        'create_time' => SORT_DESC,
                    ]);

                    $findArr = [];
                    $user_id=  Yii::$app->user->id;
                    $findArr[] = 'user_id = ' . (int) $user_id;
//                    foreach ($scopeUser as $u) {
//                        $findArr[] = 'user_id = ' . (int) $u;
//                    }
                    $findStr = implode(' or ', $findArr);
                    $query->where($findStr);
//                }
//            }
            if (!empty($keywords)) {
                $query->andWhere(['like', 'name', trim($keywords)]);
            }

            if ($category == 'category') {
                $query->orderBy([
                    'category_id' => SORT_ASC,
                    'create_time' => SORT_DESC,
                ]);
            }

            $provider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => [
                    'pageSize' => 10,
                ],
            ]);
            $models = $provider->getModels();

            $html = $this->getReimListHtml($models);

            $data = [
                'status' => 1,
                'content' => $html,
                'totalPage' => $provider->pagination->pageCount,
            ];

            return $data;
        } else {
            return $this->render('index', [
                    'category' => $category,
            ]);
        }
    }

    /**
     * 获取报销html内容
     *
     * @param $models 报销数据
     */
    private function getReimListHtml($models)
    {
        $userId = Yii::$app->user->id;
        $html = '';
        $typeData = Common::getLinkTypeData();
        foreach ($models as &$model) {
            $model['name'] = StringHelper::truncate($model['name'], 14);
            $date = date('m-d', $model['reim_time']);
            $year = date('Y', $model['reim_time']);
            $url = Url::to(['detail', 'id' => $model['reim_id']]);
            $model['reim_money'] = number_format($model['reim_money'], 2, '.', ' ,');
            $categoryName = isset($model['category']) ? $model['category']['name'] : '';
            $typeName = (isset($model['link_type']) && isset($typeData[$model['link_type']])) ? $typeData[$model['link_type']]['name'] : '';
            $styleIcon = '';
            $verifyIcon = '';
            $checkIcon = '';
            $styleCheck = '';
            switch ($model['isverify']) {
                case '0':
                    $verifyIcon = 'icon-minus-sign';
                    if ($model['isverify'] == Reimbursement::ISVERIFY_WAIT && in_array(Yii::$app->user->identity->user_id, explode(',', $model->verify_ids)) && Reimbursement::readAccess('reimbursement/reimbursement/set-status')) {
                        $checkIcon = 'icon-check-minus';
                        $styleCheck = 'color:red';
                    }
                    break;
                case '1':
                    $verifyIcon = 'icon-ok-sign';
                    $styleIcon = "color:green";
                    break;
                case '2':
                    $verifyIcon = 'icon-remove-sign';
                    $styleIcon = "color:red";
                    break;
            }
            $html .= <<<TPL
                <li>
                <a href="{$url}">
                    <p class="reimburs-date"><span>{$date}</span><br>
                    {$year}</p>
                    <div class="reimburs-info">
                        <h4 class="{$checkIcon}" style="{$styleCheck}">{$model['name']}</h4>
                        <p><span>{$model['bill_amount']}张</span><span>{$categoryName}</span><span>{$typeName}</span> </p>
                    </div>
                    <span class="reimburs-amount">{$model['reim_money']}元</span>
                    <i class="{$verifyIcon}" style="{$styleIcon}"></i>
                </a>
                </li>
TPL;
        }
        return $html;
    }

    /**
     * 新增报销
     */
    public function actionCreate()
    {
        $this->model = new Reimbursement();
        $request = Yii::$app->request;
        $reimburseInfo = Yii::$app->session->get('reimbursement_save');

        if ($this->model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if ($this->model->save()) {
                $linkId = $this->model->link_id;
                $linkType = $this->model->link_type;
                //清除保存的数据
                if (!empty($reimburseInfo) && isset($reimburseInfo[$linkType . '-' . $linkId])) {
                    unset($reimburseInfo[$linkType . '-' . $linkId]);
                    Yii::$app->session->set('reimbursement_save', $reimburseInfo);
                }
                $data = ['status' => 1, 'info' => '新增报销成功', 'url' => Url::to(['index'])];
            } elseif ($this->model->hasErrors()) {
                $firstError = reset($this->model->getFirstErrors());
                $data = ['status' => 0, 'info' => $firstError];
            }
            return $data;
        }

        $linkId = $request->get('link_id');
        $linkType = $request->get('link_type');
        $linkData = Common::getLinkData($linkType, $linkId);
        if (empty($linkData)) {
            throw new NotFoundHttpException('关联信息不存在');
        }

        //获取已保存的报销
        if (!empty($reimburseInfo) && isset($reimburseInfo[$linkType . '-' . $linkId])) {
            $this->model->attributes = $reimburseInfo[$linkType . '-' . $linkId];
        }

        return $this->render('create',
                [
                'model' => $this->model,
                'linkData' => $linkData,
                'linkId' => $linkId,
                'linkType' => $linkType,
        ]);
    }

    /**
     * 获取关联的报销
     */
    public function actionGetLinkReim()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $linkId = $request->get('link_id');
        $linkType = $request->get('link_type');

        /*
         * wap下报销申请下放的报销列报只能查看自己对改任务的报销情况
         * HuLimin 20150205
         */
        $query = Reimbursement::find()
            ->where(['link_type' => $linkType, 'link_id' => $linkId, 'user_id' => Yii::$app->user->id])
            ->orderBy(['create_time' => SORT_DESC]);

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);
        $models = $provider->getModels();

        $html = $this->getReimListHtml($models);

        $data = [
            'status' => 1,
            'content' => $html,
            'totalPage' => $provider->pagination->pageCount,
        ];

        return $data;
    }

    /**
     * 选择申请单，并保存当前的报销申请信息
     */
    public function actionChooseAppli()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $session = Yii::$app->session;
        $post = Yii::$app->request->post('Reimbursement');
        $reimburseInfo = $session->get('reimbursement_save');
        $reimburseInfo[$post['link_type'] . '-' . $post['link_id']] = $post;
        $session->set('reimbursement_save', $reimburseInfo);
        $url = (!empty($post['appli_id'])) ? Url::to(['/application/choose-detail', 'link_id' => $post['link_id'], 'link_type' => $post['link_type'], 'id' => $post['appli_id']]) : Url::to(['/application/choose-appli',
                'link_id' => $post['link_id'], 'link_type' => $post['link_type']]);

        return ['status' => 1, 'url' => $url];
    }

    /**
     * 报销详情
     */
    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)) {
            throw new NotFoundHttpException('该报销不存在或已被删除');
        }

        //权限检测
        $scopeUser = PermissionScope::getScopeUser('reimbursement/reimbursement/detail');
        $verify_ids = explode(',', $model['verify_ids']);
        if (!empty($scopeUser) && !in_array($model['user_id'], $scopeUser) && !in_array($user_id, $verify_ids)) {
            throw new ForbiddenHttpException('当前没有浏览该报销详情的权限');
        }

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