package vip.xiaonuo.production.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.erp.entity.SysBaseFilterInfo;
import vip.xiaonuo.erp.mapper.SysBaseFilterInfoMapper;
import vip.xiaonuo.production.entity.*;
import vip.xiaonuo.production.entity.vo.ProductionLocationVo;
import vip.xiaonuo.production.mapper.*;
import vip.xiaonuo.production.param.ProductionParam;
import vip.xiaonuo.production.param.ProductionVoParam;
import vip.xiaonuo.production.param.TargetListDetailVo;
import vip.xiaonuo.production.param.TargetListDetailVos;
import vip.xiaonuo.production.service.IProductionTargetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import vip.xiaonuo.production.service.IProductionWorkstopPlanService;
import vip.xiaonuo.purchase.entity.PurchaseOrder;
import vip.xiaonuo.purchase.entity.vo.PurchaseOrderVo;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static vip.xiaonuo.money.service.impl.MoneyBusinessServiceImpl.*;

/**
 * <p>
 * 生产管控指标 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-12
 */
@Service
public class ProductionTargetServiceImpl extends ServiceImpl<ProductionTargetMapper, ProductionTarget> implements IProductionTargetService {

    @Autowired
    private ProductionTargetMapper targetMapper;
    @Autowired
    private ProductionWorkstopPlanMapper planMapper;
    @Autowired
    private ProductionWritePlanMapper writePlanMapper;
    @Autowired
    private ProductionWriteRateMapper rateMapper;
    @Autowired
    private ProductionEnergyPriceMapper priceMapper;
    @Autowired
    private ProductionWriteEnergyMapper energyMapper;
    @Autowired
    private IProductionWorkstopPlanService planService;
    @Autowired
    private SysBaseFilterInfoMapper baseFilterInfoMapper;

    @Override
    public ProductionTarget getTarget(ProductionParam productionParam) {
        String orgId = productionParam.getOrgId();
        String time = productionParam.getTime();
        String produceName = productionParam.getProduceName();
        String locationName = productionParam.getLocationName();
        ProductionTarget productionTarget = new ProductionTarget();
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        QueryWrapper<SysBaseFilterInfo> baseFilterInfoQueryWrapper = new QueryWrapper<>();
        baseFilterInfoQueryWrapper.eq("user_id", loginUser.getId()).eq("module_type", "produce");
        if ("".equals(orgId) || null == orgId) {
            baseFilterInfoQueryWrapper.eq("org_id", "0");
        } else {
            baseFilterInfoQueryWrapper.eq("org_id",orgId);
        }
        SysBaseFilterInfo sysBaseFilterInfo = baseFilterInfoMapper.selectOne(baseFilterInfoQueryWrapper);
        String type = "";
        if (ObjectUtil.isEmpty(sysBaseFilterInfo)) {
             sysBaseFilterInfo = new SysBaseFilterInfo();
            sysBaseFilterInfo.setFilter("0");
            sysBaseFilterInfo.setUserId(loginUser.getId());
            sysBaseFilterInfo.setModuleType("produce");
            sysBaseFilterInfo.setOrgId(orgId);
            baseFilterInfoMapper.insert(sysBaseFilterInfo);
            type = "0";
        } else {
            type = sysBaseFilterInfo.getFilter();//填报实际产量 0 erp数据  1填报数据
        }

        if ("0".equals(type)) {
            QueryWrapper<ProductionWorkstopPlan> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
            queryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
            queryWrapper.select("Convert(IFNULL(sum(actual_production),'0'),decimal(10,2)) actualProduction");
            if (StringUtils.isNotBlank(produceName)) {
                queryWrapper.like("produce_name", produceName);
            }
            queryWrapper.eq(StringUtils.isNotBlank(locationName), "location_name", locationName);
            ProductionWorkstopPlan workstopPlan = planMapper.selectOne(queryWrapper);//实际产量

            QueryWrapper<ProductionWritePlan> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
            queryWrapper1.eq(StringUtils.isNotBlank(locationName), "location_name", locationName);
            queryWrapper1.eq(StringUtils.isNotBlank(produceName), "production_name", produceName);
            queryWrapper1.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
            queryWrapper1.select(" Convert(IFNULL(sum(production_plan),'0'),decimal(10,2)) productionPlan," +
                    "Convert(IFNULL(sum(actual_production),'0'),decimal(10,2)) actualProduction");
            ProductionWritePlan writePlan = writePlanMapper.selectOne(queryWrapper1);//计划生产量

            if (ObjectUtil.isEmpty(writePlan) || "0.00".equals(writePlan.getProductionPlan())) {
                productionTarget.setPlanProduction("0");
                productionTarget.setPlanCompleteRate("0");
            } else {
                productionTarget.setPlanProduction(writePlan.getProductionPlan());
                double v = Double.valueOf(workstopPlan.getActualProduction()) / Double.valueOf(writePlan.getProductionPlan());
                if (v > 1.0) {
                    productionTarget.setPlanCompleteRate("100");
                } else {
                    DecimalFormat def = new DecimalFormat("0.00");
                    productionTarget.setPlanCompleteRate(def.format(v * 100));
                }
            }
            productionTarget.setActualProduction(workstopPlan.getActualProduction());
        } else {
            QueryWrapper<ProductionWritePlan> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
            queryWrapper1.eq(StringUtils.isNotBlank(locationName), "location_name", locationName);
            queryWrapper1.eq(StringUtils.isNotBlank(produceName), "production_name", produceName);
            queryWrapper1.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
            queryWrapper1.select(" Convert(IFNULL(sum(production_plan),'0'),decimal(10,2)) productionPlan," +
                    "Convert(IFNULL(sum(actual_production),'0'),decimal(10,2)) actualProduction");
            ProductionWritePlan writePlan = writePlanMapper.selectOne(queryWrapper1);//计划生产量


            if (ObjectUtil.isEmpty(writePlan) || "0.00".equals(writePlan.getProductionPlan())) {
                productionTarget.setPlanProduction("0");
                productionTarget.setPlanCompleteRate("0");
            } else {
                productionTarget.setPlanProduction(writePlan.getProductionPlan());
                double v = Double.valueOf(writePlan.getActualProduction()) / Double.valueOf(writePlan.getProductionPlan());
                if (v > 1.0) {
                    productionTarget.setPlanCompleteRate("100");
                } else {
                    DecimalFormat def = new DecimalFormat("0.00");
                    productionTarget.setPlanCompleteRate(def.format(v * 100));
                }
            }
            productionTarget.setActualProduction(writePlan.getActualProduction());
        }

        QueryWrapper<ProductionWriteRate> rateQueryWrapper = new QueryWrapper<>();
        rateQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        rateQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        if (StringUtils.isNotBlank(produceName)) {
            rateQueryWrapper.like("produce_name", produceName);
        }
        rateQueryWrapper.eq(StringUtils.isNotBlank(locationName), "location_name", locationName);
        rateQueryWrapper.select(" convert(IFNULL(avg(production_rate),'0'),decimal(10,2)) productionRate");
        ProductionWriteRate writeRate = rateMapper.selectOne(rateQueryWrapper);
        productionTarget.setReceiveRate(writeRate.getProductionRate());

        QueryWrapper<ProductionWriteEnergy> energyQueryWrapper = new QueryWrapper<>();
        energyQueryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        if (StringUtils.isNotBlank(produceName)) {
            energyQueryWrapper.like("produce_name", produceName);
        }
        rateQueryWrapper.between("create_time", time + "-01 00:00:00", time + "-31 23:59:59");
        energyQueryWrapper.eq(StringUtils.isNotBlank(locationName), "location_name", locationName);
        energyQueryWrapper.select("IFNULL(sum(electricity),'0') electricity,IFNULL(sum(zheng_qi),'0') zhengQi,IFNULL(sum(dan_qi),'0') danQi" +
                ",IFNULL(sum(ya_suo),'0') yaSuo,IFNULL(sum(ro_water),'0') roWater,IFNULL(sum(zl_water),'0') zlWater, IFNULL(sum(xh_water),'0') xhWater" +
                ",IFNULL(sum(qd_water),'0') qdwater,IFNULL(sum(swd_water),'0') swdWater,IFNULL(sum(eswd_water),'0') eswdWater,IFNULL(sum(re_water),'0') reWater" +
                ",IFNULL(sum(diwen_water),'0') diwenWater,IFNULL(sum(fu_swd_yierchun),'0') fuSwdYierchun" +
                ",IFNULL(sum(fu_eswd_yierchun),'0') fuEswdYierchun,location_id locationId,org_id orgId");
        energyQueryWrapper.groupBy("location_id");
        List<ProductionWriteEnergy> energyList = energyMapper.selectList(energyQueryWrapper);
        Double count = 0.00;
        for (ProductionWriteEnergy energy : energyList) {
            if (energy.getLocationId() != null) {
                QueryWrapper<ProductionEnergyPrice> priceQueryWrapper = new QueryWrapper<>();
                priceQueryWrapper.eq("org_id", energy.getOrgId()).eq("create_time",time);
                ProductionEnergyPrice energyPrice = priceMapper.selectOne(priceQueryWrapper);
                if (ObjectUtil.isNotEmpty(energyPrice)) {
                    if ("".equals(energyPrice.getElectricity())) {
                        energyPrice.setElectricity("0");
                    }
                    if ("".equals(energyPrice.getZhengQi())) {
                        energyPrice.setZhengQi("0");
                    }
                    if ("".equals(energyPrice.getDanQi())) {
                        energyPrice.setDanQi("0");
                    }
                    if ("".equals(energyPrice.getYaSuo())) {
                        energyPrice.setYaSuo("0");
                    }
                    if ("".equals(energyPrice.getRoWater())) {
                        energyPrice.setRoWater("0");
                    }
                    if ("".equals(energyPrice.getZlWater())) {
                        energyPrice.setZlWater("0");
                    }
                    if ("".equals(energyPrice.getXhWater())) {
                        energyPrice.setXhWater("0");
                    }
                    if ("".equals(energyPrice.getQdWater())) {
                        energyPrice.setQdWater("0");
                    }
                    if ("".equals(energyPrice.getSwdWater())) {
                        energyPrice.setSwdWater("0");
                    }
                    if ("".equals(energyPrice.getEswdWater())) {
                        energyPrice.setEswdWater("0");
                    }
                    if ("".equals(energyPrice.getReWater())) {
                        energyPrice.setReWater("0");
                    }
                    if ("".equals(energyPrice.getDiwenWater())) {
                        energyPrice.setDiwenWater("0");
                    }
                    if ("".equals(energyPrice.getFuSwdYierchun())) {
                        energyPrice.setFuSwdYierchun("0");
                    }
                    if ("".equals(energyPrice.getFuEswdYierchun())) {
                        energyPrice.setFuEswdYierchun("0");
                    }


                    count = count + Double.valueOf(energy.getElectricity()) * Double.valueOf(energyPrice.getElectricity())+Double.valueOf(energy.getZhengQi()) * Double.valueOf(energyPrice.getZhengQi())
                            +Double.valueOf(energy.getDanQi()) * Double.valueOf(energyPrice.getDanQi())+Double.valueOf(energy.getYaSuo()) * Double.valueOf(energyPrice.getYaSuo())+
                            Double.valueOf(energy.getRoWater()) * Double.valueOf(energyPrice.getRoWater())+Double.valueOf(energy.getZlWater()) * Double.valueOf(energyPrice.getZlWater())+
                            Double.valueOf(energy.getXhWater()) * Double.valueOf(energyPrice.getXhWater())+Double.valueOf(energy.getQdWater()) * Double.valueOf(energyPrice.getQdWater())+
                            Double.valueOf(energy.getSwdWater()) * Double.valueOf(energyPrice.getSwdWater())+Double.valueOf(energy.getEswdWater()) * Double.valueOf(energyPrice.getEswdWater())+
                            Double.valueOf(energy.getReWater()) * Double.valueOf(energyPrice.getReWater())+Double.valueOf(energy.getDiwenWater()) * Double.valueOf(energyPrice.getDiwenWater())+
                            Double.valueOf(energy.getFuSwdYierchun()) * Double.valueOf(energyPrice.getFuSwdYierchun())+Double.valueOf(energy.getFuEswdYierchun()) * Double.valueOf(energyPrice.getFuEswdYierchun());
                }
            }
        }
        DecimalFormat def = new DecimalFormat("0.00");
        productionTarget.setProductionEnergy(def.format(count));

        return productionTarget;
    }

    @Override
    public List<TargetListDetailVo> getListDetail(ProductionParam productionParam) {
        String orgId = productionParam.getOrgId();
        ProductionVoParam productionVoParam = new ProductionVoParam();
        productionVoParam.setOrgId(orgId);
        List<ProductionLocationVo> productionLocationVos = planService.listLocation(productionVoParam);
        QueryWrapper<ProductionWritePlan> wrapper = new QueryWrapper<>();

        List<TargetListDetailVo> targetListDetailVos = new ArrayList<>();
        for (ProductionLocationVo productionLocationVo : productionLocationVos) {
            wrapper.clear();
            wrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId).orderByAsc("create_time");
            wrapper.eq("location_id",productionLocationVo.getLocationId());
            wrapper.groupBy("ymonth").orderByAsc("ymonth");

            TargetListDetailVo targetListDetailVo = new TargetListDetailVo();
            targetListDetailVo.setChenJian(productionLocationVo.getLocationName());
            List<TargetListDetailVos> listDetail = energyMapper.getListDetail(wrapper);
            wrapper.clear();
            wrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId).orderByAsc("create_time");
            wrapper.eq("location_id",productionLocationVo.getLocationId());
            TargetListDetailVos listDetailVo =  energyMapper.getCountDetaile(wrapper);
            targetListDetailVo.setActualProduction(listDetailVo.getActualProduction());
            targetListDetailVo.setProductionPlan(listDetailVo.getProductionPlan());
            targetListDetailVo.setProductionRate(calculateWanChenLv(Double.parseDouble(listDetailVo.getActualProduction()),Double.parseDouble(listDetailVo.getProductionPlan())));

            if (ObjectUtil.isNotEmpty(listDetail)){
                for (TargetListDetailVos listDetailVos : listDetail) {
                  listDetailVos.setProductionRate(calculateWanChenLv(Double.parseDouble(listDetailVos.getActualProduction()),Double.parseDouble(listDetailVos.getProductionPlan())));
                }
            }
            targetListDetailVo.setValues(listDetail);
            targetListDetailVos.add(targetListDetailVo);
        }

        return targetListDetailVos;
    }


    @Override
    public List<TargetListDetailVo> getListShouLvChengDetail(ProductionParam productionParam) {
        String orgId = productionParam.getOrgId();
        ProductionVoParam productionVoParam = new ProductionVoParam();
        productionVoParam.setOrgId(orgId);
        List<ProductionLocationVo> productionLocationVos = planService.listLocation(productionVoParam);
        QueryWrapper<ProductionWritePlan> wrapper = new QueryWrapper<>();

        List<TargetListDetailVo> targetListDetailVos = new ArrayList<>();
        for (ProductionLocationVo productionLocationVo : productionLocationVos) {
            wrapper.clear();
            wrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId).orderByAsc("create_time");
            wrapper.eq("location_id", productionLocationVo.getLocationId());
            wrapper.groupBy("ymonth").orderByAsc("ymonth");

            TargetListDetailVo targetListDetailVo = new TargetListDetailVo();
            targetListDetailVo.setChenJian(productionLocationVo.getLocationName());
            targetListDetailVo.setValues(rateMapper.productionParam(wrapper));
            targetListDetailVos.add(targetListDetailVo);
        }
        return targetListDetailVos;

    }

    @Override
    public List<TargetListDetailVo> getListNengHaoDetail(ProductionParam productionParam) {
        String orgId = productionParam.getOrgId();
        ProductionVoParam productionVoParam = new ProductionVoParam();
        productionVoParam.setOrgId(orgId);
        List<ProductionLocationVo> productionLocationVos = planService.listLocation(productionVoParam);
        QueryWrapper<ProductionWritePlan> wrapper = new QueryWrapper<>();

        List<TargetListDetailVo> targetListDetailVos = new ArrayList<>();
        for (ProductionLocationVo productionLocationVo : productionLocationVos) {
            wrapper.clear();
            wrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId).orderByAsc("create_time");
            wrapper.eq("location_id", productionLocationVo.getLocationId());
            wrapper.groupBy("ymonth").orderByAsc("ymonth");

            TargetListDetailVo targetListDetailVo = new TargetListDetailVo();
            targetListDetailVo.setChenJian(productionLocationVo.getLocationName());
            QueryWrapper<ProductionEnergyPrice> priceQueryWrapper = new QueryWrapper<>();
            List<ProductionEnergyPrice> energyPrice = priceMapper.selectList(priceQueryWrapper);
            ProductionEnergyPrice productionEnergyPrice = energyPrice.get(0);
            if (ObjectUtil.isNotEmpty(energyPrice)) {

                if ("".equals(productionEnergyPrice.getElectricity())) {
                    productionEnergyPrice.setElectricity("0");
                }
                if ("".equals(productionEnergyPrice.getZhengQi())) {
                    productionEnergyPrice.setZhengQi("0");
                }
                if ("".equals(productionEnergyPrice.getDanQi())) {
                    productionEnergyPrice.setDanQi("0");
                }
                if ("".equals(productionEnergyPrice.getYaSuo())) {
                    productionEnergyPrice.setYaSuo("0");
                }
                if ("".equals(productionEnergyPrice.getRoWater())) {
                    productionEnergyPrice.setRoWater("0");
                }
                if ("".equals(productionEnergyPrice.getZlWater())) {
                    productionEnergyPrice.setZlWater("0");
                }
                if ("".equals(productionEnergyPrice.getXhWater())) {
                    productionEnergyPrice.setXhWater("0");
                }
                if ("".equals(productionEnergyPrice.getQdWater())) {
                    productionEnergyPrice.setQdWater("0");
                }
                if ("".equals(productionEnergyPrice.getSwdWater())) {
                    productionEnergyPrice.setSwdWater("0");
                }
                if ("".equals(productionEnergyPrice.getEswdWater())) {
                    productionEnergyPrice.setEswdWater("0");
                }
                if ("".equals(productionEnergyPrice.getReWater())) {
                    productionEnergyPrice.setReWater("0");
                }
                if ("".equals(productionEnergyPrice.getDiwenWater())) {
                    productionEnergyPrice.setDiwenWater("0");
                }
                if ("".equals(productionEnergyPrice.getFuSwdYierchun())) {
                    productionEnergyPrice.setFuSwdYierchun("0");
                }
                if ("".equals(productionEnergyPrice.getFuEswdYierchun())) {
                    productionEnergyPrice.setFuEswdYierchun("0");
                }
            }
            targetListDetailVo.setValues(rateMapper.getListNengHaoDetail(wrapper , productionEnergyPrice.getElectricity() ,
                    productionEnergyPrice.getZhengQi(),
                    productionEnergyPrice.getDanQi(),
                    productionEnergyPrice.getYaSuo(),
                    productionEnergyPrice.getRoWater(),
                    productionEnergyPrice.getZlWater(),
                    productionEnergyPrice.getXhWater(),
                    productionEnergyPrice.getQdWater(),
                    productionEnergyPrice.getSwdWater(),
                    productionEnergyPrice.getEswdWater(),
                    productionEnergyPrice.getReWater(),
                    productionEnergyPrice.getDiwenWater(),
                    productionEnergyPrice.getFuSwdYierchun(),
                    productionEnergyPrice.getFuEswdYierchun()
                    ));
            targetListDetailVos.add(targetListDetailVo);
            }
            return targetListDetailVos;
    }

}
