package cn.com.ty.lift.ud.payment.service.impl;

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

import cn.com.ty.lift.ud.payment.controller.query.TyBillQuery;
import cn.com.xwy.util.collection.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.ty.lift.ud.payment.mapper.TyBillMapper;
import cn.com.ty.lift.ud.payment.mapper.entity.TyBillEntity;
import cn.com.ty.lift.ud.payment.service.ITyBillService;
import cn.com.xwy.boot.web.dto.RestResponse;
import lombok.Data;

/**
 * 天域账单流水 -ServiceImpl
 *
 * @author Xson
 * @date 2020-04-23
 */
@Service
@Transactional
public class TyBillServiceImpl extends ServiceImpl<TyBillMapper, TyBillEntity> implements ITyBillService {

    private @Autowired TyBillMapper tyBillMapper;

    /**
     * 列表查询
     * @param query
     * @return
     */
    @Override
    public RestResponse selectByExample(TyBillQuery query) {
        IPage page = query.page();
        List<TyBillEntity> list = tyBillMapper.selectByQuery(query.condition(), query);

        Double outcome = tyBillMapper.sumByType(query.condition(),1);
        Double income = tyBillMapper.sumByType(query.condition(),2);
        if(ListUtil.isNotEmpty(list)){
            list.get(0).setIncome(income);
            list.get(0).setOutcome(outcome);
        }

        page.setRecords(list);
        int total = tyBillMapper.countByQuery(query.condition());
        page.setTotal(total);
        return RestResponse.success(page, "Select successfully");
    }

    /**
     * 查询最新的余额
     * @return
     */
    @Override
    public BigDecimal getLatestBalance() {
        BigDecimal balance = tyBillMapper.getLatestBalance();
        if (null != balance) {
            return balance;
        } else {
            return new BigDecimal("0");
        }
    }

    @Data
    class ToAmount {

        private Integer type;

        private Double amount;
    }
}
