<?php

namespace Controller;

use Lib\Mail\MailFun;
use Model\emailSql;
use Model\listsSql;
use function Swoole\Coroutine\Http\request;

/**
 * @author:dc
 * @time 2023/2/13 11:28
 * Class Home
 * @package Controller
 */
class Home extends Base {


    /**
     * 邮件列表
     * @author:dc
     * @time 2023/2/17 14:12
     */
    public function lists(){

        // 分页 页数
        $page   =   app()->request('page',1,'intval');
        $page   =   $page ? $page : 1;

        $lists = db()->all(listsSql::lists($this->login_email['id'],$page));

        app()->_json(listsPage($lists,100,1,30));

    }



    /**
     * 发送邮件
     * @author:dc
     * @time 2023/2/18 17:32
     */
    public function send_mail(){
        $ret = MailFun::sendEmail();

        if($ret[0]===true) {
            app()->_json(['messageId'=>$ret[1]]);
        }else {
            app()->e($ret[1]);
        }
    }


    /**
     * 收到前端的同步请求操作
     * @author:dc
     * @time 2023/3/10 10:38
     */
    public function sync(){
        $emails = app()->request('emails');
        if (empty($emails)){
            $tokens = app()->request('tokens');
            $tokens = is_array($tokens) ? $tokens : [$tokens];
            foreach ($tokens as $k=>$token){
                if(!preg_match('/^[0-9a-zA-Z]{32}$/',$token)){
                    unset($tokens[$k]);
                }
            }
            if(!empty($tokens)){
                $where['token'] = array_values($tokens);
            }
        }else{
            $emails = is_array($emails) ? $emails : [$emails];
            foreach ($emails as $k=>$email){
                if(!preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',$email)){
                    unset($emails[$k]);
                }
            }
            if(!empty($emails)){
                $where['email'] = array_values($emails);
            }
        }

        if(empty($where)){
            app()->e('sync_request_param_error');
        }else{
            // 查询id
            $ids = db()->all(emailSql::getValues($where));
            foreach ($ids as $v){
                redis()->rPush('sync_email_lists', $v['id']);
            }
            // 返回成功的参数值
            app()->_json(array_values($where));
        }

    }





}