/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.watermeter.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.watermeter.entity.*;
import com.tofly.watermeter.mapper.WateryieldMapper;
import com.tofly.watermeter.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 取供水量数据存储表
 *
 * @author admin
 * @date Sat May 28 00:00:00 CST 2022
 */
@Service("wateryieldService")
public class WateryieldServiceImpl extends ServiceImpl<WateryieldMapper, Wateryield> implements WateryieldService {


    @Autowired
    private WateryieldconfigService wateryieldconfigService;
    @Autowired
    private WateryieldMapper wateryieldMapper;
    @Autowired
    private HourwateryieldService hourwateryieldService;
    @Autowired
    private DaywateryieldService daywateryieldService;
    @Autowired
    private MonthwateryieldService monthwateryieldService;
    @Autowired
    private ReadmeterhisService readmeterhisService;

    private final static String FORMAT_HOUR = "yyyy-mm-dd hh24";
    private final static String FORMAT_DAY = "yyyy-mm-dd";
    private final static String FORMAT_MONTH = "yyyy-mm";

//    @Autowired
//    private WateryieldService wateryieldService;
//    @Autowired
//    private BwrkdetailService bwrkdetailService;
//
//    private final static String WATER_YIELD_TABLE = "TF_YWPN_WATERYIELD_W";
//
//    private final static Integer MAX_INSERT_NUM = 1000;
//    @Value("${meter.factory.oneFactory}")
//    private long oneFactory;
//    @Value("${meter.factory.twoFactory}")
//    private long twoFactory;
//    @Value("${meter.factory.sumFactory}")
//    private long factory;


    @Override
    public boolean handleWaterYield() {
        //获取配置信息
        List<Wateryieldconfig> configList = wateryieldconfigService.list();
        List<String> itcdList = configList.stream().map(Wateryieldconfig::getItem).collect(Collectors.toList());


        DateTime date = DateUtil.date();
//        //获取前一个小时
//        DateTime beforeHour = DateUtil.offsetHour(date, -1);
       //获取前一个天
       DateTime beforeDay = DateUtil.offsetDay(date, -1);
       //获取前一个月
       DateTime beforeMonth = DateUtil.offsetMonth(date, -1);

        Daywateryield day;
        Hourwateryield hour;
        Monthwateryield month;

        for (String itcd : itcdList) {

            Hourwateryield hourwateryield = hourwateryieldService.getOne(Wrappers.<Hourwateryield>lambdaQuery()
                    .eq(Hourwateryield::getItcd, itcd)
                    .eq(Hourwateryield::getTime, DateUtil.format(date, "yyyy-MM-dd HH")));
            if (hourwateryield == null) {
                hour = new Hourwateryield();
                hour.setFlow(this.getVal(itcd, date, FORMAT_HOUR));
                hour.setItcd(itcd);
                hour.setTime(DateUtil.format(date, "yyyy-MM-dd HH"));

                hourwateryieldService.save(hour);
            }

            Daywateryield daywateryield = daywateryieldService.getOne(Wrappers.<Daywateryield>lambdaQuery()
                    .eq(Daywateryield::getItcd, itcd)
                    .eq(Daywateryield::getTime, DateUtil.format(beforeDay, "yyyy-MM-dd")));
            if (daywateryield == null) {
                day = new Daywateryield();
                day.setFlow(this.getVal(itcd, beforeDay, FORMAT_DAY));
                day.setItcd(itcd);
                day.setTime(DateUtil.format(beforeDay, "yyyy-MM-dd"));
                daywateryieldService.save(day);
            }

            Monthwateryield monthwateryield = monthwateryieldService.getOne(Wrappers.<Monthwateryield>lambdaQuery()
                    .eq(Monthwateryield::getItcd, itcd)
                    .eq(Monthwateryield::getTime, DateUtil.format(beforeMonth, "yyyy-MM")));
            if (monthwateryield == null) {
                month = new Monthwateryield();
                month.setFlow(this.getVal(itcd, beforeMonth, FORMAT_MONTH));
                month.setItcd(itcd);
                month.setTime(DateUtil.format(beforeMonth, "yyyy-MM"));
                monthwateryieldService.save(month);
            }
        }
        return true;
    }

    @Override
    public double getVal(String itcd, Date time, String format) {
        String min = wateryieldMapper.queryHistoryInfo(itcd, time, format, null);
        String max = wateryieldMapper.queryHistoryInfo(itcd, time, format, "desc");
        BigDecimal minVal = new BigDecimal(StringUtils.isEmpty(min) ? "0" : min);
        BigDecimal maxVal = new BigDecimal(StringUtils.isEmpty(max) ? "0" : max);
        return maxVal.subtract(minVal).doubleValue();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMeterReadingInfo(String month) {
        List<Map> meterInfo = baseMapper.getMeterInfo(month);
        if (meterInfo != null && !meterInfo.isEmpty()) {
            for (Map map : meterInfo) {
                String yhbh = map.get("yhbh").toString();
                long scds = Long.parseLong(map.get("sl").toString());
                Long bcds = !StringUtils.isEmpty(map.get("bcds")) ? Long.parseLong(map.get("bcds").toString()) : null;
                long waterVal = 0L;
                if (bcds != null) {
                    waterVal = bcds - scds;
                }
                readmeterhisService.update(Wrappers.<Readmeterhis>lambdaUpdate()
                        .set(Readmeterhis::getScds, scds)
                        .set(bcds != null, Readmeterhis::getBcjjl, waterVal)
                        .set(bcds != null, Readmeterhis::getCbsl, waterVal)
                        .set(bcds != null, Readmeterhis::getUpdateBcds, bcds)
                        .set(Readmeterhis::getUpdateScds, scds)
                        .set(bcds != null, Readmeterhis::getUpdateWater, waterVal)
                        .eq(Readmeterhis::getYhbh, yhbh)
                        .eq(Readmeterhis::getIsGeneral, "1")
                        .eq(Readmeterhis::getMonthPlan, month));
            }
        }
        return true;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean batchHandleWaterYield() {
//        //首先清除数据
//        wateryieldService.remove(null);
//
//        //获取配置信息
//        List<Wateryieldconfig> configs = wateryieldconfigService.list();
//        //获取最大id
//        Long maxId = bwrkdetailService.getMaxId(WATER_YIELD_TABLE);
//        //分组取得所有小时为单位的时间段
//        List<String> timeList = wateryieldMapper.groupTimeList();
//
//        List<Wateryield> wateryields = saveBatchWaterYield(timeList, configs, oneFactory, maxId);
//        wateryields.addAll(saveBatchWaterYield(timeList, configs, twoFactory, maxId + wateryields.size()));
//        //当添加数量超过1000，分批添加
//        int size = wateryields.size();
//        if (size <= 1000) {
//            wateryieldMapper.batchInsertWaterYield(wateryields);
//        } else {
//            List<Wateryield> list;
//            int number = (int) Math.ceil((float) size / MAX_INSERT_NUM);
//            //截取下标范围
//            int startIndex;
//            int endIndex;
//
//            for (int i = 1; i <= number; i++) {
//                startIndex = (i - 1) * MAX_INSERT_NUM;
//                if (i == number) {
//                    endIndex = size;
//                } else {
//                    endIndex = i * MAX_INSERT_NUM;
//                }
//                list = wateryields.subList(startIndex, endIndex);
//                wateryieldMapper.batchInsertWaterYield(list);
//            }
//        }
//        return true;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void saveWaterYield(List<Wateryieldconfig> configs, Long factoryId) {
//
//        BigDecimal sumGetWater = handleCode(configs, factory, "0", "");
//        BigDecimal sumWaterSupply = handleCode(configs, factory, "1", "");
//        BigDecimal hourWaterSupply = handleCode(configs, factoryId, "1", "");
//        BigDecimal hourGetWater = handleCode(configs, factoryId, "0", "");
//
//        DateTime date = DateUtil.date();
//        DateTime dateTime = DateUtil.offsetHour(date, -1);
//
//        Wateryield wateryield = new Wateryield();
//        wateryield.setFactoryId(factoryId)
//                .setSumGetWater(sumGetWater)
//                .setSumWaterSupply(sumWaterSupply)
//                .setHourWaterSupply(hourWaterSupply)
//                .setUhour(DateUtil.format(dateTime, "yyyy-MM-dd HH") + ":00:00")
//                .setUday(DateUtil.format(dateTime, "yyyy-MM-dd"));
//
//        if (factoryId == oneFactory) {
//            wateryield.setHourGetWater(sumGetWater.subtract(handleCode(configs, twoFactory, "0", "")));
//        } else {
//            wateryield.setHourGetWater(hourGetWater);
//        }
//        wateryieldService.save(wateryield);
//    }
//
//    @Override
//    public List<Wateryield> saveBatchWaterYield(List<String> timeList, List<Wateryieldconfig> configs, Long factoryId, Long tableId) {
//
//        List<Wateryield> result = new ArrayList<>();
//        //厂家取水量配置
//        List<String> getWaterConfig = configs.stream()
//                .filter(c -> c.getFactory().equals(factoryId) && "0".equals(c.getFlag()))
//                .map(Wateryieldconfig::getItem).collect(Collectors.toList());
//        //厂家供水量配置
//        List<String> waterSupplyConfig = configs.stream()
//                .filter(c -> c.getFactory().equals(factoryId) && "1".equals(c.getFlag()))
//                .map(Wateryieldconfig::getItem).collect(Collectors.toList());
//        //总取水量配置
//        List<String> sumGetWaterConfig = configs.stream()
//                .filter(c -> c.getFactory().equals(factory) && "0".equals(c.getFlag()))
//                .map(Wateryieldconfig::getItem).collect(Collectors.toList());
//        //总供水量配置
//        List<String> sumWaterSupplyConfig = configs.stream()
//                .filter(c -> c.getFactory().equals(factory) && "0".equals(c.getFlag()))
//                .map(Wateryieldconfig::getItem).collect(Collectors.toList());
//
//        if (!timeList.isEmpty()) {
//            Wateryield wateryield;
//            for (String time : timeList) {
//                String formatTime = DateUtil.format(DateUtil.offsetHour(DateUtil.parse(time, "yyyy-MM-dd HH"), -1), "yyyy-MM-dd HH");
//                BigDecimal sumGetWater = handleCode(sumGetWaterConfig, formatTime);
//                BigDecimal sumWaterSupply = handleCode(sumWaterSupplyConfig, formatTime);
//                BigDecimal hourWaterSupply = handleCode(waterSupplyConfig, formatTime);
//                BigDecimal hourGetWater = handleCode(getWaterConfig, formatTime);
//
//                DateTime dateTime = DateUtil.offsetHour(DateUtil.parse(time, "yyyy-MM-dd HH:mm:ss"), -1);
//
//                wateryield = new Wateryield();
//                wateryield.setFactoryId(factoryId)
//                        .setSumGetWater(sumGetWater)
//                        .setSumWaterSupply(sumWaterSupply)
//                        .setHourWaterSupply(hourWaterSupply)
//                        .setUhour(DateUtil.format(dateTime, "yyyy-MM-dd HH") + ":00:00")
//                        .setId(tableId)
//                        .setUday(DateUtil.format(dateTime, "yyyy-MM-dd"));
//
//                if (factoryId == oneFactory) {
//                    wateryield.setHourGetWater(sumGetWater.subtract(handleCode(configs, twoFactory, "0", formatTime)));
//                } else {
//                    wateryield.setHourGetWater(hourGetWater);
//                }
//                tableId++;
//                result.add(wateryield);
//            }
//        }
//        return result;
//    }
//
//    /**
//     * 计算水量信息
//     *
//     * @param config    配置信息
//     * @param factoryId 厂家id
//     * @param flag      0 取水 1 供水
//     * @return Wateryield
//     */
//    @Override
//    public BigDecimal handleCode(List<Wateryieldconfig> config, Long factoryId, String flag, String time) {
//        //过滤并收集符合条件的指标编号
//        List<String> itemList = config.stream()
//                .filter(c -> c.getFactory().equals(factoryId) && flag.equals(c.getFlag()))
//                .map(Wateryieldconfig::getItem).collect(Collectors.toList());
//        return getBigDecimal(itemList, time);
//    }
//
//    @Override
//    public BigDecimal handleCode(List<String> config, String time) {
//        return getBigDecimal(config, time);
//    }
//
//    private BigDecimal getBigDecimal(List<String> config, String time) {
//        BigDecimal minVal = new BigDecimal(0);
//        BigDecimal maxVal = new BigDecimal(0);
//        if (!config.isEmpty()) {
//            for (String item : config) {
//
//                if (StringUtils.isEmpty(time)) {
//                    DateTime date = DateUtil.date();
//                    DateTime dateTime = DateUtil.offsetHour(date, -1);
//                    time = DateUtil.format(dateTime, "yyyy-MM-dd HH");
//                }
//                String mx = wateryieldMapper.getScadaItVal(item, time, "desc");
//                String mn = wateryieldMapper.getScadaItVal(item, time, null);
//
//                BigDecimal max = new BigDecimal(StringUtils.isEmpty(mx) ? "0" : mx);
//                BigDecimal min = new BigDecimal(StringUtils.isEmpty(mn) ? "0" : mn);
//
//                //获取指标前一个小时的最大最小值
//                maxVal = maxVal.add(max);
//                minVal = minVal.add(min);
//            }
//        }
//        return maxVal.subtract(minVal);
//    }
}
