package com.kingdee.eas.custom.dormitorysystem.service;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
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.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.common.EASBizException;
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.SHRWebException;
import com.kingdee.util.NumericExceptionSubItem;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 水电表读数查询服务
 * coyle
 */
public class GetWaterPowerReadingService implements IHRMsfService {

    private static final Logger logger = LoggerFactory.getLogger(GetWaterPowerReadingService.class);
    // 仅保留使用的日期格式化器
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");



    @Override
    public Object process(Context ctx, Map<String, Object> param) throws EASBizException, BOSException {
        // 1. 基础参数校验，防止空指针
        if (param == null) {
            logger.warn("查询水电表读数时，入参param为null，返回空集合");
            return new WaterPowerMeterReadingCollection();
        }
        if (ctx == null) {
            logger.error("查询水电表读数时，上下文Context为null");
            throw new BOSException("上下文Context不能为空");
        }

        
        FilterInfo filterInfo = new FilterInfo();
        Object fidObj = param.get("fid");
        if (fidObj != null && !StringUtils.isEmpty(fidObj.toString())) {
            String fid = fidObj.toString().trim();
            fid = getString(fid);
            buildWaterPowerInfo(ctx, fid);
        }else{

            // 标记各过滤条件是否存在，用于动态构建maskString
            boolean hasDateFilter = false;
            boolean hasRoomFilter = false;
            boolean hasDataTypeFilter = false;
            // 存储过滤条件的逻辑片段，最后拼接成maskString
            List<String> filterLogicSegments = new ArrayList<>();


            // 2. 处理日期参数（原years参数，语义为查询月份/日期）
            Object dateParamObj = param.get("years");
            if (dateParamObj != null && !StringUtils.isEmpty(dateParamObj.toString())) {
                String dateParam = dateParamObj.toString().trim();
                dateParam = getString(dateParam);
                try {
                    LocalDate startDate;
                    LocalDate endDate;

                    // 处理 yyyy-MM 格式（如2025-08）
                    if (dateParam.matches("\\d{4}-\\d{2}")) {
                        LocalDate monthDate = LocalDate.parse(dateParam + "-01", DATE_FORMATTER);
                        startDate = monthDate.with(TemporalAdjusters.firstDayOfMonth());
                        endDate = monthDate.with(TemporalAdjusters.firstDayOfNextMonth());
                    }
                    // 处理 yyyy-MM-dd 格式（如2025-08-15）
                    else if (dateParam.matches("\\d{4}-\\d{2}-\\d{2}")) {
                        LocalDate inputDate = LocalDate.parse(dateParam, DATE_FORMATTER);
                        startDate = inputDate.with(TemporalAdjusters.firstDayOfMonth());
                        endDate = inputDate.with(TemporalAdjusters.firstDayOfNextMonth());
                    } else {
                        logger.warn("日期参数格式不合法，值为：{}，支持格式：yyyy-MM 或 yyyy-MM-dd", dateParam);
                        return buildWaterPowerCollection(ctx, filterInfo);
                    }

                    // 添加日期过滤项（索引0：>=startTime，索引1：<endTime）
                    String startTime = startDate.format(DATE_FORMATTER);
                    String endTime = endDate.format(DATE_FORMATTER);
                    filterInfo.getFilterItems().add(new FilterItemInfo("years", startTime, CompareType.GREATER_EQUALS));
                    filterInfo.getFilterItems().add(new FilterItemInfo("years", endTime, CompareType.LESS));
                    hasDateFilter = true;
                    // 日期条件逻辑：#0 and #1
                    filterLogicSegments.add("#0 and #1");
                    logger.info("添加日期过滤条件：years >= {} 且 years < {}", startTime, endTime);

                } catch (Exception e) {
                    logger.error("处理日期参数时发生异常，参数值：{}", dateParam, e);
                    // 直接抛出框架规范的EASBizException，避免嵌套异常和RuntimeException
                    throw new EASBizException(new NumericExceptionSubItem("00001","日期参数解析失败：" + e.getMessage()));
                }
            }

            // 3. 处理房间号参数（模糊查询number/name）
            Object roomNumberObj = param.get("roomNumber");
            if (roomNumberObj != null && !StringUtils.isEmpty(roomNumberObj.toString())) {
                String roomNumber = roomNumberObj.toString().trim();
                roomNumber = getString(roomNumber);
                String likePattern = "%" + roomNumber + "%";
                // 计算房间号过滤项的起始索引（根据前面的日期项数量）
                int roomFilterStartIndex = hasDateFilter ? 2 : 0;
                // 添加房间号过滤项
                filterInfo.getFilterItems().add(new FilterItemInfo("dormitory.number", likePattern, CompareType.LIKE));
                filterInfo.getFilterItems().add(new FilterItemInfo("dormitory.name", likePattern, CompareType.LIKE));
                hasRoomFilter = true;
                // 房间号条件逻辑：(#n or #n+1)
                String roomLogic = String.format("(#%d or #%d)", roomFilterStartIndex, roomFilterStartIndex + 1);
                filterLogicSegments.add(roomLogic);
                logger.info("添加房间号模糊过滤条件：dormitory.number LIKE {} 或 dormitory.name LIKE {}", likePattern, likePattern);
                logger.info("房间号过滤逻辑片段：{}", roomLogic);
            }

            // 4. 处理数据类型参数（筛选无水费/无电费记录）
            Object dataTypeObj = param.get("dataType");
            if (dataTypeObj != null && !StringUtils.isEmpty(dataTypeObj.toString())) {
                String dataType = dataTypeObj.toString().trim();
                // 计算数据类型过滤项的起始索引（日期2项 + 房间号2项 = 4；无前置则0/2）
                int dataTypeIndex = filterInfo.getFilterItems().size();
                String dataTypeLogic = "";
                if(StringUtils.equals(dataType, ShowType.UNPAPER.getValue())){
                    // 无水费：totalWaterTons为空
                    filterInfo.getFilterItems().add(new FilterItemInfo("totalWaterTons", null, CompareType.EMPTY));
                    dataTypeLogic = String.format("#%d", dataTypeIndex);
                    logger.info("添加数据类型过滤条件：无水费记录（totalWaterTons 为空）");
                }else if(StringUtils.equals(dataType, ShowType.UNELECTRICITY.getValue())){
                    // 无电费：totalElecDegrees为空
                    filterInfo.getFilterItems().add(new FilterItemInfo("totalElecDegrees", null, CompareType.EMPTY));
                    dataTypeLogic = String.format("#%d", dataTypeIndex);
                    logger.info("添加数据类型过滤条件：无电费记录（totalElecDegrees 为空）");
                }
                if (StringUtils.isNotBlank(dataTypeLogic)) {
                    hasDataTypeFilter = true;
                    filterLogicSegments.add(dataTypeLogic);
                }
            }

            // 5. 动态构建最终的maskString（所有条件用AND连接）
            if (!filterLogicSegments.isEmpty()) {
                String finalMaskString = String.join(" and ", filterLogicSegments);
                filterInfo.setMaskString(finalMaskString);
                logger.info("最终过滤条件组合逻辑（maskString）：{}", finalMaskString);
            } else {
                logger.info("无任何过滤条件，查询全部水电表读数记录");
            }

        }

        // 6. 构建查询结果并返回
        return buildWaterPowerCollection(ctx, filterInfo);
    }

    @NotNull
    private static String getString(String fid) {
        if(fid.startsWith("'") && fid.endsWith("'")){
            fid = fid.substring(1, fid.length() - 1);
        }else if(fid.startsWith("\"") && fid.endsWith("\"")){
            fid = fid.substring(1, fid.length() - 1);
        }
        return fid;
    }

    /**
     * 构建排序条件并查询水电表读数集合
     * 抽离通用逻辑，提高代码复用性
     */
    private WaterPowerMeterReadingCollection buildWaterPowerCollection(Context ctx, FilterInfo filterInfo) throws BOSException {
        // 构建排序条件
        SorterItemCollection sorterItemCollection = new SorterItemCollection();
        SorterItemInfo yearsSorter = new SorterItemInfo("years");
        yearsSorter.setSortType(SortType.DESCEND);
        sorterItemCollection.add(yearsSorter);
        sorterItemCollection.add(new SorterItemInfo("dormitory.number")); // 按房间号升序
        SelectorItemCollection selectCol = new SelectorItemCollection();
        selectCol.add(new SelectorItemInfo("*"));
        selectCol.add(new SelectorItemInfo("dormitory.displayName"));
        selectCol.add(new SelectorItemInfo("dormitory.name"));
        // 构建视图并查询
        EntityViewInfo entityViewInfo = new EntityViewInfo();
        entityViewInfo.setFilter(filterInfo);
        entityViewInfo.setSorter(sorterItemCollection);
        entityViewInfo.setSelector(selectCol);
        IWaterPowerMeterReading wpIns = WaterPowerMeterReadingFactory.getLocalInstance(ctx);
        WaterPowerMeterReadingCollection wpCol = wpIns.getWaterPowerMeterReadingCollection(entityViewInfo);
        logger.info("水电表读数查询完成，共查询到 {} 条记录", wpCol.size());
        return wpCol;
    }


    
    /**
     * 构建排序条件并查询水电表读数集合
     * 抽离通用逻辑，提高代码复用性
     */
    private WaterPowerMeterReadingInfo buildWaterPowerInfo(Context ctx, String fid) throws BOSException, EASBizException {
        IWaterPowerMeterReading wpIns = WaterPowerMeterReadingFactory.getLocalInstance(ctx);
        WaterPowerMeterReadingInfo wpCol = wpIns.getWaterPowerMeterReadingInfo(new ObjectUuidPK(fid));
        logger.info("水电表读数查询完成，共查询到 {} 条记录", wpCol.size());
        return wpCol;
    }
}