<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 邮件body
 * @time 2022/7/29 15:09
 * Class EmailList
 * @package App\Mail\Models
 */
class Body extends Model{

    const UPDATED_AT = null;

    const CREATED_AT = null;

    // 主键
    protected $primaryKey = 'email_lists_id';

    /**
     * 是否转换成html实体,返回前端时要注意,邮件内容的编码不统一,会导致程序异常
     * @var bool
     */
    public $is_base64_de = true;

    /**
     * 内容
     * @param $v
     * @return array|mixed
     * @author:dc
     * @time 2022/10/25 11:44
     */
    public function getTextHtmlAttribute($v)
    {
        if($v){
            $v = json_decode($v,true);

            if($this->is_base64_de){
                $v = self::_base64($v,false);
            }
        }

        return $v;
    }


    /**
     * 查询一条
     * @param int $email_lists_id
     * @return mixed
     * @time 2022/8/2 14:14
     */
    public static function _first(int $email_lists_id){
        return static::where('email_lists_id',$email_lists_id)->first();
    }

    /**
     * 插入
     * @param $id
     * @param $text_html
     * @return bool
     * @time 2022/8/2 14:59
     */
    public static function _insert($id,$text_html){
        $model = new static();
        $model->email_lists_id = $id;

        $model->text_html = json_encode(self::_base64($text_html));
        return $model->save();
    }


    /**
     * 挨个进行base64处理,避免出现乱码无法存储,编码不统一
     * @param $content
     * @param bool $is_en
     * @return array|mixed
     * @author:dc
     * @time 2022/8/12 14:49
     */
    private static function _base64($content, $is_en = true){
        if($content){
            if(is_array($content)){
                foreach ($content as $key=>$item){
                    if(is_array($item)){
                        $content[$key] = self::_base64($item, $is_en);
                    }else{
                        $content[$key] = $is_en ? base64_encode($item) : base64_decode($item);
                    }
                }
            }
        }
        return $content;
    }



}