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

namespace home\modules\schedule\controllers;

use Yii;
use home\controllers\Controller;
use home\models\Message;
use home\models\MessageLink;
use common\models\Common;
use yii\data\ActiveDataProvider;
use common\components\Tool;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\User;
use yii\helpers\Url;
use home\modules\customer\models\Customer;
use home\modules\sale\models\Opportunity;
use home\modules\schedule\models\Schedule;
use common\models\PermissionScope;
use home\models\Attachment;

/**
 * <日程管理控制器>
 * 
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class ScheduleController extends Controller
{

    public function actions()
    {
        $actions = parent::actions();
        $actions['create']['layout'] = '//modal';
        $actions['update']['layout'] = '//modal';
        $actions['update']['scopeAccessFields'] = ['user_id', 'join_ids'];
        $actions['view']['layout'] = '//modal';
        $actions['view']['scopeAccessFields'] = ['user_id', 'join_ids'];
        $actions['delete'] = [
            'class' => 'home\actions\TrashDelete',
            'to' => ['list-iframe'],
            'trashModel' => 'home\modules\schedule\models\ScheduleTrash',
            'scopeAccessFields' => ['user_id', 'join_ids'],
        ];
        return $actions;
    }

    public function actionList()
    {
        $request = Yii::$app->request;

        return $this->render('list', [
                'get' => $request->get(),
                'model' => new Schedule(),
        ]);
    }

    public function actionListIframe()
    {
        $query = Schedule::find();
        $query->orderBy(['create_time' => SORT_DESC, 'link_type' => SORT_ASC]);
        $request = Yii::$app->request;
        $keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');

        $category_id = $request->get('category_id');

        $beginTime = trim($request->get('begin_time'));
        $endTime = trim($request->get('end_time'));
        $ids = $request->get('ids');

        if (!empty($keywords) && !empty($field)) {
            switch ($field) {
                case 'name':
                    //当为关联名称时
                    $array = Schedule::getDataLink();
                    $customerNos = Customer::find()->where(['like', $field, $keywords])->andWhere(['in', 'customer_no', $array['customer']])->select('customer_no')->asArray()->all();
                    $customerArray = arrayHelper::getColumn($customerNos, 'customer_no');

                    $opportunityNos = Opportunity::find()->where(['like', $field, $keywords])->andWhere(['in', 'opportunity_no', $array['opportunity']])->select('customer_no')->select('opportunity_no')->asArray()->all();
                    $opportunityArray = arrayHelper::getColumn($opportunityNos, 'opportunity_no');

                    $data = array_merge($customerArray, $opportunityArray);

                    $query->where(['in', 'link_id', $data]);
                    break;
                case 'executor':
                    //当为执行人时
                    $customerNo = Customer::find()->where(['like', 'name', $keywords])->select('customer_no')->asArray()->column();
                    $query->where(['in', 'customer_no', $customerNo]);
                    break;
                default :
                    $query->where(['like', $field, $keywords]);
            }
        }

        //日程类别
        if (!empty($category_id)) {
            $query->andWhere(['category_id' => $category_id]);
        }

        //添加日期
        if (!empty($beginTime)) {
            $beginTime = strtotime($beginTime);
            $query->andWhere('create_time >= :beginTime', [':beginTime' => $beginTime]);
        }
        if (!empty($endTime)) {
            $endTime = strtotime($endTime);
            $query->andWhere('create_time <= :endTime', [':endTime' => $endTime + 24 * 60 * 60]);
        }

        //左侧树筛选
        if ($ids != '') {
            $ids = explode(',', $ids);
            $idsArr = [];
            foreach ($ids as $id) {
                $idsArr[] = 'FIND_IN_SET(' . (int) $id . ', join_ids)';
            }
            $idsArr = implode(' or ', $idsArr);

            $query->andWhere($idsArr);
        }

        $permission = 'schedule/schedule/list';
        $scopeUser = PermissionScope::getScopeUser($permission);
        //权限判断
        if (!Yii::$app->session->get('isSuperAdmin') && !empty($scopeUser)) {
            $findArr = [];
            foreach ($scopeUser as $u) {
                $findArr[] = 'FIND_IN_SET(' . (int) $u . ', join_ids)';
            }
            $findStr = implode(' or ', $findArr);
            $query->andWhere(' `user_id` in (' . implode(', ', $scopeUser) . ') or ' . $findStr);
        }
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 15,
            ],
        ]);
        $models = $provider->models;
        foreach ($models as $k => $v) {
            $linkData = Common::getLinkData($v['link_type'], $v['link_id']);
            $models[$k]['name'] = ArrayHelper::getValue($linkData, 'name');
            $models[$k]['type_name'] = Common::getLinkTypeData($v['link_type'])['name'];
            $models[$k]['join_names'] = implode(',', ArrayHelper::getColumn(User::getUserByDot($v['join_ids']), 'realname'));
            if ($v['link_type'] != 'customer') {
                if (isset($linkData['opportunity_id'])) {
                    $oppo = Opportunity::findOne($linkData['opportunity_id']);
                    $models[$k]['customer'] = $oppo->customer;
                }
            } else {
                $models[$k]['customer'] = $linkData;
            }
        }
        return $this->renderPartial('list-iframe',
                [
                'get' => $request->get(),
                'model' => new Schedule(),
                'models' => $models,
                'pages' => $provider->pagination,
        ]);
    }

    /**
     * 查看当前日程的详情
     */
    public function actionDetail()
    {
        $id = (int) Yii::$app->request->get('id');
        $model = Schedule::findOne($id);
        if (!$model) {
            return $this->flash('查看的日程不存在', 'error');
        }
        $permission = Common::getActionPermission($this->action);
        $scopeUser = PermissionScope::getScopeUser($permission);

        //权限判断
        if (!Yii::$app->session->get('isSuperAdmin') && !empty($scopeUser)) {
            if (!in_array($model->user_id, $scopeUser) && count(array_intersect(explode(',', $model->join_ids), $scopeUser)) <= 0) {
                return $this->flash('您没有权限查看', 'error');
            }
        }

        $model->type_name = Common::getLinkTypeData($model->link_type)['name'];
        $model->name = ArrayHelper::getValue(Common::getLinkData($model->link_type, $model->link_id), 'name');
        $model->join_names = implode(',', ArrayHelper::getColumn(User::getUserByDot($model->join_ids), 'realname'));
        $this->layout = "//modal";
        return $this->render('detail', [
                'model' => $model,
        ]);
    }

    /**
     * 关联跳转
     */
    public function actionSkip()
    {
        $request = Yii::$app->request;
        $type = $request->get('link_type');
        $no = $request->get('link_id');
        $data = Common::getLinkData($type, $no);
        if ($type == 'sale_opportunity') {
            $this->redirect(['/sale/opportunity/detail', 'id' => ArrayHelper::getValue($data, 'opportunity_id')]);
        } else if ($type == 'customer') {
            $this->redirect(['/customer/customer/detail', 'id' => ArrayHelper::getValue($data, 'customer_id')]);
        }
    }

    /**
     * ajax获取关联日志
     */
    public function actionAjaxGetLinkSchedule()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $request = Yii::$app->request;
        $linkId = $request->get('link_id');
        $linkType = $request->get('link_type');
        $userId = $request->get('user_id');
        $scopeUser = '';

        $linkData = Common::getLinkData($linkType, $linkId);

        if (empty($linkData)) {
            return ['status' => 0, 'info' => '关联信息不存在'];
        }

        $types = Common::getLinkTypes([$linkType]);
        if (empty($types)) {
            return ['status' => 0, 'info' => '关联类型不支持'];
        }
        $linkData['link_type'] = $types[$linkType];


        $linkIds = $linkData[$linkData['link_type']['link_field']];

        $query = Schedule::find()
            ->with('user', 'contacter', 'category')
            ->where(['link_type' => $linkType, 'link_id' => $linkIds])
            ->orderBy(['schedule_time' => SORT_DESC, 'create_time' => SORT_DESC])
            ->asArray();

        if (!empty($scopeUser) && empty($userId)) {
            $query->andWhere(['user_id' => $scopeUser]);
        }

        if (!empty($userId)) {
            $query->andWhere(['user_id' => $userId]);
        }

        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);
        $models = $provider->getModels();
        foreach ($models as &$model) {
            $model['schedule_time'] = date('Y-m-d ', $model['schedule_time']);
            $model['create_time'] = date('Y-m-d H:i', $model['create_time']);
            $model['avatar'] = (!empty($model['user']['avatar'])) ? $model['user']['avatar'] : Yii::getAlias('@web') . '/static/images/headpic.jpg';
            $model['join_names'] = implode(',', ArrayHelper::getColumn(User::getUserByDot($model['join_ids']), 'realname'));
            if (Schedule::checkScheduleAccess('schedule/schedule/update')) {
                $model['url'] = Url::to(['/schedule/view', 'id' => $model['schedule_id'], 'from' => Url::to('')]);
                $model['classify'] = 'open-dialog';
            } else {
                $model['url'] = '';
                $model['classify'] = '';
            }

            if (empty($model['contacter'])) {
                $model['contacter']['name'] = '无';
            }

            //附件
            $attachHtml = '';
            if ($model['attach_ids'] != '' && $attachs = Attachment::getAttachByDot($model['attach_ids'])) {
                foreach ($attachs as $attach) {
                    $attachHtml .= '<p><a href="' . Url::to(['/attachment/download', 'id' => $attach['attach_id']]) . '" title="点击下载" >' . $attach['file_name'] . '</a> ' . ($attach['is_image'] == 1 ? '<a href="javascript:imagePriview(\'' . $attach['file_path'] . '\')" >[预览]</a>'
                                : '' ) . '</p>';
                }
            }
            $model['attach_html'] = $attachHtml;
        }

        $data = [
            'models' => $models,
            'pages' => \yii\widgets\LinkPager::widget(['pagination' => $provider->pagination, 'prevPageLabel' => '上一页', 'nextPageLabel' => '下一页', 'firstPageLabel' => '首页', 'lastPageLabel' => '末页']),
            'count' => $query->count(),
        ];

        return $data;
    }

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

    /**
     * 获取日程
     */
    public function actionGetSchedules()
    {
        $request = \Yii::$app->request;
        $startTime = trim($request->post('start'));
        $endTime = trim($request->post('end'));
        $queryType = trim($request->post('query_type'));
        $queryValue = trim($request->post('query_value'));
        $andWhere[] = ['between', 'schedule_time', strtotime($startTime), strtotime($endTime)];
        if ($queryValue != '0') {
            $queryValue = explode(',', $queryValue);
            $scopeUser = PermissionScope::getScopeUser('schedule/schedule/index'); //权限控制数据范围
            if (!empty($scopeUser)) {
                $queryValue = array_intersect($queryValue, $scopeUser); //取交集
            }
            //权限判断
            $findArr = [];
            foreach ($queryValue as $u) {
                $findArr[] = 'FIND_IN_SET(' . (int) $u . ', join_ids)';
            }
            $findStr = implode(' or ', $findArr);
            $andWhere[] = $findStr;
        }

        $list = Schedule::getCalendarData($andWhere);
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return [
            'data' => $list,
        ];
    }
}