package com.jy.business.capital.dao;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.business.capital.mapper.CapitalTransactionsMapper;
import com.jy.business.capital.model.dto.CapitalTransactionsSelectDto;
import com.jy.business.capital.model.entity.CapitalTransactions;
import com.jy.business.capital.model.table.CapitalAccountTable;
import com.jy.business.capital.model.table.CapitalTransactionsTable;
import com.jy.business.capital.model.vo.CapitalTransactionsVo;
import com.jy.business.corporation.model.table.CorporationTable;
import com.jy.framework.model.base.BaseDao;
import org.springframework.stereotype.Service;

@Service
public class CapitalTransactionsDao extends BaseDao<CapitalTransactionsMapper, CapitalTransactions> {

    /**
     * 资金流水分页
     */
    public Page<CapitalTransactionsVo> getPage(CapitalTransactionsSelectDto dto) {
        CapitalTransactionsTable ct = CapitalTransactionsTable.ct;
        CapitalAccountTable ca = CapitalAccountTable.ca;
        CorporationTable c = CorporationTable.c;

        return sql(CapitalTransactionsVo.class)
                .select(
                        ct.all,
                        ca.accountAlias.as(CapitalTransactionsVo::getAccountAlias),
                        ca.amount.as(CapitalTransactionsVo::getBalance),
                        c.name.as(CapitalTransactionsVo::getCorporationName)
                )
                .from(ct)
                .leftJoin(ca).on(ct.capitalAccountId.eq(ca.id))
                .leftJoin(c).on(ca.corporationId.eq(c.id))
                .where(
                        ca.corporationId.eq(dto.getCorporationId()),
                        ct.capitalAccountId.eq(dto.getCapitalAccountId()),
                        ct.tradingTime.between(dto.getTradingTime()),
                        ct.type.eq(dto.getType()),
                        ct.targetType.eq(dto.getTargetType())
                )
                .orderBy(
                        ct.id.desc()
                )
                .page(dto.getPage());
    }

    /**
     * 资金流水明细
     */
    public CapitalTransactionsVo getDetail(Long id) {
        CapitalTransactionsTable ct = CapitalTransactionsTable.ct;

        return sql(CapitalTransactionsVo.class)
                .select(
                        ct.all
                )
                .from(ct)
                .where(
                        ct.id.eq(id)
                )
                .one();
    }

    public boolean capitalAccountExists(Long id) {
        return lambdaQuery().eq(CapitalTransactions::getCapitalAccountId, id).exists();
    }
}
