package com.hdkj.lt.bf.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdkj.lt.base.exception.BusinessException;
import com.hdkj.lt.bf.entity.convert.DTOToEntityConvertor;
import com.hdkj.lt.bf.entity.convert.EntityToVOConvertor;
import com.hdkj.lt.bf.entity.dto.SwitchContactEffectiveUpdateBatchRequest;
import com.hdkj.lt.bf.entity.dto.SwitchInfoListRequest;
import com.hdkj.lt.bf.entity.dto.SwitchInfoUpdateRequest;
import com.hdkj.lt.bf.entity.vo.FeederSwitchInfoVO;
import com.hdkj.lt.bf.entity.vo.SwitchIndoPageVO;
import com.hdkj.lt.bf.entity.vo.SwitchInfoVO;
import com.hdkj.lt.bf.mapper.DwdShbDsSwitchBaseMapper;
import com.hdkj.lt.bf.service.DwdShbDsSwitchBaseService;
import com.hdkj.lt.bf.service.IDisableLlkgConfigService;
import com.hdkj.lt.core.bizms.modle.po.DisableLlkgConfig;
import com.hdkj.lt.core.bizms.modle.po.DwdShbDsSwitchBase;
import com.hdkj.lt.core.bizms.modle.po.FhzgSwitchProtectionSettings;
import com.hdkj.lt.core.sys.dao.FhzgOrganSuffixMapper;
import com.hdkj.lt.core.sys.service.SwitchProtectionSettingsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Sunlit
 * @description 针对表【dwd_shb_ds_switch_base(配电开关台账台账信息)】的数据库操作Service实现
 * @createDate 2025-06-26 17:19:37
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DwdShbDsSwitchBaseServiceImpl extends ServiceImpl<DwdShbDsSwitchBaseMapper, DwdShbDsSwitchBase>
        implements DwdShbDsSwitchBaseService {

    private final SwitchProtectionSettingsService switchProtectionSettingsService;

    private final IDisableLlkgConfigService disableLlkgConfigService;

    private final FhzgOrganSuffixMapper fhzgOrganSuffixMapper;

    @Override
    public SwitchIndoPageVO getSwitchInfoList(SwitchInfoListRequest request) {
        Page<DwdShbDsSwitchBase> page = new Page<>();
        page.setCurrent(request.getPageNum());
        page.setSize(request.getPageSize());
        LambdaQueryWrapper<DwdShbDsSwitchBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(request.getFeederName()), DwdShbDsSwitchBase::getFeederName, request.getFeederName())
                .like(StringUtils.isNotEmpty(request.getSwitchName()), DwdShbDsSwitchBase::getName, request.getSwitchName())
                .like(StringUtils.isNotEmpty(request.getSwitchId()), DwdShbDsSwitchBase::getPsrId, request.getSwitchId())
                .eq(StringUtils.isNotEmpty(request.getMaintOrg()), DwdShbDsSwitchBase::getMaintOrg, request.getMaintOrg());
        Page<DwdShbDsSwitchBase> switchInfoList = this.page(page, wrapper);
        SwitchIndoPageVO result = new SwitchIndoPageVO();
        List<SwitchInfoVO> switchInfoVOList = EntityToVOConvertor.INSTANCE.toSwitchInfoVOList(switchInfoList.getRecords());

        List<String> switchIdList = switchInfoList.getRecords().stream().map(DwdShbDsSwitchBase::getPsrId).collect(Collectors.toList());
        if (!switchIdList.isEmpty()) {
            List<FhzgSwitchProtectionSettings> switchProtectionSettingsList = switchProtectionSettingsService.list(new LambdaQueryWrapper<FhzgSwitchProtectionSettings>().in(FhzgSwitchProtectionSettings::getDevicePrsId, switchIdList));
            Map<String, FhzgSwitchProtectionSettings> map = switchProtectionSettingsList.stream().collect(Collectors.toMap(FhzgSwitchProtectionSettings::getDevicePrsId, i -> i));
            List<SwitchInfoVO> collect = switchInfoVOList.stream().map(i -> EntityToVOConvertor.INSTANCE.FhzgSwitchProtectionSettingstoSwitchInfoVOList(i, map.get(i.getSwitchId()))).collect(Collectors.toList());
            result.setSwitchInfoVOList(collect);
        } else {
            result.setSwitchInfoVOList(switchInfoVOList);
        }
        result.setTotal(switchInfoList.getTotal());
        result.setPageNum(request.getPageNum());
        result.setPageSize(request.getPageSize());
        return result;
    }

    @Override
    public String updateSwitchInfo(SwitchInfoUpdateRequest request) {
        String prsId = request.getSwitchId();
        Optional.ofNullable(prsId).orElseThrow(() -> new BusinessException("开关主键为空"));
        FhzgSwitchProtectionSettings switchInfoUpdateRequest = DTOToEntityConvertor.INSTANCE.toSwitchInfoUpdateRequest(request);
        try {
            switchInfoUpdateRequest.setOc1Value(getNumString(switchInfoUpdateRequest.getOc1Value()));
            switchInfoUpdateRequest.setOc1Delay(getNumString(switchInfoUpdateRequest.getOc1Delay()));
            switchInfoUpdateRequest.setOc2Value(getNumString(switchInfoUpdateRequest.getOc2Value()));
            switchInfoUpdateRequest.setOc2Delay(getNumString(switchInfoUpdateRequest.getOc2Delay()));
            switchInfoUpdateRequest.setOc3Value(getNumString(switchInfoUpdateRequest.getOc3Value()));
            switchInfoUpdateRequest.setOc3Delay(getNumString(switchInfoUpdateRequest.getOc3Delay()));
        } catch (Exception e) {
            throw new BusinessException("参数不合法");
        }
        switchInfoUpdateRequest.setLastTime(new Date());
        FhzgSwitchProtectionSettings switchProtectionSettings = switchProtectionSettingsService.getOne(new LambdaQueryWrapper<FhzgSwitchProtectionSettings>().eq(FhzgSwitchProtectionSettings::getDevicePrsId, switchInfoUpdateRequest.getDevicePrsId()));
        if(switchProtectionSettings != null) {
            switchProtectionSettingsService.update(switchInfoUpdateRequest, new LambdaUpdateWrapper<FhzgSwitchProtectionSettings>().eq(FhzgSwitchProtectionSettings::getDevicePrsId, switchInfoUpdateRequest.getDevicePrsId()));
        }else {
            switchProtectionSettingsService.save(switchInfoUpdateRequest);
        }
        //更新联络开关是否有效字段
        String contactEffective = request.getContactEffective();
        if (StrUtil.isNotBlank(contactEffective)) {
            //更新联络开关是否有效值  配置类型：0-系统判定无效,1-人工设置无效,2-系统判定有效,3-人工设置有效
            LambdaUpdateWrapper<DisableLlkgConfig> wrapper = setUpdateContactEffective(contactEffective);
            wrapper.eq(DisableLlkgConfig::getLlsbId, prsId);
            disableLlkgConfigService.update(wrapper);
        }
        return "修改成功";
    }

    /**
     * @author luorui
     * @date 2025/8/8 9:06
     * @discription 分页查询开关配置信息，包含是否为联络开关
     **/
    @Override
    public SwitchIndoPageVO getSwitchInfoPageByCondition(SwitchInfoListRequest request) {
        Page page = new Page<>();
        page.setCurrent(request.getPageNum());
        page.setSize(request.getPageSize());
        // 动态切换topo表名
//        String maintOrg = request.getMaintOrg();
//        ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByMaintOrg(maintOrg));
        Page<SwitchInfoVO> pageResult = baseMapper.getSwitchInfoPageByCondition(page, request);
        SwitchIndoPageVO result = new SwitchIndoPageVO();
        result.setSwitchInfoVOList(pageResult.getRecords());
        result.setTotal(pageResult.getTotal());
        result.setPageNum(request.getPageNum());
        result.setPageSize(request.getPageSize());
        return result;
    }

    @Override
    public List<SwitchInfoVO> getSwitchInfoByCondition(SwitchInfoListRequest request) {
//        String maintOrg = request.getMaintOrg();
//        ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByMaintOrg(maintOrg));
        List<SwitchInfoVO> result = baseMapper.getSwitchInfoByCondition(request);
        return result;
    }

    /**
     * @author luorui
     * @date 2025/8/8 9:43
     * @discription 批量更新联络是否有效
     **/
    @Override
    public String updateContactEffectiveBatch(SwitchContactEffectiveUpdateBatchRequest request) {
        List<String> prsIdList = request.getSwitchIdList();
        String contactEffective = request.getContactEffective();
        if (CollUtil.isEmpty(prsIdList)) {
            throw new BusinessException("开关id列表为空");
        }
        if (StrUtil.isBlank(contactEffective)) {
            throw new BusinessException("开关是否有效字段为空");
        }
        LambdaUpdateWrapper<DisableLlkgConfig> wrapper = setUpdateContactEffective(contactEffective);
        wrapper.in(DisableLlkgConfig::getLlsbId, prsIdList);
        disableLlkgConfigService.update(wrapper);
        return "批量更新完成";
    }

    private LambdaUpdateWrapper<DisableLlkgConfig> setUpdateContactEffective(String contactEffective) {
        LambdaUpdateWrapper<DisableLlkgConfig> wrapper = Wrappers.lambdaUpdate();
        wrapper.set(DisableLlkgConfig::getLastTime, LocalDateTime.now());
        if (StrUtil.equals("0", contactEffective)) {//无效，数据库更新成“1”
            wrapper.set(DisableLlkgConfig::getLlsbType, "1");
        }
        if (StrUtil.equals("1", contactEffective)) {//有效，数据库更新成“3”
            wrapper.set(DisableLlkgConfig::getLlsbType, "3");
        }
        return wrapper;
    }

    private String getNumString(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        return new BigDecimal(str).stripTrailingZeros().toPlainString();
    }

    @Override
    public List<FeederSwitchInfoVO> getSwitchListByFeederId(String feederId) {
        FeederSwitchInfoVO startSwitchInfoVO = this.baseMapper.getStartSwitchInfoByFeederId(feederId);
        List<FeederSwitchInfoVO> switchListByFeederId = this.baseMapper.getSwitchListByFeederId(feederId);
        List<FeederSwitchInfoVO> result = new ArrayList<>();
        sortSwitchInfo(result,switchListByFeederId,startSwitchInfoVO.getPsrId());
        result.add(0, startSwitchInfoVO);
        return result.stream().filter(i -> Arrays.asList("PD_30500000", "PD_30700000", "PD_11100000").contains(i.getPsrType())).collect(Collectors.toList());
    }

    private void sortSwitchInfo(List<FeederSwitchInfoVO> result, List<FeederSwitchInfoVO> switchListByFeederId, String pid) {
        List<FeederSwitchInfoVO> collect = switchListByFeederId.stream().filter(i -> pid.equals(i.getPid())).collect(Collectors.toList());
        if (collect.isEmpty()) {
            return;
        }
        result.addAll(collect);
        collect.forEach(i -> sortSwitchInfo(result, switchListByFeederId, i.getPsrId()));
    }

    /**
     *
     * @author luorui
     * @date 2025/9/15 16:03
     * @discription 根据prsIs批量新增或更新
     *
     **/
    @Override
    @Transactional
    public int saveOrUpdateBatchByPrsId(List<FhzgSwitchProtectionSettings> fhzgSwitchProtectionSettingsList) {
         int result = 0;
        //1.查询过滤掉不在台账数据中的prsId
        if(CollUtil.isEmpty(fhzgSwitchProtectionSettingsList)){
            log.info("开关信息待保存数据集为空");
            return result;
        }
        List<String> prsIdListAll = fhzgSwitchProtectionSettingsList.stream().map(FhzgSwitchProtectionSettings::getDevicePrsId).collect(Collectors.toList());
        log.info("excel文件中记录条数:{}", prsIdListAll.size());
        LambdaQueryWrapper<DwdShbDsSwitchBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DwdShbDsSwitchBase::getPsrId, prsIdListAll);
        wrapper.select(DwdShbDsSwitchBase::getPsrId);
        List<DwdShbDsSwitchBase> dwdShbDsSwitchBaseList = this.list(wrapper);
        Set<String> prsIdBase = dwdShbDsSwitchBaseList.stream().map(DwdShbDsSwitchBase::getPsrId).collect(Collectors.toSet());//去重后的 prsId
        Set<String> distinctSet = new HashSet<>();//用于去重的空Set
        List<FhzgSwitchProtectionSettings> fhzgSwitchProtectionSettingInBase = fhzgSwitchProtectionSettingsList.stream().filter(e -> prsIdBase.contains(e.getDevicePrsId()) && distinctSet.add(e.getDevicePrsId())).collect(Collectors.toList());//最终需要处理的数据,根据prsId去重(利用Set集合去重，保留首次出现的元素)
        //2. 将数据分为两组更新的数据和新增的数据
        if(CollUtil.isEmpty(fhzgSwitchProtectionSettingInBase)){
            log.info("导入的数据prsId都不在台账数据中");
            return result;
        } else {
            result = fhzgSwitchProtectionSettingInBase.size();
            log.info("去重过滤后待更新和新增的开关信息条数:{}",fhzgSwitchProtectionSettingInBase.size());
        }
        List<String> prsIdListSettingAll = fhzgSwitchProtectionSettingInBase.stream().map(FhzgSwitchProtectionSettings::getDevicePrsId).collect(Collectors.toList());

        LambdaQueryWrapper<FhzgSwitchProtectionSettings> wrapperSwitchSetting = new LambdaQueryWrapper<>();
        wrapperSwitchSetting.in(FhzgSwitchProtectionSettings::getDevicePrsId, prsIdListSettingAll);
        wrapperSwitchSetting.select(FhzgSwitchProtectionSettings::getDevicePrsId);

        List<FhzgSwitchProtectionSettings> switchProtectionSettingsForUpdateFromDB = switchProtectionSettingsService.getBaseMapper().selectList(wrapperSwitchSetting);
        //需要更新的数据集合,和需要新增的数据集合分开
        List<FhzgSwitchProtectionSettings>  switchProtectionSettingsForUpdate = new ArrayList<>();
        List<FhzgSwitchProtectionSettings>  switchProtectionSettingsForSave = new ArrayList<>();
        if (CollUtil.isEmpty(switchProtectionSettingsForUpdateFromDB)) {
            //全部是需要新增的数据
            switchProtectionSettingsForSave.addAll(fhzgSwitchProtectionSettingInBase);
            log.info("新增的开关信息条数:{}",switchProtectionSettingsForSave.size());
        } else {
            List<String> prsIdListSettingForUpdate = switchProtectionSettingsForUpdateFromDB.stream().map(FhzgSwitchProtectionSettings::getDevicePrsId).distinct().collect(Collectors.toList());
            fhzgSwitchProtectionSettingInBase.forEach(e -> {
                if ( prsIdListSettingForUpdate.contains(e.getDevicePrsId())) {
                    switchProtectionSettingsForUpdate.add(e);
                } else {
                    switchProtectionSettingsForSave.add(e);
                }
            });
        }
        //3.分别新增和更新数据
        if(CollUtil.isNotEmpty(switchProtectionSettingsForUpdate)){
            switchProtectionSettingsService.updateBatchByPrsId(switchProtectionSettingsForUpdate);
            log.info("更新开关信息条数:{}",switchProtectionSettingsForUpdate.size());
        }
        if(CollUtil.isNotEmpty(switchProtectionSettingsForSave)){
            switchProtectionSettingsService.saveBatch(switchProtectionSettingsForSave);
            log.info("新增开关信息条数:{}",switchProtectionSettingsForSave.size());
        }
        return result;
    }

    @Override
    public List<SwitchInfoVO> getSwitchListByFeeder(SwitchInfoListRequest request) {
        String feederId = request.getFeederId();
        if (StrUtil.isBlank(feederId)) {
            throw new BusinessException("请求参数缺少线路id");
        }
        LambdaQueryWrapper<DwdShbDsSwitchBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DwdShbDsSwitchBase::getFeeder, feederId)
                .eq(DwdShbDsSwitchBase::getPsrState, "20")
                .eq(DwdShbDsSwitchBase::getPubPrivFlag, "0")
                .orderByDesc(DwdShbDsSwitchBase::getPsrId);
        List<DwdShbDsSwitchBase> list = this.list(wrapper);
        List<SwitchInfoVO> result = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(e -> {
                SwitchInfoVO switchInfoVO = new SwitchInfoVO();
                switchInfoVO.setSwitchId(e.getPsrId());
                switchInfoVO.setSwitchName(e.getName());
                result.add(switchInfoVO);
            });
        }
        return result;
    }

}




