package com.awspaas.user.apps.bnbm.datalinkup.job;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.schedule.IJob;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: YyglbDbHtJob
 * @Description: 运营管理部对标回填
 * @date: 2025/9/29 13:27
 * @Blog: https://
 */
public class YyglbDbHtJob implements IJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(YyglbDbHtJob.class);
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        LocalDate now = LocalDate.now().minusMonths(1);
        int year = now.getYear();
        int monthValue = now.getMonthValue();
        //分别遍历龙牌梦牌泰山 护面纸、石膏、煤的对标数量
        //公式为：当月材料出库数量/当月石膏板折标产量
        //龙牌取数为：生产出库用量 护面纸取全部、脱硫石膏取物料编码为101115110000130、煤为包含煤、生物质、天然气、蒸汽
        String[] bkgsArr = new String[]{"龙牌","梦牌","泰山石膏"};
        HashMap<String, String> wlmcMap = new HashMap<>();
        wlmcMap.put("护面纸","HMZ");
        wlmcMap.put("石膏","SG");
        wlmcMap.put("煤","MEI");
        ArrayList<BO> boList = new ArrayList<>();

        try {
            int update = DBSql.update("DELETE FROM BO_EU_YY_WLDHCKB WHERE YEAR = '" + year + "' AND MONTH = '" + monthValue + "'");
            LOGGER.info("删除{}-{}的数据{}条",year,monthValue,update);
        }catch (Exception e){
            LOGGER.error("删除运营_物料单耗出库表出错，删除范围为：{}-{}：e",year,monthValue,e.getLocalizedMessage());
        }
        try {
            for (String bkgs : bkgsArr) {
                List<RowMap> maps1 = DBSql.getMaps("SELECT FLZZ FROM BO_EU_BNBM_SCCK_HZ WHERE BKGS = '"+bkgs+"' " +
                        " AND (DJZT = '已审核' OR DJZT = '签字')" +
                        " AND YEAR = '" + year + "' AND MONTH = '" + monthValue + "' GROUP BY FLZZ");
                for (RowMap map2 : maps1) {
                    BO bo = new BO();
                    for (String wlmckey : wlmcMap.keySet()) {
                        String wlmcValue = wlmcMap.get(wlmckey);
                        String sql = "SELECT SUM(SFSL) AS SFSL FROM BO_EU_BNBM_SCCK_HZ WHERE BKGS = '" + bkgs + "' AND (DJZT = '已审核' OR DJZT = '签字') " +
                                " AND YEAR = '" + year + "' AND MONTH = '" + monthValue + "'" +
                                " AND FLZZ = '"+map2.getString("FLZZ")+"'";
                        if (wlmckey.equals("石膏")){
                            sql+="  AND WLMC IN ('脱硫石膏','磷石膏','天然石膏')";
                        }else {
                            sql+="  AND WLMC LIKE '%" + wlmckey + "%' ";
                        }
                        if (bkgs.equals("泰山石膏")){
                            sql+="AND SCBM NOT LIKE '%穿孔板%' AND SCBM NOT LIKE '%装饰板%'";
                        }
                        RowMap map = DBSql.getMap(sql);
                        bo.set(wlmcValue,map.getString("SFSL"));
                        if (StringUtils.isNotBlank(map2.getString("FLZZ"))){
                            bo.set("FLZZ",map2.getString("FLZZ"));
                            RowMap flzz = DBSql.getMap("SELECT SJZZID FROM BO_EU_BNBM_ZZWHB WHERE GSMC = '" + map2.getString("FLZZ") + "'");
                            if (flzz!=null){
                                bo.set("ZZNM",flzz.getString("SJZZID"));
                            }
                        }
                    }
                    bo.set("YEAR",year);
                    bo.set("MONTH",monthValue);
                    bo.set("NF",year);
                    bo.set("YF",monthValue);
                    bo.set("BKGS",bkgs);
                    bo.set("BK",bkgs.equals("泰山石膏")?"泰山":bkgs);
                    RowMap map1 = DBSql.getMap("SELECT SUM(ZBCL) AS zbcl FROM BO_EU_BNBM_SCRK_HZ " +
                            " WHERE BKGS = '" + bkgs + "' AND YEAR = '" + year + "' AND MONTH = '" + monthValue + "'" +
                            " AND WLMC LIKE '%石膏板%' AND KCZZ = '"+bo.getString("FLZZ")+"'");
                    if (map1!=null){
                        bo.set("SGBZBCL",map1.getString("zbcl"));
                    }else{
                        bo.set("SGBZBCL",0);
                    }
                    LOGGER.info("存储的值为：{}",bo.toJSONObject().toJSONString());
                    boList.add(bo);
                }
            }
            List<BO> zzwhb = SDK.getBOAPI().query("BO_EU_BNBM_ZZWHB").list();
            Map<String, BO> zzwhbMap = zzwhb.stream()
                    .collect(Collectors.toMap(
                            bo -> bo.getString("GSMC"), // Key映射器
                            bo -> bo,                   // Value映射器
                            (existing, replacement) -> replacement // 重复键处理策略
                    ));
            SDK.getBOAPI().createDataBO("BO_EU_YY_WLDHCKB",boList, UserContext.fromUID("admin"));

            for (BO bo : boList) {
                String nf = bo.getString("NF");
                String yf = bo.getString("YF");
                String bk = bo.getString("BK");
                BO flzz = zzwhbMap.get(bo.getString("FLZZ"));
                if (flzz!=null) {
                    BO detail = SDK.getBOAPI().query("BO_EU_YYGLB_DB_SGBYDDF_XMDBZ").addQuery("NF=", nf)
                            .addQuery("YF=", yf).addQuery("BK=", bk).addQuery("XM =", flzz.getString("JC")).detail();
                    try {
                        // 安全解析数值，添加异常处理
                        Double hmz = 0.00;
                        Double sg = 0.00;
                        Double mei = 0.00;
                        Double sgbzbcl = 0.00;

                        try {
                            hmz = StringUtils.isNotBlank(bo.getString("HMZ")) ? Double.parseDouble(bo.getString("HMZ").trim()) : 0.00;
                        } catch (NumberFormatException e) {
                            LOGGER.warn("HMZ格式错误，使用默认值0.00，原始值: {}", bo.getString("HMZ"));
                            hmz = 0.00;
                        }

                        try {
                            sg = StringUtils.isNotBlank(bo.getString("SG")) ? Double.parseDouble(bo.getString("SG").trim()) : 0.00;
                        } catch (NumberFormatException e) {
                            LOGGER.warn("SG格式错误，使用默认值0.00，原始值: {}", bo.getString("SG"));
                            sg = 0.00;
                        }

                        try {
                            mei = StringUtils.isNotBlank(bo.getString("MEI")) ? Double.parseDouble(bo.getString("MEI").trim()) : 0.00;
                        } catch (NumberFormatException e) {
                            LOGGER.warn("MEI格式错误，使用默认值0.00，原始值: {}", bo.getString("MEI"));
                            mei = 0.00;
                        }

                        try {
                            sgbzbcl = StringUtils.isNotBlank(bo.getString("SGBZBCL")) ? Double.parseDouble(bo.getString("SGBZBCL").trim()) : 0.00;
                        } catch (NumberFormatException e) {
                            LOGGER.warn("SGBZBCL格式错误，使用默认值0.00，原始值: {}", bo.getString("SGBZBCL"));
                            sgbzbcl = 0.00;
                        }

                        // 检查detail对象是否为空
                        if (detail == null) {
                            LOGGER.error("detail对象为null，无法进行计算和更新");
                            continue;
                        }

                        // 检查flzz对象和JC字段
                        String jcValue = "";
                        if (flzz != null && StringUtils.isNotBlank(flzz.getString("JC"))) {
                            jcValue = flzz.getString("JC");
                        } else {
                            LOGGER.warn("flzz或JC字段为空，使用空字符串");
                        }

                        LOGGER.info("nf:{};yf:{};bk:{};jc:{};hmz:{};sg:{};mei:{};sgbzbcl:{}",
                                nf, yf, bk, jcValue, hmz, sg, mei, sgbzbcl);

                        if (sgbzbcl != null && sgbzbcl != 0.00) {
                            // 安全处理hmz
                            if (hmz != null && hmz != 0.00) {
                                double result = (hmz*1000000) / sgbzbcl;
                                detail.set("HMZ", result);
                                LOGGER.debug("HMZ计算结果: {} / {} = {}", hmz, sgbzbcl, result);
                            } else {
                                detail.set("HMZ", 0.00);
                            }

                            // 安全处理sg
                            if (sg != null && sg != 0.00) {
                                double result = (sg*1000) / sgbzbcl;
                                detail.set("SG", result);
                                LOGGER.debug("SG计算结果: {} / {} = {}", sg, sgbzbcl, result);
                            } else {
                                detail.set("SG", 0.00);
                            }

                            // 安全处理mei
                            if (mei != null && mei != 0.00) {
                                double result = (mei*1000) / sgbzbcl;
                                detail.set("MH", result);
                                LOGGER.debug("MH计算结果: {} / {} = {}", mei, sgbzbcl, result);
                            } else {
                                detail.set("MH", 0.00);
                            }

                            // 添加数据库更新前的日志和异常处理
                            try {
                                SDK.getBOAPI().update("BO_EU_YYGLB_DB_SGBYDDF_XMDBZ", detail);
                                LOGGER.info("单耗对标计算成功更新，nf:{};yf:{};bk:{}", nf, yf, bk);
                            } catch (Exception e) {
                                LOGGER.error("更新数据库失败，nf:{};yf:{};bk:{};错误信息:{}",
                                        nf, yf, bk, e.getMessage(), e);
                                // 可以根据需要决定是否抛出异常
                                throw new RuntimeException("数据库更新失败: " + e.getMessage(), e);
                            }
                        } else {
                            LOGGER.warn("sgbzbcl为0或null，跳过计算，nf:{};yf:{};bk:{}", nf, yf, bk);
                            // 设置默认值
                            detail.set("HMZ", 0.00);
                            detail.set("SG", 0.00);
                            detail.set("MH", 0.00);
                        }
                    } catch (Exception e) {
                        LOGGER.error("单耗对标计算报错，错误时间范围为：{}-{}，错误信息：{}",
                                nf, yf, e.getMessage(), e);
                        throw e; // 重新抛出异常
                    }
                }
            }
            LOGGER.info("单耗对标计算完成时间范围为：{}-{}",year,monthValue);
        }catch (Exception e){
            LOGGER.error("单耗对标计算报错，错误时间范围为：{}-{}：{}",year,monthValue,e.fillInStackTrace());
        }

    }
}
