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

namespace home\modules\sale\controllers;

use Yii;
use yii\web\Controller;
use common\models\Common;
use common\models\PermissionScope;
use yii\data\ActiveDataProvider;
use home\modules\sale\models\Opportunity;
use home\modules\customer\models\Customer;
use home\modules\customer\models\Contacter;
use yii\helpers\ArrayHelper;

/**
 * 销售机会控制器
 *
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class OpportunityController extends \home\controllers\Controller
{

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);

		$actions['create']['layout'] = '//modal';
		$actions['view']['layout'] = '//modal';
		$actions['update']['layout'] = '//modal';

        return $actions;
    }

    public function actionIndex()
    {
        $id = Yii::$app->user->identity->user_id;
        $query = Opportunity::find();
        $query->orderBy([
            'opportunity_id' => SORT_DESC,
            'create_time' => SORT_DESC,
        ]);

//        $permission = Common::getActionPermission($this->action);
//        $scopeUser = PermissionScope::getScopeUser($permission);
//        if (!empty($scopeUser)) {
//            $query->where(['in', 'leader_id', $scopeUser]);
//        }
        //搜索
        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $status = $request->get('status_id');
        $field = $request->get('search_field');
        $category = $request->get('category_id');
        $origin = $request->get('origin_id');
        if (!empty($keywords) && !empty($field)) {
            switch ($field) {
                case "customer":
                    $customers = Customer::find()->where(['like', 'name', $keywords])->select('customer_no')->asArray()->column();
                    $query->andWhere(['customer_no' => $customers]);
                    break;
                case "leader":
                    $leaders = \common\models\User::find()->where(['like', 'realname', $keywords])->select('user_id')->asArray()->column();
                    $query->andWhere(['leader_id' => $leaders]);
                    break;
                default :$query->andWhere(['like', $field, $keywords]);
            }
        }
        if ($status != '') {
            $query->andWhere(['status_id' => (int) $status]);
        }
        if ($category != '') {
            $query->andWhere("FIND_IN_SET(category_id,:ids)", [':ids' => $category]);
        }
        if ($origin != '') {
            $query->andwhere(['origin_id' => (int) $origin]);
        }
        //权限判断，除了超级管理员以外的都只能看到自己权限负责的
        $permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);
        if (!Yii::$app->session->get('isSuperAdmin') && !empty($scopeUser)) {
            $findArr = [];
            $userId = Yii::$app->user->id;
            $findArr[] = 'FIND_IN_SET(' . (int) $userId . ', share_user_ids)';
            $findStr = implode(' or ', $findArr);
            $district = Customer::find()->select('customer_no')->where(['in', 'leader_id', $scopeUser])->orWhere($findStr)->asArray()->all();
            $customerArray = arrayHelper::getColumn($district, 'customer_no');
            $query->andWhere(['in', 'customer_no', $customerArray]);
            //销售机会负责人是自己的
            $query->andWhere(['in', 'leader_id', $scopeUser]);
        }
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return $this->render('index',
            [
                'get' => $request->get(),
                'model' => new Opportunity(),
                'models' => $provider->models,
                'pages' => $provider->pagination,
            ]);
    }

    /**
     * 详情
     */
    public function actionDetail()
    {
        $request = Yii::$app->request;
        $id = (int) $request->get('id');
        $model = Opportunity::findOne(['opportunity_id' => $id]);
        if (empty($model)) {
            Yii::$app->getSession()->setFlash('error', '销售机会不存在');
            return $this->flash();
        }

        //权限检测
        $permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);
        if (!Yii::$app->session->get('isSuperAdmin') && !empty($scopeUser)) {
            
            $findArr = [];
            $userId = Yii::$app->user->id;
            $findArr[] = 'FIND_IN_SET(' . (int) $userId . ', share_user_ids)';
            $findStr = implode(' or ', $findArr);
            $district = Customer::find()->select('customer_no')->where(['in', 'leader_id', $scopeUser])->orWhere($findStr)->asArray()->all();
            $customerArray = arrayHelper::getColumn($district, 'customer_no');
            if (!in_array($model['customer_no'], $customerArray)) {
                Yii::$app->getSession()->setFlash('error', '你没有浏览该销售机会详情的权限');
                return $this->flash();
            }
            if (!in_array($model['leader_id'], $scopeUser)) {
                Yii::$app->getSession()->setFlash('error', '你没有浏览该销售机会详情的权限');
                return $this->flash();
            }
        }
        return $this->render('detail', [
            'model' => $model,
        ]);
    }

    /**
     * 选择客户后的关联操作
     */
    public function actionSelectLink()
    {
        $json = [
            'status' => 0,
            'customer_data' => '',
            'contacts_data' => ''
        ];
        $where['customer_no'] = Yii::$app->request->post('customer_no');
        $address = Customer::find()->where($where)->select('province_id, city_id, area_id, street')->one();
        $contacts = Contacter::find()->where($where)->andWhere(['status' => Contacter::STATUS_ENABLE])->select('contacter_id, name')->orderBy(['create_time' => SORT_DESC])->one();
        if (!empty($contacts)) {
            $json = [
                'status' => 1,
                'customer_data' => $address,
                'contacts_data' => $contacts
            ];
        } else {
            $json = [
                'status' => 1,
                'customer_data' => $address,
                'contacts_data' => ['contacter_id' => '', 'name' => '']
            ];
        }

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