<?php
namespace app\lib\model;

use think\Model;
use think\facade\{Log, Cache};

class Pay extends Model
{
    // 设置当前模型对应的主键名
    protected $pk = 'id';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 设置json类型字段
	protected $json = ['common_json'];
    
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    // 一对一关联 Order
    public function OrderHasOne() {
        return $this->hasOne(Order::class);
    }

    // 一对多关联 Order
    public function OrderHasMany()
    {
        return $this->hasMany(Order::class);
    }

    //新增后
    protected static function onAfterInsert($data)
    {
        try {
            Cache::store('redis_Pay')->tag('Pay_'.md5(env('token')))->set(md5(env('token')).'_'.$data['id'],$data);
        } catch (\Exception $e) {
            Log::error('[收款账号]新增失败:'.$e->getMessage());
        }
    }

    //更新后
    protected static function onAfterUpdate($data)
    {
        try {
            if($data['state'] == '0'){
                Cache::store('redis_Pay')->delete(md5(env('token')).'_'.$data['id']);
            }else{
                Cache::store('redis_Pay')->tag('Pay_'.md5(env('token')))->set(md5(env('token')).'_'.$data['id'],$data);
            }
        } catch (\Exception $e) {
            Log::error('[收款账号]更新失败:'.$e->getMessage());
        }
    }

    //删除后
    protected static function onAfterDelete($data)
    {
        try {
            Cache::store('redis_Pay')->delete(md5(env('token')).'_'.$data['id']);
        } catch (\Exception $e) {
            Log::error('[收款账号]删除失败:'.$e->getMessage());
        }
    }
}