package com.kingdee.eas.custom.dormitorysystem.waterelectricity.handler;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kingdee.eas.base.codingrule.CodingRuleManagerFactory;
import com.kingdee.eas.base.codingrule.ICodingRuleManager;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.person.IPerson;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.dormitorysystem.waterelectricity.WaterElectricitySpecialInfo;
import com.kingdee.eas.custom.dormitorysystem.waterelectricity.WaterElectricityStutas;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;


/**
 * description: WaterElectricitySpecialEditHandler <br>
 * date: 20251227
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class WaterElectricitySpecialEditHandler extends EditHandler {
   
	private static Logger logger = LoggerFactory.getLogger(WaterElectricitySpecialEditHandler.class);
 
	
	@Override
	protected void beforeSave(HttpServletRequest request, HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		super.beforeSave(request, response, model);
		Context ctx = SHRContext.getInstance().getContext();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
		WaterElectricitySpecialInfo  info = (WaterElectricitySpecialInfo)model ;
		
		try {
			Date startDate = info.getStartDate();
			String format = dateFormat.format(startDate);
			info.setYearMonth(format);
			//根据startdate获取这个月的最后一天
			String endDate = dateFormat.format(startDate);
			endDate = endDate + "-31";
			dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			info.setEndDate(dateFormat.parse(endDate));
			//
			info.setStutas(WaterElectricityStutas.UnLock);
			SelectorItemCollection selectCol = new SelectorItemCollection(); 
			selectCol.add(new SelectorItemInfo("number"));
			selectCol.add(new SelectorItemInfo("name"));
			selectCol.add(new SelectorItemInfo("employeeType.name"));
			IPerson personIns  = PersonFactory.getLocalInstance(ctx);
			PersonInfo  personInfo = personIns.getPersonInfo(new ObjectUuidPK(info.getPerson().getId()), selectCol);
			info.setEmpNumber(personInfo.getNumber());
			info.setEmpName (personInfo.getName());
			info.setPositionStatus(personInfo.getString("employeeType"));
			//编码规则
			if(StringUtils.isEmpty(info.getNumber())){
				HROrgUnitInfo hrOrgUnit = info.getHrOrgUnit();
				ICodingRuleManager iCodingRuleManager = CodingRuleManagerFactory.getLocalInstance(ctx);
				if (iCodingRuleManager.isExist(info, hrOrgUnit.getId().toString())) {
					String  number = iCodingRuleManager.getNumber(info, hrOrgUnit.getId().toString());
					info.setNumber(number);
				}
			}
		} catch (EASBizException e) {
			e.printStackTrace();
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}


	}
	
	
        /**
         * 根据房间ID获取水电单价
         * @return Map<String, Double>  key：CFWaterprice（水单价）、CFElectricityprice（电单价）；value：对应单价（无数据返回0.0D）
         * @throws BOSException 金蝶BOS异常
         * @throws SQLException 数据库异常
         */
    public void getWaterElecPriceAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap ) throws SHRWebException, BOSException, SQLException {
        Context ctx = SHRContext.getInstance().getContext();
        String dormFid = request.getParameter("dormFid");
        String startDate = request.getParameter("startDate");
        try {
        	Map<String, Double> priceMap  = getDormWaterElectricityPrice(ctx, dormFid, startDate);
        	JSONUtils.writeJson(response, priceMap);
        } catch (ParseException e) {
        	e.printStackTrace();
        }
     }
    
    
    
    
    
    public Map<String, Double> getDormWaterElectricityPrice (Context ctx, String dormFid, String dateStr)
            throws BOSException, SQLException, ParseException   {
        Map<String, Double> priceMap = new HashMap<>(2);
        priceMap.put("CFWaterprice", 0.0D);
        priceMap.put("CFElectricityprice", 0.0D);

        if (dormFid == null || dormFid.trim().isEmpty() || dateStr == null || dateStr.trim().isEmpty()) {
            return priceMap;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.parse(dateStr);

        // 参数化SQL模板（用?占位符，避免拼接）
        String sqlTemplate = "/*dialect*/ WITH DormPriceCTE AS (" +
                "    SELECT fid AS DormId, fparentId, CFWaterprice, CFElectricityprice, 0 AS RecursionLevel " +
                "    FROM CT_DOR_Dormitory WHERE fid = ? " +
                "    UNION ALL " +
                "    SELECT child.DormId, parent.fparentId, parent.CFWaterprice, parent.CFElectricityprice, child.RecursionLevel + 1 " +
                "    FROM DormPriceCTE child INNER JOIN CT_DOR_Dormitory parent ON child.fparentId = parent.fid AND parent.fid != child.DormId " +
                "), WaterLatestPrice AS (" +
                "    SELECT DormId, CFWaterprice AS LatestWaterPrice, " +
                "           ROW_NUMBER() OVER (PARTITION BY DormId ORDER BY CASE WHEN CFWaterprice IS NOT NULL THEN 0 ELSE 1 END, RecursionLevel ASC) AS WaterRowNum " +
                "    FROM DormPriceCTE " +
                "), ElecLatestPrice AS (" +
                "    SELECT DormId, CFElectricityprice AS LatestElecPrice, " +
                "           ROW_NUMBER() OVER (PARTITION BY DormId ORDER BY CASE WHEN CFElectricityprice IS NOT NULL THEN 0 ELSE 1 END, RecursionLevel ASC) AS ElecRowNum " +
                "    FROM DormPriceCTE " +
                ") " +
                "SELECT COALESCE(wlp.LatestWaterPrice, wpp.CFWaterprice, 0.0) AS CFWaterprice, " +
                "       COALESCE(elp.LatestElecPrice, wpp.CFElectricityprice, 0.0) AS CFElectricityprice " +
                "FROM WaterLatestPrice wlp " +
                "INNER JOIN ElecLatestPrice elp ON wlp.DormId = elp.DormId " +
                "LEFT JOIN CT_WAT_WaterPowerPricing wpp ON wpp.CFStartDate <= CONVERT(date, ?) AND wpp.CFEndDate >= CONVERT(date, ?) " +
                "WHERE wlp.WaterRowNum = 1 AND elp.ElecRowNum = 1 AND wlp.DormId = ? " +
                "OPTION (MAXRECURSION 10)";

        // 执行参数化查询
        
        IRowSet rowSet = DbUtil.executeQuery(ctx, sqlTemplate, new Object[]{dormFid, dateStr, dateStr, dormFid});

        if (rowSet.next()) {
            priceMap.put("CFWaterprice", rowSet.getDouble("CFWaterprice"));
            priceMap.put("CFElectricityprice", rowSet.getDouble("CFElectricityprice"));
        }
        return priceMap;
    }
}
    
    
    
    
    
    
 
    
    
