package com.energy.manage.service.service.windenginegroup.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.EasyExcel;
import com.energy.manage.common.base.BaseServiceImpl;
import com.energy.manage.common.base.Page;
import com.energy.manage.common.constant.Constants;
import com.energy.manage.common.constant.redis.ManagerRedisKeyConstant;
import com.energy.manage.common.enums.DataSourceTypeEnum;
import com.energy.manage.common.enums.DeleteStatusEnum;
import com.energy.manage.common.enums.IdPrefixEnum;
import com.energy.manage.common.po.windenginegroup.WindEngineGroupPO;
import com.energy.manage.common.po.windenginemill.WindEngineMillPO;
import com.energy.manage.common.po.windfield.WindFieldPO;
import com.energy.manage.common.reponse.ResultResp;
import com.energy.manage.common.util.IdGeneratorUtil;
import com.energy.manage.service.domain.dto.windenginegroup.*;
import com.energy.manage.service.domain.dto.windfield.WindFieldCodeDto;
import com.energy.manage.service.domain.dto.windfield.WindFieldUpdateDto;
import com.energy.manage.service.domain.vo.analysis.AnalysisErrorCodeVo;
import com.energy.manage.service.domain.vo.anemometertower.AnemometerTowerByFieldVo;
import com.energy.manage.service.domain.vo.cockpit.WindFieldGroupTowerVo;
import com.energy.manage.service.domain.vo.excel.WindEngineGroupExcelVo;
import com.energy.manage.service.domain.vo.excel.WindFieldExceVo;
import com.energy.manage.service.domain.vo.windenginegroup.WindEngineGroupPageVo;
import com.energy.manage.service.domain.vo.windenginegroup.WindEngineGroupVo;
import com.energy.manage.service.domain.vo.windenginemill.WindEngineMillVo;
import com.energy.manage.service.domain.vo.windfield.WindFieldVo;
import com.energy.manage.service.mappers.windenginegroup.WindEngineGroupMapper;
import com.energy.manage.service.service.analysiserr.AnalysisErrService;
import com.energy.manage.service.service.anemometertower.AnemometerTowerService;
import com.energy.manage.service.service.cache.CacheService;
import com.energy.manage.service.service.windenginegroup.WindEngineGroupService;
import com.energy.manage.service.service.windenginemill.WindEngineMillService;
import com.energy.manage.service.service.windfield.WindFieldService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@Service
public class WindEngineGroupServiceImpl extends BaseServiceImpl<WindEngineGroupPO> implements WindEngineGroupService {


    @Autowired
    private CacheService cacheService;

    @Autowired
    private AnemometerTowerService anemometerTowerService;

    @Autowired
    private WindEngineGroupMapper windEngineGroupMapper;

    @Autowired
    private WindFieldService windFieldService;

    @Autowired
    private WindEngineMillService windEngineMillService;

    @Autowired
    private AnalysisErrService analysisErrService;

    /**
     * 手动创建风机机组信息
     *
     * @param windEngineGroupCreateDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createWindEngineGroup(WindEngineGroupCreateDto windEngineGroupCreateDto) {
        WindEngineGroupPO windEngineGroupPO = new WindEngineGroupPO();
        BeanUtil.copyProperties(windEngineGroupCreateDto, windEngineGroupPO);
        String number = IdPrefixEnum.WIND_GROUP_NUMBER.getCode().concat(IdGeneratorUtil.zeroFillUtil(cacheService.incr(ManagerRedisKeyConstant.build(ManagerRedisKeyConstant.IDGENERATOR_CONSTANTS_KEY, IdPrefixEnum.WIND_GROUP_NUMBER.getCode()))));
        windEngineGroupPO.setEngineCode(number);
        windEngineGroupPO.setCreateTime(new Date());
        windEngineGroupPO.setUpdateTime(new Date());
        windEngineGroupPO.setState(Constants.GLOBAL_IN_USE);
        windEngineGroupPO.setDelState(DeleteStatusEnum.NODELETE.getCode());
        windEngineGroupPO.setDataSource(DataSourceTypeEnum.TERRACE_SOURCE.getCode());
        // 风机机组客户内部编号（远景内部风机编号）
        if (!StringUtils.isEmpty(windEngineGroupCreateDto.getEngineId())) {
            windEngineGroupPO.setEngineId(windEngineGroupCreateDto.getEngineId());
        }
        if (windEngineGroupMapper.insertUseGeneratedKeys(windEngineGroupPO) <= 0) {
            return false;
        }
        // 处理总额定功率
        outerLoop:
        if (windEngineGroupCreateDto.getRatedCapacity() != null) {
            WindFieldCodeDto windFieldCodeDto = new WindFieldCodeDto();
            windFieldCodeDto.setFieldCode(windEngineGroupCreateDto.getFieldCode());
            WindFieldVo windFieldVo = windFieldService.getWindFieldVo(windFieldCodeDto);
            if (windFieldVo == null) {
                break outerLoop;
            }
            WindFieldUpdateDto windFieldUpdateDto = new WindFieldUpdateDto();
            windFieldUpdateDto.setFieldCode(windEngineGroupCreateDto.getFieldCode());
            double value = windFieldVo.getRatedCapacityNumber() == null ? 0 : windFieldVo.getRatedCapacityNumber().doubleValue();
            if (windEngineGroupCreateDto.getRatedCapacity() != null && windEngineGroupCreateDto.getRatedCapacity() > 0) {
                windFieldUpdateDto.setRatedCapacityNumber(value + windEngineGroupCreateDto.getRatedCapacity().doubleValue());
                windFieldService.updateWindField(windFieldUpdateDto);
            }
        }
        return true;
    }


    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultResp windEngineGroupImportData(MultipartFile file, String fieldCode, Integer userId) {
        List<WindEngineGroupExcelVo> windEngineGroupExcelVos = EasyExcel.read(file.getInputStream()).head(WindEngineGroupExcelVo.class).sheet().doReadSync();
        if (CollectionUtils.isEmpty(windEngineGroupExcelVos)) {
            return ResultResp.FAIL("未读取到文件数据，请核对数据准确性！");
        }
        // 过滤空数据
        List<WindEngineGroupExcelVo> windEngineGroupExceVoList = windEngineGroupExcelVos.stream().filter(item ->
                !StringUtils.isEmpty(item.getEngineName())).collect(Collectors.toList());

        // 校验数据非空
        for (WindEngineGroupExcelVo exceVo : windEngineGroupExceVoList) {
            if (exceVo.getLongitude() == null || exceVo.getLatitude() == null || StringUtils.isEmpty(exceVo.getMachineTypeCode())) {
                return ResultResp.FAIL("当前导入风机数据未填写经纬度，请核查导入数据！");
            }
        }

        // 校验是否有重复的风机编号
        Set<String> engineNames = windEngineGroupExceVoList.stream().map(item -> item.getEngineName()).collect(Collectors.toSet());
        if (windEngineGroupExceVoList.size() != engineNames.size()) {
            return ResultResp.FAIL("当前导入风机数据有重复风机编号，请核查导入数据！");
        }

        // 处理机型编号
        List<String> millTypeCodes = windEngineGroupExceVoList.stream().map(item -> item.getMachineTypeCode()).collect(Collectors.toList());
        List<WindEngineMillVo> windEngineMillVoList = windEngineMillService.getWindEngineMillListByInMachineTypeCode(millTypeCodes);
        //校验机型准确性
        for (String millTypeCode : millTypeCodes) {
            boolean flg = windEngineMillVoList.stream().anyMatch(item -> item.getMachineTypeCode().equals(millTypeCode));
            if (!flg) {
                return ResultResp.FAIL("当前导入机型编号系统中不存在，请核查导入数据！");
            }
        }
        for (WindEngineGroupExcelVo windEngineGroupExcelVo : windEngineGroupExceVoList) {
            for (WindEngineMillVo windEngineMillVo : windEngineMillVoList) {
                if (windEngineGroupExcelVo.getMachineTypeCode().equals(windEngineMillVo.getMachineTypeCode())) {
                    windEngineGroupExcelVo.setMillTypeCode(windEngineMillVo.getMillTypeCode());
                }
            }
        }

        // 数据校验是否有重名风机编号
        List<String> engineNamees = windEngineGroupExceVoList.stream().map(item -> item.getEngineName()).collect(Collectors.toList());
        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("fieldCode", fieldCode);
        criteria.andIn("engineName", engineNamees);
        criteria.andEqualTo("delState", DeleteStatusEnum.NODELETE.getCode());
        int count = windEngineGroupMapper.selectCountByExample(queryExample);
        if (count > 0) {
            return ResultResp.FAIL("当前风场中有存在的风机，请核查导入数据！");
        }

        WindEngineGroupPO windEngineGroupPO = null;
        List<WindEngineGroupPO> list = Lists.newArrayList();
        for (WindEngineGroupExcelVo windFieldExceVos : windEngineGroupExceVoList) {
            windEngineGroupPO = new WindEngineGroupPO();
            BeanUtil.copyProperties(windFieldExceVos, windEngineGroupPO);
            String number = IdPrefixEnum.WIND_GROUP_NUMBER.getCode().concat(IdGeneratorUtil.zeroFillUtil(cacheService.incr(ManagerRedisKeyConstant.build(ManagerRedisKeyConstant.IDGENERATOR_CONSTANTS_KEY, IdPrefixEnum.WIND_GROUP_NUMBER.getCode()))));
            windEngineGroupPO.setEngineCode(number);
            windEngineGroupPO.setFieldCode(fieldCode);
            windEngineGroupPO.setCreateTime(new Date());
            windEngineGroupPO.setUpdateTime(new Date());
            windEngineGroupPO.setState(Constants.GLOBAL_IN_USE);
            windEngineGroupPO.setDelState(DeleteStatusEnum.NODELETE.getCode());
            if (windFieldExceVos.getSightcingString().equals("是")) {
                windEngineGroupPO.setSightcing(1);
            }
            if (windFieldExceVos.getSightcingString().equals("否")) {
                windEngineGroupPO.setSightcing(2);
            }
            windEngineGroupPO.setCreateBy(userId);
            windEngineGroupPO.setDataSource(DataSourceTypeEnum.UPLOAD_SOURCE.getCode());
            // 风机机组客户内部编号（远景内部风机编号）
            if (!StringUtils.isEmpty(windFieldExceVos.getEngineId())) {
                windEngineGroupPO.setEngineId(windFieldExceVos.getEngineId());
            }
            list.add(windEngineGroupPO);
        }
        if (CollectionUtils.isEmpty(list)) {
            return ResultResp.FAIL("数据处理异常！");
        }
        if (windEngineGroupMapper.insertList(list) <= 0) {
            return ResultResp.FAIL();
        }
        return ResultResp.SUCCESS();
    }

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultResp windEngineGroupAndIdImportData(MultipartFile file, String fieldCode, Integer userId) {
        List<WindEngineGroupExcelVo> windEngineGroupExcelVos = EasyExcel.read(file.getInputStream()).head(WindEngineGroupExcelVo.class).sheet().doReadSync();
        if (CollectionUtils.isEmpty(windEngineGroupExcelVos)) {
            return ResultResp.FAIL("未读取到文件数据，请核对数据准确性！");
        }
        // 过滤空数据
        List<WindEngineGroupExcelVo> windEngineGroupExceVoList = windEngineGroupExcelVos.stream().filter(item ->
                !StringUtils.isEmpty(item.getEngineName())).collect(Collectors.toList());

        // 校验数据非空
        for (WindEngineGroupExcelVo exceVo : windEngineGroupExceVoList) {
            if (exceVo.getLongitude() == null || exceVo.getLatitude() == null || StringUtils.isEmpty(exceVo.getMachineTypeCode())) {
                return ResultResp.FAIL("当前导入风机数据未填写经纬度，请核查导入数据！");
            }
        }

        // 校验是否有重复的风机编号
        Set<String> engineNames = windEngineGroupExceVoList.stream().map(item -> item.getEngineName()).collect(Collectors.toSet());
        if (windEngineGroupExceVoList.size() != engineNames.size()) {
            return ResultResp.FAIL("当前导入风机数据有重复风机编号，请核查导入数据！");
        }

        //处理客户风机内部编号问题
        Set<String> engineIdSet = windEngineGroupExceVoList.stream()
                .filter(item -> item.getEngineId() != null)
                .map(WindEngineGroupExcelVo::getEngineId)
                .collect(Collectors.toSet());
        if (engineIdSet == null || engineIdSet.size() != windEngineGroupExceVoList.size()) {
            return ResultResp.FAIL(" 当前导入风机数据内部风机ID不正确，请核查导入数据！");
        }

        // TODO 增加客户内部风机id校验，调用亮亮接口




        // 处理机型编号
        List<String> millTypeCodes = windEngineGroupExceVoList.stream().map(item -> item.getMachineTypeCode()).collect(Collectors.toList());
        List<WindEngineMillVo> windEngineMillVoList = windEngineMillService.getWindEngineMillListByInMachineTypeCode(millTypeCodes);
        //校验机型准确性
        for (String millTypeCode : millTypeCodes) {
            boolean flg = windEngineMillVoList.stream().anyMatch(item -> item.getMachineTypeCode().equals(millTypeCode));
            if (!flg) {
                return ResultResp.FAIL("当前导入机型编号系统中不存在，请核查导入数据！");
            }
        }
        for (WindEngineGroupExcelVo windEngineGroupExcelVo : windEngineGroupExceVoList) {
            for (WindEngineMillVo windEngineMillVo : windEngineMillVoList) {
                if (windEngineGroupExcelVo.getMachineTypeCode().equals(windEngineMillVo.getMachineTypeCode())) {
                    windEngineGroupExcelVo.setMillTypeCode(windEngineMillVo.getMillTypeCode());
                }
            }
        }

        // 数据校验是否有重名风机编号
        List<String> engineNamees = windEngineGroupExceVoList.stream().map(item -> item.getEngineName()).collect(Collectors.toList());
        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("fieldCode", fieldCode);
        criteria.andIn("engineName", engineNamees);
        criteria.andEqualTo("delState", DeleteStatusEnum.NODELETE.getCode());
        int count = windEngineGroupMapper.selectCountByExample(queryExample);
        if (count > 0) {
            return ResultResp.FAIL("当前风场中有存在的风机，请核查导入数据！");
        }

        WindEngineGroupPO windEngineGroupPO = null;
        List<WindEngineGroupPO> list = Lists.newArrayList();
        for (WindEngineGroupExcelVo windFieldExceVos : windEngineGroupExceVoList) {
            windEngineGroupPO = new WindEngineGroupPO();
            BeanUtil.copyProperties(windFieldExceVos, windEngineGroupPO);
            String number = IdPrefixEnum.WIND_GROUP_NUMBER.getCode().concat(IdGeneratorUtil.zeroFillUtil(cacheService.incr(ManagerRedisKeyConstant.build(ManagerRedisKeyConstant.IDGENERATOR_CONSTANTS_KEY, IdPrefixEnum.WIND_GROUP_NUMBER.getCode()))));
            windEngineGroupPO.setEngineCode(number);
            windEngineGroupPO.setFieldCode(fieldCode);
            windEngineGroupPO.setCreateTime(new Date());
            windEngineGroupPO.setUpdateTime(new Date());
            windEngineGroupPO.setState(Constants.GLOBAL_IN_USE);
            windEngineGroupPO.setDelState(DeleteStatusEnum.NODELETE.getCode());
            if (windFieldExceVos.getSightcingString().equals("是")) {
                windEngineGroupPO.setSightcing(1);
            }
            if (windFieldExceVos.getSightcingString().equals("否")) {
                windEngineGroupPO.setSightcing(2);
            }
            windEngineGroupPO.setCreateBy(userId);
            windEngineGroupPO.setDataSource(DataSourceTypeEnum.UPLOAD_SOURCE.getCode());
            // 风机机组客户内部编号（远景内部风机编号）
            if (!StringUtils.isEmpty(windFieldExceVos.getEngineId())) {
                windEngineGroupPO.setEngineId(windFieldExceVos.getEngineId());
            }
            list.add(windEngineGroupPO);
        }
        if (CollectionUtils.isEmpty(list)) {
            return ResultResp.FAIL("数据处理异常！");
        }
        if (windEngineGroupMapper.insertList(list) <= 0) {
            return ResultResp.FAIL();
        }
        return ResultResp.SUCCESS();
    }


    @Override
    public Page<WindEngineGroupPageVo> windEngineGrouPage(WindEngineGroupPageDto windEngineGroupPageDto) {
        PageHelper.startPage(windEngineGroupPageDto.getPageNum(), windEngineGroupPageDto.getPageSize());
        List<WindEngineGroupPageVo> list = windEngineGroupMapper.selectWindEngineGroupByNames(windEngineGroupPageDto);
        Long total = org.apache.commons.collections.CollectionUtils.isEmpty(list) ? 0L : new PageInfo<>(list).getTotal();
        return Page.build(windEngineGroupPageDto.getPageNum(), windEngineGroupPageDto.getPageSize(), total, list);
    }

    @Override
    public List<WindEngineGroupPageVo> getWindEngineGroupListByFieldCode(WindEngineGroupPageDto windEngineGroupPageDto) {
        return windEngineGroupMapper.selectWindEngineGroupListByFieldCode(windEngineGroupPageDto.getFieldCode());
    }

    @Override
    public Page<WindEngineGroupPageVo> getWindEngineGroupRatedListByFieldCodePage(WindEngineGroupPageDto windEngineGroupPageDto) {

        PageHelper.startPage(windEngineGroupPageDto.getPageNum(), windEngineGroupPageDto.getPageSize());
        List<WindEngineGroupPageVo> list = windEngineGroupMapper.selectWindEngineGroupRatedListByFieldCode(windEngineGroupPageDto.getFieldCode());
        Long total = org.apache.commons.collections.CollectionUtils.isEmpty(list) ? 0L : new PageInfo<>(list).getTotal();
        return Page.build(windEngineGroupPageDto.getPageNum(), windEngineGroupPageDto.getPageSize(), total, list);

    }

    @Override
    public WindFieldGroupTowerVo getWindEngineGroupByFieldCode(String fieldCode, String batchCode) {

        WindFieldGroupTowerVo windFieldGroupTowerVo = new WindFieldGroupTowerVo();

        // 处理风机信息
        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("fieldCode", fieldCode);
        criteria.andEqualTo("delState", DeleteStatusEnum.NODELETE.getCode());
        List<WindEngineGroupPO> engineGroupPOS = windEngineGroupMapper.selectByExample(queryExample);
        if (CollectionUtils.isEmpty(engineGroupPOS)) {
            return null;
        }
        WindEngineGroupVo windEngineGroupVo = null;
        List<WindEngineGroupVo> engineGroupVoArrayList = Lists.newArrayList();
        for (WindEngineGroupPO po : engineGroupPOS) {
            windEngineGroupVo = new WindEngineGroupVo();
            BeanUtil.copyProperties(po, windEngineGroupVo);
            if (windEngineGroupVo.getLongitude() != null && windEngineGroupVo.getLatitude() != null) {
                DecimalFormat df = new DecimalFormat("#.00000");
                String longitude = df.format(windEngineGroupVo.getLongitude());
                String latitude = df.format(windEngineGroupVo.getLatitude());
                windEngineGroupVo.setLongitudeAndLatitudeString(longitude + "," + latitude);
            }
            engineGroupVoArrayList.add(windEngineGroupVo);
        }
        windFieldGroupTowerVo.setWindEngineGroupVoList(engineGroupVoArrayList);

        // 处理测风塔信息
        List<AnemometerTowerByFieldVo> anemometerTowerByFields = anemometerTowerService.getAnemometerTowerByField(fieldCode);
        if (!CollectionUtils.isEmpty(anemometerTowerByFields)) {
            for (AnemometerTowerByFieldVo vo : anemometerTowerByFields) {
                if (vo.getLongitude() != null && vo.getLatitude() != null) {
                    DecimalFormat df = new DecimalFormat("#.00000");
                    String longitude = df.format(vo.getLongitude());
                    String latitude = df.format(vo.getLatitude());
                    vo.setLongitudeAndLatitudeString(longitude + "," + latitude);
                }
            }
            windFieldGroupTowerVo.setAnemometerTowerList(anemometerTowerByFields);
        }

        // 处理批次异常状体
        List<AnalysisErrorCodeVo> analysisErrorCodeVoList = analysisErrService.AnalysisErrorCodeQuery(batchCode);
        if (!CollectionUtils.isEmpty(analysisErrorCodeVoList)) {
            for (WindEngineGroupVo wgVo : windFieldGroupTowerVo.getWindEngineGroupVoList()) {
                for (AnalysisErrorCodeVo errorCodeVo : analysisErrorCodeVoList) {
                    if (wgVo.getEngineCode().equals(errorCodeVo.getEngineCode())) {
                        wgVo.setErrorState(true);
                    }
                }
            }
        }

        return windFieldGroupTowerVo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delWindEngineGroup(WindEngineGroupCodeDto windEngineGroupCodeDto) {
        WindEngineGroupPO po = new WindEngineGroupPO();
        po.setDelState(DeleteStatusEnum.DELETE.getCode());
        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("engineCode", windEngineGroupCodeDto.getEngineCode());
        if (windEngineGroupMapper.updateByExampleSelective(po, queryExample) <= 0) {
            return false;
        }
        // 处理总额定功率
        WindEngineGroupPO windEngineGroupPO = new WindEngineGroupPO();
        windEngineGroupPO.setEngineCode(windEngineGroupCodeDto.getEngineCode());
        WindEngineGroupPO windEngineGroup = windEngineGroupMapper.selectOne(windEngineGroupPO);
        outerLoop:
        if (windEngineGroup.getRatedCapacity() != null) {
            WindFieldCodeDto windFieldCodeDto = new WindFieldCodeDto();
            windFieldCodeDto.setFieldCode(windEngineGroup.getFieldCode());
            WindFieldVo windFieldVo = windFieldService.getWindFieldVo(windFieldCodeDto);
            if (windFieldVo == null) {
                break outerLoop;
            }
            WindFieldUpdateDto windFieldUpdateDto = new WindFieldUpdateDto();
            windFieldUpdateDto.setFieldCode(windFieldCodeDto.getFieldCode());
            double value = windFieldVo.getRatedCapacityNumber() == null ? 0 : windFieldVo.getRatedCapacityNumber().doubleValue();
            if (windEngineGroup.getRatedCapacity() != null && value > windEngineGroup.getRatedCapacity()) {
                windFieldUpdateDto.setRatedCapacityNumber(value - windEngineGroup.getRatedCapacity().doubleValue());
                windFieldService.updateWindField(windFieldUpdateDto);
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStateWindEngineGroup(WindEngineGroupStateDto windEngineGroupStateDto) {
        WindEngineGroupPO po = new WindEngineGroupPO();
        po.setState(windEngineGroupStateDto.getState());
        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("engineCode", windEngineGroupStateDto.getEngineCode());
        return windEngineGroupMapper.updateByExampleSelective(po, queryExample) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWindEngineGroup(WindEngineGroupUpdateDto windEngineGroupUpdateDto) {

        WindEngineGroupPO po = new WindEngineGroupPO();
        BeanUtil.copyProperties(windEngineGroupUpdateDto, po);
        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("engineCode", windEngineGroupUpdateDto.getEngineCode());

        // 查询当前风机信息
        WindEngineGroupPO windEngineGroupPO = new WindEngineGroupPO();
        windEngineGroupPO.setEngineCode(windEngineGroupUpdateDto.getEngineCode());
        WindEngineGroupPO windEngineGroup = windEngineGroupMapper.selectOne(windEngineGroupPO);

        if (windEngineGroupMapper.updateByExampleSelective(po, queryExample) <= 0) {
            return false;
        }

        // 处理总额定功率
        outerLoop:
        if (windEngineGroup.getRatedCapacity().doubleValue() == windEngineGroupUpdateDto.getRatedCapacity().doubleValue()) {
            return true;
        } else {
            WindFieldCodeDto windFieldCodeDto = new WindFieldCodeDto();
            windFieldCodeDto.setFieldCode(windEngineGroup.getFieldCode());
            WindFieldVo windFieldVo = windFieldService.getWindFieldVo(windFieldCodeDto);
            if (windFieldVo == null) {
                break outerLoop;
            }
            WindFieldUpdateDto windFieldUpdateDto = new WindFieldUpdateDto();
            windFieldUpdateDto.setFieldCode(windFieldCodeDto.getFieldCode());
            double value = windFieldVo.getRatedCapacityNumber() == null ? 0 : windFieldVo.getRatedCapacityNumber().doubleValue();
            if (windEngineGroup.getRatedCapacity().doubleValue() < windEngineGroupUpdateDto.getRatedCapacity().doubleValue()) {
                double less = NumberUtil.round(windEngineGroupUpdateDto.getRatedCapacity().doubleValue() - windEngineGroup.getRatedCapacity().doubleValue(), 2).doubleValue();
                windFieldUpdateDto.setRatedCapacityNumber(value + less);
                windFieldService.updateWindField(windFieldUpdateDto);
            }
            if (windEngineGroup.getRatedCapacity().doubleValue() > windEngineGroupUpdateDto.getRatedCapacity().doubleValue()) {
                double greater = NumberUtil.round(windEngineGroup.getRatedCapacity().doubleValue() - windEngineGroupUpdateDto.getRatedCapacity().doubleValue(), 2).doubleValue();
                if (value > windEngineGroup.getRatedCapacity()) {
                    windFieldUpdateDto.setRatedCapacityNumber(value - greater);
                    windFieldService.updateWindField(windFieldUpdateDto);
                }
            }
        }

        return true;
    }

    @Override
    public boolean updateWindEngineGroupList(WindEngineGroupBathUpdateDto windEngineGroupBathUpdateDto) {
        return windEngineGroupMapper.updateWindEngineGroupList(windEngineGroupBathUpdateDto.getWindEngineGroupUpdateDtoList()) > 0 ? true : false;
    }

    @Override
    public WindEngineGroupVo getWindEngineGroup(WindEngineGroupCodeDto windEngineGroupCodeDto) {
        WindEngineGroupPO po = new WindEngineGroupPO();
        po.setEngineCode(windEngineGroupCodeDto.getEngineCode());
        WindEngineGroupPO windEngineGroupPO = windEngineGroupMapper.selectOne(po);
        if (windEngineGroupPO == null) {
            return null;
        }
        WindEngineGroupVo windEngineGroupVo = new WindEngineGroupVo();
        BeanUtil.copyProperties(windEngineGroupPO, windEngineGroupVo);
        return windEngineGroupVo;
    }

    @Override
    public int getWindEngineGroupCountByField(String fieldCode) {
        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("fieldCode", fieldCode);
        return windEngineGroupMapper.selectCountByExample(queryExample);

    }


    @Override
    public List<WindEngineGroupVo> getWindEngineGroupByRoleId(Integer roleId) {
        return windEngineGroupMapper.selectWindEngineGroupByRoleId(roleId);
    }


    @Override
    public int getCountWindEngineGroupByCode(String engineName, String fieldCode) {

        Example queryExample = new Example(WindEngineGroupPO.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("fieldCode", fieldCode);
        criteria.andEqualTo("engineName", engineName);
        criteria.andEqualTo("delState", DeleteStatusEnum.NODELETE.getCode());
        return windEngineGroupMapper.selectCountByExample(queryExample);

    }


}
