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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.dto.CustomerPowerProtectionConfigDTO;
import com.hdkj.lt.bf.entity.dto.CustomerPowerProtectionConfigUpdateDTO;
import com.hdkj.lt.bf.entity.vo.CustomerPowerProtectionConfigVO;
import com.hdkj.lt.bf.mapper.CustomerPowerProtectionConfigMapper;
import com.hdkj.lt.bf.service.ICustomerPowerProtectionConfigHistService;
import com.hdkj.lt.bf.service.ICustomerPowerProtectionConfigService;
import com.hdkj.lt.core.bizms.modle.dto.TransformerNameDTO;
import com.hdkj.lt.core.bizms.modle.po.CustomerPowerProtectionConfig;
import com.hdkj.lt.core.bizms.modle.po.CustomerPowerProtectionConfigHist;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 保电用户配置信息 服务实现类
 * </p>
 *
 * @author luorui
 * @since 2025-06-05
 */
@Service
@AllArgsConstructor
@Slf4j
public class CustomerPowerProtectionConfigServiceImpl extends ServiceImpl<CustomerPowerProtectionConfigMapper, CustomerPowerProtectionConfig> implements ICustomerPowerProtectionConfigService {

    private final ICustomerPowerProtectionConfigHistService customerPowerProtectionConfigHistService;


    private final static String CANCEL = "02";

    /**
     * @author luorui
     * @date 2025/6/5 14:31
     * @discription 分页查询
     **/
    @Override
    public Page<CustomerPowerProtectionConfigVO> getConfigPage(CustomerPowerProtectionConfigDTO customerPowerProtectionConfigDTO) {
        Optional.ofNullable(customerPowerProtectionConfigDTO).orElseThrow(() -> new BusinessException("请求参数为空"));
        Optional.ofNullable(customerPowerProtectionConfigDTO.getPageSize()).orElseThrow(() -> new BusinessException("分页页长pageSize为空"));
        Optional.ofNullable(customerPowerProtectionConfigDTO.getPageNum()).orElseThrow(() -> new BusinessException("分页页码pageNum为空"));
        Page<CustomerPowerProtectionConfig> page = new Page(customerPowerProtectionConfigDTO.getPageNum(), customerPowerProtectionConfigDTO.getPageSize());
        Page<CustomerPowerProtectionConfigVO> result = baseMapper.getConfigPage(page, customerPowerProtectionConfigDTO);
        List<String> transformerNoList = result.getRecords().stream().filter(i -> "02".equals(i.getPublClgFlag())).map(CustomerPowerProtectionConfig::getTransformerNo).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(transformerNoList)) {
            List<CustomerPowerProtectionConfigVO> joinecType = baseMapper.getJoinecType(transformerNoList);
            Map<String, CustomerPowerProtectionConfigVO> collect = joinecType.stream().collect(Collectors.toMap(CustomerPowerProtectionConfigVO::getTransformerNo, i -> i));
            result.getRecords().forEach(i -> {
                        if ("02".equals(i.getPublClgFlag()) && i.getTransformerList() != null) {
                            i.setDedicatedTransformerNameList(Arrays.asList(i.getTransformerList().split(",")));
                            i.setIsCriticalUser(collect.get(i.getTransformerNo()).getIsCriticalUser());
                            i.setIsSensitiveUser(collect.get(i.getTransformerNo()).getIsSensitiveUser());
                        }
                    }
            );
        }

        return result;
    }

    private String getTransformerName(String transformerNo, String transformerName, Map<String, TransformerNameDTO> transfermerNameMap) {
        TransformerNameDTO transformerNameDTO = transfermerNameMap.get(transformerNo);
        if (transformerNameDTO == null || transformerNameDTO.getTransformerName() == null) {
            if (transformerNameDTO == null || transformerNameDTO.getDedicatedName() == null) {
                return transformerName;
            } else {
                return transformerNameDTO.getDedicatedName();
            }
        }
        return transformerNameDTO.getTransformerName();
    }

    /**
     * @author luorui
     * @date 2025/6/5 14:31
     * @discription 批量修改设置,（将当前数据移动到hist表,删除当前表数据，新增新的数据）
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void batchUpdate(CustomerPowerProtectionConfigUpdateDTO customerPowerProtectionConfigUpdateDTO) {
        if (Objects.isNull(customerPowerProtectionConfigUpdateDTO)) {
            throw new BusinessException("请求参数为空");
        }
        String updateType = customerPowerProtectionConfigUpdateDTO.getUpdateType();
        if (StrUtil.isBlank(updateType)) {
            throw new BusinessException("更新类型为空");
        }
        List<CustomerPowerProtectionConfig> dataList = customerPowerProtectionConfigUpdateDTO.getDataList();
        if (CollUtil.isEmpty(dataList)) {
            throw new BusinessException("更新数据集合参数为空");
        }
        //数据校验,开始和结束时间
        boolean isCancel = StrUtil.equals(updateType, CANCEL);
        if (!isCancel) {
            checkData(dataList);
        }
        List<Long> idList = dataList.stream().filter(e -> !Objects.isNull(e.getId())).map(CustomerPowerProtectionConfig::getId).collect(Collectors.toList());
        //将当前数据移动到hist表
        moveDataToHist(idList);
        //新增新的数据 // 前端传值可能存在id为空的数据(这部分数据存在于fhzg_dist_transformer_customer表fhzg_customer_power_protection_config表中没有配置信息)
        saveData(dataList, isCancel);
    }

    /**
     * @author luorui
     * @date 2025/6/6 11:16
     * @discription 初始化保电配置表数据
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void initData() {
        //删除两张表的数据
        customerPowerProtectionConfigHistService.getBaseMapper().delete(null);
        baseMapper.delete(null);
        //新增数据
        baseMapper.insertAllData();
    }

    //批量新增配置数据
    private void saveData(List<CustomerPowerProtectionConfig> dataList, boolean isCancel) {
        dataList.forEach(e -> {
            e.setId(null);//主键设置为空新增数据
            e.setCreateTime(LocalDateTime.now());//配置表修改创建时间
            e.setLastTime(null);//配置表最后修改时间设置为空
            if (isCancel) {
                //如果是取消操作则将时间更新为空
                e.setProtectionStartTime(null);
                e.setProtectionEndTime(null);
            }
        });
        this.saveBatch(dataList, 500);
        log.info("批量新增保电配置完成");
    }

    //数据校验,开始时间和结束时间不能为空，开始时间必须小结束时间
    private void checkData(List<CustomerPowerProtectionConfig> dataList) {
        dataList.forEach(e -> {
            if (Objects.isNull(e.getProtectionStartTime()) || Objects.isNull(e.getProtectionEndTime())) {
                throw new BusinessException("保电开始时间或结束时间为空,transformerNo:" + e.getTransformerNo());
            }
            if (e.getProtectionStartTime().compareTo(e.getProtectionEndTime()) >= 0) {
                throw new BusinessException("数据不正确保电开始时间大于结束时间,transformerNo:" + e.getTransformerNo());
            }
        });
    }

    //将当前数据移动到hist表
    private void moveDataToHist(List<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            log.info("移动保电数据主键集合为空");
            return;
        }
        List<CustomerPowerProtectionConfig> customerPowerProtectionConfigListFromDB = baseMapper.selectBatchIds(idList);
        List<CustomerPowerProtectionConfigHist> customerPowerProtectionConfigHistList = new ArrayList<>();
        customerPowerProtectionConfigListFromDB.forEach(e -> {
            CustomerPowerProtectionConfigHist customerPowerProtectionConfigHist = new CustomerPowerProtectionConfigHist();
            BeanUtil.copyProperties(e, customerPowerProtectionConfigHist);
            customerPowerProtectionConfigHist.setLastTime(LocalDateTime.now());//历史表更新，最后修改时间
            customerPowerProtectionConfigHistList.add(customerPowerProtectionConfigHist);
        });
        if (CollUtil.isNotEmpty(customerPowerProtectionConfigHistList)) {
            customerPowerProtectionConfigHistService.saveBatch(customerPowerProtectionConfigHistList, 500);
            log.info("批量新增保电配置历史信息完成");
            //删除当前表数据
            baseMapper.deleteBatchIds(idList);
            log.info("批量删除保电配置完成");
        } else {
            log.info("保电配置未查询到数据，idList：{}", idList);
        }
    }

}
