package com.testor.module.environment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.constant.DefaultRule;
import com.testor.common.util.DateUtil;
import com.testor.module.environment.dao.TEnvironmentMonthlyDao;
import com.testor.module.environment.model.domain.TEnvironmentMonthly;
import com.testor.module.environment.model.dto.HomeEnvironment;
import com.testor.module.environment.model.dto.TEnvironmentMonthlyParam;
import com.testor.module.environment.service.TEnvironmentMonthlyService;
import com.testor.module.lease.controller.TLeaseBankController;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 节能环保月报Service业务层处理
 *
 * @author testor-framework
 * @date 2022-09-22 17:21:15
 */
@Service
public class TEnvironmentMonthlyServiceImpl extends SuperServiceImpl<TEnvironmentMonthlyDao, TEnvironmentMonthly> implements TEnvironmentMonthlyService {
    @Autowired(required = false)
    private TEnvironmentMonthlyDao tEnvironmentMonthlyDao;
    @Autowired
    private SysRuleService sysRuleService;
    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private TLeaseBankController tLeaseBankController;


    @Override
    public BaseResponse<List<HomeEnvironment>> getMonthHome(String orgId) {
        //ToDo 获取上一个月的月份
        Date lastMonth = DateUtil.getLastMonth(new Date());
        String lastMonthT = DateUtil.convertDateToYMDStrs(lastMonth);

        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取上个月的第一天
        LocalDate firstDayOfLastMonth = today.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
        // 获取上个月的最后一天
        LocalDate lastDayOfLastMonth = today.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());

        BaseResponse<List<HomeEnvironment>> homeEnvironmentBaseResponse = new BaseResponse<>();
        QueryWrapper<TEnvironmentMonthly> wrapper = new QueryWrapper<>();

        wrapper.ge(TEnvironmentMonthly.MONTH, firstDayOfLastMonth.toString());
        wrapper.le(TEnvironmentMonthly.MONTH, lastDayOfLastMonth.toString());

        wrapper.eq(TEnvironmentMonthly.STATUS, "0");
        if (StringHelper.isEmpty(orgId)) {
            String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
            if (StringUtils.isNotEmpty(rule)) {
                wrapper.apply(rule);
            }
        } else {
            List<String> list = tLeaseBankController.getSubordinate(orgId);
            wrapper.in(TEnvironmentMonthly.ORG_ID, list);
        }
        List<TEnvironmentMonthly> list = this.list(wrapper);
        // energyCoal 煤炭  energyPower 电力  energyGasoline 汽油   energyNatural 天然气   energyHeating 热力  energyOther 其它
        List<HomeEnvironment> environments = new ArrayList<>();
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        // 煤炭
        double energyCoal = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyCoal += Double.parseDouble(tEnvironmentMonthly.getEnergyCoal());
        }
        HomeEnvironment homeEnvironment = new HomeEnvironment();
        homeEnvironment.setName("原煤/吨");
        homeEnvironment.setNum(Double.parseDouble(decimalFormat.format(energyCoal)));
        environments.add(homeEnvironment);
        // 电力
        double energyPower = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyPower += Double.parseDouble(tEnvironmentMonthly.getEnergyPower());
        }
        HomeEnvironment energyPowers = new HomeEnvironment();
        energyPowers.setName("电力/吨");
        energyPowers.setNum(Double.parseDouble(decimalFormat.format(energyPower)));
        environments.add(energyPowers);
        // 汽油
        double energyGasoline = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyGasoline += Double.parseDouble(tEnvironmentMonthly.getEnergyGasoline());
        }
        HomeEnvironment energyGasolines = new HomeEnvironment();
        energyGasolines.setName("汽油/吨");
        energyGasolines.setNum(Double.parseDouble(decimalFormat.format(energyGasoline)));
        environments.add(energyGasolines);

        // 柴油
        double energyDerv = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyDerv += Double.parseDouble(tEnvironmentMonthly.getEnergyDerv());
        }
        HomeEnvironment energyEnergyDerv = new HomeEnvironment();
        energyEnergyDerv.setName("柴油/吨");
        energyEnergyDerv.setNum(Double.parseDouble(decimalFormat.format(energyDerv)));
        environments.add(energyEnergyDerv);

        // 燃料油
        double energyFuel = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyFuel += Double.parseDouble(tEnvironmentMonthly.getEnergyFuel());
        }
        HomeEnvironment energyEnergyFuel = new HomeEnvironment();
        energyEnergyFuel.setName("燃料油/吨");
        energyEnergyFuel.setNum(Double.parseDouble(decimalFormat.format(energyFuel)));
        environments.add(energyEnergyFuel);
        //天然气
        double energyNatural = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyNatural += Double.parseDouble(tEnvironmentMonthly.getEnergyNatural());
        }
        HomeEnvironment energyNaturals = new HomeEnvironment();
        energyNaturals.setName("天然气/吨");
        energyNaturals.setNum(Double.parseDouble(decimalFormat.format(energyNatural)));
        environments.add(energyNaturals);
        //热力
        double energyHeating = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyHeating += Double.parseDouble(tEnvironmentMonthly.getEnergyHeating());
        }
        HomeEnvironment energyHeatings = new HomeEnvironment();
        energyHeatings.setName("热力/吨");
        energyHeatings.setNum(Double.parseDouble(decimalFormat.format(energyHeating)));
        environments.add(energyHeatings);
        //其它
        double energyOther = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            energyOther += Double.parseDouble(tEnvironmentMonthly.getEnergyHeating());
        }
        HomeEnvironment energyOthers = new HomeEnvironment();
        energyOthers.setName("其它/吨");
        energyOthers.setNum(Double.parseDouble(decimalFormat.format(energyOther)));
        environments.add(energyOthers);
        //consumption
        double consumption = 0.0;
        for (TEnvironmentMonthly tEnvironmentMonthly : list) {
            consumption += Double.parseDouble(tEnvironmentMonthly.getEnergySynthesize());
        }
        HomeEnvironment consumptions = new HomeEnvironment();
        consumptions.setName("上月能耗统计(吨标煤)");
        consumptions.setNum(Double.parseDouble(decimalFormat.format(consumption)));
        environments.add(consumptions);

//        // 能耗总消耗
//        double sumCount = 0.0 ;
//        for (HomeEnvironment environment : environments) {
//            sumCount += environment.getNum();
//        }
//        HomeEnvironment sumCounts = new HomeEnvironment();
//        sumCounts.setNum(sumCount);
//        sumCounts.setName("上月能耗(标准煤)");
//        environments.add(sumCounts);

        homeEnvironmentBaseResponse.setData(environments);
        return homeEnvironmentBaseResponse;
    }

    /**
     * 判断是够为空
     *
     * @param s
     * @return
     */
    private boolean parseHomeBoolean(String s) {
        return (StringHelper.isNotEmpty(s));
    }

    @Override
    public TEnvironmentMonthly getListCount(TEnvironmentMonthlyParam queryParam) {
        List<String> companyIds = new ArrayList<>();
        String orgId = ContextUtils.getLoginUser().getOrgId();
        if (StringHelper.isNotEmpty(queryParam.getOrgId())) {
            String[] split = queryParam.getOrgId().split(",");
            companyIds = Arrays.asList(split);
        }
        if (companyIds.size() > 0) {
            orgId = null;
        }
        TEnvironmentMonthly listCount = tEnvironmentMonthlyDao.getListCount(queryParam, companyIds, orgId);
        if (ObjectHelper.isNotEmpty(listCount)) {
            listCount.setOrgName("合计");
            listCount.setProcessId("11");
        }
        return listCount;
    }

    @Override
    public IPage<TEnvironmentMonthly> getListMonth(TEnvironmentMonthlyParam param, String orgId) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TEnvironmentMonthly> resultPage = new Page<>(page, limit);
        return tEnvironmentMonthlyDao.getListMonth(resultPage, param, orgId);
    }

    @Override
    public BaseResponse<List<TEnvironmentMonthly>> getPastMonth() {
        String orgId = ContextUtils.getLoginUser().getOrgId();
        List<TEnvironmentMonthly> list = this.list(new QueryWrapper<TEnvironmentMonthly>().eq(TEnvironmentMonthly.ORG_ID, orgId)
                .ne(TEnvironmentMonthly.STATUS, BizConstants.STATUS_DELETE));
        list.stream().forEach(item -> {
            String month = item.getMonth();
            int endIndex = month.lastIndexOf("-");
            month = month.substring(0, endIndex);
            item.setMonth(month);
        });
        BaseResponse<List<TEnvironmentMonthly>> response = new BaseResponse<>();
        response.setData(list);
        return response;
    }

    @Override
    public int updateUnit() {
        return this.getBaseMapper().updateUnit();
    }

    @Override
    public TEnvironmentMonthly getTEnvironmentMonthlyById(String id) {
        TEnvironmentMonthly byId = this.baseMapper.getById(id);
        return byId;
    }

    @Override
    public Page<TEnvironmentMonthly> getPage(Page<TEnvironmentMonthly> resultPage, QueryWrapper<TEnvironmentMonthly> queryWrapper) {
        return this.baseMapper.getPage(resultPage, queryWrapper);
    }

    public static void main(String[] args) {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 获取上个月的第一天
        LocalDate firstDayOfLastMonth = today.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());

        // 获取上个月的最后一天
        LocalDate lastDayOfLastMonth = today.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());

        // 输出结果
        System.out.println("上个月的第一天是: " + firstDayOfLastMonth.toString());
        System.out.println("上个月的最后一天是: " + lastDayOfLastMonth);

    }

}
