<?php

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

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\Url;

/**
 * 共用模型
 *
 * @author legendjw http://blog.u-bo.com
 * @since 0.1
 */
class Common extends ActiveRecord
{

    /**
     * 获取关联信息类型
     *
     * @param type $type  类型
     * @return array
     */
    public static function getLinkTypeData($type = NULL)
    {
        $datas = [
            'task' => ['name' => '任务', 'type' => 'task', 'class' => 'select-task', 'pk' => 'task_id', 'url' => ['/link/task'], 'view_url' => ['/task/task/detail'], 'link_field' => 'task_no'],
            'project' => ['name' => '项目', 'type' => 'project', 'class' => 'select-project', 'pk' => 'project_id', 'url' => ['/link/project'], 'view_url' => ['/project/project/detail'], 'wap_view_url' => ['/project/detail'], 'link_field' => 'project_no'],
            'customer' => ['name' => '客户', 'type' => 'customer', 'class' => 'select-customer', 'pk' => 'customer_id', 'url' => ['/link/customer'], 'view_url' => ['/customer/customer/detail'], 'link_field' => 'customer_no'],
            'sale_opportunity' => ['name' => '销售', 'type' => 'sale_opportunity', 'class' => 'select-opportunity', 'pk' => 'opportunity_id', 'url' => ['/link/opportunity'], 'view_url' => ['/sale/opportunity/detail'],
                'link_field' => 'opportunity_no']
        ];
        if($type !== NULL){
            return isset($datas[$type]) ? $datas[$type] : FALSE;
        } else {
            return $datas;
        }
    }

    /**
     * 获取要关联的类型
     *
     * @param type $types 要关联的类型，比如之关联项目['project']
     * @return array
     */
    public static function getLinkTypes($types = [])
    {
        $selectTypes = [];
        $datas = self::getLinkTypeData();
        if(!empty($types) && is_array($types)){
            foreach ($datas as $type => $data) {
                if(in_array($type, $types)){
                    $selectTypes[$type] = $data;
                }
            }
        }
        return $selectTypes;
    }

    /**
     * 获取要改用户对应模块有权关联的类型
     *
     * @param type $module 模块名 注：节点的module，controller都为模块名
     * @return array
     * @author HuLimin
     */
    public static function getAccessLinkTypes($module = '')
    {
        $selectTypes = [];
        $datas = self::getLinkTypeData();
        if(!empty($module) && is_array($datas)){
            foreach ($datas as $type => $data) {
                $auth_url = $module . '/' . $module . '/link-' . $type;
                if(\qcbase\models\Auth::checkAccess($auth_url)){
                    $selectTypes[$type] = $data;
                }
            }
        }

        return $selectTypes;
    }

    /**
     * 获取关联的数据
     * 
     * @param type $linkType 关联类型
     * @param type $linkId 关联字段的值
     * @return type
     */
    public static function getLinkData($linkType, $linkId)
    {
        $types = self::getLinkTypes([$linkType]);
        if (empty($types)) {
            return false;
        }
        $data = (new Query)
                ->from("{{%{$linkType}}}")
                ->where([$types[$linkType]['link_field'] => $linkId])
                ->one();
        $data['link_type'] = $types[$linkType];

        return $data;
    }

    /**
     * 获取一个动作的权限名称
     */
    public static function getActionPermission($action)
    {
        $moduleId = $action->controller->module->id;
        $controllerId = $action->controller->id;
        $actionId = $action->id;
        $permission = $moduleId . '/' . $controllerId . '/' . $actionId;
        return $permission;
    }

    /**
     * 邮件发送
     * @param type $toEmail  接收人
     * @param type $subject  邮件主题
     * @param type $content  信息
     * @param type $toUser   接收人ID
     * @return boolean
     */
    public function sendEmail($toEmail = [], $subject = '', $content = [], $toUser = [])
    {
        $userInfo = [];
        $realname = [];
        $cache_system = \Yii::$app->cache->get('system_config');
        if(!empty($cache_system)){

            \Yii::$app->mailer->transport = [
                'class' => 'Swift_SmtpTransport',
                'host' => $cache_system['mail_host'],
                'username' => $cache_system['mail_user'],
                'password' => $cache_system['mail_pwd'],
                'port' => $cache_system['mail_post'],
                'encryption' => 'ssl',
            ];

            $userList = Yii::$app->cache->get('user_list');
            if(!empty($toUser)){
                if(is_array($toUser)){
                    foreach ($toUser as $k => $userId) {
                        $realname[] = $userList[$userId]['realname'];
                        $toEmail[] = $userList[$userId]['email'];
                    }
                } else {
                    $realname[] = $userList[$toUser]['realname'];
                    $toEmail[] = $userList[$toUser]['email'];
                }
            }
            $link_name='';
            if(!empty($link_type) && !empty($link_id)){
                $link_name = ArrayHelper::getValue(common\models\Common::getLinkData($task['link_type'], $task['link_id']), 'name');
            }

            $realname = empty($content['realn$realnameame']) ? implode(',', $realname) : $content['realname'];
            $content = str_replace(['{realname}', '{num}', ' {name}', ' {project}', '{reporter}', ' {assignee}'], [$realname, $content['num'], $content['title'],$link_name, $cache_system['mail_content'],$userList[$content['user_id']]['realname']],$userList[$content['leader_id']]['realname']);

            empty($subject) ? $subject = $cache_system['mail_subject'] : $subject;

            if(!empty($toEmail) && !empty($cache_system) && !empty($subject) && !empty($content)){
                $result = \Yii::$app->mailer->compose()
                        ->setFrom($cache_system['mail_user'])
                        ->setTo($toEmail)
                        ->setSubject($subject)
                        ->setHtmlBody($content)
                        ->send();
            }
        }
//        return $result;
    }

}
