package com.bailuntec.balancesheet.mapper;

import com.bailuntec.balancesheet.dto.PayPalBalanceDTO;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

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

@Repository
public interface DcPlatformBalanceMapper {
    @Select("select sum(case platformcode when 'Ebay' then userable_amount_rmb when 'Aliexpress' then userable_amount_rmb " +
            "else (before_balance+amount_sales-withdraw_amount)*exchangerate end) platform_balance from dc_platform_balance where day=#{lastDay} and delstatus=0")
    BigDecimal getPlatformBalanceSum(@Param("lastDay") Date lastDay);

    @Insert("<script>" +
            "insert into dc_platform_balance(paycompanyid, platformcode, platformname, account, currency, amount, userable_amount, freeze_amount, exchangerate, " +
            "amount_rmb, userable_amount_rmb, freeze_amount_rmb, day, puttime, delstatus, fromsource, createtime, createuserid, createusername) values" +
            "<foreach collection='list' item='item' index='index' separator=','>" +
            "(2,'Ebay','Ebay',#{item.account},#{item.currencyCode},#{item.balance},#{item.balance},0,0,0,0,0,#{lastDay},#{lastDay},0,'paypal',now(),0,'admin')" +
            "</foreach>" +
            "</script>")
    void insertPayPalBalance(@Param("list") List<PayPalBalanceDTO> payPalBalanceDTOList, @Param("lastDay") Date lastDay);

    @Update("update dc_platform_balance b left join dc_exchange_rate r on b.day = r.record_time and b.currency = r.init_curreny and r.final_curreny = 'CNY' " +
            "set b.exchangerate = r.exchange_rate, b.amount_rmb = b.amount * r.exchange_rate, b.userable_amount_rmb = b.userable_amount * r.exchange_rate " +
            "where b.fromsource = 'paypal' and b.platformcode = 'Ebay' and b.day = #{lastDay}")
    void updatePayPalBalance(@Param("lastDay") Date lastDay);
}