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

import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.MetaDataLoaderFactory;
import com.kingdee.bos.metadata.data.ColumnInfo;
import com.kingdee.bos.metadata.data.SQLType;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.eas.common.EASBizException;
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.WaterPowerMeterReadingFactory;
import com.kingdee.eas.custom.dormitorysystem.waterpower.WaterPowerMeterReadingInfo;
import com.kingdee.eas.framework.CoreBaseInfo;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kingdee.eas.base.core.util.EmptyUtil;
import com.kingdee.eas.base.permission.UserCollection;
import com.kingdee.eas.base.permission.UserFactory;
import com.kingdee.eas.base.permission.UserInfo;

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



/**
 * 保存水电读书
 * coyle
 * 2025/12/19 10:37
 */
public class SaveWaterPowerReadService  implements IHRMsfService {

    private static final Logger logger = LoggerFactory.getLogger(SaveWaterPowerReadService.class);
    // 定义日期格式化器，避免重复创建

    @Override
    public Object process(Context ctx, Map<String, Object> param) throws EASBizException, BOSException {

        if (ctx == null) {
            throw new BOSException("上下文Context不能为空");
        }
        IWaterPowerMeterReading localInstance = WaterPowerMeterReadingFactory.getLocalInstance(ctx);
        WaterPowerMeterReadingInfo info = new WaterPowerMeterReadingInfo();
        Object fidObj = param.get("fid");

        if (fidObj != null && !StringUtils.isEmpty(fidObj.toString()) && (fidObj.toString()).length()> 5) {
            String fid = fidObj.toString().trim();
             info = localInstance.getWaterPowerMeterReadingInfo(new ObjectUuidPK(fid));
        }
        EntityObjectInfo enty = MetaDataLoaderFactory.getLocalMetaDataLoader(ctx).getEntity(info.getBOSType());
        PropertyCollection ps = enty.getInheritedNoDuplicatedPropertiesRuntime();
        List<String> ColumnNames = new ArrayList<>();
        List<String> bigCol = new ArrayList<>();
        for (int j = 0; j < ps.size(); ++j) {
            PropertyInfo p = ps.get(j);
            ColumnInfo mappingField = p.getMappingField();
            SQLType typeName = mappingField.getTypeName();
          
            String fkey = p.getName();
            if (EmptyUtil.isEmpty(fkey)) continue;
            if(StringUtils.equals( typeName.toString() ,  "NUMERIC")) {
            	bigCol.add(fkey);
            }
            ColumnNames.add(fkey);
        }
            // 4. 构建查询结果并返回
        setObjectPropertyValue (info, param, ColumnNames, bigCol );
        
        if (fidObj != null && !StringUtils.isEmpty(fidObj.toString())  && (fidObj.toString()).length()> 5 )
            localInstance.update(new ObjectUuidPK(fidObj.toString()), info);
        else {
        	//抄表人
        	if(param.containsKey("creatorNum")) {
        		String creatorNum = String.valueOf(param.get("creatorNum"));
                UserCollection userCollection = UserFactory.getLocalInstance(ctx).getUserCollection(" where number = '" + creatorNum +"'");
                if(null != userCollection && userCollection.size() > 0) {
                	UserInfo userInfo = userCollection.get(0);
                	info.setMeterReaPerson(userInfo.getPerson());
                }
        	}else {
        		IObjectPK userId = ctx.getCaller();
            	UserInfo user = UserFactory.getRemoteInstance().getUserByID(userId);
            	String personId = user.getPerson().getId().toString();
                info.put("meterReaPerson",personId);
        	}
        	
            IObjectPK addnew = localInstance.addnew(info);
        }
        return "success";
    }



    protected void setObjectPropertyValue(CoreBaseInfo coreBaseInfo,Map<String, Object> param, List<String> ColumnNames ,List<String> bigCol) {
        Object data = param.get("data");
        if (data == null) {
            return;
        }
        String dataStr = data.toString().trim();
        if(dataStr.startsWith("'") && dataStr.endsWith("'")){
            dataStr = dataStr.substring(1, dataStr.length() - 1);
        }else if(dataStr.startsWith("\"") && dataStr.endsWith("\"")){
            dataStr = dataStr.substring(1, dataStr.length() - 1);
        }
        dataStr = dataStr  .replace("\\", "");
         
        //转换为json后，再转换为map
        Map<String, Object> dataMap = (Map<String, Object>) JSONObject.parse(dataStr.toString());
        // 1. 预处理：生成 小写键 -> 原值 的映射（仅需执行一次）
        Map<String, Object> lowerCaseDataMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            // 键转小写，值保留原值
            String lowerKey = entry.getKey().toLowerCase();
            lowerCaseDataMap.put(lowerKey, entry.getValue());
        }

        // 3. 遍历ColumnNames，不区分大小写匹配
        for (String propName : ColumnNames) {
            // propName也转小写，匹配预处理后的映射
            String lowerPropName = propName.toLowerCase();
            if (lowerCaseDataMap.containsKey(lowerPropName)) {
                Object value = lowerCaseDataMap.get(lowerPropName);
                if (value != null && !StringUtils.isAllEmpty(value.toString())) {
                	if(  bigCol.contains(propName) ) {
                		coreBaseInfo.put(propName, safeConvertToBigDecimal(value.toString())); // 最终存入的键还是原propName（保持原有命名）
                	}else {
                		coreBaseInfo.put(propName, value); // 最终存入的键还是原propName（保持原有命名）
                	}
                	 
//                	if("dormitory".equals(lowerPropName)) {
//                		 coreBaseInfo.put(propName, "gMIDv2SBRdqAf5nD2B1DzlUo6p0="); // 最终存入的键还是原propName（保持原有命名）
//                	}
                }
            }
        }




    }


    /**
     * 安全将字符串转换为BigDecimal
     * @param str 待转换的字符串（可能为空、非数字）
     * @param defaultValue 转换失败时的默认值（如BigDecimal.ZERO）
     * @return 合法的BigDecimal值
     */
    public static BigDecimal safeConvertToBigDecimal(String str, BigDecimal defaultValue) {
        // 1. 处理空值（null/空字符串/全空格）
        if (str == null || str.trim().isEmpty()) {
            return defaultValue;
        }
        try {
            // 2. 尝试转换为BigDecimal
            return new BigDecimal(str.trim());
        } catch (NumberFormatException e) {
            // 3. 转换失败返回默认值（可记录日志便于排查）
            System.err.println("字符串转换BigDecimal失败，值为：" + str + "，原因：" + e.getMessage());
            return defaultValue;
        }
    }

    // 重载方法：默认值为0
    public static BigDecimal safeConvertToBigDecimal(String str) {
        return safeConvertToBigDecimal(str, BigDecimal.ZERO);
    }




}