<?php
namespace app\lib\model;
use think\facade\{Log, Cache};

use think\Model;

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

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

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

    //新增后
    protected static function onAfterInsert($data)
    {
        try {
            $Pay = Pay::getById($data['pay_id']);
            $Type = Type::where("name",$data['type'])->find();
            $Json = $Pay['common_json'];
            Cache::store('redis_Order')->tag('Order_'.md5(env('token')))->set(md5(env('token')).'_'.$data['trade_no'],[$data,$Type,$Pay,$Json],60*30);
        } catch (\Exception $e) {
            Log::error('[订单记录]新增失败:'.$e->getMessage());
        }
    }

    //更新后
    protected static function onAfterUpdate($data)
    {
        try {
            if($data['settle'] == '2'){
                Cache::store('redis_Notify')->tag('Notify_'.md5(env('token')))->set('Notify_'.md5(env('token')).'_'.$data['trade_no'],$data,60*10);
            }
            if($data['settle'] == '1'){
                Cache::store('redis_Order')->delete('Notify_'.md5(env('token')).'_'.$data['trade_no']);
            }
            if($data['status'] == '1'){
                Cache::store('redis_Order')->delete(md5(env('token')).'_'.$data['trade_no']);
            }else{
                $Pay = Pay::getById($data['pay_id']);
                $Type = Type::where("name",$data['type'])->find();
                $Json = $Pay['common_json'];
                Cache::store('redis_Order')->tag('Order_'.md5(env('token')))->set(md5(env('token')).'_'.$data['trade_no'],[$data,$Type,$Pay,$Json],60*30);
            }
        } catch (\Exception $e) {
            Log::error('[订单记录]更新失败:'.$e->getMessage());
        }
    }

    //删除后
    protected static function onAfterDelete($data)
    {
        try {
            Cache::store('redis_Order')->delete(md5(env('token')).'_'.$data['trade_no']);
        } catch (\Exception $e) {
            Log::error('[订单记录]删除失败:'.$e->getMessage());
        }
    }
}