jiangping
2025-06-06 a2299a6d4a6f99e9c11132138f5d3e9ec68f03ea
server/visits/dmvisit_service/src/main/java/com/doumee/service/business/impl/YwContractServiceImpl.java
@@ -12,6 +12,7 @@
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.*;
import com.doumee.dao.business.dao.CompanyMapper;
import com.doumee.dao.business.dto.YwContractBillDTO;
import com.doumee.dao.business.model.*;
import com.doumee.dao.system.MultifileMapper;
import com.doumee.dao.system.SystemUserMapper;
@@ -25,14 +26,17 @@
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 运维合同信息表Service实现
@@ -44,6 +48,8 @@
    @Autowired
    private YwContractMapper ywContractMapper;
    @Autowired
    private YwContractRoomMapper ywContractRoomMapper;
    @Autowired
    private YwContractDetailMapper ywContractDetailMapper;
    @Autowired
@@ -71,20 +77,267 @@
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public Integer create(YwContract model) {
        isParamValidCreated(model);
        model.setCreator(model.getLoginUserInfo().getId());
        model.setIsdeleted(Constants.ZERO);
        model.setCreateDate(new Date());
        model.setStatus(Constants.ZERO);
        model.setEditDate(model.getCreateDate());
        model.setEditor(model.getCreator());
        model.setStatus(Constants.ZERO);//待执行
        if(model.getStartDate().getTime() > System.currentTimeMillis()){
            model.setStatus(Constants.ZERO);
        }else if(model.getStartDate().getTime() <= System.currentTimeMillis() && Utils.Date.getEnd(model.getEndDate()).getTime() > System.currentTimeMillis()){
            model.setStatus(Constants.ONE);
        }else{
            model.setStatus(Constants.TWO);
        }
        model.setRemark(getRemarlByParam(model));
        ywContractMapper.insert(model);
        dealDetailListBiz(model);//处理条款信息
        dealDetailListBiz(model,false);//处理条款信息
        dealMultifileBiz(model);//处理附件信息
        dealLogBiz(model,Constants.YwLogType.CONTRACT_CREATE,null,null);//记录新建日志
        dealRoomsForContract(model);//处理房源关联表
        dealLogBiz(model,Constants.YwLogType.CONTRACT_CREATE,model.getLoginUserInfo().getRealname(),"【"+model.getRemark().replace("合同摘要:","")+"】");//记录新建日志
        return model.getId();
    }
    private void dealRoomsForContract(YwContract model) {
        this.dealRoomsValid(model);
        List<YwContractRoom> list = new ArrayList<>();
        for(YwRoom room :model.getRoomList()){
            YwContractRoom t = new YwContractRoom();
            t.setContractId(model.getId());
            t.setRoomId(room.getId());
            t.setCreator(model.getCreator());
            t.setIsdeleted(Constants.ZERO);
            t.setCreateDate(model.getCreateDate());
            t.setEditDate(model.getCreateDate());
            t.setEditor(model.getCreator());
            t.setType(Constants.ZERO);
            list.add(t);
        }
        if(Constants.equalsInteger(model.getStatus(),Constants.ONE)){
            //更新房源数据为租赁中
            roomMapper.update(new UpdateWrapper<YwRoom>().lambda().set(YwRoom::getLeaseNowStatus,Constants.ONE)
                    .in(YwRoom::getId,model.getRoomList().stream().map(i->i.getId()).collect(Collectors.toList()))
            );
        }
        ywContractRoomMapper.insert(list);
    }
    private void dealRoomsValid(YwContract model){
        List<Integer> roomIds = model.getRoomList().stream().map(i->i.getId()).collect(Collectors.toList());
        if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(roomIds)){
            if(ywContractMapper.selectJoinCount(new MPJLambdaWrapper<YwContract>()
                    .leftJoin(YwContractRoom.class,YwContractRoom::getContractId,YwContract::getId)
                    .eq(YwContractRoom::getType,Constants.ZERO)
                    .in(YwContractRoom::getRoomId,roomIds)
                    .in(YwContract::getStatus,Constants.ZERO,Constants.ONE,Constants.TWO)
                    .apply(" (" +
                            " ( t.START_DATE < '"+DateUtil.getFomartDate(model.getEndDate(),"yyyy-MM-dd HH:mm:ss")+"'  and t.END_DATE > '"+DateUtil.getFomartDate(model.getStartDate(),"yyyy-MM-dd HH:mm:ss")+"' ) " +
                            "or " +
                            " ( t.START_DATE < '"+DateUtil.getFomartDate(model.getEndDate(),"yyyy-MM-dd HH:mm:ss")+"'  and t.END_DATE > '"+DateUtil.getFomartDate(model.getStartDate(),"yyyy-MM-dd HH:mm:ss")+"' ) " +
                            " ) ")
            )>Constants.ZERO){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"房源已被占用请刷新重试");
            };
            if(ywContractMapper.selectJoinCount(new MPJLambdaWrapper<YwContract>()
                    .leftJoin(YwContractRoom.class,YwContractRoom::getContractId,YwContract::getId)
                    .eq(YwContractRoom::getType,Constants.ZERO)
                    .in(YwContractRoom::getRoomId,roomIds)
                    .in(YwContract::getStatus,Constants.THREE)
                    .apply(" ( t.START_DATE < '"+DateUtil.getFomartDate(model.getEndDate(),"yyyy-MM-dd HH:mm:ss")+"' " +
                            " and t.BT_DATE > '"+DateUtil.getFomartDate(model.getStartDate(),"yyyy-MM-dd HH:mm:ss")+"' ) " )
            )>Constants.ZERO){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"房源已被占用请刷新重试");
            };
        }
    }
    @Override
    public   List<YwContractBill> getBillList(YwContract model){
        isParamValidForBill(model);
        model.setCreateDate(new Date());
        model.setEditDate(model.getCreateDate());
        dealDetailListBiz(model,true);//处理条款信息
        return model.getBillList();
    }
    private void isParamValidForBill(YwContract model) {
        if(model.getStartDate() == null
                ||model.getEndDate() == null
                ||model.getProjectId() == null
                ||model.getCompanyId() == null
                ||model.getRoundedUp() == null
                ||model.getRoomIds() == null
                ||model.getRoomIds().size() == 0
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写合同信息");
        }
        if(model.getEndDate().getTime()< model.getStartDate().getTime()){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,合同有效期结束时间不得早于开始时间!");
        }
        if(model.getBillType() ==0 ){
            //如果生成租赁条款
            if(  model.getZlDeposit() == null
                    ||model.getZlPayType() == null
                    || model.getZlPayType()>3
                    || model.getZlPayType()<0
                    ||model.getZlDetailList()==null
                    ||model.getZlDetailList().size() ==0){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写租赁条款信息");
            }
            model.setType(Constants.TWO);
            model.setWyDetailList(null);
            if(!(model.getZlFreeEndDate()==null &&  model.getZlFreeStartDate()==null) && (
                    (model.getZlFreeEndDate()!=null &&  model.getZlFreeStartDate()==null)
                            ||(model.getZlFreeEndDate()==null &&  model.getZlFreeStartDate()!=null)
                            ||model.getZlFreeEndDate().getTime()<= model.getZlFreeStartDate().getTime())
            ){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择正确的租赁条款免租期信息!");
            }
            for(YwContractDetail d :model.getZlDetailList()){
                if(  d.getStartDate() == null
                        ||d.getEndDate() == null
                        ||d.getPrice() == null
                        ||d.getCircleType() == null
                        || d.getCircleType()>6
                        || d.getCircleType()<0
                ){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写租赁条款信息!");
                }
                if(d.getEndDate().getTime()< d.getStartDate().getTime()){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,租赁条款有效期结束时间不得早于开始时间!");
                }
                if(!Constants.equalsInteger(model.getWyPayType(),Constants.ZERO) &&
                        Constants.equalsInteger(d.getCircleType(),Constants.SIX)){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,租赁条款只有选择一次性付款时,才能选择该按每场收费;");
                }
            }
        }
        if(model.getBillType() == 1 ){
            //如果生成物业条款
            if(  model.getWyDeposit() == null
                    ||model.getWyPayType() == null
                    || model.getWyPayType()>3
                    || model.getWyPayType()<0
                    ||model.getWyDetailList()==null
                    ||model.getWyDetailList().size() ==0
            ){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写物业条款信息");
            }
            model.setType(Constants.ONE);
            model.setZlDetailList(null);
            if(!(model.getWyFreeEndDate()==null &&  model.getWyFreeStartDate()==null) && (
                    (model.getWyFreeEndDate()!=null &&  model.getWyFreeStartDate()==null)
                            ||(model.getWyFreeEndDate()==null &&  model.getWyFreeStartDate()!=null)
                            ||model.getWyFreeEndDate().getTime()<= model.getWyFreeStartDate().getTime())){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择正确的物业条款免租期信息!");
            }
            for(YwContractDetail d :model.getWyDetailList()){
                if(  d.getStartDate() == null
                        ||d.getEndDate() == null
                        ||d.getPrice() == null
                        ||d.getCircleType() == null
                        || d.getCircleType()>6
                        || d.getCircleType()<0
                ){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写物业条款信息!");
                }
                if(d.getEndDate().getTime()<= d.getStartDate().getTime()){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,物业条款有效期结束时间不得早于开始时间!");
                }
                if(!Constants.equalsInteger(model.getWyPayType(),Constants.ZERO) &&
                        Constants.equalsInteger(d.getCircleType(),Constants.SIX)){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,物业条款只有选择一次性付款时,才能选择该按每场收费;");
                }
            }
        }
        YwProject project = projectMapper.selectById(model.getProjectId());
        if(project ==null || Constants.equalsInteger(project.getIsdeleted(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,请选择正确的项目信息!");
        }
        List<YwRoom> rooms = roomMapper.selectList(new QueryWrapper<YwRoom>().lambda()
                .eq(YwRoom::getIsdeleted,Constants.ZERO)
                .in(YwRoom::getId,model.getRoomIds())
                .eq(YwRoom::getProjectId,model.getProjectId())  );
        if(rooms ==null || rooms.size()==0){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择对应项目下正确的房源信息");
        }
        if(rooms.size() != rooms.size()){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,存在无效的房源信息!");
        }
        model.setTotalArea(new BigDecimal(0));
        for(YwRoom r : rooms){
            model.setTotalArea(model.getTotalArea().add(Constants.formatBigdecimal(r.getRentArea())));
        }
        model.setRoomList(rooms);
    }
    private String getRemarlByParam(YwContract model) {
        String str = "";
        //起租日2024/06/01,租赁数为500㎡。首期租赁三月一付,租金单价35元/㎡·月。首期物业三月一付,物业单价4.3元/㎡·月
        String str0 = "合同摘要:起租日{param1},租赁数为{param2}㎡。首期租赁{param3},租金单价{param4}{param5}。首期物业{param6},物业单价{param7}{param8}";
        String str1 = "合同摘要:起租日{param1},租赁数为{param2}㎡。首期租赁{param3},租金单价{param4}{param5}。";
        String str2 = "合同摘要:起租日{param1},首期物业{param6},物业单价{param7}{param8}";
        if(Constants.equalsInteger(model.getType(),Constants.ZERO)){
            str= str0;
        }
        if(Constants.equalsInteger(model.getType(),Constants.TWO)){
            str= str1;
        }
        if(Constants.equalsInteger(model.getType(),Constants.ONE)){
            str= str2;
        }
        str = str.replace("{param1}",DateUtil.getDateLongSlash(model.getStartDate()))
                .replace("{param2}",model.getTotalArea().intValue()+"")
                .replace("{param3}",Constants.getPayTypeByNum(model.getZlPayType()))
                .replace("{param4}",Constants.formatBigdecimal(model.getZlFirstPrice()).intValue()+"")
                .replace("{param5}",Constants.getUnitTypeByNum(model.getZlFirstCircle()))
                .replace("{param6}",Constants.getPayTypeByNum(model.getWyPayType()))
                .replace("{param7}",Constants.formatBigdecimal(model.getWyFirstPrice()).intValue()+"")
                .replace("{param8}",Constants.getUnitTypeByNum(model.getWyFirstCircle()));
        return  str;
    }
    private String getbackRentRemarkByParam(YwContract model) {
        BigDecimal fee = Constants.formatBigdecimal(model.getBtFee());
        String str = "退租摘要:剩余未结清账单{param1}份,关闭账单{param2}份【退租日{param3},退租费用合计需{param4}{param5}元。】";
        str = str.replace("{param1}",model.getBtWaitBill()+"")
                .replace("{param2}",model.getBtCLoseBill()+"")
                .replace("{param3}",DateUtil.getDateLongSlash(model.getBtDate()))
                .replace("{param4}",fee.compareTo(new BigDecimal(0)) >=0?"收":"付")
                .replace("{param5}",(fee.compareTo(new BigDecimal(0)) >=0?
                        Constants.formatBigdecimal2Float(model.getBtFee())
                        :(Constants.formatBigdecimal2Float(model.getBtFee()).multiply(new BigDecimal(-1)))).toString());
        return  str;
    }
    private String getbackRentLogByParam(YwContract model) {
        BigDecimal fee = Constants.formatBigdecimal(model.getBtFee());
        String str = "【退租日{param1},退租原因:{param2},退租协议中统计的费用总计需{param4}{param5}元。】";
        str = str.replace("{param1}",DateUtil.getDateLongSlash(model.getBtDate()))
                .replace("{param2}",StringUtils.defaultString(model.getBtInfo(),""))
                .replace("{param4}",fee.compareTo(new BigDecimal(0)) >=0?"收":"付")
                .replace("{param5}",(fee.compareTo(new BigDecimal(0)) >=0?
                        Constants.formatBigdecimal2Float(model.getBtFee())
                        :(Constants.formatBigdecimal2Float(model.getBtFee()).multiply(new BigDecimal(-1)))).toString());
        return  str;
    }
    /**
     * 退租提交
     * @param param
@@ -94,25 +347,260 @@
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public  Integer backRent(YwContract param){
        isParamValidBackRent(param);
        YwContract model = ywContractMapper.selectById(param.getId());
        if(Objects.isNull(model)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!(model.getStartDate().getTime()<=param.getBtDate().getTime()&&model.getEndDate().getTime()>=param.getBtDate().getTime())){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"退租日期错误,请检查退租日期需在合同日期内!");
        }
        param.setEditDate(new Date());
        param.setEditor(param.getLoginUserInfo().getId());
        //处理
        dealBackRentBillBiz(param);
        YwContract update = new YwContract();
        update.setId(param.getId());
        update.setEditDate(new Date());
        update.setEditor(param.getLoginUserInfo().getId());
        update.setBtActDate(update.getEditDate());
        update.setBtActUserId(update.getEditor());
        update.setStatus(Constants.THREE);
        if(Objects.nonNull(param.getBtWaitBill()) && param.getBtWaitBill() > Constants.ZERO){
            update.setStatus(Constants.THREE);
        }else{
            update.setStatus(Constants.FOUR);
        }
        update.setBtInfo(param.getBtInfo());
        update.setBtDate(param.getBtDate());
        update.setBtType(param.getBtType());
        update.setBtUserId(param.getBtUserId());
        update.setBtFee(param.getBtFee());
        update.setBtRemark(getbackRentRemarkByParam(param));
        ywContractMapper.updateById(update);
        dealLogBiz(param,Constants.YwLogType.CONTRACT_BACK,null,null);
        dealLogBiz(param,Constants.YwLogType.CONTRACT_BACK, param.getLoginUserInfo().getRealname(),getbackRentLogByParam(param));
        //如果退租日期小于当前日期 则直接释放房源信息 未租赁
        if(Utils.Date.getEnd(param.getBtDate()).getTime()<System.currentTimeMillis()){
            List<YwContractRoom> contractRoomList = ywContractRoomMapper.selectList(new QueryWrapper<YwContractRoom>().lambda()
                    .eq(YwContractRoom::getContractId, param.getId()));
            if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(contractRoomList)){
                //更新房源数据为未租赁
                roomMapper.update(new UpdateWrapper<YwRoom>().lambda().set(YwRoom::getLeaseNowStatus,Constants.ZERO)
                        .in(YwRoom::getId,contractRoomList.stream().map(i->i.getRoomId()).collect(Collectors.toList()))
                );
            }
        }
        return param.getId();
    }
    @Override
    public  void dealTimeOut(){
        List<YwContract> listA = ywContractMapper.selectList(new QueryWrapper<YwContract>().lambda()
                .eq(YwContract::getIsdeleted,Constants.ZERO)
                .in(YwContract::getStatus,Constants.ZERO)
                .apply(" START_DATE < NOW()  AND END_DATE > NOW() ")
        );
        if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(listA)){
            //定时处理合同执行中
            ywContractMapper.update(new UpdateWrapper<YwContract>()
                    .lambda()
                    .set(YwContract::getStatus,Constants.ONE)
                    .set(YwContract::getEditDate,DateUtil.getCurrDateTime())
                    .in(YwContract::getId,listA.stream().map(i->i.getId()).collect(Collectors.toList()))
            );
            List<YwContractRoom> contractRoomList = ywContractRoomMapper.selectList(new QueryWrapper<YwContractRoom>().lambda().in(YwContractRoom::getContractId,
                    listA.stream().map(i->i.getId()).collect(Collectors.toList())));
            if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(contractRoomList)){
                //更新房源数据为租赁中
                roomMapper.update(new UpdateWrapper<YwRoom>().lambda().set(YwRoom::getLeaseNowStatus,Constants.ONE)
                        .in(YwRoom::getId,contractRoomList.stream().map(i->i.getRoomId()).collect(Collectors.toList()))
                );
            }
        }
    }
    private void dealBackRentBillBiz(YwContract param) {
        //查询合同全部账单信息
        List<YwContractBill> closeBills = new ArrayList<>();//带关闭
        List<YwContractBill> newBills = new ArrayList<>();//新的账单
        List<YwContractBill> noBills = new ArrayList<>();//不需要结算的账单
        List<YwContractBill> yjBills = new ArrayList<>();//押金账单
        List<YwContractBill> canBills = new ArrayList<>();//可退租修改数据
        Integer canBillCount = Constants.ZERO;
        List<YwContractBill> allBills = ywContractBillMapper.selectList(new QueryWrapper<YwContractBill>().
                select("*," +
                        "( select ifnull(sum(case when yw.REVENUE_TYPE = 0 then yw.ACT_RECEIVABLE_FEE  else  -yw.ACT_RECEIVABLE_FEE end),0) from  yw_contract_revenue yw where yw.bill_id = yw_contract_bill.id and yw.status = 0 and yw.isdeleted = 0 ) as  actReceivableFee " )
                .lambda().
                eq(YwContractBill::getIsdeleted,Constants.ZERO)
                .eq(YwContractBill::getContractId,param.getId()));
        if(allBills!=null && allBills.size()>0){
            for(YwContractBill bill: allBills){
                //付款状态:0=待收款;1=已结清;2=部分结清;3=待付款;4=待退款;5=已关闭
                // 如果是押金或者保证金,不支持退款,保持原来的状态, 0=租赁费;1=物业费;2=租赁押金;3=物业押金;4=水电费;5=杂项费;6=其他;7=保证金
                if(Constants.equalsInteger(Constants.THREE,bill.getCostType())
                        ||  Constants.equalsInteger(Constants.TWO,bill.getCostType())
                        ||Constants.equalsInteger(Constants.SEVEN,bill.getCostType())){
                    //押金和保证金
                    yjBills.add(bill);
                    continue;
                }
                if(Constants.equalsInteger(bill.getPayStatus(),Constants.ZERO)
                        ||Constants.equalsInteger(bill.getPayStatus(),Constants.THREE)){
                    if(bill.getStartDate().getTime()<=param.getBtDate().getTime()){
                        canBills.add(bill);
                        canBillCount = canBillCount + 1 ;
                    }else{
                        //如果还没开始,账单直接关闭
                        closeBills.add(bill);
                        noBills.add(bill);
                    }
                }else  if(Constants.equalsInteger(bill.getPayStatus(),Constants.ONE) ){
                    if(bill.getStartDate().getTime()>param.getBtDate().getTime()){
                        //如果已结清,账单直接关闭
                        noBills.add(bill);
                    }else{
                        canBills.add(bill);
                        canBillCount = canBillCount + 1 ;
                    }
                }else  if(Constants.equalsInteger(bill.getPayStatus(),Constants.TWO) ){
                     canBills.add(bill);
                    canBillCount = canBillCount + 1 ;
                }
            }
        }
        if(closeBills.size()>0){
            //直接关闭关闭账单
            for(YwContractBill b : closeBills){
                b.setStatus(Constants.ONE);
                b.setEditDate(param.getEditDate());
                b.setEditor(param.getEditor());
                //关闭订单
                ywContractBillMapper.updateById(b);
            }
        }
        BigDecimal totalBackFee = new BigDecimal(0);
        if(canBills.size()>0){
            //
            for(YwContractBill b : canBills){
                BigDecimal fee = new BigDecimal(0);
                YwContractBill editBill = getEditBillFromListByParam(b,param.getCanBackRentBills());
                if(editBill != null){
                    //付款状态:0=待收款;1=已结清;2=部分结清;3=待付款;4=待退款;5=已关闭
                    //如果账单信息做了编辑,金额计算 实收金额 和 修改后应收金额作对比,判断是否应该退款
                    fee = editBill.getReceivableFee().subtract(Constants.formatBigdecimal(b.getActReceivableFee()));
                    if(fee.compareTo(new BigDecimal(0))== 0){
                        //如果费用正好,则修改账单信息为已结清
                        b.setPayStatus(Constants.ONE);
                        canBillCount = canBillCount - 1 ;
                    }else if(fee.compareTo(new BigDecimal(0))< 0){
                        //如果需要进行退款,更新账单信息为待退款
                        b.setPayStatus(Constants.FOUR);
                    }else if(fee.compareTo(new BigDecimal(0)) > 0){
                        //如果账单还有款待收,则更新账单为待收款
                        if(b.getPayStatus()==Constants.ZERO){
                            b.setPayStatus(Constants.ZERO);
                        }else if(b.getPayStatus()!=Constants.TWO){
                            b.setPayStatus(Constants.TWO);
                        }
                    }
                    b.setReceivableFee(editBill.getReceivableFee());
                }
                b.setEditDate(param.getEditDate());
                b.setEditor(param.getEditor());
                b.setBtActDate(param.getBtActDate());
                b.setBtDate(param.getBtDate());
                b.setBtFee(fee);
                b.setBtInfo(param.getBtInfo());
                b.setBtUserId(param.getBtUserId());
                b.setBtSignDate(param.getBtSignDate());
                b.setBtType(param.getBtType());
                //关闭订单
                ywContractBillMapper.updateById(b);
                totalBackFee = totalBackFee.add(fee);//累计退款金额
            }
        }
        if(param.getAddBillList()!=null && param.getAddBillList().size()>0){
            for(YwContractBill addBill : param.getAddBillList()){
                addBill.setIsdeleted(Constants.ZERO);
                addBill.setContractId(param.getId());
                addBill.setCreateDate(new Date());
                addBill.setCreator(param.getEditor());
                addBill.setType(Constants.TWO);
                addBill.setStatus(Constants.ZERO);
                addBill.setTotleFee(addBill.getReceivableFee());
                addBill.setCompanyId(param.getCompanyId());
                if(Constants.equalsInteger(addBill.getFeeType(),Constants.ONE)){
                    addBill.setStartDate(addBill.getPlanPayDate());
                    addBill.setEndDate(addBill.getPlanPayDate());
                }
                if(Constants.equalsInteger(addBill.getBillType(),Constants.ZERO)){
                    //如果是收款
//                    totalBackFee = totalBackFee.add(Constants.formatBigdecimal(addBill.getActReceivableFee()));
                    addBill.setPayStatus(Constants.ZERO);
                    addBill.setBtFee(Constants.formatBigdecimal(addBill.getReceivableFee()));
                }else{
                    //如果是付款
                    addBill.setPayStatus(Constants.THREE);
                    addBill.setBtFee(Constants.formatBigdecimal(addBill.getReceivableFee()).multiply(new BigDecimal(-1)));
                }
                totalBackFee = totalBackFee.add(Constants.formatBigdecimal(addBill.getBtFee()));
                addBill.setEditDate(param.getEditDate());
                addBill.setEditor(param.getEditor());
                addBill.setBtActDate(param.getBtActDate());
                addBill.setBtDate(param.getBtDate());
                addBill.setBtInfo(param.getBtInfo());
                addBill.setBtUserId(param.getBtUserId());
                addBill.setBtSignDate(param.getBtSignDate());
                addBill.setBtType(param.getBtType());
                newBills.add(addBill);
            }
            ywContractBillMapper.insert(param.getAddBillList());//批量插入数据
        }
        int yjNoBills =0;
        if(yjBills.size()>0){
            // 如果是押金或者保证金,不支持退款,保持原来的状态, 0=租赁费;1=物业费;2=租赁押金;3=物业押金;4=水电费;5=杂项费;6=其他;7=保证金
            for(YwContractBill bill : yjBills){
                if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(param.getCanBackRentBills())){
                    List<YwContractBill> optional = param.getCanBackRentBills().stream().filter(i->Constants.equalsInteger(bill.getId(),i.getId())).collect(Collectors.toList());
                    if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(optional)){
                        YwContractBill canBill = optional.get(Constants.ZERO);
                        YwContractBill yjBill = new YwContractBill();
                        yjBill.setId(bill.getId());
                        yjBill.setEditDate(param.getEditDate());
                        yjBill.setEditor(param.getEditor());
                        yjBill.setReceivableFee(BigDecimal.ZERO);
                        if(Constants.formatBigdecimal(canBill.getActReceivableFee()).compareTo(new BigDecimal(0)) == 0){
                            //未支付的押金,直接关闭
                            yjBill.setStatus(Constants.ONE);
                            closeBills.add(yjBill);
                        }else{
                            yjBill.setBtFee(Constants.formatBigdecimal(canBill.getActReceivableFee()).multiply(new BigDecimal(-1)));
                            yjBill.setPayStatus(Constants.FOUR);
                            yjBill.setPlanPayDate(canBill.getPlanPayDate());
                            totalBackFee = totalBackFee.add(Constants.formatBigdecimal(yjBill.getBtFee()));
                            yjNoBills ++;
                        }
                        ywContractBillMapper.updateById(yjBill);
                    }
                }
            }
        }
        param.setBtWaitBill(canBillCount  + newBills.size()+yjNoBills);//未清算的账单数量
        param.setBtCLoseBill(closeBills.size());
        param.setBtFee(totalBackFee);
    }
    private YwContractBill getEditBillFromListByParam(YwContractBill b, List<YwContractBill> canBackRentBills) {
        for(YwContractBill d : canBackRentBills){
            if(Constants.equalsInteger(b.getId(),d.getId())){
                return d;
            }
        }
        return null;
    }
    private void isParamValidBackRent(YwContract param) {
@@ -129,7 +617,7 @@
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,合同信息不存在,请返回列表刷新重试!");
        }
        SystemUser user = systemUserMapper.selectById(param.getUserId());
        SystemUser user = systemUserMapper.selectById(param.getBtUserId());
        if(user ==null ||  (user.getDeleted()!=null&& user.getDeleted() )){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,经办人信息不存在!");
        }
@@ -138,21 +626,29 @@
                if(bill.getCostType() == null
                        ||bill.getFeeType() == null
                        ||bill.getReceivableFee() == null
                        ||bill.getReceivableFee().compareTo(new BigDecimal(0)) < 1
                        ||bill.getCompanyId() == null
                        ||bill.getPlanPayDate() == null
                        ||(Constants.equalsInteger(bill.getFeeType(),Constants.ZERO)
                        ||bill.getBillType() == null
                        ||(Constants.equalsInteger(bill.getBillType(),Constants.ZERO)
                        &&Constants.equalsInteger(bill.getFeeType(),Constants.ZERO)
                        && (bill.getStartDate() ==null || bill.getEndDate() ==null) )){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按要求填写自建账单信息!");
                }
            }
        }
    }
    private void dealDetailListBiz(YwContract model) {
        List<YwContractDetail> details = new ArrayList<>();
    /**
     * @param model
     * @param createBill  根据条款生成账单 false 则根据前端编辑后的数据生成
     */
    private void dealDetailListBiz(YwContract model,boolean createBill) {
        List<YwContractDetail> details1 = new ArrayList<>();
        List<YwContractDetail> details2 = new ArrayList<>();
        int num = 0;
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.ONE)){
                || Constants.equalsInteger(model.getType(),Constants.TWO)){
            for(YwContractDetail d :model.getZlDetailList()){
               d.setCreateDate(model.getEditDate());
               d.setCreator(model.getEditor());
@@ -161,12 +657,12 @@
               d.setType(Constants.ZERO);
               d.setSortnum(num++);
               d.setStatus(Constants.ZERO);
               details.add(d);
               details1.add(d);
            }
        }
        num = 0;
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.TWO)){
                || Constants.equalsInteger(model.getType(),Constants.ONE)){
            for(YwContractDetail d :model.getWyDetailList()){
                d.setCreateDate(model.getEditDate());
                d.setCreator(model.getEditor());
@@ -175,71 +671,187 @@
                d.setContractId(model.getId());
                d.setSortnum(num++);
                d.setStatus(Constants.ZERO);
                details.add(d);
                details2.add(d);
            }
        }
        ywContractDetailMapper.insert(details);//批量插入条款信息信息
        if(model.getId()!=null){
            if(details1.size()>0){
                ywContractDetailMapper.insert(details1);//批量插入条款信息信息
            }
            if(details2.size()>0){
                ywContractDetailMapper.insert(details2);//批量插入条款信息信息
            }
        }
        //处理账单信息
        dealBillListBiz(model,details);
        if(createBill){
            dealBillListBiz(model,details1,details2);
        }else{
            //2025-1-23 13:56:53 加入 前端入参调整后的账单信息
            List<YwContractBill> ywContractBillList = new ArrayList<>();
            //查询租赁条款
            if((Constants.equalsInteger(model.getType(),Constants.ZERO )
                    || Constants.equalsInteger(model.getType(),Constants.TWO))&& com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(details1)){
                YwContractDetail ywContractDetail = details1.get(Constants.ZERO);
                YwContractBill zlBill = new YwContractBill();
                BeanUtils.copyProperties(model.getZlBillDTO(),zlBill);
                zlBill.setCreator(model.getCreator());
                zlBill.setCreateDate(model.getCreateDate());
                zlBill.setIsdeleted(Constants.ZERO);
                zlBill.setStatus(Constants.ZERO);
                zlBill.setReceivableFee(zlBill.getTotleFee());
                zlBill.setType(Constants.ZERO);
                zlBill.setCompanyId(model.getCompanyId());
                zlBill.setContractId(model.getId());
                zlBill.setBillType(Constants.ZERO);
                zlBill.setPayStatus(Constants.ZERO);
                ywContractBillList.add(zlBill);
                Integer sortnum = Constants.ONE;
                for (YwContractBillDTO zlBillDTO:model.getZlBillDTOList()) {
                    YwContractBill zl = new YwContractBill();
                    BeanUtils.copyProperties(zlBillDTO,zl);
                    zl.setCreator(model.getCreator());
                    zl.setCreateDate(model.getCreateDate());
                    zl.setIsdeleted(Constants.ZERO);
                    zl.setStatus(Constants.ZERO);
                    zl.setReceivableFee(zl.getTotleFee());
                    zl.setType(Constants.ZERO);
                    zl.setCompanyId(model.getCompanyId());
                    zl.setContractId(model.getId());
                    zl.setBillType(Constants.ZERO);
                    zl.setPayStatus(Constants.ZERO);
                    zl.setSortnum(sortnum);
                    zl.setDetailId(ywContractDetail.getId());
                    ywContractBillList.add(zl);
                    sortnum++;
                }
            }
            //查询物业账单
            if((Constants.equalsInteger(model.getType(),Constants.ZERO )
                    || Constants.equalsInteger(model.getType(),Constants.ONE))&& com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(details2)){
                YwContractDetail ywContractDetail = details2.get(Constants.ZERO);
                YwContractBill wyBill = new YwContractBill();
                BeanUtils.copyProperties(model.getWyBillDTO(),wyBill);
                wyBill.setCreator(model.getCreator());
                wyBill.setCreateDate(model.getCreateDate());
                wyBill.setIsdeleted(Constants.ZERO);
                wyBill.setStatus(Constants.ZERO);
                wyBill.setReceivableFee(wyBill.getTotleFee());
                wyBill.setType(Constants.ZERO);
                wyBill.setCompanyId(model.getCompanyId());
                wyBill.setContractId(model.getId());
                wyBill.setBillType(Constants.ZERO);
                wyBill.setPayStatus(Constants.ZERO);
                ywContractBillList.add(wyBill);
                Integer sortnum = Constants.ONE;
                for (YwContractBillDTO wyBillDTO:model.getWyBillDTOList()) {
                    YwContractBill wy = new YwContractBill();
                    BeanUtils.copyProperties(wyBillDTO,wy);
                    wy.setCreator(model.getCreator());
                    wy.setCreateDate(model.getCreateDate());
                    wy.setIsdeleted(Constants.ZERO);
                    wy.setStatus(Constants.ZERO);
                    wy.setReceivableFee(wy.getTotleFee());
                    wy.setType(Constants.ZERO);
                    wy.setCompanyId(model.getCompanyId());
                    wy.setContractId(model.getId());
                    wy.setBillType(Constants.ZERO);
                    wy.setPayStatus(Constants.ZERO);
                    wy.setSortnum(sortnum);
                    wy.setDetailId(ywContractDetail.getId());
                    ywContractBillList.add(wy);
                    sortnum++;
                }
            }
            if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(ywContractBillList)){
                ywContractBillMapper.insert(ywContractBillList);
            }
        }
    }
    /**
     * 支付方式 0=一次性付款;1=每三个月一付;2=六个月一付;3=一年一付
     * @param model
     * @param details
     * @param details1 租赁条款
     * @param details2 物业条款
     */
    private void dealBillListBiz(YwContract model, List<YwContractDetail> details) {
        List<YwContractBill> billList = new ArrayList<>();
    private void dealBillListBiz(YwContract model, List<YwContractDetail> details1, List<YwContractDetail> details2) {
        List<YwContractBill> billList1 = new ArrayList<>();
        List<YwContractBill> billList2 = new ArrayList<>();
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.ONE)){
                || Constants.equalsInteger(model.getType(),Constants.TWO)){
            //如果有租赁条款
            if(Constants.formatBigdecimal(model.getZlDeposit()).compareTo(new BigDecimal(0))>0){
                    //如果有租赁押金
                billList.add(initDepoistBill(Constants.THREE,model));
                billList1.add(initDepoistBill(Constants.TWO,model));
            }
            if(Constants.equalsInteger(model.getZlPayType(), Constants.ZERO)){
                //如果是一次性付清
                billList.addAll(getBillsByParamOnce(model,details,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
                billList1.addAll(getBillsByParamOnce(model,details1,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
            }else if(Constants.equalsInteger(model.getZlPayType(), Constants.ONE)){
                //如果每三个月一付
                billList.addAll(getBillsByParam3Months(model,details,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
                billList1.addAll(getBillsByParam3Months(model,details1,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
            }else if(Constants.equalsInteger(model.getZlPayType(), Constants.TWO)){
                //如果六个月一付
                billList.addAll(getBillsByParam6Months(model,details,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
                billList1.addAll(getBillsByParam6Months(model,details1,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
            }else if(Constants.equalsInteger(model.getZlPayType(), Constants.THREE)){
                //如果一年一付
                billList.addAll(getBillsByParam1Year(model,details,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
                billList1.addAll(getBillsByParam1Year(model,details1,model.getZlFreeStartDate(),model.getZlFreeEndDate()));
            }
        }
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.TWO)){
                || Constants.equalsInteger(model.getType(),Constants.ONE)){
            //如果物业条款
            if(Constants.formatBigdecimal(model.getWyDeposit()).compareTo(new BigDecimal(0))>0){
                //如果有租赁押金
                billList.add(initDepoistBill(Constants.FOUR,model));
                billList2.add(initDepoistBill(Constants.THREE,model));
            }
            if(Constants.equalsInteger(model.getWyPayType(), Constants.ZERO)){
                //如果是一次性付清
                billList.addAll(getBillsByParamOnce(model,details,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
                billList2.addAll(getBillsByParamOnce(model,details2,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
            }else if(Constants.equalsInteger(model.getWyPayType(), Constants.ONE)){
                //如果每三个月一付
                billList.addAll(getBillsByParam3Months(model,details,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
                billList2.addAll(getBillsByParam3Months(model,details2,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
            }else if(Constants.equalsInteger(model.getWyPayType(), Constants.TWO)){
                //如果六个月一付
                billList.addAll(getBillsByParam6Months(model,details,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
                billList2.addAll(getBillsByParam6Months(model,details2,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
            }else if(Constants.equalsInteger(model.getWyPayType(), Constants.THREE)){
                //如果一年一付
                billList.addAll(getBillsByParam1Year(model,details,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
                billList2.addAll(getBillsByParam1Year(model,details2,model.getWyFreeStartDate(),model.getWyFreeEndDate()));
            }
        }
        for(int i=0;i<billList.size();i++){
            billList.get(i).setSortnum(i+1);
        }
        ywContractBillMapper.insert(billList);
        if(model.getBillType() == 0){
            model.setBillList(billList1);
        }else  if(model.getBillType() == 1){
            model.setBillList(billList2);
        }
        int num =1;
        for(int i=0;i<billList1.size();i++){
            if(Constants.formatBigdecimal(billList1.get(i).getReceivableFee()).compareTo(new BigDecimal(0)) == 0){
                billList1.get(i).setPayStatus(Constants.ONE);
            }
            if(Constants.equalsInteger(billList1.get(i).getCostType(),Constants.ZERO)){
                billList1.get(i).setSortnum(num);
                num++;
            }
        }
        for(int i=0;i<billList2.size();i++){
            if(Constants.formatBigdecimal(billList2.get(i).getReceivableFee()).compareTo(new BigDecimal(0)) == 0){
                billList2.get(i).setPayStatus(Constants.ONE);
            }
            if(Constants.equalsInteger(billList2.get(i).getCostType(),Constants.ONE)) {
                billList2.get(i).setSortnum(num);
                num++;
            }
        }
        if(model.getId()!=null){
            ywContractBillMapper.insert(billList1);
            ywContractBillMapper.insert(billList2);
        }
    }
    private YwContractBill initDepoistBill(int type,  YwContract model) {
    private YwContractBill initDepoistBill(int type,  YwContract model ) {
        YwContractBill bill  = new YwContractBill();
        bill.setCreateDate(model.getEditDate());
        bill.setCreator(model.getEditor());
@@ -252,8 +864,16 @@
        bill.setEndDate(model.getEndDate());
        bill.setType(Constants.ZERO);
        bill.setCostType(type);
        bill.setTotleFee(type==Constants.THREE?model.getZlDeposit():model.getWyDeposit());//押金费用
        bill.setPlanPayDate(bill.getStartDate());
        bill.setTotleFee(type==Constants.TWO?
                Objects.isNull(model.getZlDeposit())?BigDecimal.ZERO:model.getZlDeposit()
                :
                Objects.isNull(model.getWyDeposit())?BigDecimal.ZERO:model.getWyDeposit());//押金费用
        bill.setReceivableFee(bill.getTotleFee());
        bill.setBillType(Constants.ZERO);
        bill.setPayStatus(Constants.ZERO);
        bill.setSortnum(0);
        bill.setCompanyId(model.getCompanyId());
        return bill;
    }
@@ -300,13 +920,12 @@
        int monthSix = months / 6;//6个月维度数量
        int restMonth = months % 6;//剩余的整月
        int monthDays =   dateCompare.getMonthDays();//不满一个月的天数
        Date date = new Date();
        List<Date> list = new ArrayList<>();
        for (int i = 0; i < monthSix; i++) {
            list.add(DateUtil.addMonthToDate(date,i*6));
            list.add(DateUtil.addMonthToDate(startDate,i*6));
        }
        if(restMonth>0 || monthDays>0){
            list.add(DateUtil.addDaysToDate(date,monthSix));
            list.add(DateUtil.addMonthToDate(startDate,monthSix*6));
        }
        return list;
    }
@@ -316,13 +935,12 @@
        int monthThree = months / 3;//3个月维度数量
        int restMonth = months % 3;//剩余的整月
        int monthDays =   dateCompare.getMonthDays();//不满一个月的天数
        Date date = new Date();
        List<Date> list = new ArrayList<>();
        for (int i = 0; i < monthThree; i++) {
            list.add(DateUtil.addMonthToDate(date,i*3));
            list.add(DateUtil.addMonthToDate(startDate,i*3));
        }
        if(restMonth>0 || monthDays>0){
            list.add(DateUtil.addDaysToDate(date,monthThree));
            list.add(DateUtil.addMonthToDate(startDate,monthThree*3));
        }
        return list;
    }
@@ -347,56 +965,61 @@
    }
    private void dealCircleDateBillBiz(  List<Date> dateList ,YwContract model, YwContractDetail d, Date freeStart, Date freeEnd, List<YwContractBill> list ) {
        int temp = 0;
        for(Date start : dateList){
            Date end = DateUtil.addDaysToDate(DateUtil.addYearToDate(start,1),-1);//结束日期为下一个周期的前一天
            if(end.getTime()> d.getEndDate().getTime() ){
                end = d.getEndDate();
            Date end = d.getEndDate();
            if(temp+1 < dateList.size()){
                end =DateUtil.addDaysToDate(dateList.get(temp+1),-1);
            }
            temp++;
            YwContractBill bill = initCreateBillModel(model,d );
            bill.setStartDate(start);//账单开始
            bill.setEndDate(end);//账单结束
            bill.setPlanPayDate(DateUtil.addDaysToDate(d.getStartDate(),Constants.formatIntegerNum(d.getAdvanceDays()) * -1));
            BigDecimal totalFee =getTotalFeeByStartEnd(model,d,freeStart,freeEnd);
            Date planPayDate = DateUtil.addDaysToDate(bill.getStartDate(),Constants.formatIntegerNum(d.getAdvanceDays()) * -1);
            bill.setPlanPayDate(planPayDate.getTime()>System.currentTimeMillis()?planPayDate:new Date());
            BigDecimal totalFee =getTotalFeeByStartEnd(model,d,bill,freeStart,freeEnd);
            bill.setTotleFee(totalFee);
            bill.setReceivableFee(totalFee);
            bill.setBillType(Constants.ZERO);
            bill.setCompanyId(model.getCompanyId());
            list.add(bill);
        }
    }
    private BigDecimal getTotalFeeByStartEnd(YwContract model, YwContractDetail d,Date freeStart,Date freeEnd) {
    private BigDecimal getTotalFeeByStartEnd(YwContract model, YwContractDetail d, YwContractBill bill,Date freeStart,Date freeEnd) {
        BigDecimal totalFee = new BigDecimal(0);
        DateCompare dateCompare =   DateCompare.dayCompare(d.getStartDate(),d.getEndDate(),freeStart,freeEnd);
        DateCompare dateCompare =   DateCompare.dayCompare(bill.getStartDate(),bill.getEndDate(),freeStart, freeEnd);
        if(Constants.equalsInteger(d.getCircleType(),Constants.ZERO)){
            //0=元每平米天
            int days = dateCompare.getDay();
            //0=元每平米天 账单金额=账单周期的天数*租赁面积*单价;
            int days = dateCompare.getDay() ;
            BigDecimal areas = getAreasNumBYRooms(model.getRoomList());
            totalFee = new BigDecimal(days).multiply(areas).multiply(Constants.formatBigdecimal(d.getPrice()));//总价格
        }else  if(Constants.equalsInteger(d.getCircleType(),Constants.ONE)){
            //1=元每平米月
            //1=元每平米月 账单金额=账单周期的月数(开始日期计算自然月)*租赁面积*单价+不满一个月的天数*租赁面积*单价*12/365;
            BigDecimal areas = getAreasNumBYRooms(model.getRoomList());
            BigDecimal month =dateCompare.getMonthFloat();
            totalFee = month.multiply(areas).multiply(Constants.formatBigdecimal(d.getPrice()));//总价格
        }else  if(Constants.equalsInteger(d.getCircleType(),Constants.TWO)){
            //2=元每平米年
            //2=元每平米年 账单金额=账单周期的月数(开始日期计算自然月)*单价*面积/12+不满一个月的天数*租赁面积*单价/365;
            BigDecimal areas = getAreasNumBYRooms(model.getRoomList());
            BigDecimal year =  dateCompare.getYearFloat();
            totalFee = year.multiply(areas).multiply(Constants.formatBigdecimal(d.getPrice()));//总价格
            BigDecimal month = new BigDecimal(dateCompare.getMonth());
            totalFee = ((month.multiply(Constants.formatBigdecimal(d.getPrice())).divide(new BigDecimal(12),2, RoundingMode.HALF_UP))
                    .add(new BigDecimal(dateCompare.getMonthDays()).multiply(Constants.formatBigdecimal(d.getPrice())).divide(new BigDecimal(365),2, RoundingMode.HALF_UP)))
                    .multiply(areas);//总价格
        }else  if(Constants.equalsInteger(d.getCircleType(),Constants.THREE)){
            //3=元每天
            int days = dateCompare.getDay();
            //3=元每天 账单金额=账单周期的天数*单价;
            int days = dateCompare.getDay() ;
            totalFee = new BigDecimal(days).multiply(Constants.formatBigdecimal(d.getPrice()));//总价格
        }else  if(Constants.equalsInteger(d.getCircleType(),Constants.FOUR)){
            //4=元每月
            //4=元每月 账单金额=账单周期的月数(开始日期计算自然月)*单价+不满一个月的天数*单价*12/365
            BigDecimal month = dateCompare.getMonthFloat();
            totalFee = month.multiply(Constants.formatBigdecimal(d.getPrice()));//总价格
        }else  if(Constants.equalsInteger(d.getCircleType(),Constants.FIVE)){
            //5=元每年
            BigDecimal year =  dateCompare.getYearFloat();
            totalFee = year.multiply(Constants.formatBigdecimal(d.getPrice()));//总价格
            //5=元每年 账单金额=账单周期的月数(开始日期计算自然月)*单价*面积/12+不满一个月的天数*租赁面积*单价/365;
            BigDecimal month = new BigDecimal(dateCompare.getMonth());
            totalFee =( month.multiply(Constants.formatBigdecimal(d.getPrice())).divide(new BigDecimal(12),2, RoundingMode.HALF_UP))
                    .add(new BigDecimal(dateCompare.getMonthDays()).multiply(Constants.formatBigdecimal(d.getPrice())).divide(new BigDecimal(365),2, RoundingMode.HALF_UP));//总价格
        }else  if(Constants.equalsInteger(d.getCircleType(),Constants.SIX)){
            //6=元每场
            //6=元每场 账单金额=单价;只有选择一次性付款时,才能选择该单价维度;
            totalFee =Constants.formatBigdecimal(d.getPrice());
        }
        if(Constants.equalsInteger(model.getRoundedUp(),Constants.ONE)){
@@ -413,13 +1036,12 @@
        DateCompare dateCompare =   DateCompare.monthYearCompare(startDate, endDate );
        int years = dateCompare.getYear();
        int yeardays = dateCompare.getYearDays();
        Date date = new Date();
        List<Date> list = new ArrayList<>();
        for (int i = 0; i < years; i++) {
            list.add(DateUtil.addYearToDate(date,i));
            list.add(DateUtil.addYearToDate(startDate,i));
        }
        if(yeardays>0){
            list.add(DateUtil.addYearToDate(date,years));
            list.add(DateUtil.addYearToDate(startDate,years));
        }
        return list;
    }
@@ -437,8 +1059,10 @@
            YwContractBill bill = initCreateBillModel(model,d);
            bill.setStartDate(d.getStartDate());//账单开始
            bill.setEndDate(d.getEndDate());//账单结束
            bill.setPlanPayDate(DateUtil.addDaysToDate(d.getStartDate(),Constants.formatIntegerNum(d.getAdvanceDays()) * -1));
            bill.setTotleFee(getTotalFeeByStartEnd(model,d,freeStart,freeEnd));
            bill.setPlanPayDate(DateUtil.addDaysToDate(bill.getStartDate(),Constants.formatIntegerNum(d.getAdvanceDays()) * -1));
            bill.setTotleFee(getTotalFeeByStartEnd(model,d,bill,freeStart,freeEnd));
            bill.setReceivableFee(bill.getTotleFee());
            bill.setBillType(Constants.ZERO);
            list.add(bill);
        }
        return list;
@@ -454,6 +1078,7 @@
        bill.setIsdeleted(Constants.ZERO);
        bill.setContractId(model.getId());
        bill.setStatus(Constants.ZERO);
        bill.setPayStatus(Constants.ZERO);
        bill.setDetailId(d.getId());
        bill.setCostType(d.getType());
        bill.setType(Constants.ZERO);
@@ -463,15 +1088,21 @@
    private BigDecimal getAreasNumBYRooms(List<YwRoom> roomList) {
        BigDecimal data= new BigDecimal(0);
        for(YwRoom r :roomList){
            data = data.add(Constants.formatBigdecimal(r.getArea()));
        if(roomList!=null){
            for(YwRoom r :roomList){
                data = data.add(Constants.formatBigdecimal(r.getRentArea()));
            }
        }
        return  data;
    }
    private void initFiles(YwContract model) {
        List<Multifile> multifiles = multifileMapper.selectList(new QueryWrapper<Multifile>().lambda()
                .eq(Multifile::getObjId, model.getId() )
        List<Multifile> multifiles = multifileMapper.selectJoinList(Multifile.class,new MPJLambdaWrapper<Multifile>()
                .selectAll(Multifile.class)
                .selectAs(SystemUser::getRealname,Multifile::getUserName)
                .leftJoin(SystemUser.class,SystemUser::getId,Multifile::getCreator)
                .eq(Multifile::getObjId,model.getId())
                .in(Multifile::getObjType, Arrays.asList(new Integer[]{Constants.MultiFile.YW_CONTRACT_FILE.getKey()}))
                .eq(Multifile::getIsdeleted,Constants.ZERO));
        if(multifiles!=null){
@@ -533,13 +1164,11 @@
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写合同信息");
        }
        if(model.getEndDate().getTime()<= model.getStartDate().getTime()){
        if(model.getEndDate().getTime()< model.getStartDate().getTime()){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,合同有效期结束时间不得早于开始时间!");
        }
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.ONE)){
                || Constants.equalsInteger(model.getType(),Constants.TWO)){
            if(  model.getZlDeposit() == null
                    ||model.getZlPayType() == null
                    || model.getZlPayType()>3
@@ -548,12 +1177,18 @@
                    ||model.getZlDetailList().size() ==0){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写租赁条款信息");
            }
            if(!(model.getZlFreeEndDate()==null &&  model.getZlFreeStartDate()==null) && (
                        (model.getZlFreeEndDate()!=null &&  model.getZlFreeStartDate()==null)
                        ||(model.getZlFreeEndDate()==null &&  model.getZlFreeStartDate()!=null)
                        ||model.getZlFreeEndDate().getTime()<= model.getZlFreeStartDate().getTime())
                  ){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择正确的租赁条款免租期信息!");
            }
            if((model.getZlFreeStartDate()!=null && model.getZlFreeEndDate()!=null)
                    && (model.getZlFreeEndDate().getTime()>model.getEndDate().getTime()
                    || model.getZlFreeStartDate().getTime()<model.getStartDate().getTime())){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,免租期开始日期和结束日期限制在合同时间范围内!");
            }
            for(YwContractDetail d :model.getZlDetailList()){
                if(  d.getStartDate() == null
@@ -565,18 +1200,24 @@
                ){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写租赁条款信息!");
                }
                if(d.getEndDate().getTime()<= d.getStartDate().getTime()){
                if(d.getEndDate().getTime()< d.getStartDate().getTime()){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,租赁条款有效期结束时间不得早于开始时间!");
                }
                if(d.getEndDate().getTime()>model.getEndDate().getTime() ||d.getStartDate().getTime()<model.getStartDate().getTime()){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,条款开始日期和结束日期限制在合同时间范围内!");
                }
                if(!Constants.equalsInteger(model.getWyPayType(),Constants.ZERO) &&
                        Constants.equalsInteger(d.getCircleType(),Constants.SIX)){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,租赁条款只有选择一次性付款时,才能选择该按每场收费;");
                }
                if(model.getZlFirstCircle() == null){//首期信息
                    model.setZlFirstPrice(d.getPrice());
                    model.setZlFirstCircle(d.getCircleType());
                }
            }
        }
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.TWO)){
                || Constants.equalsInteger(model.getType(),Constants.ONE)){
            if(  model.getWyDeposit() == null
                    ||model.getWyPayType() == null
                    || model.getWyPayType()>3
@@ -586,15 +1227,21 @@
            ){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按页面要求填写物业条款信息");
            }
            if(!(model.getWyFreeEndDate()==null &&  model.getWyFreeStartDate()==null) && (
                    (model.getWyFreeEndDate()!=null &&  model.getWyFreeStartDate()==null)
                            ||(model.getWyFreeEndDate()==null &&  model.getWyFreeStartDate()!=null)
                            ||model.getWyFreeEndDate().getTime()<= model.getWyFreeStartDate().getTime())){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请选择正确的物业条款免租期信息!");
            }
            if((model.getWyFreeStartDate()!=null && model.getWyFreeEndDate()!=null)
                    && (model.getWyFreeEndDate().getTime()>model.getEndDate().getTime()
                    || model.getWyFreeStartDate().getTime()<model.getStartDate().getTime())){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,免租期开始日期和结束日期限制在合同时间范围内!");
            }
            for(YwContractDetail d :model.getWyDetailList()){
                if(  d.getStartDate() == null
                        ||d.getEditDate() == null
                        ||d.getEndDate() == null
                        ||d.getPrice() == null
                        ||d.getCircleType() == null
                        || d.getCircleType()>6
@@ -605,14 +1252,22 @@
                if(d.getEndDate().getTime()<= d.getStartDate().getTime()){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,物业条款有效期结束时间不得早于开始时间!");
                }
                if(d.getEndDate().getTime()>model.getEndDate().getTime() ||d.getStartDate().getTime()<model.getStartDate().getTime()){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,条款开始日期和结束日期限制在合同时间范围内!");
                }
                if(!Constants.equalsInteger(model.getWyPayType(),Constants.ZERO) &&
                        Constants.equalsInteger(d.getCircleType(),Constants.SIX)){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,物业条款只有选择一次性付款时,才能选择该按每场收费;");
                }
                if(model.getWyFirstCircle() == null){
                    //首期信息
                    model.setWyFirstPrice(d.getPrice());
                    model.setWyFirstCircle(d.getCircleType());
                }
            }
        }
        YwProject project = projectMapper.selectById(model.getCompanyId());
        YwProject project = projectMapper.selectById(model.getProjectId());
        if(project ==null || Constants.equalsInteger(project.getIsdeleted(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,请选择正确的项目信息!");
        }
@@ -626,6 +1281,11 @@
        if(rooms.size() != rooms.size()){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,存在无效的房源信息!");
        }
        model.setTotalArea(new BigDecimal(0));
        for(YwRoom r : rooms){
            model.setTotalArea(model.getTotalArea().add(Constants.formatBigdecimal(r.getRentArea())));
        }
        model.setRoomList(rooms);
        YwCustomer customer = customerMapper.selectById(model.getRenterId());
        if(customer ==null || Constants.equalsInteger(customer.getIsdeleted(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,选择租客信息不存在,请返回刷新重试!");
@@ -648,7 +1308,53 @@
        if(user ==null || (user.getDeleted()!=null && user.getDeleted()) ){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,经办人信息不存在,请尝试刷新页面重试!");
        }
        if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isEmpty(model.getYwContractBillDTOList())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"无账单信息,请刷新重试");
        }
        for (YwContractBillDTO billDTO:model.getYwContractBillDTOList()) {
            if(
                    Objects.isNull(billDTO.getStartDate())
                    ||Objects.isNull(billDTO.getEndDate())
                    ||Objects.isNull(billDTO.getPlanPayDate())
                    ||Objects.isNull(billDTO.getTotleFee())
                    ||Objects.isNull(billDTO.getCostType())
            ){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"账单明细参数错误");
            }
        }
        List<YwContractBillDTO> ywContractBillDTOList = model.getYwContractBillDTOList();
        //查询租赁条款
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.TWO)){
            List<YwContractBillDTO> leaseBillDTOList = ywContractBillDTOList.stream()
                    .filter(i->Constants.equalsInteger(i.getCostType(),Constants.ZERO)).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(leaseBillDTOList)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"无租赁费账单!");
            }
            model.setZlBillDTOList(leaseBillDTOList);
            Optional<YwContractBillDTO> leaseBillOptional = ywContractBillDTOList.stream()
                    .filter(i->Constants.equalsInteger(i.getCostType(),Constants.TWO)).findAny();
            if(!leaseBillOptional.isPresent()){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"无租赁押金账单!");
            }
            model.setZlBillDTO(leaseBillOptional.get());
        }
        if(Constants.equalsInteger(model.getType(),Constants.ZERO )
                || Constants.equalsInteger(model.getType(),Constants.ONE)){
            List<YwContractBillDTO> wyBillDTOList = ywContractBillDTOList.stream()
                    .filter(i->Constants.equalsInteger(i.getCostType(),Constants.ONE)).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(wyBillDTOList)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"无物业费账单!");
            }
            model.setWyBillDTOList(wyBillDTOList);
            Optional<YwContractBillDTO> wyBillOptional = ywContractBillDTOList.stream()
                    .filter(i->Constants.equalsInteger(i.getCostType(),Constants.THREE)).findAny();
            if(!wyBillOptional.isPresent()){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"无物业押金账单!");
            }
            model.setWyBillDTO(wyBillOptional.get());
        }
    }
    @Override
@@ -694,77 +1400,168 @@
        log.setObjType(type.getKey());
        log.setParam1(param1);
        log.setParam2(param2);
        log.setContent(param2);
        log.setTitle(type.getNoteinfo());
        ywWorkorderLogMapper.insert(log);
    }
    @Override
    public YwContract findById(Integer id) {
        YwContract model =queryDetailInfoById(id);
        //查询操作日志记录
        YwWorkorderLog log = new YwWorkorderLog();
        log.setJobId(model.getId());
        log.setIsdeleted(Constants.ZERO);
        model.setLogList(ywWorkorderLogMapper.selectList(new QueryWrapper<YwWorkorderLog>(log)
                .lambda()
                .in(YwWorkorderLog::getObjType,Constants.YwLogType.CONTRACT_BACK.getKey()
                        ,Constants.YwLogType.CONTRACT_CREATE.getKey()
                        ,Constants.YwLogType.CONTRACT_UPDATE.getKey())
                .orderByAsc(YwWorkorderLog::getCreateDate)));
        //查询账单集合
        queryBillListByModel(model,new Date());
        return model;
    }
    private YwContract queryDetailInfoById(Integer id) {
        MPJLambdaWrapper<YwContract> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(YwContract.class )
                .selectAs(Company::getName,YwContract::getCompanyName )
                .selectAs(SystemUser::getRealname,YwContract::getUserName )
                .selectAs(YwCustomer::getName,YwContract::getRenterName )
                .selectAs(YwProject::getName,YwContract::getProjectName )
                .select("t4.realname",YwContract::getCreatorName )
                .leftJoin(Company.class,Company::getId,YwContract::getCompanyId)
                .leftJoin(SystemUser.class,SystemUser::getId,YwContract::getUserId)
                .leftJoin(SystemUser.class,SystemUser::getId,YwContract::getCreator)
                .leftJoin(YwProject.class,YwProject::getId,YwContract::getProjectId)
                .leftJoin(YwCustomer.class,YwCustomer::getId,YwContract::getRenterId);
        YwContract model = ywContractMapper.selectJoinOne(YwContract.class,queryWrapper);
        if(model != null){
            //合同附件
            initFiles(model);
            //查询房源信息数据
            MPJLambdaWrapper<YwRoom> rw = new MPJLambdaWrapper<>();
            rw.selectAll(YwRoom.class )
                    .selectAs(YwProject::getName,YwRoom::getProjectName)
                    .selectAs(YwFloor::getName,YwRoom::getFloorName)
                    .selectAs(YwBuilding::getName,YwRoom::getBuildingName)
                    .leftJoin(YwProject.class,YwProject::getId,YwRoom::getProjectId)
                    .leftJoin(YwBuilding.class,YwBuilding::getId,YwRoom::getBuildingId)
                    .leftJoin(YwFloor.class,YwFloor::getId,YwRoom::getFloor)
                    .eq(YwRoom::getIsdeleted,Constants.ZERO)
                    .exists("(select a.id from yw_contract_room a where a.isdeleted=1 and a.room_id=t.id and a.contract_id="+model.getId()+")");
            model.setRoomList(roomMapper.selectJoinList(YwRoom.class,rw));
            //查询租賃条款信息
            MPJLambdaWrapper<YwContractDetail> dw = new MPJLambdaWrapper<>();
            dw.selectAll(YwContractDetail.class )
                    .eq(YwContractDetail::getIsdeleted,Constants.ZERO)
                    .eq(YwContractDetail::getContractId,model.getId())
                    .in(YwContractDetail::getType,Constants.ZERO,Constants.TWO)
                    .orderByAsc(YwContractDetail::getSortnum);
            model.setZlDetailList(ywContractDetailMapper.selectJoinList(YwContractDetail.class,dw));
            //查询物業条款信息
            dw = new MPJLambdaWrapper<>();
            dw.selectAll(YwContractDetail.class )
                    .eq(YwContractDetail::getIsdeleted,Constants.ZERO)
                    .eq(YwContractDetail::getContractId,model.getId())
                    .in(YwContractDetail::getType,Constants.ONE,Constants.THREE)
                    .orderByAsc(YwContractDetail::getSortnum);
            model.setWyDetailList(ywContractDetailMapper.selectJoinList(YwContractDetail.class,dw));
            //查询操作日志记录
            YwWorkorderLog log = new YwWorkorderLog();
            log.setJobId(model.getId());
            log.setIsdeleted(Constants.ZERO);
            model.setLogList(ywWorkorderLogMapper.selectList(new QueryWrapper<YwWorkorderLog>(log)
                    .lambda()
                    .in(YwWorkorderLog::getObjType,Constants.YwLogType.CONTRACT_BACK.getKey()
                            ,Constants.YwLogType.CONTRACT_CREATE.getKey()
                            ,Constants.YwLogType.CONTRACT_UPDATE.getKey())
                    .orderByAsc(YwWorkorderLog::getCreateDate)));
            //查询账单集合
            model.setBillList(ywContractBillMapper.selectJoinList(YwContractBill.class,new MPJLambdaWrapper<YwContractBill>()
                            .selectAll(YwContractBill.class )
                            .eq(  YwContractBill::getContractId,model.getId())
                            .eq(YwContractBill::getIsdeleted,Constants.ZERO)
                            .orderByAsc(YwContractBill::getSortnum,YwContractBill::getCreateDate)));
        queryWrapper.selectAll(YwContract.class)
                .selectAs(Company::getName, YwContract::getCompanyName)
                .selectAs(SystemUser::getRealname, YwContract::getUserName)
                .selectAs(YwCustomer::getName, YwContract::getRenterName)
                .selectAs(YwProject::getName, YwContract::getProjectName)
                .select("t3.realname", YwContract::getCreatorName)
                .select("(select sum(r.RENT_AREA) from yw_contract_room cr left join yw_room r on r.id = cr.room_id where r.isdeleted=0 and cr.contract_id =t.id)", YwContract::getTotalArea)
                .leftJoin(Company.class, Company::getId, YwContract::getCompanyId)
                .leftJoin(SystemUser.class, SystemUser::getId, YwContract::getUserId)
                .leftJoin(SystemUser.class, SystemUser::getId, YwContract::getCreator)
                .leftJoin(YwProject.class, YwProject::getId, YwContract::getProjectId)
                .leftJoin(YwCustomer.class, YwCustomer::getId, YwContract::getRenterId)
                .eq(YwContract::getId, id);
        YwContract model = ywContractMapper.selectJoinOne(YwContract.class, queryWrapper);
        if (model == null) {
                throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        //合同附件
        initFiles(model);
        //查询房源信息数据
        MPJLambdaWrapper<YwRoom> rw = new MPJLambdaWrapper<>();
        rw.selectAll(YwRoom.class)
                .selectAs(YwProject::getName, YwRoom::getProjectName)
                .selectAs(YwFloor::getName, YwRoom::getFloorName)
                .selectAs(YwBuilding::getName, YwRoom::getBuildingName)
                .leftJoin(YwProject.class, YwProject::getId, YwRoom::getProjectId)
                .leftJoin(YwBuilding.class, YwBuilding::getId, YwRoom::getBuildingId)
                .leftJoin(YwFloor.class, YwFloor::getId, YwRoom::getFloor)
                .eq(YwRoom::getIsdeleted, Constants.ZERO)
                .exists("(select a.id from yw_contract_room a where a.isdeleted=0 and a.type=0 and a.room_id=t.id and a.contract_id=" + model.getId() + ")");
        model.setRoomList(roomMapper.selectJoinList(YwRoom.class, rw));
        model.setWyFirstCircleStr(Constants.getUnitTypeByNum(model.getWyFirstCircle()));
        model.setZlFirstCircleStr(Constants.getUnitTypeByNum(model.getZlFirstCircle()));
        //查询租賃条款信息
        MPJLambdaWrapper<YwContractDetail> dw = new MPJLambdaWrapper<>();
        dw.selectAll(YwContractDetail.class)
                .eq(YwContractDetail::getIsdeleted, Constants.ZERO)
                .eq(YwContractDetail::getContractId, model.getId())
                .in(YwContractDetail::getType, Constants.ZERO, Constants.TWO)
                .orderByAsc(YwContractDetail::getSortnum);
        model.setZlDetailList(ywContractDetailMapper.selectJoinList(YwContractDetail.class, dw));
        //查询物業条款信息
        dw = new MPJLambdaWrapper<>();
        dw.selectAll(YwContractDetail.class)
                .eq(YwContractDetail::getIsdeleted, Constants.ZERO)
                .eq(YwContractDetail::getContractId, model.getId())
                .in(YwContractDetail::getType, Constants.ONE, Constants.THREE)
                .orderByAsc(YwContractDetail::getSortnum);
        model.setWyDetailList(ywContractDetailMapper.selectJoinList(YwContractDetail.class, dw));
        return model;
    }
   @Override
    public YwContract findForBills(YwContract param) {
        YwContract model = queryDetailInfoById(param.getId());
        queryBillListByModel(model,param.getBtDate());
        return model;
    }
    private void queryBillListByModel(YwContract model,Date date) {
        if(date ==null){
            date = new Date();
        }
        //查询账单集合
        model.setBillList(ywContractBillMapper.selectJoinList(YwContractBill.class,new MPJLambdaWrapper<YwContractBill>()
                .selectAll(YwContractBill.class )
                .select(" ( select ifnull( sum( CASE WHEN t.bill_type = 0 and yw.REVENUE_TYPE = 0 THEN yw.ACT_RECEIVABLE_FEE when  t.bill_type = 0 and yw.REVENUE_TYPE = 1 then -yw.ACT_RECEIVABLE_FEE  when t.bill_type = 1 and yw.REVENUE_TYPE = 0 then -yw.ACT_RECEIVABLE_FEE else  yw.ACT_RECEIVABLE_FEE END),0) from  yw_contract_revenue yw where yw.bill_id = t.id and yw.status = 0 and yw.isdeleted = 0 ) as  actReceivableFee  ")
                .eq(  YwContractBill::getContractId,model.getId())
                .eq(YwContractBill::getIsdeleted,Constants.ZERO)
                .orderByAsc(YwContractBill::getSortnum,YwContractBill::getCreateDate)));
        for (YwContractBill ywContractBill:model.getBillList()) {
            ywContractBill.setNeedReceivableFee(ywContractBill.getReceivableFee());
        }
        model.setCanBackRentBills(new ArrayList<>());
        long nowStart = Utils.Date.getStart(date).getTime();
        long nowEnd = Utils.Date.getDayEnd(date).getTime();
        if(model.getBillList()!=null && model.getBillList().size()>0){
            for(YwContractBill bill: model.getBillList()){
                //付款状态:0=待收款;1=已结清;2=部分结清;3=待付款;4=待退款;5=已关闭
                if( Constants.formatBigdecimal(bill.getReceivableFee()).compareTo(new BigDecimal(0)) ==0){
                    //如果还没开始,账单直接关闭
                    continue;
                }
                if(Constants.equalsInteger(bill.getPayStatus(),Constants.ZERO)
                        ||Constants.equalsInteger(bill.getPayStatus(),Constants.THREE)){
                    if(bill.getStartDate().getTime()>nowEnd ){
                        //如果还没开始,账单直接关闭
                        continue;
                    }
                    model.getCanBackRentBills().add(bill);
                }else  if(Constants.equalsInteger(bill.getPayStatus(),Constants.ONE) ){
                    if(bill.getEndDate().getTime()<nowStart){
                        //如果已结清,账单直接关闭
                        continue;
                    }
                    model.getCanBackRentBills().add(bill);
                }else  if(Constants.equalsInteger(bill.getPayStatus(),Constants.TWO) ){
                    model.getCanBackRentBills().add(bill);
                }
            }
            for(YwContractBill bill : model.getCanBackRentBills()){
                YwContractDetail detail = null;
                if(Constants.equalsInteger(bill.getCostType(),Constants.ZERO)){
                    detail = getDetailByIdFromList(bill.getDetailId(),model.getZlDetailList());
                    if(detail!=null&& bill.getStartDate()!=null && bill.getEndDate()!=null
                            &&(date.getTime() <= bill.getStartDate().getTime() || (date.getTime() >= bill.getStartDate().getTime() && date.getTime()<= bill.getEndDate().getTime()))){
                        Date odate = bill.getEndDate();
                        bill.setEndDate(date);
                        BigDecimal actFee = getTotalFeeByStartEnd(model,detail,bill,model.getZlFreeStartDate(),model.getZlFreeEndDate());
                        bill.setEndDate(odate);
                        bill.setNeedReceivableFee(actFee);
                    }
                }else if(Constants.equalsInteger(bill.getCostType(),Constants.ONE)){
                    detail = getDetailByIdFromList(bill.getDetailId(),model.getWyDetailList());
                    if(detail!=null&& bill.getStartDate()!=null && bill.getEndDate()!=null
                            &&(date.getTime() <= bill.getStartDate().getTime() || (date.getTime() >= bill.getStartDate().getTime() && date.getTime()<= bill.getEndDate().getTime()))){
                        Date odate = bill.getEndDate();
                        bill.setEndDate(date);
                        BigDecimal actFee = getTotalFeeByStartEnd(model,detail,bill,model.getWyFreeStartDate(),model.getWyFreeEndDate());
                        bill.setEndDate(odate);
                        bill.setNeedReceivableFee(actFee);
                    }
                }
            }
        }
    }
    private YwContractDetail getDetailByIdFromList(Integer detailId, List<YwContractDetail> list) {
        if(list!=null){
            for(YwContractDetail d : list){
                if(Constants.equalsInteger(detailId,d.getId())){
                    return d;
                }
            }
        }
        return  null;
    }
    @Override
@@ -775,8 +1572,18 @@
    @Override
    public List<YwContract> findList(YwContract ywContract) {
        QueryWrapper<YwContract> wrapper = new QueryWrapper<>(ywContract);
        return ywContractMapper.selectList(wrapper);
        return ywContractMapper.selectJoinList(YwContract.class,new MPJLambdaWrapper<YwContract>().selectAll(YwContract.class )
                .selectAs(Company::getName,YwContract::getCompanyName )
                .selectAs(SystemUser::getRealname,YwContract::getUserName )
                .selectAs(YwCustomer::getName,YwContract::getRenterName )
                .selectAs(YwProject::getName,YwContract::getProjectName )
                .leftJoin(Company.class,Company::getId,YwContract::getCompanyId)
                .leftJoin(SystemUser.class,SystemUser::getId,YwContract::getUserId)
                .leftJoin(SystemUser.class,SystemUser::getId,YwContract::getCreator)
                .leftJoin(YwProject.class,YwProject::getId,YwContract::getProjectId)
                .leftJoin(YwCustomer.class,YwCustomer::getId,YwContract::getRenterId)
                .eq(YwContract::getIsdeleted,Constants.ZERO)
                .in(YwContract::getStatus,Constants.ZERO,Constants.ONE,Constants.TWO));
    }
  
    @Override
@@ -785,8 +1592,11 @@
        MPJLambdaWrapper<YwContract> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(YwContract.class )
                .selectAs(Company::getName,YwContract::getCompanyName )
                .select("(select sum(r.area) from yw_contract_room cr left join yw_room r on r.id = cr.room_id where r.isdeleted=0 and cr.contract_id =t.id)",YwContract::getTotalArea )
                .leftJoin(Company.class,Company::getId,YwContract::getCompanyId);
                .selectAs(YwCustomer::getName,YwContract::getRenterName )
                .select("(select sum(r.RENT_AREA) from yw_contract_room cr left join yw_room r on r.id = cr.room_id where r.isdeleted=0 and cr.contract_id =t.id)",YwContract::getTotalArea )
                .select(" ( select  ifnull(sum(y.TOTLE_FEE),0)  from yw_contract_bill y   where y.CONTRACT_ID = t.id and y.type = 0 and y.COST_TYPE=0 and y.BILL_TYPE = 0 ) " , YwContract::getTotalFee)
                .leftJoin(Company.class,Company::getId,YwContract::getCompanyId)
                .leftJoin(YwCustomer.class,YwCustomer::getId,YwContract::getRenterId);
        Utils.MP.blankToNull(pageWrap.getModel());
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.eq(YwContract::getId, pageWrap.getModel().getId());
@@ -797,6 +1607,9 @@
        if (pageWrap.getModel().getCreateDate() != null) {
            queryWrapper.ge(YwContract::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.le(YwContract::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
        }
        if (pageWrap.getModel().getStatusList() != null) {
            queryWrapper.in(YwContract::getStatus, pageWrap.getModel().getStatusList());
        }
        if (pageWrap.getModel().getEditor() != null) {
            queryWrapper.eq(YwContract::getEditor, pageWrap.getModel().getEditor());
@@ -879,6 +1692,7 @@
            queryWrapper.ge(YwContract::getWyFreeEndDate, Utils.Date.getStart(pageWrap.getModel().getWyFreeEndDate()));
            queryWrapper.le(YwContract::getWyFreeEndDate, Utils.Date.getEnd(pageWrap.getModel().getWyFreeEndDate()));
        }
        if (pageWrap.getModel().getZlTotalFee() != null) {
            queryWrapper.eq(YwContract::getZlTotalFee, pageWrap.getModel().getZlTotalFee());
        }
@@ -888,10 +1702,45 @@
        if (pageWrap.getModel().getCompanyName() != null) {
            queryWrapper.like(Company::getName, pageWrap.getModel().getCompanyName());
        }
        if (pageWrap.getModel().getRoomId() != null) {
            queryWrapper.apply(" t.id in ( select ycr.CONTRACT_ID from yw_contract_room ycr where ycr.type = 0 and  ycr.ROOM_ID = "+pageWrap.getModel().getRoomId()+" )  ");
        }
        if (pageWrap.getModel().getBuildingId() != null) {
            queryWrapper.apply(" t.id in ( select ycr.CONTRACT_ID from yw_contract_room ycr left join yw_room yr on ycr.ROOM_ID = yr.id where ycr.type = 0 and  yr.BUILDING_ID = "+pageWrap.getModel().getBuildingId()+" )  ");
        }
        queryWrapper.ge(Objects.nonNull(pageWrap.getModel().getQueryStartTime()), YwContract::getStartDate, pageWrap.getModel().getQueryStartTime())
                        .le(Objects.nonNull(pageWrap.getModel().getQueryEndTime()), YwContract::getEndDate, pageWrap.getModel().getQueryEndTime());
        queryWrapper.orderByDesc(YwContract::getCreateDate );
        return PageData.from(ywContractMapper.selectJoinPage(page, YwContract.class,queryWrapper));
        PageData<YwContract> data = PageData.from(ywContractMapper.selectJoinPage(page, YwContract.class,queryWrapper));
        if(data!=null && data.getRecords()!=null){
            for(YwContract model : data.getRecords()){
                model.setWyFirstCircleStr(Constants.getUnitTypeByNum(model.getWyFirstCircle()));
                model.setZlFirstCircleStr(Constants.getUnitTypeByNum(model.getZlFirstCircle()));
                //查询房源信息数据
                MPJLambdaWrapper<YwRoom> rw = new MPJLambdaWrapper<>();
                rw.selectAll(YwRoom.class)
                        .selectAs(YwProject::getName, YwRoom::getProjectName)
                        .selectAs(YwFloor::getName, YwRoom::getFloorName)
                        .selectAs(YwBuilding::getName, YwRoom::getBuildingName)
                        .leftJoin(YwProject.class, YwProject::getId, YwRoom::getProjectId)
                        .leftJoin(YwBuilding.class, YwBuilding::getId, YwRoom::getBuildingId)
                        .leftJoin(YwFloor.class, YwFloor::getId, YwRoom::getFloor)
                        .eq(YwRoom::getIsdeleted, Constants.ZERO)
                        .exists("(select a.id from yw_contract_room a where a.isdeleted=0 and a.type=0 and a.room_id=t.id and a.contract_id=" + model.getId() + ")");
                model.setRoomList(roomMapper.selectJoinList(YwRoom.class, rw));
                model.setLeaseDays(
                        DateUtil.daysBetweenDates(model.getEndDate(),model.getStartDate()) + 1
                );
                if(Objects.nonNull(model.getLeaseDays())&&Objects.nonNull(model.getTotalArea())&&Objects.nonNull(model.getTotalFee())){
                    model.setLeasePrice(model.getTotalFee().divide((model.getTotalArea().multiply(new BigDecimal(model.getLeaseDays()))),2,BigDecimal.ROUND_HALF_UP));
                }else{
                    model.setLeasePrice(BigDecimal.ZERO);
                }
            }
        }
        return data;
    }
    @Override
@@ -899,4 +1748,63 @@
        QueryWrapper<YwContract> wrapper = new QueryWrapper<>(ywContract);
        return ywContractMapper.selectCount(wrapper);
    }
    /**
     * 到期合同 未发起退租的进行数据调整 把合同下的房源释放 定时时间需要在每天晚上12点前
     */
    @Override
    public void updRoomLeaseNowStatus(){
        //定时处理合同已过期
        List<YwContract> ywContractList = ywContractMapper.selectList(new QueryWrapper<YwContract>().lambda()
                .eq(YwContract::getIsdeleted,Constants.ZERO)
                .in(YwContract::getStatus,Constants.ONE,Constants.ZERO)
                .apply(" DATE(END_DATE) = CURRENT_DATE ")
        );
        if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(ywContractList)){
            ywContractMapper.update(new UpdateWrapper<YwContract>()
                    .lambda()
                    .set(YwContract::getStatus,Constants.TWO)
                    .set(YwContract::getEditDate,DateUtil.getCurrDateTime())
                    .in(YwContract::getId,ywContractList.stream().map(i->i.getId()).collect(Collectors.toList()))
            );
            List<YwContractRoom> contractRoomList = ywContractRoomMapper.selectList(new QueryWrapper<YwContractRoom>().lambda().in(YwContractRoom::getContractId,
                    ywContractList.stream().map(i->i.getId()).collect(Collectors.toList())));
            if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(contractRoomList)){
                //更新房源数据为租赁中
                roomMapper.update(new UpdateWrapper<YwRoom>().lambda().set(YwRoom::getLeaseNowStatus,Constants.ZERO)
                        .in(YwRoom::getId,contractRoomList.stream().map(i->i.getRoomId()).collect(Collectors.toList()))
                );
            }
        }
    }
    /**
     * 退租中/已退租合同 把到了退租日期时间的数据 进行房源释放 定时时间需要在每天晚上12点前
     */
    @Override
    public void updRentContractStatus(){
        List<YwContract> ywContractList = ywContractMapper.selectList(new QueryWrapper<YwContract>().lambda()
                .eq(YwContract::getIsdeleted,Constants.ZERO)
                .in(YwContract::getStatus,Constants.THREE,Constants.FOUR)
                .eq(YwContract::getBtDate,DateUtil.getCurrDate())
        );
        if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(ywContractList)){
            List<YwContractRoom> contractRoomList = ywContractRoomMapper.selectList(new QueryWrapper<YwContractRoom>().lambda().in(YwContractRoom::getContractId,
                    ywContractList.stream().map(i->i.getId()).collect(Collectors.toList())));
            if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(contractRoomList)){
                //更新房源数据为待租赁
                roomMapper.update(new UpdateWrapper<YwRoom>().lambda().set(YwRoom::getLeaseNowStatus,Constants.ZERO)
                        .in(YwRoom::getId,contractRoomList.stream().map(i->i.getRoomId()).collect(Collectors.toList()))
                );
            }
        }
    }
}