<?php
namespace model;

use Exception;
/**
 * 审计类
 * @package model
 */
class audit extends \model
{

	public function __construct()
    {
        $this->table = 'audit';
		parent::__construct();
	}

    /**
     * 添加审计记录
     *
     * @param string $type 审计类型 'insert', 'update', 'delete'
     * @param string $tablename 表名
     * @param integer $recordId 主键记录
     * @param array|null $rowData 数据
     * @param string $from 来自 'user', 'api', 'trigger', 'system'
     * @param string $from_operator 操作者
     * @return int 插入的ID
     */
    public function add(string $type, string $tablename, int $recordId, ?array $rowData, string $from, string $from_operator)
    {
        if ($tablename == '' || empty($recordId)) {
            throw new Exception("tablename(表名) 和 recordId(主键记录) 不能为 空 或为 0", 1);
        }
        if ($from == '' || $from_operator == '') {
            throw new Exception("from(来自) 和 from_operator(操作者) 不能为空", 1);
        }
        $typeEnum = ['insert', 'update', 'delete'];
        if (!in_array($type, $typeEnum)) {
            throw new Exception("type(类型) 必须是 " . implode(',', $typeEnum) . " (添加,修改,删除)其中的一个", 1);
        }
        $fromEnum = ['user', 'api', 'trigger', 'system'];
        if (!in_array($from, $fromEnum)) {
            throw new Exception("from(来自) 必须是 " . implode(',', $fromEnum) . " (用户,接口,触发器,系统)其中的一个", 1);
        }
        $insertData = [
            'audit_type' => $type,
            'audit_tablename' => $tablename,
            'audit_record_id' => $recordId,
            'audit_from' => $from,
            'audit_from_operator' => $from_operator
        ];
        if (!empty($rowData)) {
            $insertData['audit_data'] = json_encode($rowData, JSON_UNESCAPED_UNICODE);
        }
        $this->db->insert($this->table, $insertData);
        return $this->db->id();
    }

    /**
     * 获取审计记录 by 表名 + 主键记录
     *
     * @param string $tablename 表名
     * @param integer $recordId 主键记录
     * @return void
     */

    public function getListByRecordId(array $params): ?array
    {
        if ($params['tablename'] == '' || empty($params['recordId'])) {
            throw new Exception("tablename(表名) 和 recordId(主键记录) 不能为 空 或为 0", 1);
        }
        $filters = $params['filters'];
        $page = $params['page'];
        $pagesize = $params['rows'];
        $sidx = empty($params['sidx']) ? '' : $params['sidx'];
        $sord = empty($params['sord']) ? 'asc' : $params['sord'];
        $orderby = $params['orderby'] ?: 'audit_id DESC';
        if ($filters) {
            $where = $this->filter2medoo($filters, function (&$field, &$op, &$data) {
                ; // do some
            });
        }
        $where['audit_tablename'] = $params['tablename'];
        $where['audit_record_id'] = $params['recordId'];
        $where = $this->listWhere($where, $page, $pagesize, $sidx, $sord, $orderby);
        if ($page > 0 && $pagesize > 0) {
            $pages = $this->paging($this->table, $where, $page, $pagesize);
        }
        $rows = $this->db->select($this->table, '*', $where);
        foreach ($rows as &$row) {
            if (!empty($row['audit_data'])) {
                $arr = json_decode($row['audit_data'], true);
                foreach ($arr as $key => $value) {
                    $row[$key] = $value;
                }
            }
            unset($row['audit_data']);
        }
        $data = [
            'page' => $page,
            'total' => $pages['total'],
            'records' => $pages['records'],
            'rows' => $rows
        ];
        return $data;
    }

}