<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/1/001
 * Time: 16:27
 */

namespace backend\controllers;

use backend\helpers\DateTimeHelper;
use backend\helpers\MailHelper;
use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\Config;
use backend\models\Mail;
use backend\models\MailEvent;
use backend\models\MailRecord;

class MailController extends BaseController
{
    const EVENT_EMAIL_SEND = 'send';

    /**
     * 获取邮件列表
     */
    public function actionGetMailList()
    {
        $request = \Yii::$app->request->get();
        $data = [];
        $data['page'] = isset($request['page']) ? (int)$request['page'] : 1;
        $data['pageSize'] = isset($request['page']) ? (int)$request['pageSize'] : 20;
        $data['orderBy'] = isset($request['orderBy']) ? $request['orderBy'] : 'id desc';
        $data['search'] = isset($request['search']) ? $request['search'] : '';

        $data = ValidatorHelper::validateData($data, [
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }

        $query = Mail::find()->orderBy($data['orderBy']);
        if (!empty($data['search'])) {
            $query->andFilterWhere(['like', 'subject', $data['search']]);
        }

        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        return $this->outJson(1, $result);
    }

    /**
     * 获取邮件发送记录
     */
    public function actionGetMailRecordList()
    {
        $request = \Yii::$app->request->get();
        $data = [];
        $data['page'] = isset($request['page']) ? (int)$request['page'] : 1;
        $data['pageSize'] = isset($request['page']) ? (int)$request['pageSize'] : 20;
        $data['orderBy'] = isset($request['orderBy']) ? $request['orderBy'] : 'id desc';
        $data['search'] = isset($request['search']) ? $request['search'] : '';

        $data = ValidatorHelper::validateData($data, [
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);

        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }

        $query = MailRecord::find()->orderBy($data['orderBy']);
        if (!empty($data['search'])) {
            $query->andFilterWhere(['like', 'receiver', $data['search']]);
        }
        
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        return $this->outJson(1, $result);
    }

    /**
     * 获取邮件详情
     */
    public function actionViewMail()
    {
        $request = \Yii::$app->request->get();
        $id = isset($request['id']) ? (int)$request['id'] : '';

        $result = Mail::find()->where(['id' => $id])->one();
        return $this->outJson(1, $result);
    }

    /**
     * 获取邮件记录详情
     */
    public function actionViewMailRecord()
    {
        $request = \Yii::$app->request->get();
        $id = isset($request['id']) ? (int)$request['id'] : '';

        $result = MailRecord::find()->where(['id' => $id])->one();
        return $this->outJson(1, $result);
    }

    /**
     * 新增邮件
     */
    public function actionSaveMail()
    {
        $request = \Yii::$app->request->post();
        $params['type'] = isset($request['type']) ? (int)$request['type'] : '';
        $params['subject'] = isset($request['subject']) ? $request['subject'] : '';
        $params['content'] = isset($request['content']) ? $request['content'] : '';
        $params['other'] = isset($request['other']) ? $request['other'] : '';
        $params['state'] = 0;
        $params['in_time']  = DateTimeHelper::microtime_float(); 

        $mail = new Mail();
        $mail->setAttributes($params);
        if ($mail->save()) {
            return $this->outJson(1, $mail->getAttributes());
        } else {
            return $this->outJson(0, [], $mail->getErrors());
        }
    }
    
    /**
     * 删除邮件
     */
    public function actionDelMail()
    {
        $request = \Yii::$app->request->post();
        $id = isset($request['id']) ? (int)$request['id'] : '';
        
        $mail = new Mail();
        $result = $mail->deleteAll(['id' => $id]);
        return $this->outJson(1, $result);
    }

    /**
     * 批量发送邮件(该方法慎用会员，代理商，会员+代理商)!!!!
     * 因为会往crm_mail_record插入大量state=0的记录
     * 自动计划脚本SendMailJob每分钟都在跑，该脚本就是发送state=0的邮件
     */
    public function actionSendMail()
    {
        $request = \Yii::$app->request->post();
        $id = isset($request['id']) ? (int)$request['id'] : '';
        $mail = Mail::findOne(['id' => $id]);
        if ($mail->state == 0) {
            // 事件的绑定
            // $result = EventHelper::saveMailRecord($id, $mail->type);
            $mailModel = new Mail();
            $mailEvent = new MailEvent();
            $mailEvent->mailId = $id;
            $mailEvent->type = $mail->type;

            $this->on(self::EVENT_EMAIL_SEND, [$mailModel, 'sendEvent']);
            // 事件的触发
            $this->trigger(self::EVENT_EMAIL_SEND, $mailEvent);

            $mail->state = 1;
            $mail->save();
            return $this->outJson(1, $mail, '操作成功');
        } else {
            return $this->outJson(0, [], '已发送，不能重复发送');
        }
    }

    /**
     * 邮件记录-重新发送邮件
     */
    public function actionSendMailRecord()
    {
        $request = \Yii::$app->request->post();
        $id = isset($request['id']) ? (int)$request['id'] : '';
        $mailRecord = MailRecord::findOne(['id' => $id]);
        $config = Config::findOne(1);
        $rs = MailHelper::sendButNotSaveRecord($mailRecord->subject, $mailRecord->receiver, $config->smtp_from_mail, $mailRecord->content, $id);
        if ($rs) {
            return $this->outJson(1, $rs, '发送成功');
        } else {
            return $this->outJson(0, [], '发送失败');
        }
    }

    /**
     * 邮件记录-删除
     */
    public function actionDelMailRecord()
    {
        $request = \Yii::$app->request->post();
        $id = isset($request['id']) ? (int)$request['id'] : '';

        $mail = new MailRecord();
        $result = $mail->deleteAll(['id' => $id]);
        return $this->outJson(1, $result);
    }

    /**
     * 邮箱验证码
     * @param $email
     * @param $code
     */
    public function actionSendMailCode()
    {
        $request = \Yii::$app->request->post();
        $email = $request['email'];
        $code = MailHelper::sendCodeSms($email);
        if (!$email || !$code) {
            return $this->outJson(0, [], '参数错误');
        }
        $config = Config::findOne(1);
        $paramArray = [
            'email' => $email,
            'code' => $code,
        ];
        // 发送邮件
        MailHelper::sendMail("邮箱验证码", $email, $paramArray, '', $config->mail_code);

        return $this->outJson(1, [], 'OK');
    }

    /**
     * 邮箱验证码
     * @param $email
     * @param $code
     */
    public function actionGetMailCode()
    {
        $email = trim(\Yii::$app->getRequest()->get('email'));
        if ($email == '') {
            return $this->outJson(0, [], '邮箱不能为空');
        }
        $result = MailHelper::getCodeSms($email);
        return $this->outJson(1, $result, 'OK');
    }
}