<?php

namespace app\common\logic;

use app\common\model\finance\PayNotifyLog;
use support\Log;

class PayNotifyLogLogic extends BaseLogic
{

    public function insert($payType, $data, $type = PayNotifyLog::TYPE_ORDER)
    {
        try {
            $exist = PayNotifyLog::where('order_sn', $data['out_trade_no'])->where('pay_type', $payType)->where('type', $type)->count();
            if ($exist) {
                return false;
            }
            $model = new PayNotifyLog();
            $model->pay_type = $payType;
            $model->order_sn = $data['out_trade_no'];
            $model->type = $type;
            if($type == PayNotifyLog::TYPE_REFUND){
                $model->amount = $data['amount']['refund'];
                $model->out_trade_no = $data['refund_id'];
            }else{
                $model->amount = $payType == 'wechat_common' ? $data['amount']['payer_total'] : $data['buyer_pay_amount'];
                $model->out_trade_no = $payType == 'wechat_common' ? $data['transaction_id'] : $data['trade_no'];

            }

            $model->transaction_id = $data['transaction_id'];
            $model->attach = $data['attach'] ?? '';
            if (isset($data['pay_time'])) {
                $model->create_time = $data['pay_time'];
            }
            if (isset($data['success_time'])) {
                $model->create_time = $data['success_time'];
            }
            $model->create_time = $model->create_time ?: date('Y-m-d H:i:s');
            $model->save();
            return $model->id;
        } catch (\Exception $e) {
            $message = 'pay notify log insert error: ' . $e->getMessage();
            Log::error($message . ', trace: ' . $e->getTraceAsString());
        }
        return false;
    }

}