<?php


namespace App\Form\Services;

use App\Common\Facades\ComSmsFacade;
use App\Common\Library\DES;
use App\Exceptions\ApiException;
use App\Form\Facades\FormProductDetailFacade;
use App\Form\Facades\FormProductFacade;
use App\Form\Models\FormRecordModel;
use App\Services\CommonUserBaseService;
use App\Form\Facades\FormContentFacade;
use App\Form\Facades\FormInfoFacade;
use App\Form\Facades\FormItemFacade;
use App\Web\Facades\SysGlobalConfigFacade;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class FormRecordService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'FormRecord:';

    const RELATIVE_TABLE_ORDER = 'website_order';

    const RELATIVE_FORM_PRODUCT = 'form_product';

    const DES_KEY = '1dgDG2ksghw';

    const SYS_MAIL_BOX = 'cXdWWktRNno0eitSL1Q1LzVKalRnUUlleTdESzZ5S2NDdW89OmZhY3A3WjNza0x6YmdJb0U0djlCR3c9PQ==';

    public function __construct(FormRecordModel $model)
    {
        parent::__construct($model);
        $this->cacheBucket = config('cache.prefix').'_'.$this->cacheBucket;
    }


    /**
     * 获取列表数据
     * @param $params
     */
    public function getList($params,$getQuery = false)
    {
        $formId = $params['form_id'] ?? '';
        $keyword = $params['keyword'] ?? '';
        $pageSize = $params['page_size'] ?? 0;
        $date = $params['date'] ?? '';
        $formatList = $params['format_list'] ?? true;//是否进行格式化列表
        $order = $params['order'] ?? 'desc';
        $sort = $params['sort'] ?? 'id';
        $status = $params['status'] ?? '';
        $formId && $where['r.form_id'] = $formId;
        $keyword && $where['c.content'] = [['like', "%{$keyword}%"]];
        !empty($date) &&  $where['r.create_time'] = [['between', [$date.' 00:00:00', $date.' 23:59:59']]];
        if ($status) {
            is_array($status) && $status = [$status];
        } else {
            $status = [['<', 2]];
        }
        if(!empty($params['id_list'])){
            $where['r.id']=[['in',$params['id_list']]];
        }
        $where['r.status'] = $status;

        $fields = 'r.*,c.content';
        $model = $this->getModel();
        $model = $model->buildQuery($where)
            ->from($this->getTable().' as r')
            ->select(DB::raw($fields))
            ->leftJoin('form_content as c', function ($join) {
            return $join->on('r.id', '=', 'c.record_id');
        });

        $model = $model->groupBy('r.id');
        if ($sort) {
            $model = $model->orderBy('is_read', 'asc')->orderBy($sort, $order);
        }
        if ($getQuery) {
            return $model;
        }
        if ($pageSize) {
            $rst = $model->paginate($pageSize)->toArray();
            $formatList && $this->formatList($rst['data']);
        } else {
            $rst = $model->get()->toArray();
            $formatList && $this->formatList($rst);
        }
        return $rst;
    }

    /**
     * 格式化列表
     * @param $list
     */
    public function formatList(&$list)
    {
        if (empty($list)) {
            return ;
        }
        $recordIds = array_column($list, 'id');
        //获取所有表单内的内容
        $contentList = FormContentFacade::getListByRecordIds($recordIds);
        $formProductIds = [];
        foreach ($list as $value){
            if($value['relative_table'] == FormRecordService::RELATIVE_FORM_PRODUCT){
                $formProductIds[] = $value['relative_id'];
            }
        }
        if (!empty($formProductIds)){
            $formProductList = FormProductDetailFacade::getListByRelativeIds($formProductIds);
        }
        foreach ($list as &$v) {
            $v['items'] = $contentList[$v['id']] ?? [];
            $v['content'] = json_decode($v['content'], true);
            is_array($v['content']) && $v['content'] = implode(';', $v['content']);
            if($v['relative_table'] == FormRecordService::RELATIVE_FORM_PRODUCT && !empty($formProductList)){
                $v['product_list'] = $formProductList[$v['relative_id']];
                if(!empty($v['product_list'])){
                    $v['is_product'] = 1;
                }else{
                    $v['is_product'] = 0;
                }
            }else{
                $v['is_product'] = 0;
            }
        }
    }

    /**
     * 导出数据
     * @param $params
     */
    public function exportList($params)
    {
        $list = $this->getList($params);
       if (!empty($list)) {
            $ids = array_column($list, 'id');
            $itemList = FormContentFacade::getListByRecordIds([$ids]);
            foreach ($list as &$v) {
                if (isset($itemList[$v['id']])) {
                    $v['items'][] = $v;
                } else {
                    $v['items'][] = [];
                }
            }
        }
        return $list;
        //导出excel处理
    }

    /**
     * 获取记录
     * @param $id
       * @return mixed
     */
    public function getRecord($id)
    {
        $data = $this->findOneBy([
            'id' => $id,
        ]);
        if (empty($data)) {
            return [];
        }
        $itemList = FormContentFacade::getListByRecordIds([$id]);
        $data['items'] = $itemList[$id] ?? [];
        return $data;
    }

    public function addRecord($params)
    {
        $params['id'] = !empty($params['id']) ? $params['id'] : getClientIp(0, true);
        $ret= $this->addRecordJob($params);
        return $ret;
    }

    /**
     * 添加记录
     * @param $params
     * @return int
     * @throws ApiException
     */
    public function addRecordJob($params)
    {
        $formId = $params['form_id'] ?? '';
        $formData = $params['form_data'] ?? [];//表单数据
        $relativeId =  $params['r_id'] ?? 0;//关联表id
        $relativeTable =  $params['r_ta'] ?? '';//关联表
        $productIds =  $params['product_ids'] ?? '';//产品id数组
        //自定义表单数据处理
        if(empty($formData)){
            $formData = [];
            foreach ($params as $k => $v){
                if(strpos($k, '_') !== false){
                    if(strpos($k, 'option') !== false){
                        $options = explode('_', $k);
                        if(isset($options[1]) && isset($options[2])){
                            $formData[$options[1]][] =  $options[2].':'.$v.';';
                        }
                        if(isset($options[1]) && !isset($options[2])){
                            $formData[$options[1]] = $v ?? '';
                        }

                    } else if(strpos($k, 'name') !== false){
                        $options = explode('_', $k);
                        if(isset($options[0])){
                            $formData[$options[1]] = $v ?? '';
                        }
                    }
                }
            }

            if(!empty($formData)){
                foreach ($formData as $m => $n){
                    if(is_array($n)){
                        $formData[$m] = implode('', $n);
                    }
                }
            }
        }

        $formInfo = FormItemFacade::getData($formId);
        if (empty($formInfo)) {
            throw new ApiException(1000);
        }


        $data = [];
        $data_to=[];
        foreach ($formInfo as $v) {
            $content = $formData[$v['id']] ?? '';
            if ($v['is_required'] && $content === '') {
                throw new ApiException(1002);
            }
            if ($v['is_email']&&!empty(trim($content)) && strpos($content, '@') === false) {
                throw new ApiException(1002);
            }
            if($v['is_phone']&&!empty($v['is_code_valid'])){
                //短信验证

                if(empty($params['valid_code'])){
                    throw new ApiException(10021);
                }
                $validateCode=empty($params['valid_code'])?'':$params['valid_code'];
                $smsRet = ComSmsFacade::validateCode(trim($content), $validateCode);
                if ($smsRet['code'] !== 1) {
                    if ($smsRet['code'] == -2) {
                        throw new ApiException(10002);
                    } else {
                        throw new ApiException(10003);
                    }
                }
            }
            if ($v['is_max'] && $content > $v['max_val']) {
                throw new ApiException(1002);
            }
            if ($v['is_min'] && $content < $v['is_min']) {
                throw new ApiException(1002);
            }
            $data[] = [
                'form_id' => $formId,
                'form_item_id' => $v['id'],
                'content' => json_encode($content, JSON_UNESCAPED_UNICODE)
            ];
            $data_to[] = [
                'name' => $v['name'],
                'content' => json_encode($content, JSON_UNESCAPED_UNICODE)
            ];

        }
        if (!empty($productIds)){
            $formProductData['product_ids'] = $productIds;
            $formProductData['form_id'] = $formId;
            $formProductId = FormProductFacade::addFormProduct($formProductData);
            // 产品表单提交，重新组成关联表和关联表id
            $relativeId =  $formProductId;//关联表id
            $relativeTable =  FormRecordService::RELATIVE_FORM_PRODUCT;//关联表
        }
        $record = $this->save([
            'form_id' => $formId,
            'relative_id' => $relativeId,
            'relative_table' => $relativeTable,
            'ip' => $params['ip'] ?? getClientIp(0, true),
            'status' => 0
        ]);
        if (empty($record)) {
            throw new ApiException(1001);
        }
        FormInfoFacade::setDataUpdateTime($formId);
        foreach ($data as &$v) {
            $v['record_id'] = $record['id'];
        }
        FormContentFacade::saveAll($data);
        if(!empty($formId)){
            FormInfoFacade::reActivateFormById($formId);
        }
        // todo 系统通知邮箱
        //系统通知邮箱
        $referer = empty($params['referer']) ? '' : $params['referer'];
        $this->addToEmailSendRedis($record['id'], $referer, $data_to);
        return $record['id'];
    }

    /**
     * 发询盘邮件
     * @param $data
     * @return mixed
     * */
    public function mailInvite($data){
       // print_r($data);die;
        $mail = $data['email'];
        $mail_user = $data['mail_user'];
        $mail_pwd = $data['mail_pwd'];
        $smtp_host = $data['smtp_host'];
        $smtp_port = $data['smtp_port'];
        $title='您有一封新的询盘邮件';
        $httpData['data'][]='';
        foreach (array_reverse($data['data']) as $v) {
            $httpData['data'][] = $v['name'] .':'.$v['content'];
        }
        $httpData['name']= $data['name'];
        $httpData['referer']= empty($data['referer'])?'':$data['referer'];

        // 邮件底部信息
        $httpData['logo']= 'https://oss.matchpages.cn/matchpages/share_center/2023/0323/1821/641bc6b30f79f/logo-starify2X.webp';

        $mailSwift=Mail::getSwiftMailer();
        $mailgunTransport = $mailSwift->getTransport();
        $mailgunTransport->setUsername($mail_user);
        $mailgunTransport->setPassword($mail_pwd);
        $mailgunTransport->setHost($smtp_host);
        $mailgunTransport->setPort($smtp_port);
        if($smtp_port==465){
            $mailgunTransport->setEncryption('ssl');
        }else{
            $mailgunTransport->setEncryption('tls');
        }
        Mail::send('mail.inviteModel', $httpData, function ($message) use ($mail,$title,$mail_user) {
            $message->from($mail_user,$mail_user);
            $message->to($mail)->subject($title);
        });

      /*  $mailgunDomainArray=config('mail.mailgun_domain_array');
        $email_from_config = config('mail.from');
        $email_from = $email_from_config[mt_rand(0, (count($email_from_config) - 1))];
        $mailSwift= Mail::getSwiftMailer();
        $mailgunTransport = $mailSwift->getTransport();
        $keys=array_keys($mailgunDomainArray);
        $max= count($keys)-1;
        $index= $keys[mt_rand(0, $max)];
        $sendDomain=$mailgunDomainArray[$index]['domain'];
        $mailgunTransport->setDomain($sendDomain);
        $mailgunTransport->setKey($mailgunDomainArray[$index]['secret']);
        Mail::send('mail.invitationModel',$httpData,
            function($message)use($mail,$email_from,$title){
                $message->from(trim($email_from['address']),$email_from['name']);
                $message->to(trim($mail))->subject($title);
            });
        $error= Mail::failures();
        if (!empty($error)) {
            Log::info('mail_error:'.json_encode($error));
        }*/
      /*  Mail::send('mail.inviteModel', $httpData, function ($message) use ($mail,$title) {
            $message->to($mail)->subject($title);
        });*/
    }

    /**
     * 删除记录
     * @param $id
     */
    public function changeStatus($id, $status)
    {
        if(!is_array($id)){
            $id=[$id];
        }
        $where = [
            'id' => [['in',$id]]
        ];
        $data = [
            'status' => $status
        ];
        return $this->updateBy($where, $data);

    }

    /**
     * 根据id列表获取记录
     * */
    public function getRecordByIds($ids){
        if(!is_array($ids)){
            $ids=[$ids];
        }
        $itemList = FormContentFacade::getListByRecordIds($ids);
        return $itemList;
    }

    /**
     * 根据订单id获取对应提交表单数据
     *
     * */
    public function getRecordDataByRelativeTable($relativeId,$relativeTable){
        $list=[];
        $data = [];
        $where=[];
        $where['relative_table']=$relativeTable;
        if(!is_array($relativeId)){
            $relativeId=[$relativeId];
        };
        $formData= $this->model->where($where)
            ->whereIn('relative_id',$relativeId)
            ->selectRaw('id,relative_id')->get();
        if(!empty($formData)){
            $formData=  $formData->toArray();
            if(!empty($formData)){
                foreach ($formData as $v){
                    $ids[]=$v['id'];
                    $rids[$v['id']]=$v['relative_id'];
                }
                $list= $this->getRecordByIds($ids);
            }
            foreach ($list as $k=>$l) {
                $data[$rids[$k]] = $l;
            }
        }
        return $data;
    }
    /**
     * 询盘数据设置为已读
     * */
    public function recordSetIsRead($ids){
        $formData= $this->model
            ->whereIn('id',$ids)
            ->pluck('form_id');
        $formIds = array_unique(json_decode($formData));
        FormInfoFacade::setFormIdsUpdateTime($formIds);
        $updateData=[];
        $updateData['is_read']=1;
        if(!empty($ids)){
            $ret = $this->model
                ->whereIn('id',$ids)
                ->update($updateData);
        }else{
            $ret=[];
        }
        return $ret;
    }


    /**
     * 用于记录恢复
     * @param $websiteId
     * @param $formId
     * @return mixed
     */
    public function getRecordByTmp($formId)
    {
        return $records = $this->model->buildQuery(
            [
                'form_id' => $formId,
                'status' => 0,
                'create_time' => array(['>', '2021-09-01'])
            ]
        )
            ->get()->toArray();
    }

    /**
     * 用于记录恢复
     * @param $params
     * @throws ApiException
     */
    public function addRecordJobTmp($params)
    {
        $formId = $params['form_id'] ?? '';
        $formData = $params['form_data'] ?? [];//表单数据
        $relativeId =  $params['r_id'] ?? 0;//关联表id
        $relativeTable =  $params['r_ta'] ?? '';//关联表
        //自定义表单数据处理
        if(empty($formData)){
            $formData = [];
            foreach ($params as $k => $v){
                if(strpos($k, '_') !== false){
                    if(strpos($k, 'option') !== false){
                        $options = explode('_', $k);
                        if(isset($options[1]) && isset($options[2])){
                            $formData[$options[1]][] =  $options[2].':'.$v.';';
                        }
                        if(isset($options[1]) && !isset($options[2])){
                            $formData[$options[1]] = $v ?? '';
                        }

                    } else if(strpos($k, 'name') !== false){
                        $options = explode('_', $k);
                        if(isset($options[0])){
                            $formData[$options[1]] = $v ?? '';
                        }
                    }
                }
            }

            if(!empty($formData)){
                foreach ($formData as $m => $n){
                    if(is_array($n)){
                        $formData[$m] = implode('', $n);
                    }
                }
            }
        }
        $formInfo = FormItemFacade::getData($formId);

        if (empty($formInfo)) {
            throw new ApiException(1000);
        }
        $data = [];
        foreach ($formInfo as $v) {
            $content = $formData[$v['id']] ?? '';
            if ($v['is_required'] && $content === '') {
                throw new ApiException(1002);
            }
            if ($v['is_email']&&!empty(trim($content)) && strpos($content, '@') === false) {
                throw new ApiException(1002);
            }
            if ($v['is_max'] && $content > $v['max_val']) {
                throw new ApiException(1002);
            }
            if ($v['is_min'] && $content < $v['is_min']) {
                throw new ApiException(1002);
            }
            $data[] = [
                'form_id' => $formId,
                'form_item_id' => $v['id'],
                'content' => json_encode($content, JSON_UNESCAPED_UNICODE)
            ];
            $data_to[] = [
                'name' => $v['name'],
                'content' => json_encode($content, JSON_UNESCAPED_UNICODE)
            ];

        }

//        $relativeId =  $params['r_id'] ?? 0;//关联表id
//        $relativeTable =  $params['r_ta'] ?? '';//关联表

        $recordId = $params['record_id'] ?? 0;
        if(!empty($params['remote_addr'])){
            $this->model->buildQuery(['id' => $recordId])
                ->update(['ip' => $params['remote_addr']]);
        }
        // print_r($recordId);

        foreach ($data as &$v) {
            $v['record_id'] = $recordId;
        }
        FormContentFacade::saveAll($data);
        if(!empty($formId)){
            FormInfoFacade::reActivateFormById($formId);
        }

        FormInfoFacade::setDataUpdateTime($formId);
    }

    /**
     * 获取列表数据
     * @param $params
     */
    public function getFormRecordList($params, $getQuery = false)
    {
        if(!empty($params['id'])){
            $where['r.form_id']=[['in',$params['id']]];
        }
        $where['r.status'] = 0;
        $where['b.status'] = 0;
        $fields = 'r.*,c.content';
        $model = $this->getModel();
        $model = $model->buildQuery($where)
            ->from($this->getTable().' as r')
            ->select(DB::raw($fields))
            ->leftJoin('form_content as c', function ($join) {
                return $join->on('r.id', '=', 'c.record_id');
            });

        $model = $model->groupBy('r.id');
        $rst = $model->get()->toArray();
        return $rst;
    }

    /**
     * @param $ip
     * @param $formId
     * @param $limit
     * @return bool
     */
    public function countRecordByIp($ip, $formId, $limit = 100)
    {
        $count = 0;
        if($formId) {
            $count = $this->count([
                'form_id' => $formId,
                'ip' => $ip,
                'create_time' => array([
                    '>',
                    date('Y-m-d',
                        strtotime('-1 day', time()))
                ])
            ]);
        }
        return $count < $limit;
    }

    /**
     * 添加表单记录
     * */
    public function addFormRecord($params,$ip){
        try {
            $formId = $params['form_id'] ?? 0;
            $rst = $this->countRecordByIp($ip, $formId, 10);
            if($rst) {
                $params['ip']=$ip;
                $rst = $this->addRecord($params);
            } else {
                 Log::info('检测到该IP恶意提交'.$ip.'，addRecordFail::::'.json_encode($params));
            }
            return $rst;
        } catch (\Exception $e){
            $code=$e->getCode();
            if($code==1001){
                $params['ip']=$ip;
                $this->addFormRecordToRedis($params);
            }
            throw new ApiException(1004,['msg'=> $e->getMessage()]);
        }
    }

    /**
     * 保存失败的输入扔入 redis
     * @param $method
     * @param $url
     * @param $params
     * @return mixed
     */
    public function addFormRecordToRedis($params)
    {
        $cacheKey = $this->cacheBucket.'form_record_list';
        $redis = app('redis')->connection('default');
        $data = json_encode(
            array([
                'params' => $params
            ])
        );
        return $redis->rpush($cacheKey, $data);
    }

    /**
     * 将Redis缓存的数据存入数据库
     */
    public function processRedisFormRecord()
    {
        set_time_limit(0);
        ignore_user_abort(true);
        $processingKey =  $this->cacheBucket.'form_record_list_processing';
        $reProcessing = Cache::get($processingKey);
        if($reProcessing){
            return 'processing......';
        }
        Cache::put($processingKey, 1, 60*12);
        $cacheKey =  $this->cacheBucket.'form_record_list';
        $redis = app('redis')->connection('default');
        $length = $redis->llen($cacheKey);
        $data = $redis->blpop($cacheKey, 1);
        $i = 0;
        while($data && $data[1]){
            $data[1] = json_decode($data[1], true);
            if(!empty($data[1][0]) && !empty($data[1][0]['params'])){
                try {
                    $this->addRecord($data[1][0]['params']);
                } catch (\Exception $e){
                    $this->addFormRecordToRedis($data[1][0]['params']);
                }
            }
            //每次运行最多处理8000条数据
            if($i < $length && $i < 8000){
                $data = $redis->blpop($cacheKey, 1);
            } else {
                break;
            }
            usleep(50);
            $i++;
        }
        Cache::forget($processingKey);
        return $i;
    }

    /**
     * 把需要发送邮件的表单输入扔入redis
     * @param $recordId
     * @param $referer
     * @param $dataTo
     * @param $processCount
     * @return mixed
     */
    public function addToEmailSendRedis($recordId, $referer, $dataTo, $processCount = 0)
    {
        $cacheKey = $this->cacheBucket.'record_send_list';
        $redis = app('redis')->connection('default');
        $data = json_encode(
            array([
                'record_id' => $recordId, //表单记录ID
                'referer' => $referer, //表单引用地址
                'data_to' => $dataTo, //数据指向
                'process_count' => $processCount //执行次数记录
            ])
        );
        return $redis->rpush($cacheKey, $data);
    }

    /**
     * 系统邮箱通知
     * @param $recordId
     * @param $dataTo
     * @return int
     */
    public function sendRecordToEmail($recordId, $referer, $dataTo)
    {
        $globalParams = [];
        $globalData = SysGlobalConfigFacade::getGlobalConfig($globalParams);
        $globalData = mapByKey($globalData, 'global_key');
        $sysDesKey = config('mail.des_key');
        $sysMailBox = config('mail.sys_mail_box');
        if (empty($sysDesKey)) {
            $sysDesKey = self::DES_KEY;
        }
        if (empty($sysMailBox)) {
            $sysMailBox = self::SYS_MAIL_BOX;
        }
        if (!empty($globalData['FORM_RECEIVE_MAIL']['value']) && !empty($recordId)) { // 插入数据成功，并且有邮箱。发送邮件
            $mail_pwd = empty($globalData['FORM_RECEIVE_MAIL']['value']['mail_pwd']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['mail_pwd'];
            $mail_user = empty($globalData['FORM_RECEIVE_MAIL']['value']['mail_user']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['mail_user'];
            $smtp_host = empty($globalData['FORM_RECEIVE_MAIL']['value']['smtp_host']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['smtp_host'];
            $smtp_port = empty($globalData['FORM_RECEIVE_MAIL']['value']['smtp_port']) ? '' : $globalData['FORM_RECEIVE_MAIL']['value']['smtp_port'];
            if (!empty($mail_pwd) && !empty($mail_user) && !empty($smtp_host) && !empty($smtp_port)) {
                $getter = new DES($sysDesKey);
                if ($mail_user == $getter->decrypt($sysMailBox)) {
                    $mail_pwd = $getter->decrypt($mail_pwd);
                }
                foreach ($globalData['FORM_RECEIVE_MAIL']['value']['to_mail'] as $value) {
                    $mail_data['email'] = $value;
                    $mail_data['name'] = $value;
                    $mail_data['mail_user'] = $mail_user;
                    $mail_data['mail_pwd'] = $mail_pwd;
                    $mail_data['smtp_host'] = $smtp_host;
                    $mail_data['smtp_port'] = $smtp_port;
                    $mail_data['referer'] = $referer;
                    $mail_data['data'] = $dataTo;
                    $this->mailInvite($mail_data);
                }
            }
        }
    }

    /**
     * @return int|string
     */
    public function processRecordEmailSend()
    {
        set_time_limit(0);
        ignore_user_abort(true);
        $processingKey = $this->cacheBucket . 'record_email_send_processing';
        $reProcessing = Cache::get($processingKey);
        if ($reProcessing) {
            return 'processing......';
        }
        Cache::put($processingKey, 1, 60 * 12);
        $cacheKey = $this->cacheBucket . 'record_send_list';
        $redis = app('redis')->connection('default');
        $length = $redis->llen($cacheKey);
        $data = $redis->blpop($cacheKey, 1);
        $i = 0;
        while ($data && $data[1]) {
            $data[1] = json_decode($data[1], true);
            if (!empty($data[1][0]) && !empty($data[1][0]['record_id'])) {
                $recordId = $data[1][0]['record_id'];
                $referer = $data[1][0]['referer'];
                $dataTo = $data[1][0]['data_to'];
                $processCount = $data[1][0]['process_count'];
                try {
                    $this->sendRecordToEmail($recordId, $referer, $dataTo);
                } catch (\Exception $e) {
                    if ($data[1][0]['process_count'] > 3) {
                        Log::info('process_error_for_email_send_message::'.$e->getMessage().',CODE:'.$e->getCode());
                        Log::info('process_error_for_email_send::' . json_encode($data[1][0], JSON_UNESCAPED_UNICODE));
                    } else {
                        $this->addToEmailSendRedis($recordId, $referer, $dataTo, ++$processCount);
                    }
                }
            }
            //每次运行最多处理8000条数据
            if ($i < $length && $i < 8000) {
                $data = $redis->blpop($cacheKey, 1);
            } else {
                break;
            }
            usleep(50);
            $i++;
        }
        Cache::forget($processingKey);
        return $i;
    }
}
