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

namespace home\modules\schedule\models;

use Yii;
use qcbase\models\Auth;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
use common\models\User;
use common\models\Common;
use home\assets\LinkAsset;
use common\models\PermissionScope;
use home\modules\customer\models\Contacter;
use home\modules\customer\models\Customer;
use home\modules\sale\models\Opportunity;
use yii\helpers\Url;

/**
 * This is the model class for table "{{%schedule%}}".
 *
 * 日程模型
 *
 * @property integer $schedule_id  (ID)
 * @property string $title  (主题)
 * @property string $link_type  (日志类型（customer客户）)
 * @property string $link_id  (关联信息标识)
 * @property string $join_ids  (执行人)
 * @property integer $work_time  (工作日期)
 * @property float $workload  (工作量（小时）)
 * @property text $content  (行动描述)
 * @property string $remark  (备注)
 * @property integer $create_time  (创建时间)
 * @property integer $update_time  (最后更新时间)
 * @property smallint $status  (状态  99逻辑删除)
 * @property string $attach_ids  (附件)
 * @property integer $user_id  (创建人ID)
 * @property string $ip  (创建人IP)
 * @property integer $read_time  (阅读时间)
 * @property integer $read_user_id  (阅读人ID)
 * @property integer $category_id  (日程类型)
 * @property integer $contacter_id  (联系人ID)
 * @property integer $schedule_time  (日程时间)
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class Schedule extends \yii\db\ActiveRecord
{
    public $link_name; //关联信息名称
    public $join_names; //关联信息名称
    public $contacter_name; //关联信息名称
    public $link_customer_no;
    public $url;
    public $name;
    public $type_name;
    public $customer;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%schedule}}';
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        $scenario = parent::scenarios();
        $scenario['insert'] = ['title', 'link_type', 'link_id', 'contacter_id', 'category_id', 'join_ids', 'content', 'attach_ids', 'schedule_time', 'create_time', 'update_time', 'user_id', 'ip'];
        $scenario['update'] = ['title', 'link_type', 'link_id', 'contacter_id', 'category_id', 'join_ids', 'content', 'attach_ids', 'schedule_time', 'update_time'];
        $scenario['detail'] = [];
        return $scenario;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'schedule_time', 'join_names', 'category_id'], 'required'],
            [['work_time', 'create_time', 'update_time', 'status', 'user_id', 'read_time', 'read_user_id', 'category_id', 'contacter_id'], 'integer'],
            [['workload'], 'number'],
            [['contacter_id'], 'default', 'value' => 0],
            [['content'], 'required'],
            [['content'], 'string'],
            [['title'], 'string', 'max' => 200],
            [['link_type'], 'string', 'max' => 20],
            [['link_id'], 'string', 'max' => 60],
            [['join_ids', 'remark', 'attach_ids'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'schedule_id' => 'ID',
            'title' => '主题',
            'link_type' => '关联类型',
            'link_id' => '关联id',
            'join_ids' => '执行人',
            'join_names' => '执行人',
            'work_time' => '工作日期',
            'workload' => '工作量',
            'content' => '行动描述',
            'remark' => '备注',
            'create_time' => '创建时间',
            'update_time' => '最后更新时间',
            'status' => '状态',
            'attach_ids' => '附件',
            'user_id' => '创建人id',
            'ip' => 'Ip',
            'read_time' => 'Read Time',
            'read_user_id' => 'Read User ID',
            'category_id' => '类型',
            'contacter_id' => '联系人',
            'contacter_name' => '联系人',
            'schedule_time' => '日期',
            'name' => '名称',
            'type_name' => '关联类型'
        ];
    }

    /**
     * 公共搜索所需信息
     *
     * 这里返回公共搜索的信息，我们希望所有的搜索走统一的配置
     * 返回值里的键名为keywords的数组为搜索里关键字搜索所支持的字段
     * 返回值里的键名为status的数组为搜索里状态搜索所支持的字段
     */
    public function search()
    {
        return [
            'keywords' => [
                'title' => '主题',
                'name' => '关联名称',
            // 'executor' => '执行人',
            ],
        ];
    }

    function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->user_id = Yii::$app->user->identity->user_id;
                $this->create_time = time();
                $this->ip = Yii::$app->getRequest()->getUserIP();
            } else {
                $this->update_time = time();
            }
            $this->schedule_time = strtotime($this->schedule_time);
            return true;
        }
        if (strtotime($this->schedule_time) > strtotime(date('Y-m-d 23:59:59'))) {
            $this->addError('schedule_time', '日期有误,不可选择大于当前日期！');
            return false;
        }
    }

    /**
     * 关联获取创建人的姓名
     */
    public function getUser()
    {
        $fields = User::getSafeFields();
        return $this->hasOne(User::className(), ['user_id' => 'user_id'])->select($fields);
    }

    /**
     * 获取联系人名称
     */
    public function getContacter()
    {
        return $this->hasOne(Contacter::className(), ['contacter_id' => 'contacter_id'])->select('contacter_id, name');
    }

    /**
     * 获取类型名称
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['cat_id' => 'category_id'])->select('cat_id, name');
    }

    /**
     * 获取执行人名称
     */
    public function getJoinName()
    {
        return $this->hasOne(User::className(), ['user_id' => 'join_ids'])->select('user_id, realname');
    }

    /**
     * 获取关联下写日程的所有人
     */
    public static function getLinkScheduleUser($linkType, $linkId)
    {
        $linkData = Common::getLinkData($linkType, $linkId);
        if (empty($linkData)) {
            return false;
        }

        $linkIds = static::find()
            ->select('user_id')
            ->distinct()
            ->where(['link_type' => $linkType, 'link_id' => $linkId])
            ->column();

        $users = User::getUserByDot($linkIds);
        return $users;
    }

    /**
     * 检测日程主权限
     *
     * @param object $schedule 日程对象
     * @param object $action 当前动作对象
     * @param bool $skipPermission 是否越过主权限判断，适用与没有权限节点的任务配置权限
     * @return bool 返回是否有权限
     */
    public static function checkScheduleAccess($action, $skipPermission = false)
    {
        $permission = (is_string($action)) ? $action : Common::getActionPermission($action);
        //如果是管理员
        if (Yii::$app->session->get('isSuperAdmin')) {
            return true;
        }

        //有主权限,进行范围过滤
        if (!$skipPermission && Yii::$app->user->can($permission)) {
            return true;
        }

        return false;
    }

    /**
     * 获取不同类型的各自数组
     *
     * @return array 返回各自数组
     */
    public static function getDataLink()
    {
        $data = [];

        $customerNos = Schedule::find()->where(['link_type' => 'customer'])->groupBy('link_id')->select('link_id')->asArray()->all();
        $data['customer'] = arrayHelper::getColumn($customerNos, 'link_id');

        $opportunityNos = Schedule::find()->where(['link_type' => 'sale_opportunity'])->groupBy('link_id')->select('link_id')->asArray()->all();
        $data['opportunity'] = arrayHelper::getColumn($opportunityNos, 'link_id');

        return $data;
    }

    /**
     * 获取日程
     *
     * @param type $map   查询条件
     * @param type $field 获取字段
     * @param type $order 排序
     */
    public static function getSchedule($map = NULL, $andWhere = NULL, $field = "*", $order = ['update_time' => SORT_ASC])
    {
        $list = [];
        $query = static::find();
        $query = $query->select($field);
        $query = $query->orderBy($order);

        if (!empty($map)) {
            $query = $query->where($map);
        }
        if (!empty($andWhere) && is_array($andWhere)) {
            foreach ($andWhere as $andMap) {
                $query = $query->andWhere($andMap);
            }
        }
        $query = $query->asArray();
        $list = $query->all();
        return $list;
    }

    /**
     * 获取日程日历呈现内容
     *
     * @param type $andWhere
     * @return type
     */
    public static function getCalendarData($andWhere = [])
    {
        $lists = [];
        //权限范围过滤
        $scopeUser = PermissionScope::getScopeUser("schedule/schedule/index");
        $map='';

         //权限判断
        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);
            $map=' `user_id` in (' . implode(', ', $scopeUser) . ') or ' . $findStr;
        }

        $field = 'schedule_id,title,work_time,schedule_time,workload,status,user_id,link_type,link_id,update_time,content,attach_ids,join_ids';
        $lists = static::getSchedule($map, $andWhere, $field, ['join_ids' => SORT_ASC]);

        $userLists = Yii::$app->cache->get('user_list');
        if (!empty($lists)) {
            foreach ($lists as $k => $vo) {
                $usersName=implode(',', ArrayHelper::getColumn(User::getUserByDot($vo['join_ids']), 'realname'));
                $lists[$k]['title'] = '【' .$usersName. '】' . $vo['title'];
                $lists[$k]['start'] = date("Y-m-d", $vo['schedule_time']);
                $lists[$k]['update_time'] = date("Y-m-d", $vo['update_time']);
                $lists[$k]['allDay'] = true;
                $lists[$k]['link_name'] = '【' .$usersName. '】' . ArrayHelper::getValue(Common::getLinkData($vo['link_type'],
                            $vo['link_id']), 'name');
                $lists[$k]['user_name'] = $usersName;
//日志处理。编辑自己的，批示别人的
                if ($vo['user_id'] == \Yii::$app->user->id) {
                    $lists[$k]['view_url'] = Url::to(['/schedule/schedule/view', 'id' => $vo['schedule_id']]);
                } else {
                    $lists[$k]['view_url'] = Url::to(['/schedule/schedule/detail', 'id' => $vo['schedule_id']]);
                }
            }
        }
        return $lists;
    }
}