package com.ruoyi.doubledefense.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.core.domain.entity.TbSysArea;
import com.ruoyi.common.core.domain.entity.TbSysAreaUser;
import com.ruoyi.common.utils.CodeUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.doubledefense.domain.Hazard;
import com.ruoyi.doubledefense.dto.HazardDTO;
import com.ruoyi.doubledefense.dto.HazardStatisticsDTO;
import com.ruoyi.doubledefense.dto.res.CheckUserCountStatisticsDTO;
import com.ruoyi.doubledefense.dto.res.HazardResultDTO;
import com.ruoyi.doubledefense.mapper.HazardMapper;
import com.ruoyi.doubledefense.service.ICheckTaskInventoryRecordService;
import com.ruoyi.doubledefense.service.IHazardService;
import com.ruoyi.system.domain.vo.AreaUserDTO;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TbSysAreaMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * 风险分析对象Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-03
 */
@Service
public class HazardServiceImpl implements IHazardService {
    @Autowired
    private HazardMapper hazardMapper;

    @Autowired
    private TbSysAreaMapper tbSysAreaMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ICheckTaskInventoryRecordService checkTaskInventoryRecordService;


    /**
     * 查询风险分析对象
     *
     * @param id 风险分析对象主键
     * @return 风险分析对象
     */
    @Override
    public HazardResultDTO selectHazardById(String id) {
        Hazard hazard = hazardMapper.selectById(id);
        HazardResultDTO hazardResultDTO = new HazardResultDTO();
        BeanUtils.copyProperties(hazard, hazardResultDTO);
        TbSysArea tbSysArea = tbSysAreaMapper.selectTbSysAreaById(hazard.getAreaId());
        if (tbSysArea != null) {
            hazardResultDTO.setAreaName(tbSysArea.getAreaName());
        }
        return hazardResultDTO;
    }

    /**
     * 查询风险分析对象列表
     *
     * @param hazardDTO 风险分析对象
     * @return 风险分析对象
     */
    @Override
    public List<HazardResultDTO> selectHazardList(HazardDTO hazardDTO) {
        List<HazardResultDTO> resultDTOS = new ArrayList<>();

        LambdaQueryWrapper<Hazard> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(hazardDTO.getHazardName()), Hazard::getHazardName, hazardDTO.getHazardName());
        wrapper.eq(!Objects.isNull(hazardDTO.getHazardLevel()), Hazard::getHazardLevel, hazardDTO.getHazardLevel());
        wrapper.eq(!Objects.isNull(hazardDTO.getAreaId()), Hazard::getAreaId, hazardDTO.getAreaId());
        wrapper.eq(Hazard::getIsDel, DeletedEnum.VALID.getValue());
        wrapper.orderByDesc(Hazard::getCreateDate);
        List<Hazard> list = hazardMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(list)) {
            //统计今日打卡人数
//            Map<String, Integer> hazardcheckUserMap = new HashMap<>();
//            Integer checkTimeDays = hazardDTO.getCheckTimeDays();
//            if (checkTimeDays != null) {
//                Date checkTimeStatr = DateUtils.getLastDay(0, 0, 0, 0, 0);
//                Date checkTimeEnd = DateUtils.getLastDay(0, 23, 59, 59, 999);
//                List<CheckUserCountStatisticsDTO> checkUserList = checkTaskInventoryRecordService.checkUserCountStatistics(checkTimeStatr, checkTimeEnd);
//                hazardcheckUserMap = checkUserList.stream().collect(Collectors.toMap(CheckUserCountStatisticsDTO::getHazardId, CheckUserCountStatisticsDTO::getCheckUserCount));
//            }


            //查询区域负责人
            List<Long> areaIdList = list.stream().map(Hazard::getAreaId).collect(Collectors.toList());
//            List<TbSysAreaUserRelation> sysAreaUserRelations = sysUserMapper.selectAreaUser(areaIdList);
            List<TbSysAreaUser> sysAreaUserList = sysUserMapper.selectAreaUser(areaIdList);
            Map<Long, List<AreaUserDTO>> userMap = new HashMap<>();

            Map<Long, String> areaMap = new HashMap<>();

            if (!CollectionUtils.isEmpty(sysAreaUserList)) {
                List<AreaUserDTO> areaUserDTOList = new ArrayList<>();
//                for(TbSysAreaUserRelation tbSysAreaUserRelation : sysAreaUserRelations){
                for (TbSysAreaUser areaUser : sysAreaUserList) {
                    Long areaId = areaUser.getAreaId();
                    String areaName = areaUser.getAreaName();
                    areaMap.put(areaId, areaName);

                    AreaUserDTO areaUserDTO = new AreaUserDTO();
                    BeanUtils.copyProperties(areaUser, areaUserDTO);
                    areaUserDTO.setId(areaUser.getAreaId());//设置区域ID
                    areaUserDTOList.add(areaUserDTO);
                }
                userMap = areaUserDTOList.stream().collect(Collectors.groupingBy(AreaUserDTO::getId));
            }
            for (Hazard hazard : list) {
                Long areaId = hazard.getAreaId();
                HazardResultDTO hazardResultDTO = new HazardResultDTO();
                BeanUtils.copyProperties(hazard, hazardResultDTO);
                hazardResultDTO.setAreaUserDTOList(userMap.get(hazard.getAreaId()));
                hazardResultDTO.setAreaName(areaMap.get(areaId));
//                Integer checkUserCount = hazardcheckUserMap.get(hazard.getId());
//                hazardResultDTO.setCheckUserCount(checkUserCount != null ? checkUserCount : 0);
                resultDTOS.add(hazardResultDTO);
            }
        }

        return resultDTOS;
    }

    /**
     * 新增风险分析对象
     *
     * @param hazardDTO 风险分析对象
     * @return 结果
     */
    @Override
    public int insertHazard(HazardDTO hazardDTO) {
        Hazard hazard = new Hazard();
        BeanUtils.copyProperties(hazardDTO, hazard);
        hazard.setId(UUID.randomUUID().toString());
        hazard.setHazardCode(CodeUtils.getHazardCode());
        hazard.setCreateDefault();
        return hazardMapper.insert(hazard);
    }

    /**
     * 修改风险分析对象
     *
     * @param hazardDTO 风险分析对象
     * @return 结果
     */
    @Override
    public int updateHazard(HazardDTO hazardDTO) {
        Hazard hazard = new Hazard();
        BeanUtils.copyProperties(hazardDTO, hazard);
        hazard.setUpdateDefault();
        return hazardMapper.updateById(hazard);
    }

    /**
     * 批量删除风险分析对象
     *
     * @param ids 需要删除的风险分析对象主键
     * @return 结果
     */
    @Override
    public int deleteHazardByIds(String[] ids) {
        Hazard hazard = new Hazard();
        hazard.setUpdateDefault();
        hazard.setIsDel(DeletedEnum.INVALID.getValue());
        QueryWrapper<Hazard> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        return hazardMapper.update(hazard, queryWrapper);
    }

    /**
     * 风险管理统计
     * APP首页统计
     *
     * @return
     */
    @Override
    public HazardStatisticsDTO riskStatistics() {
        HazardStatisticsDTO dto = hazardMapper.riskStatistics();
        if (dto == null) {
            dto = new HazardStatisticsDTO();
        }
        return dto;
    }

    /**
     * 统计数量
     *
     * @param companyCode
     * @return
     */
    @Override
    public Long countHazard(String companyCode) {

        LambdaQueryWrapper<Hazard> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Hazard::getCompanyCode, companyCode);
        wrapper.eq(Hazard::getIsDel,DeletedEnum.VALID.getValue());
        Long count = hazardMapper.selectCount(wrapper);
        return count;
    }
}
