<?php


namespace catchAdmin\api;

use catchAdmin\api\model\Publish as ModelPublish;
use Exception;
use think\facade\Db;

trait Listen
{
    public $imei;
    public static function onAfterInsert($obj)
    {
        $data = null;
        if (method_exists($obj, 'addContent')) {
            $data = $obj->addContent($obj);
        } else {
            throw new Exception('addContent函数不存在');
        }
        //是否要过滤
        if (array_key_exists('is_filter', $data)) {
            if ($data['is_filter']) {
                return;
            }
        }
        $time = msectime();
        //塞入版本号
        //类型
        //操作方式
        $content = [
            'Type' => 'add',
            'ContentType' => $data['type'],
            'Imei' => $obj->imei ? '' : $obj->imei,
            'ContentId' => $data['data']['id'],
            'AddTime' => $time,
            'Version' => $time,
            'Status' => 1,
            'Content' => json_encode($data['data'])
        ];
        Db::name('publish')->save($content);
    }

    public static function onAfterUpdate($obj)
    {
        $data = [];
        $where = [];
        $time = null;
        $content = null;
        if (method_exists($obj, 'addContent')) {
            $data = $obj->addContent($obj);
        } else {
            throw new Exception('addContent函数不存在');
        }
        //是否要过滤
        if (array_key_exists('is_filter', $data)) {
            if ($data['is_filter']) {
                return;
            }
        }
        $time = msectime();
        $where = [];
        $where[] = ['ContentType', '=', $data['type']];
        $where[] = ['ContentId', '=', $data['data']['id']];
        $content = [
            'Type' => 'update',
            'Imei' => $obj->imei ? '' : $obj->imei,
            'Version' => $time,
            'Status' => 1,
            'Content' => json_encode($data['data'])
        ];
        Db::name('publish')->where($where)->update($content);
    }
    public static function onAfterDelete($obj)
    {
        $data = [];
        $where = [];
        $time = null;
        $content = null;
        if (method_exists($obj, 'addContent')) {
            $data = $obj->addContent($obj);
        } else {
            throw new Exception('addContent函数不存在');
        }

        //是否要过滤
        if (array_key_exists('is_filter', $data)) {
            if ($data['is_filter']) {
                return;
            }
        }
        $time = msectime();
        $where = [];
        $where[] = ['ContentType', '=', $data['type']];
        $where[] = ['ContentId', '=', $data['data']['id']];

        $content = [
            'Type' => 'delete',
            'Imei' => $obj->imei ? '' : $obj->imei,
            'Version' => $time,
            'Status' => 1,
        ];
        Db::name('publish')->where($where)->update($content);
    }
}