package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.domain.dto.emergency.EmergencyAddRequest;
import com.ruoyi.web.domain.dto.emergency.EmergencyEditRequest;
import com.ruoyi.web.domain.dto.emergency.EmergencyQueryRequest;
import com.ruoyi.web.domain.dto.emergency.EmergencyRevokeRequest;
import com.ruoyi.web.domain.entity.Emergency;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.vo.EmergencyVO;
import com.ruoyi.web.domain.vo.PersonInfoVO;
import com.ruoyi.web.mapper.EmergencyMapper;
import com.ruoyi.web.service.EmergencyService;
import com.ruoyi.web.service.PersonInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class EmergencyServiceImpl extends ServiceImpl<EmergencyMapper, Emergency>
        implements EmergencyService {

    @Resource
    private PersonInfoService personInfoService;


    /**
     * 添加
     *
     * @param emergencyAddRequest
     * @return
     */
    @Override
    public Integer addEmergency(EmergencyAddRequest emergencyAddRequest) {
        if (emergencyAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            Emergency emergency = new Emergency();
            // 1. 接收对象 receivePersonIds -> receiveUserIds
            String receivePersonIds = emergencyAddRequest.getReceiveUserIds();
            String receiveUserIds = getChange(receivePersonIds);

            emergency.setOccurTime(   DateUtil.parse(emergencyAddRequest.getOccurTime(),"yyyy-MM-dd HH:mm:ss"));
            BeanUtil.copyProperties(emergencyAddRequest, emergency);
            emergency.setReceiveUserIds(receiveUserIds);

            //数据校验
            validEmergency(emergency, BusinessType.INSERT);
            // 保存到数据库
            this.save(emergency);
            return emergency.getId();
        } catch (Exception e) {
            log.error("添加失败", e);
            throw new ServiceException("添加失败");
        }
    }

    /**
     * 接收对象 receivePersonIds -> receiveUserIds
     *
     * @param receivePersonIds
     * @return
     */
    private String getChange(String receivePersonIds) {
        if (StrUtil.isBlank(receivePersonIds)) {
            throw new ServiceException("接收对象参数为空");
        }
        // 分割ID字符串为List<Integer>
        List<Integer> idList = Arrays.stream(receivePersonIds.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Integer::parseInt)  // 直接解析为Integer
                .collect(Collectors.toList());
        List<Integer> userIdList = personInfoService.getUserIdListByPersonIds(idList);
        // 先将List<Integer>转换为List<String>
        List<String> receiveStringList = userIdList.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        return String.join(",", receiveStringList);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteEmergency(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("id不能为空或id异常");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<Emergency> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList)
                .eq("status", 0);

        // 4. 执行删除（返回是否删除成功）
        return remove(queryWrapper);
    }

    /**
     * 编辑
     *
     * @param emergencyEditRequest
     */
    @Override
    public void editEmergency(EmergencyEditRequest emergencyEditRequest) {
        // 判断是否存在
        Integer id = emergencyEditRequest.getId();
        Emergency oldEmergency = this.getById(id);
        if (oldEmergency == null) {
            throw new ServiceException("没有找到应急指定下达");
        }
        Emergency emergency = new Emergency();
        BeanUtil.copyProperties(emergencyEditRequest, emergency);
        emergency.setOccurTime(   DateUtil.parse(emergencyEditRequest.getOccurTime(),"yyyy-MM-dd HH:mm:ss"));
        String receivePersonIds = emergencyEditRequest.getReceiveUserIds();
        String receiveUserIds = getChange(receivePersonIds);
        emergency.setReceiveUserIds(receiveUserIds);
        emergency.setUpdateTime(new Date());
        // 数据校验
        validEmergency(emergency, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(emergency);
        if (!result) {
            throw new ServiceException("修改应急指定下达操作失败");
        }
    }

    /**
     * 撤回应急指令下达
     *
     * @param emergencyRevokeRequest
     */
    @Override
    public void revokeEmergency(EmergencyRevokeRequest emergencyRevokeRequest) {
        if (ObjectUtil.isEmpty(emergencyRevokeRequest)) {
            throw new ServiceException("请求参数为空");
        }
        Integer id = emergencyRevokeRequest.getId();

        Emergency emergency = this.getById(id);
        if (emergency == null) {
            throw new ServiceException("未找到应急指令");
        }
        if (emergency.getStatus() != 1) {
            throw new ServiceException("只有下达的指令才能撤回");
        }
        emergency.setStatus(0);
        boolean result = this.updateById(emergency);
        if (!result) {
            throw new ServiceException("撤回应急指定下达操作失败");
        }
    }

    /**
     * 下达
     *
     * @param emergencyRevokeRequest
     */
    @Override
    public void downEmergency(EmergencyRevokeRequest emergencyRevokeRequest) {
        if (ObjectUtil.isEmpty(emergencyRevokeRequest)) {
            throw new ServiceException("请求参数为空");
        }
        Integer id = emergencyRevokeRequest.getId();
        Emergency emergency = this.getById(id);
        // 填充下达人 下达日期
        int issuerId = SecurityUtils.getUserId().intValue();
        emergency.setIssuerId(issuerId);
        emergency.setDate(new Date());
        if (emergency == null) {
            throw new ServiceException("未找到应急指令");
        }
        if (emergency.getStatus() != 0) {
            throw new ServiceException("只有未下达的指令才能下达");
        }
        emergency.setStatus(1);
        boolean result = this.updateById(emergency);
        if (!result) {
            throw new ServiceException("下达应急指定操作失败");
        }
    }

    /**
     * 校验数据
     *
     * @param emergency
     */
    public void validEmergency(Emergency emergency, BusinessType type) {
        if (ObjectUtil.isEmpty(emergency)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = emergency.getId();
        Date occurTime = emergency.getOccurTime();
        String name = emergency.getName();
        String location = emergency.getLocation();
        String requirement = emergency.getRequirement();
        String receiveUserIds = emergency.getReceiveUserIds();
        Integer userId = emergency.getUserId();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (ObjectUtil.isEmpty(occurTime)) {
            throw new ServiceException("事发时间不能为空");
        }
        if (StrUtil.isEmpty(name)) {
            throw new ServiceException("事发名称不能为空");
        }
        if (StrUtil.isEmpty(location)) {
            throw new ServiceException("事发地点不能为空");
        }
        if (StrUtil.isEmpty(requirement)) {
            throw new ServiceException("调度要求不能为空");
        }
        if (StrUtil.isEmpty(receiveUserIds)) {
            throw new ServiceException("接收对象不能为空");
        }
        if (ObjectUtil.isEmpty(userId)) {
            throw new ServiceException("负责人不能为空");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public EmergencyVO getEmergencyById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        Emergency emergency = this.getById(id);
        return getEmergencyVO(emergency);
    }

    /**
     * 获取应急指定下达包装类
     *
     * @param emergency
     * @return
     */
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public EmergencyVO getEmergencyVO(Emergency emergency) {
        if (ObjectUtil.isEmpty(emergency)) {
            throw new ServiceException("请求参数不存在");
        }
        EmergencyVO emergencyVO = new EmergencyVO();
        BeanUtils.copyProperties(emergency, emergencyVO);
        // 处理 接收对象信息
        String receiveUserIds = emergency.getReceiveUserIds();
        List<Integer> idList = Arrays.stream(receiveUserIds.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Integer::parseInt)  // 直接解析为Integer
                .collect(Collectors.toList());
        List<PersonInfoVO> personInfoVOListByUserIds = personInfoService.getPersonInfoVOListByUserIds(idList);
        emergencyVO.setReceivePersonInfo(personInfoVOListByUserIds);
        // 处理 负责人信息
        Integer userId = emergency.getUserId();
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(userId));
//        PersonInfoVO leaderInfoVO = personInfoService.getPersonInfoVO(leaderInfo);
        emergencyVO.setLeaderInfo(sysUser);
        // 处理 下达人信息

        Integer issuerId = emergency.getIssuerId();
        PersonInfoVO issuerInfoVO = new PersonInfoVO();
        if (ObjectUtil.isNotEmpty(issuerId)){

//        if (issuerId == 1) {
//            issuerInfoVO.setRealname("超级管理员");
//            issuerInfoVO.setUserId(1);
            if (SecurityUtils.isAdmin(issuerId.longValue())) {
                issuerInfoVO.setRealname("超级管理员");
                issuerInfoVO.setUserId(1);
            } else {
                QueryWrapper<PersonInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", issuerId);
                PersonInfo one = personInfoService.getOne(queryWrapper);
                if (one == null) {
                    throw new ServiceException("下达人不存在");
                }
                issuerInfoVO = personInfoService.getPersonInfoVO(one);
            }
        }

        emergencyVO.setIssuerInfo(issuerInfoVO);
        return emergencyVO;
    }


    /**
     * 分页获取应急指定下达列表
     *
     * @param emergencyQueryRequest
     * @return
     */
    @Override
    public Page<EmergencyVO> getListEmergencyVOByPage(EmergencyQueryRequest emergencyQueryRequest) {
        long current = emergencyQueryRequest.getPageNum();
        long size = emergencyQueryRequest.getPageSize();
        Page<Emergency> page = this.page(new Page<>(current, size),
                getQueryWrapper(emergencyQueryRequest));
        Page<EmergencyVO> emergencyVOPage = new Page<>();
        BeanUtils.copyProperties(page, emergencyVOPage, "records");
        List<EmergencyVO> voList = page.getRecords().stream()
                .map(Emergency -> {
                    return getEmergencyVO(Emergency);
                })
                .collect(Collectors.toList());
        emergencyVOPage.setRecords(voList);
        return emergencyVOPage;
    }


    /**
     * 获取查询条件
     *
     * @param emergencyQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Emergency> getQueryWrapper(EmergencyQueryRequest emergencyQueryRequest) {
        QueryWrapper<Emergency> queryWrapper = new QueryWrapper<>();
        if (emergencyQueryRequest == null) {
            return queryWrapper;
        }


        // 从对象中取值
        String startTime = emergencyQueryRequest.getStartTime();
        String endTime = emergencyQueryRequest.getEndTime();
        String location = emergencyQueryRequest.getLocation();
        String sortField = emergencyQueryRequest.getSortField();
        String sortOrder = emergencyQueryRequest.getSortOrder();

        queryWrapper.eq(StrUtil.isNotEmpty(location), "location", location);

        // 日期范围查询（优先判断范围）
        if (startTime != null && endTime != null) {
            queryWrapper.between("occur_time", startTime, endTime);
        } else if (startTime != null) {
            queryWrapper.ge("occur_time", startTime); // >= 开始日期
        } else if (endTime != null) {
            queryWrapper.le("occur_time", endTime);   // <= 结束日期
        }

        // 根据登录用户 筛选数据  管理员->返回全部数据  非管理员—> 返回负责人 & 下达人数据
        long loginUserId = SecurityUtils.getUserId();
        if (!SecurityUtils.isAdmin(loginUserId)) {
            queryWrapper.apply("FIND_IN_SET({0}, receive_user_ids)", loginUserId)
                    .or().eq("user_id", loginUserId)
                    .or().eq("issuer_id", loginUserId);
        }
        // 排序
        queryWrapper.orderByDesc("id");
//        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }
}




