package com.payment_system.mapper;

import com.payment_system.entity.FreezeOrder;
import com.payment_system.entity.TradeOrder;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface OrderMapper {
    @Options(useGeneratedKeys = true, keyProperty = "id") //自动生成增加数据的id主键，指定id主键传递给对象的id
    @Insert("insert into freeze_order(user_id,trade_number,amount,create_time) values(#{userId},#{tradeNumber},#{amount},#{createTime}) ")
    void saveFeezeOrder(FreezeOrder freezeOrder); //生成预授权订单信息

    @Options(useGeneratedKeys = true, keyProperty = "id") //自动生成增加数据的id主键，指定id主键传递给对象的id
    @Insert("insert into trade_order(user_id,trade_number,amount,balance,create_time) values(#{userId},#{tradeNumber},#{amount},#{balance},#{createTime})")
    void saveTradeOrder(TradeOrder tradeOrder);  //生成交易订单信息

    @Options(useGeneratedKeys = true, keyProperty = "id") //自动生成增加数据的id主键，指定id主键传递给对象的id
    @Insert("insert into trade_order(user_id,trade_number,status,amount,balance,create_time) values(#{userId},#{tradeNumber},#{status},#{amount},#{balance},#{createTime})")
    void saveTradeOrder2(TradeOrder tradeOrder);  //生成交易订单信息之无需调用支付宝接口版

    @Update("update freeze_order set status=#{status},auth_number=#{authNumber},operation_number=#{operationNumber} where trade_number=#{tradeNumber}")
    void updateFeezeOrder(@Param("status") short status,
                          @Param("authNumber") String authNumber,
                          @Param("operationNumber") String operationNumber,
                          @Param("tradeNumber") String tradeNumber); //更新预授权订单信息

    @Update("update trade_order set status=#{status} where trade_number=#{tradeNumber}")
    void updateTradeOrder(@Param("status") short status,
                          @Param("tradeNumber") String tradeNumber); //更新交易订单信息

    @Select("select auth_number from freeze_order where user_id = #{userId} and status=1")
    String select1(long userId); //根据用户id来查询相应的支付宝授权码

    @Select("select operation_number from freeze_order where user_id = #{userId} and status=1")
    String select2(long userId); //根据用户id来查询相应的支付宝资金操作流水号

    @Select("select * from freeze_order where user_id = #{userId} and status=1 and amount > 0")
    FreezeOrder findById(long userId); //根据用户id来查询有没有该用户的冻结订单

    @Update("update freeze_order set amount = amount - #{amount} where user_id = #{userId}")
    void updateAmount(@Param("amount") BigDecimal amount,
                      @Param("userId") long userId); //更新冻结表的金额

    @Select("select amount from freeze_order where user_id = #{userId} and status = 1 and amount > 0")
    BigDecimal getBalance(long userId); //查询有效的冻结表金额

    @Delete("delete from freeze_order where user_id = #{userId} and amount <= 0")
    void delete(long userId); //删除金额<=0的冻结表防止上述查询结果出现多个

    @Select("select * from trade_order where user_id = #{userId}")
    List<TradeOrder> findTrade(long userId);
}
