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

namespace home\controllers;

use Yii;
use common\models\User;
use qcbase\models\Department;
use yii\db\Query;
use yii\data\ActiveDataProvider;
use home\modules\task\models\Category as TaskCategory;
use common\models\PermissionScope;
use home\modules\task\models\Task;
use home\modules\customer\models\Customer;
use home\modules\customer\models\District;
use yii\helpers\ArrayHelper;
use common\models\Common;
use home\modules\contract\models\Contract;
use common\components\Tool;


/**
 * 关联控制器
 * 
 * 专门用来弹出各种关联的页面,比如任务合同项目
 * 
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class LinkController extends Controller
{
    public $layout = 'modal';

    /**
     * 弹出单项选择用户
     */
    public function actionSingleUser()
    {
        $request = Yii::$app->request;

        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $deptId = $request->get('dept_id');
        $value = $request->get('value', '');
        $value = explode(',', $value);

        $map = [];
        if (!empty($keywords) && !empty($field)) {
            $map[] = ['like', $field, $keywords];
        }
        $list = User::getListByMultDept($map, $deptId, true);

        return $this->render('single-user', [
            'get' => Yii::$app->request->get(),
            'models' => $list,
            'value' => $value,
        ]);
    }

    /**
     * 弹出多选用户
     */
    public function actionMultiUser()
    {
        $request = Yii::$app->request;

        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $deptId = (int) $request->get('dept_id');
        $value = $request->get('value', '');
        $value = explode(',', $value);
        $typeModule = trim($request->get('type_module'));
        $typeModule = !empty($typeModule) ? $typeModule : '';

        $map = [];
        if (!empty($keywords) && !empty($field)) {
            $map[] = ['like', $field, $keywords];
        }

        $list = User::getListByDepartment($map, $deptId, true, $typeModule);

        return $this->render('multi-user', [
                'get' => Yii::$app->request->get(),
                'models' => $list,
                'value' => $value,
        ]);
    }

    /**
     * 弹出选择项目
     */
    public function actionProject()
    {
        $request = Yii::$app->request;

        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $catId = (int) $request->get('cat_id');

        $typeModule = trim($request->get('type_module'));
        $typeModule = !empty($typeModule) ? $typeModule : '';
        $workTime = trim($request->get('work_time'));

        $query = (new Query())
            ->select('p.*,c.name as cat_name')
            ->from('{{%project}} p')
            ->orderBy(['p.project_id' => SORT_DESC])
            ->leftJoin('{{%project_category}} c', 'c.cat_id = p.category_id');

        //权限范围过滤
        $scopeUser = PermissionScope::getScopeUser('project/project/index');
        if (!empty($scopeUser)) {
            $findArr = [];
            foreach ($scopeUser as $u) {
                $findArr[] = 'p.user_id = ' . (int) $u;
                $findArr[] = 'p.leader_id = ' . (int) $u;
            }
            $projectWhere = implode(' or ', $findArr);
        }
        if (!empty($projectWhere)) {
            $query->where($projectWhere);
        }

        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', 'p.' . $field, $keywords]);
        }
        if (!empty($catId)) {
            $query->andWhere(['p.category_id' => $catId]);
        }

        //数据过滤
        if (!empty($typeModule)) {
            switch ($typeModule) {
                case 'blog':
                    $time = [strtotime($workTime), strtotime($workTime) + 86400];
                    $modeuleWhere = \home\modules\blog\models\Blog::getLinkIdByTime('task', $time);
                    break;
                case 'task':
                    $modeuleWhere = Task::find()->select('link_id')->where(['link_type' => 'project'])->distinct()->column();
                    break;
            }
        }

        if (!empty($modeuleWhere)) {
            $query->andWhere(['not in', 'p.project_no', $modeuleWhere]); //过滤已写日志的的客户
        }


        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('project', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 弹出选择合同
     */
    public function actionContract()
    {
        $request = Yii::$app->request;

        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $catId = (int) $request->get('cat_id');
        $model = new Contract();
        $query = Contract::find();
//        $query = (new Query())
//            ->select('ct.*,cc.name as cat_name,s.name as status_name')
//            ->from('{{%contract}} ct')
//            ->orderBy(['ct.contract_id' => SORT_DESC])
//            ->leftJoin('{{%contract_category}} cc', 'cc.cat_id = ct.category_id')
//            ->leftJoin('{{%contract_status}} s', 's.status_id= ct.status_id');

        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', $field, $keywords]);
        }
        if (!empty($catId)) {
            $query->andWhere(['category_id' => $catId]);
        }
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $scopeUser = PermissionScope::getScopeUser("contract/contract/index");  //查找合同的权限范围
            $result = District::getMyDistrict("customer/customer/index");  //查找客户的权限范围
            if (count($scopeUser) > 0 && count($result) > 0) {
                $district = Customer::find()->select('customer_no')->where(['in', 'district_id', $result])->asArray()->all();
                $customerArray = arrayHelper::getColumn($district, 'customer_no');
                $query->andWhere(['or', ['in', 'owner_id', $scopeUser], ['in', 'customer_no', $customerArray]]);
            } else if (count($scopeUser) > 0 && ($result === false)) {
                $query->andWhere(['in', 'owner_id', $scopeUser]);
            } else if (count($result) > 0 && ($scopeUser === false)) {
                $district = Customer::find()->select('customer_no')->where(['in', 'district_id', $result])->asArray()->all();
                $customerArray = arrayHelper::getColumn($district, 'customer_no');
                $query->andWhere( ['in', 'customer_no', $customerArray]);
            } else if (($scopeUser === false) && ($result === false)) {
                $scopeUser = [];
                $query->andWhere( ['in', 'owner_id', $scopeUser]);
            }
        }
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('contract', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 弹出选择客户
     */
    public function actionCustomer()
    {
        $request = Yii::$app->request;

        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $catId = (int) $request->get('cat_id');

        $typeModule = trim($request->get('type_module'));
        $typeModule = !empty($typeModule) ? $typeModule : '';
        $workTime = trim($request->get('work_time'));
        $query = Customer::find();
//        $query = (new Query())
//            ->select('ct.*,cc.name as cat_name,a.name as area_name')
//            ->from('{{%customer}} ct')
//            ->orderBy(['ct.customer_id' => SORT_DESC])
//            ->leftJoin('{{%customer_category}} cc', 'cc.cat_id = ct.category_id')
//            ->leftJoin('{{%customer_district}} a', 'a.district_id = ct.district_id');

        //权限判断，除了超级管理员以外的都只能看到自己负责区域的客户所关联的合同
        $scopeUser = PermissionScope::getScopeUser('customer/customer/index');
        if (!Yii::$app->session->get('isSuperAdmin') && !empty($scopeUser)) {
            $query->andWhere(['in', 'leader_id', $scopeUser]);
            $findArr = [];
            $userId = Yii::$app->user->id;
            $findArr[] = 'FIND_IN_SET(' . (int) $userId . ', share_user_ids)';
            $findStr = implode(' or ', $findArr);
            $query->orWhere($findStr);
        }
        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like',  $field, $keywords]);
        }
        if (!empty($catId)) {
            $query->andWhere(['category_id' => $catId]);
        }

        $query->orderBy(['attention' => SORT_DESC, 'customer_id' => SORT_DESC]);

        if (!empty($modeuleWhere)) {
            $query->andWhere(['not in', 'customer_no', $modeuleWhere]); //过滤已写日志的的客户
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('customer', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 弹出选择任务
     */
    public function actionTask()
    {
        $request = Yii::$app->request;

        $user_id = Yii::$app->user->id;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $catId = (int) $request->get('cat_id');
        $typePermission = trim($request->get('type_permission'));
        $typePermission = !empty($typePermission) ? $typePermission : 'create-child';

        $typeModule = trim($request->get('type_module'));
        $typeModule = !empty($typeModule) ? $typeModule : '';
        $workTime = trim($request->get('work_time'));

        $taskConfig = Yii::$app->cache->get('task_config');
        $taskWhere = [];
        $modeuleWhere = [];

        //权限范围过滤
        $scopeUser = PermissionScope::getScopeUser('task/task/list');
        if (!empty($scopeUser)) {
            $taskWhere = Task::getRelatedTaskQueryStr($scopeUser, 't.');
        }

        //数据过滤
        if (!empty($typeModule)) {
            switch ($typeModule) {
                case 'blog':
                    $time = [strtotime($workTime), strtotime($workTime) + 86400];
                    $modeuleWhere = \home\modules\blog\models\Blog::getLinkIdByTime('task', $time);
                    //如果是添加日志则需要加一些判断
                    $scopeUser = PermissionScope::getScopeUser('task/task/create-blog');
                    if (!empty($scopeUser)) {
                        $taskWhere = Task::getRelatedTaskQueryStr($scopeUser, 't.', Task::getPermissionRole('task/task/create-blog'));
                    }

                    break;
            }
        }

        $query = (new Query())
            ->select('t.*,c.name as cat_name,u.realname as leader_name')
            ->from('{{%task}} t')
            ->orderBy(['task_id' => SORT_DESC])
            ->leftJoin('{{%task_category}} c', 'c.cat_id = t.category_id')
            ->leftJoin('{{%user}} u', 'u.user_id = t.leader_id');

        //获取公共任务
        $publicCategorys = TaskCategory::getPublicCategory();

        //这里先判断有没有搜索任务分类
        if (!empty($catId)) {
            $category = TaskCategory::findOne($catId);
            if (in_array($catId, $publicCategorys)) {
                $query->andWhere(['t.category_id' => explode(',', $category['child_ids'])]);
            } else {
                if (!empty($taskWhere)) {
                    $query->where($taskWhere);
                }
                $query->andWhere(['t.category_id' => explode(',', $category['child_ids'])]);
            }
        } else {
            if (!empty($taskWhere)) {
                $query->where($taskWhere);
                //只有当有where查询时才能加or查询
                if (!empty($publicCategorys)) {
                    $query->orWhere(['t.category_id' => $publicCategorys]);
                }
            }
        }

        if (!empty($modeuleWhere)) {
            $query->andWhere(['not in', 't.task_no', $modeuleWhere]); //过滤已写日志的的任务
        }

        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', 't.' . $field, $keywords]);
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('task', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 弹出选择费用申请
     *
     * @author Strief
     */
    public function actionApplication()
    {
        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');

        $query = (new Query())
            ->select('ap.*')
            ->orderBy(['appli_id' => SORT_DESC])
            ->from('{{%reimbursement_application}} ap');

        $query->where(['isverify' => 1, 'isused' => 0]);

        //权限范围过滤
        /* $scopeUser = PermissionScope::getScopeUser('reimbursement/application/index');
          if (!empty($scopeUser)) {
          $findArr = [];
          foreach ($scopeUser as $u) {
          $findArr[] = 'ap.user_id = ' . (int) $u;
          }
          $applicationWhere = implode(' or ', $findArr);
          }
          if (!empty($applicationWhere)) {
          $query->andWhere($applicationWhere);
          } */

        $query->andWhere(['ap.user_id' => Yii::$app->user->id]);

        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', 'ap.' . $field, $keywords]);
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('application', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 弹出多选部门
     *
     * @author Strief
     */
    public function actionDepartment()
    {
        $list = Department::getList();
        return $this->render('department', [
                'models' => $list,
        ]);
    }

    /**
     * 弹出选择工作流
     *
     * @author Strief
     */
    public function actionWorkflow()
    {
        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');

        $query = (new Query())
            ->select('wo.*')
            ->from('{{%workflow}} wo');

        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', 'wo.' . $field, $keywords]);
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('workflow', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 弹出选择联系人
     *
     * @author Strief
     */
    public function actionContacter()
    {
        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $customer_no = $request->get('customer_no');
        $link_customer_no = $request->get('link_customer_no');  //当销售机会添加日程时候，$customer_no是销售机会的编号而非客户编号，所以传递客户编号过来


        $query = (new Query())
            ->select('co.*, cu.name as customer_name')
            ->from('{{%customer_contacter}} co')
            ->orderBy(['co.contacter_id' => SORT_DESC])
            ->leftJoin('{{%customer}} cu', 'cu.customer_no = co.customer_no');
        $query->where(['co.status' => 1]);
        if (!empty($customer_no)) {
            $customer_no = empty($link_customer_no) ? $customer_no : $link_customer_no;
            $query->andWhere(['co.customer_no' => $customer_no]);
        }
        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', 'co.' . $field, $keywords]);
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('contacter', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 弹出选择销售机会
     *
     * @author Strief
     */
    public function actionOpportunity()
    {
        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');

        $typeModule = trim($request->get('type_module'));
        $typeModule = !empty($typeModule) ? $typeModule : '';
        $workTime = trim($request->get('work_time'));

        $query = (new Query())
            ->select('sa.*, or.name as or_name, ca.name as ca_name, st.name as st_name')
            ->from('{{%sale_opportunity}} sa')
            ->orderBy(['sa.opportunity_id' => SORT_DESC])
            ->leftJoin('{{%sale_origin}} or', 'or.origin_id = sa.origin_id')
            ->leftJoin('{{%sale_category}} ca', 'ca.cat_id = sa.category_id')
            ->leftJoin('{{%sale_status}} st', 'st.status_id = sa.status_id');

        //权限范围过滤
        $scopeUser = PermissionScope::getScopeUser('sale/opportunity/index');
        if (!empty($scopeUser)) {
            $findArr = [];
            foreach ($scopeUser as $u) {
                $findArr[] = 'sa.user_id = ' . (int) $u;
            }
            $opportunityWhere = implode(' or ', $findArr);
        }
        if (!empty($opportunityWhere)) {
            $query->where($opportunityWhere);
        }

        if (!empty($keywords) && !empty($field)) {
            $query->andWhere(['like', 'sa.' . $field, $keywords]);
        }

        //数据过滤
        if (!empty($typeModule)) {
            switch ($typeModule) {
                case 'blog':
                    $time = [strtotime($workTime), strtotime($workTime) + 86400];
                    $modeuleWhere = \home\modules\blog\models\Blog::getLinkIdByTime('task', $time);
                    break;
            }
        }

        if (!empty($modeuleWhere)) {
            $query->andWhere(['not in', 'sa.opportunity_no', $modeuleWhere]); //过滤已写日志的的客户
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 8,
            ],
        ]);

        return $this->render('opportunity', [
                'get' => $request->get(),
                'models' => $provider->getModels(),
                'pages' => $provider->pagination,
        ]);
    }
}
