<?php

namespace app\common\library\payment;

use app\common\model\promotion\BargainUsers as BargainUsersModel;
use think\facade\Db;
use app\common\exception\BaseException;
use app\common\model\order\Recharge as RechargeModel;
use app\common\model\users\UsersLog as UsersLogModel;
use app\common\model\order\Order as OrderModel;

/**
 * @package app\common\library\payment
 * @class Order
 * @author xzncit 2024/3/18
 */
class Order {

    /**
     * @param $data
     * @return true
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function pay($data){
        $prefix = substr($data["out_trade_no"],0,1);
        // 充值
        if($prefix == "P"){
            $recharge = RechargeModel::where("order_no",$data["out_trade_no"])->find();
            if(empty($recharge)){
                throw new BaseException("充值订单".$data["out_trade_no"]."不存在",0);
            }

            if($recharge["pay_status"] == 2){
                return true;
            }

            RechargeModel::where("order_no",$data["out_trade_no"])->save([
                "pay_status" => 2,
                "money"=>Db::raw("money+" . $recharge["actual_money"]),
                "transaction_id"=>$data["trade_no"]??"",
                "pay_time"   => time()
            ]);

            UsersLogModel::create([
                "user_id"       => $recharge["user_id"],
                "type"          => 2,
                "operation"     => 1,
                "value"         => $recharge["actual_money"],
                "description"   => "用户充值",
                "create_time"   => time()
            ]);

            return true;
        }

        $order = OrderModel::where("order_no",$data["out_trade_no"])->find();
        if(empty($order)){
            throw new BaseException("购物订单".$data["out_trade_no"]."不存在",0);
        }

        if($order["pay_status"] != 1){
            throw new BaseException("购物订单".$data["out_trade_no"]."已支付",0);
        }

        OrderModel::where("order_no",$data["out_trade_no"])->save([
            "status"     => 3,
            "pay_status" => 2,
            "pay_time"   => time()
        ]);

        if($order["type"] == 3){
            BargainUsersModel::where(["user_id"=>$order["user_id"],"bargain_id"=>$order["promoter_id"]])->save(["status"=>2]);
        }

        return true;
    }

}