package com.njcn.csharmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csharmonic.pojo.param.PqSensitiveUserParam;
import com.njcn.csharmonic.pojo.vo.PqSensitiveUserVo;
import com.njcn.csharmonic.service.IPqSensitiveUserService;
import com.njcn.device.biz.mapper.PqSensitiveUserMapper;
import com.njcn.device.biz.pojo.po.PqSensitiveUser;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.pojo.po.DictData;
import com.njcn.web.pojo.param.BaseParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xy
 * @since 2025-11-17
 */
@DS("sjzx")
@Slf4j
@Service
@RequiredArgsConstructor
public class PqSensitiveUserServiceImpl extends ServiceImpl<PqSensitiveUserMapper, PqSensitiveUser> implements IPqSensitiveUserService {

    private final CsLineFeignClient csLineFeignClient;

    private final DicDataFeignClient dicDataFeignClient;

    @Override
    public Page<PqSensitiveUserVo> getList(BaseParam param) {
        Page<PqSensitiveUserVo> result = new Page<>(param.getPageNum(),param.getPageSize());
        LambdaQueryWrapper<PqSensitiveUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(PqSensitiveUser::getSort);
        if (StrUtil.isNotBlank(param.getSearchValue())) {
            lambdaQueryWrapper.like(PqSensitiveUser::getName, param.getSearchValue());
        }
        Page<PqSensitiveUser> page = this.page(new Page<>(param.getPageNum(),param.getPageSize()),lambdaQueryWrapper);
        if(CollUtil.isNotEmpty(page.getRecords())){
            List<PqSensitiveUserVo> dataGroupEventVOList = new ArrayList<>();
            Map<String,List<CsLinePO>> map = new HashMap<>();
            //获取绑定敏感用户的监测点信息
            List<String> sensitiveUserIds = page.getRecords().stream().map(PqSensitiveUser::getId).collect(Collectors.toList());
            List<CsLinePO> csLinePOList = csLineFeignClient.getLineBySensitiveUser(sensitiveUserIds).getData();
            if (CollUtil.isNotEmpty(csLinePOList)) {
                map = csLinePOList.stream().collect(Collectors.groupingBy(CsLinePO::getMonitorUser));
            }
            Map<String, List<CsLinePO>> finalMap = map;
            page.getRecords().forEach(item->{
                PqSensitiveUserVo vo = new PqSensitiveUserVo();
                BeanUtil.copyProperties(item,vo);
                if (finalMap.containsKey(item.getId())) {
                    vo.setIsMonitor("是");
                    List<CsLinePO> list = finalMap.get(item.getId());
                    boolean hasGoverned = list.stream().anyMatch(item2 -> item2.getGovern() == 1);
                    vo.setIsGovern(hasGoverned ? "是" : "否");
                } else {
                    vo.setIsMonitor("否");
                    vo.setIsGovern("否");
                }
                dataGroupEventVOList.add(vo);
            });
            result.setRecords(dataGroupEventVOList);
            result.setTotal(page.getTotal());
            result.setSize(page.getSize());
            result.setCurrent(page.getCurrent());
            result.setPages(page.getPages());
        }
        return result;
    }

    @Override
    public List<PqSensitiveUserVo> getListByUser(BaseParam param) {
        List<PqSensitiveUserVo> result = new ArrayList<>();
        //现根据用户获取监测点
        List<CsLinePO> poList = csLineFeignClient.getSimpleLine().getData();
        //获取敏感用户集合
        List<String> monitorUsers = poList.stream()
                .map(CsLinePO::getMonitorUser)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        if (CollectionUtil.isEmpty(monitorUsers)) {
            return result;
        }
        //根据敏感用户进行监测点分组
        Map<String,List<CsLinePO>> map = poList.stream()
                .filter(po -> po.getMonitorUser() != null)
                .collect(Collectors.groupingBy(CsLinePO::getMonitorUser));
        //查询敏感用户信息集合
        LambdaQueryWrapper<PqSensitiveUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(PqSensitiveUser::getId,monitorUsers).orderByAsc(PqSensitiveUser::getSort);
        if (StrUtil.isNotBlank(param.getSearchValue())) {
            lambdaQueryWrapper.like(PqSensitiveUser::getName, param.getSearchValue());
        }
        List<PqSensitiveUser> sensitiveUserList = this.list(lambdaQueryWrapper);
        sensitiveUserList.forEach(item->{
            PqSensitiveUserVo vo = new PqSensitiveUserVo();
            BeanUtil.copyProperties(item,vo);
            if (map.containsKey(item.getId())) {
                vo.setIsMonitor("是");
                List<CsLinePO> list = map.get(item.getId());
                boolean hasGoverned = list.stream().anyMatch(item2 -> item2.getGovern() == 1);
                vo.setIsGovern(hasGoverned ? "是" : "否");
            } else {
                vo.setIsMonitor("否");
                vo.setIsGovern("否");
            }
            result.add(vo);
        });
        return result;
    }

    @Override
    public boolean save(PqSensitiveUserParam pqSensitiveUserParam) {
        checkParam(pqSensitiveUserParam,false);

        PqSensitiveUser pqSensitiveUser = new PqSensitiveUser();
        BeanUtil.copyProperties(pqSensitiveUserParam,pqSensitiveUser);
        return this.save(pqSensitiveUser);
    }

    @Override
    public boolean update(PqSensitiveUserParam.UpdatePqSensitiveUserParam pqSensitiveUserParam) {
        checkParam(pqSensitiveUserParam,true);
        PqSensitiveUser pqSensitiveUser = new PqSensitiveUser();
        BeanUtil.copyProperties(pqSensitiveUserParam,pqSensitiveUser);
        return this.updateById(pqSensitiveUser);
    }


    private void checkParam(PqSensitiveUserParam param,boolean update){
        DictData data = dicDataFeignClient.getDicDataById(param.getLoadType()).getData();
        if(Objects.isNull(data)){
            throw new BusinessException(CommonResponseEnum.FAIL,"字典负荷类型缺失！");
        }

        LambdaQueryWrapper<PqSensitiveUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PqSensitiveUser::getName,param.getName());
        if(update){
            if(param instanceof PqSensitiveUserParam.UpdatePqSensitiveUserParam){
                lambdaQueryWrapper.ne(PqSensitiveUser::getId,((PqSensitiveUserParam.UpdatePqSensitiveUserParam) param).getId());
            }
        }
        int count = this.count(lambdaQueryWrapper);
        if(count>0){
            throw new BusinessException(CommonResponseEnum.FAIL,"用户名称重复！");
        }
    }

}
