<?php
declare (strict_types=1);

namespace app\model\api;

use library\basic\BaseModel;
use app\model\api\User as UserModel;
use think\Model;

/**
 * @mixin \think\Model
 */
class PayTrade extends BaseModel
{


    /**
     * 生成支付凭证
     * @param $payType 支付类型
     * @param $uid 用户UID
     * @param $code 支付code
     * @param $money 支付金额
     * @param $content 支付说明
     * @param $out_trade_no 其他订单
     * @param $djson 额外说明
     */
    public function credentials($payType, $uid, $code, $money, $content = '支付凭证', $out_trade_no = '', $djson = [],$admin_id=0)
    {
        $apple_pid = (empty($djson) || empty($djson["apple_pid"])) ? '':$djson["apple_pid"];
        $payOn = $this->mkPayOn($uid);
        $userData = (new UserModel)->where("uid",$uid)->find();
        $i_tuid = 0;
        $i_uid  = 0;
        if(!empty($userData) && $userData["i_tuid"]>0){
            $i_tuid = intval($userData["i_tuid"]);
        }
        if(!empty($userData) && $userData["i_uid"]>0){
            $i_uid = intval($userData["i_uid"]);
        }
        $bool  = $this->insert([
            'pay_no'       => $payOn,
            'out_trade_no' => empty($out_trade_no) ? $payOn : $out_trade_no,
            'uid'          => $uid,
            'pay_type'     => $payType,
            'code'         => $code,
            'money'        => $money,
            'content'      => $content,
            'd_json'       => serialize($djson),
            'time'         => time(),
            'admin_id'     => $admin_id,
            'apple_pid'    => $apple_pid,
            'i_tuid'       => $i_tuid,
            'i_uid'        => $i_uid
        ]);
        return $bool ? $payOn : null;

    }


    /**
     * 生成平台支付流水
     */
    private function mkPayOn($uid)
    {
        return 'PN' . time() . rand(1000, 9000) . $uid;
    }
}
