<?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;
use yii\helpers\ArrayHelper;
use common\models\Common;

/**
 * 邮件模型
 *
 * @author HuLimin <http://blog.u-bo.com>
 * @since 0.1
 */
class Email extends ActiveRecord
{

    /**
     * 邮件发送
     * @param type $toEmail  接收人
     * @param type $subject  邮件主题
     * @param type $content  信息
     * @return boolean
     */
    public static function sendEmail($toEmail = [], $subject = '', $content = [])
    {
        $userInfo = [];
        $realname = [];
        $result = FALSE; //默认发送失败
        $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',
            ];
            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(array_unique($toEmail))//过滤重复邮箱避免重复发送
                        ->setSubject($subject)
                        ->setHtmlBody($content)
                        ->send();
            }
        }
        return $result;
    }

    /**
     * 任务分配发送邮件
     * @param type $taskNo 任务编号
     */
    public static function sendTaskEmail($taskNo = '')
    {
        $cache_system = \Yii::$app->cache->get('system_config');
        $cache_basic = \Yii::$app->cache->get('basic_config');
        $userList = Yii::$app->cache->get('user_list');
        $toEmail = [];
        if(!empty($cache_system['mail_content'])){
            $task = \home\modules\task\models\Task::findOne(['task_no' => trim($taskNo)]);
            if(!empty($task)){
                $linkInfo=Common::getLinkData($task->link_type, $task->link_id);
                $linkName = (!empty($task->link_type) && !empty($task->link_id)) ? ArrayHelper::getValue($linkInfo, 'name') : '';
                $linkTypeName = !empty($task->link_type) ? ArrayHelper::getValue($linkInfo['link_type'], 'name') : '';
                
                $toEmail[] = $userList[$task->leader_id]['email']; //收件人邮箱
                $realName = $userList[$task->leader_id]['realname']; //收件人姓名
                $creater = $userList[$task->user_id]['realname']; //创建人姓名
                $result = self::checkEmail($toEmail[0]);
                if($result == FALSE){
                    return FALSE;
                }
                $participator =[];
                if(!empty($task->join_ids)){
                    $joinArr = explode(',', $task->join_ids);
                    if(is_array($joinArr)){
                        foreach ($joinArr as $vo) {
                            $checkResult = self::checkEmail($userList[$vo]['email']);
                            if($result !== FALSE){
                                $toEmail[] = $checkResult;
                            }
                            $participator[]=$userList[$vo]['realname'];
                        }
                    }
                }
                /**
                 * {name} 任务名称
                 * {num}  编号
                 * {url}   范围URL
                 * {link} 关联项目
                 * {type}   Task(任务)
                 * {reporter} 创建人
                 * {assignee} 负责人
                 * {participator}
                 * {description}  任务描述
                 */
                $template = ['{name}', '{num}', '{url}', '{link}', '{type}', '{reporter}', '{assignee}', '{description}','{participator}'];
                $sendInfo = [$task->name, $task->task_no, $cache_basic['web_url'] . Url::to(['/task/task/detail', 'id' => $task->task_id]), "【{$linkTypeName}】" . $linkName, "Task", $realName, $creater, $task->description,  implode(',', $participator)];
                $content = str_replace($template, $sendInfo, $cache_system['mail_content']);
                @self::sendEmail($toEmail, '【任务】' . $task->name, $content);
            }
        }
        return FALSE;
    }

    /**
     * 检测邮箱格式，正确就返回邮箱，否则返回false
     * @param type $email
     * @return boolean
     */
    public static function checkEmail($email = '')
    {
        if(empty($email)){
            return FALSE;
        }
        $string = trim($email);
        $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string);
        return $result ? $string : FALSE;
    }

}
