package com.njcn.csharmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
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.CsCommTerminalFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csharmonic.pojo.param.PqSensitiveUserParam;
import com.njcn.csharmonic.pojo.po.PqGovernPlan;
import com.njcn.csharmonic.pojo.vo.PqSensitiveUserVo;
import com.njcn.csharmonic.service.IPqGovernPlanService;
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 com.njcn.web.utils.RequestUtil;
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 DicDataFeignClient dicDataFeignClient;
    private final EquipmentFeignClient equipmentFeignClient;
    private final CsCommTerminalFeignClient csCommTerminalFeignClient;
    private final IPqGovernPlanService pqGovernPlanService;

    @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<>();
            page.getRecords().forEach(item->{
                PqSensitiveUserVo vo = new PqSensitiveUserVo();
                BeanUtil.copyProperties(item,vo);
                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<String> lineIds = csCommTerminalFeignClient.getLineIdsByUser(RequestUtil.getUserIndex()).getData();
        if (CollUtil.isEmpty(lineIds)) {
            return result;
        }
        //根据监测点获取用户
        List<PqGovernPlan> governPlans = pqGovernPlanService.getListByMonitorPoint(lineIds,null);
        if (CollUtil.isEmpty(governPlans)) {
            return result;
        }
        List<String> governUserIds = governPlans.stream().map(PqGovernPlan::getPid).distinct().collect(Collectors.toList());
        //查询敏感用户信息集合
        LambdaQueryWrapper<PqSensitiveUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(PqSensitiveUser::getId,governUserIds).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);
            vo.setIsMonitor("是");
            vo.setIsGovern("是");
            result.add(vo);
        });
        return result;
    }

    @Override
    public List<PqSensitiveUser> getListByIds(List<String> ids) {
        List<PqSensitiveUser> result = new ArrayList<>();
        List<String> governUserIds;
        if (CollUtil.isEmpty(ids) || ids.isEmpty()) {
            //根据当前用户获取监测点
            List<String> lineIds = csCommTerminalFeignClient.getLineIdsByUser(RequestUtil.getUserIndex()).getData();
            if (CollUtil.isEmpty(lineIds)) {
                return result;
            }
            //根据监测点获取用户
            List<PqGovernPlan> governPlans = pqGovernPlanService.getListByMonitorPoint(lineIds,null);
            if (CollUtil.isEmpty(governPlans)) {
                return result;
            }
            governUserIds = governPlans.stream().map(PqGovernPlan::getPid).distinct().collect(Collectors.toList());
        } else {
            governUserIds = ids;
        }
        return this.list(new LambdaQueryWrapper<PqSensitiveUser>().in(PqSensitiveUser::getId, governUserIds));
    }

    @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);
    }

    @Override
    public Map<String, List<PqGovernPlan>> getUserDevTree(String type) {
        Map<String, List<PqGovernPlan>> map = new LinkedHashMap<>();
        //根据用户获取监测点id
        List<String> lineIds = csCommTerminalFeignClient.getLineIdsByUser(RequestUtil.getUserIndex()).getData();
        if (CollUtil.isEmpty(lineIds)) {
            return map;
        }
        //根据监测点id获取治理用户
        String governType = Objects.equals(type, "apf") ? "harmonic" : "event";
        List<PqGovernPlan> governPlans = pqGovernPlanService.getListByMonitorPoint(lineIds,governType);
        if (CollUtil.isEmpty(governPlans)) {
            return map;
        }
        List<PqSensitiveUser> userList = this.list();
        if (CollUtil.isEmpty(userList)) {
            return map;
        }
        Map<String, List<PqGovernPlan>> planMap = governPlans.stream().collect(Collectors.groupingBy(
                PqGovernPlan::getPid,
                LinkedHashMap::new,
                Collectors.toList()
        ));
        Map<String, PqSensitiveUser> userMap = userList.stream().collect(Collectors.toMap(PqSensitiveUser::getId, item -> item));
        planMap.forEach((k,v)->{
            map.put(userMap.get(k).getName(), v);
        });
        return map;
    }

    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,"用户名称重复！");
        }
    }

}
