package com.kingdee.eas.custom.dormitorysystem.waterpower.utils;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.data.SortType;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemCollection;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.entity.SorterItemCollection;
import com.kingdee.bos.metadata.entity.SorterItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.base.core.util.DateUtil;
import com.kingdee.eas.custom.dormitorysystem.dormitory.DormitoryFactory;
import com.kingdee.eas.custom.dormitorysystem.dormitory.DormitoryInfo;
import com.kingdee.eas.custom.dormitorysystem.dormitory.IDormitory;
import com.kingdee.eas.custom.dormitorysystem.waterpower.IWaterPowerMeterReading;
import com.kingdee.eas.custom.dormitorysystem.waterpower.WaterPowerMeterReadingCollection;
import com.kingdee.eas.custom.dormitorysystem.waterpower.WaterPowerMeterReadingFactory;
import com.kingdee.eas.custom.dormitorysystem.waterpower.WaterPowerMeterReadingInfo;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qingwu
 * @date 2025/4/22
 * @apiNote
 */
public class WaterPowerUtil {
    static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

    public static void verifyDatEexists(Context ctx, Date years, String dormNumber, String id) throws ShrWebBizException {
        try {
            FilterInfo filterInfo = new FilterInfo();
            FilterItemCollection filterItems = filterInfo.getFilterItems();
            filterItems.add(new FilterItemInfo("years", years));
            filterItems.add(new FilterItemInfo("dormitory.number", dormNumber));
            if (id != "") {
                filterItems.add(new FilterItemInfo("id", id, CompareType.NOTEQUALS));
            }
            IDormitory iDormitory = DormitoryFactory.getLocalInstance(ctx);
            DormitoryInfo dormitoryInfo = iDormitory.getDormitoryInfo("where number = '" + dormNumber + "'");
            IWaterPowerMeterReading iWaterPowerMeterReading = WaterPowerMeterReadingFactory.getLocalInstance(ctx);
            boolean exists = iWaterPowerMeterReading.exists(filterInfo);
            if (exists) {
                throw new ShrWebBizException(dormitoryInfo.getName() + "房间已经存在" + formatter.format(years) + "月的抄表信息！");
            }
        } catch (
                Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }

    }

    public static Map getThisMonthWaterPowerTons(Context ctx, String years, String dormNumber, BigDecimal totalWaterTons, BigDecimal totalElecDegrees) throws BOSException {
        Map<String, String> dateMap = getDate(years);
        String previousMonth = dateMap.get("previousMonth");
        String twoMonthsAgo = dateMap.get("twoMonthsAgo");
        //获取上个月的水电总吨数
        //水总吨数
        BigDecimal water = BigDecimal.ZERO;
        //电总吨数
        BigDecimal power = BigDecimal.ZERO;
        //当月水吨数 ?本月实际用水量，计算（本月-上月，如上月无数据-上上月，如还无数据则直接显示“用水总吨数”）；
        BigDecimal curMonthWater = BigDecimal.ZERO;
        //当月电度数 ?本月实际用电量，计算（本月-上月，如上月无数据-上上月，如还无数据则直接显示“用电总度数”）；
        BigDecimal curMonthElecDegrees = BigDecimal.ZERO;
        Map<String, BigDecimal> previousMonthMap = getWaterPower(ctx, previousMonth, dormNumber,true);
        if (previousMonthMap.size() > 0) {
            water = previousMonthMap.get("water");
            power = previousMonthMap.get("power");
            curMonthWater = totalWaterTons.subtract(water);
            curMonthElecDegrees = totalElecDegrees.subtract(power);
        } else {
            //获取上上个月的水电总吨数
            previousMonthMap = getWaterPower(ctx, twoMonthsAgo, dormNumber,true);
            if (previousMonthMap.size() > 0) {
                water = previousMonthMap.get("water");
                power = previousMonthMap.get("power");
                curMonthWater = totalWaterTons.subtract(water);
                curMonthElecDegrees = totalElecDegrees.subtract(power);
            }
            curMonthWater = totalWaterTons;
            curMonthElecDegrees = totalElecDegrees;
        }
        Map result = new HashMap();
        result.put("curMonthWater", curMonthWater.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : curMonthWater);//当月水吨数
        result.put("curMonthElecDegrees", curMonthElecDegrees.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : curMonthElecDegrees);//当月电度数
        return result;
    }

    /**
     * 获取上月用水电吨数
     * @param date
     * @param dormNumber
     * @return
     * @throws BOSException
     */
    public static Map getWaterPower(Context ctx, String date, String roomId,boolean isEquals) throws BOSException {
        Map<String, String> map = new HashMap();
        if(StringUtils.isEmpty(date) || StringUtils.isEmpty(roomId)){
            return map;
        }

        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        //上个月:previousMonth   上上个月:
        if(isEquals) {
        	filterItems.add(new FilterItemInfo("years", date + "-01 00:00:00"));
        }else {
        	filterItems.add(new FilterItemInfo("years", date + "-01 00:00:00",CompareType.LESS_EQUALS));
        }
        filterItems.add(new FilterItemInfo("dormitory.id", roomId));
        //获取最大数
        SorterItemCollection sorter = new  SorterItemCollection();
        SorterItemInfo sorterItemInfo = new SorterItemInfo("years");
        sorterItemInfo.setSortType(SortType.DESCEND);
        sorter.add(sorterItemInfo);
        SelectorItemCollection selectItem  = new SelectorItemCollection();
        selectItem.add(new SelectorItemInfo("totalElecDegrees"));
        selectItem.add(new SelectorItemInfo("totalWaterTons"));
        selectItem.add(new SelectorItemInfo("createTime"));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, selectItem, sorter);
        
        //水电每月抄表信息
        IWaterPowerMeterReading iWaterPowerMeterReading = WaterPowerMeterReadingFactory.getLocalInstance(ctx);
        WaterPowerMeterReadingCollection waterPowerMeterReadingCollection = iWaterPowerMeterReading.getWaterPowerMeterReadingCollection(entityViewInfo);
        if(null != waterPowerMeterReadingCollection && waterPowerMeterReadingCollection.size()>0) {
            WaterPowerMeterReadingInfo waterPowerMeterReadingInfo = waterPowerMeterReadingCollection.get(0);
            map.put("water", waterPowerMeterReadingInfo.getTotalWaterTons() == null ? "": waterPowerMeterReadingInfo.getTotalWaterTons().toString());
            map.put("power", waterPowerMeterReadingInfo.getTotalElecDegrees() == null ? "": waterPowerMeterReadingInfo.getTotalElecDegrees().toString());
            String formatDate2 = DateUtil.formatDate2(waterPowerMeterReadingInfo.getCreateTime());
            map.put("createDate", formatDate2);
        }
        
        
        return map;
    }

    public static Map getDate(String dateStr) {
        Map map = new HashMap();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        // 将字符串转换为 YearMonth 对象
        YearMonth targetDate = YearMonth.parse(dateStr, formatter);
        // 获取上个月
        YearMonth previousMonth = targetDate.minusMonths(1);
        map.put("previousMonth", formatter.format(previousMonth));
        // 获取上上个月
        YearMonth twoMonthsAgo = targetDate.minusMonths(2);
        map.put("twoMonthsAgo", formatter.format(twoMonthsAgo));
        return map;

    }
    
    
    
    
    /**
     * 获取上次抄表数据 
     * @param ctx
     * @param years
     * @param dormNumber
     * @return
     * @throws BOSException
     * 20251124
     */
    public static Map getLastWaterPowerTons(Context ctx, String years, String roomId ) throws BOSException {
        Map<String, String> previousMonthMap = getWaterPower(ctx, years, roomId,false);
        return previousMonthMap;
    }
    
    
    
    
    
    
    
    
    
    
   
    
    
    
}
