package com.ruoyi.web.service.impl;

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.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.environmentWarningThresholdRole.EnvironmentWarningThresholdUserAddRequest;
import com.ruoyi.web.domain.dto.environmentWarningThresholdRole.EnvironmentWarningThresholdUserEditRequest;
import com.ruoyi.web.domain.dto.environmentWarningThresholdRole.EnvironmentWarningThresholdUserQueryRequest;
import com.ruoyi.web.domain.entity.EnvironmentWarningThresholdRole;
import com.ruoyi.web.domain.entity.EnvironmentWarningThresholdUser;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.vo.EnvironmentWarningThresholdUserVO;
import com.ruoyi.web.domain.vo.PersonInfoVO;
import com.ruoyi.web.mapper.EnvironmentWarningThresholdUserMapper;
import com.ruoyi.web.service.EnvironmentWarningThresholdRoleService;
import com.ruoyi.web.service.EnvironmentWarningThresholdUserService;
import com.ruoyi.web.service.PersonInfoService;
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 EnvironmentWarningThresholdUserServiceImpl extends ServiceImpl<EnvironmentWarningThresholdUserMapper, EnvironmentWarningThresholdUser>
        implements EnvironmentWarningThresholdUserService {
    @Resource
    private EnvironmentWarningThresholdRoleService environmentWarningThresholdRoleService;

    @Resource
    private PersonInfoService personInfoService;

    @Override
    public Integer addEnvironmentWarningThresholdUser(EnvironmentWarningThresholdUserAddRequest environmentWarningThresholdUserAddRequest) {
        if (environmentWarningThresholdUserAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            EnvironmentWarningThresholdUser environmentWarningThresholdUser = new EnvironmentWarningThresholdUser();
            Integer personId = environmentWarningThresholdUserAddRequest.getPersonId();
            QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
            wrapper.select("user_id")
                    .eq("id", personId);
            PersonInfo one = personInfoService.getOne(wrapper);
            environmentWarningThresholdUser.setUserId(one.getUserId());
            environmentWarningThresholdUser.setTypeId(environmentWarningThresholdUserAddRequest.getTypeId());
            //数据校验
            String typeId = environmentWarningThresholdUser.getTypeId();
            QueryWrapper<EnvironmentWarningThresholdRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type_id", typeId);
            int count = environmentWarningThresholdRoleService.count(queryWrapper);
            if (count <= 0) {
                throw new ServiceException("不存在该负责人类型");
            }
            // 保存到数据库
            this.save(environmentWarningThresholdUser);
            return environmentWarningThresholdUser.getId();
        } catch (Exception e) {
            log.error("添加失败", e);
            throw new ServiceException("添加失败");
        }
    }

    @Override
    public boolean deleteEnvironmentWarningThresholdUser(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<EnvironmentWarningThresholdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

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

    @Override
    public void editEnvironmentWarningThresholdUser(EnvironmentWarningThresholdUserEditRequest environmentWarningThresholdUserEditRequest) {
        // 判断是否存在
        Integer id = environmentWarningThresholdUserEditRequest.getId();
        EnvironmentWarningThresholdUser oldEnvironmentWarningThresholdUser = this.getById(id);
        if (oldEnvironmentWarningThresholdUser == null) {
            throw new ServiceException("没有找到负责人");
        }
        EnvironmentWarningThresholdUser environmentWarningThresholdUser = new EnvironmentWarningThresholdUser();
        Integer personId = environmentWarningThresholdUserEditRequest.getPersonId();
        QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
        wrapper.select("user_id")
                .eq("id", personId);
        PersonInfo one = personInfoService.getOne(wrapper);
        environmentWarningThresholdUser.setUserId(one.getUserId());
        environmentWarningThresholdUser.setTypeId(environmentWarningThresholdUserEditRequest.getTypeId());
        environmentWarningThresholdUser.setUpdateTime(new Date());
        // 数据校验
        String typeId = environmentWarningThresholdUser.getTypeId();
        QueryWrapper<EnvironmentWarningThresholdRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type_id", typeId);
        int count = environmentWarningThresholdRoleService.count(queryWrapper);
        if (count <= 0) {
            throw new ServiceException("不存在该负责人类型");
        }
        // 操作数据库
        boolean result = this.updateById(environmentWarningThresholdUser);
        if (!result) {
            throw new ServiceException("修改村委操作失败");
        }
    }


    @Override
    public EnvironmentWarningThresholdUserVO getEnvironmentWarningThresholdUserVOById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        EnvironmentWarningThresholdUser environmentWarningThresholdUser = this.getById(id);
        if (environmentWarningThresholdUser == null) {
            throw new ServiceException("未找到负责人");
        }
        return getEnvironmentWarningThresholdUserVO(environmentWarningThresholdUser);
    }

    @Override
    public EnvironmentWarningThresholdUserVO getEnvironmentWarningThresholdUserVO(EnvironmentWarningThresholdUser environmentWarningThresholdUser) {
        if (ObjectUtil.isEmpty(environmentWarningThresholdUser)) {
            throw new ServiceException("请求参数不存在");
        }
        EnvironmentWarningThresholdUserVO environmentWarningThresholdUserVO = new EnvironmentWarningThresholdUserVO();
        BeanUtils.copyProperties(environmentWarningThresholdUser, environmentWarningThresholdUserVO);
        // 填充负责人角色类型
        String typeId = environmentWarningThresholdUser.getTypeId();
        EnvironmentWarningThresholdRole environmentWarningThresholdRole = environmentWarningThresholdRoleService.getById(typeId);
        environmentWarningThresholdUserVO.setType(environmentWarningThresholdRole.getType());
        // 填充负责人信息
        Integer userId = environmentWarningThresholdUser.getUserId();
        QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        PersonInfo one = personInfoService.getOne(wrapper);
        PersonInfoVO personInfoVO = personInfoService.getPersonInfoVO(one);
        environmentWarningThresholdUserVO.setPersonInfo(personInfoVO);
        return environmentWarningThresholdUserVO;
    }


    @Override
    public List<EnvironmentWarningThresholdUserVO> getListEnvironmentWarningThresholdUserVO(EnvironmentWarningThresholdUserQueryRequest environmentWarningThresholdUserQueryRequest) {

        if (ObjectUtil.isEmpty(environmentWarningThresholdUserQueryRequest)) {
            throw new ServiceException("请求参数为空");
        }
        Integer id = environmentWarningThresholdUserQueryRequest.getId();
        String typeId = environmentWarningThresholdUserQueryRequest.getTypeId();
        QueryWrapper<EnvironmentWarningThresholdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotEmpty(typeId), "type_id", typeId)
                .eq(ObjectUtil.isNotEmpty(id), "id", id);
        List<EnvironmentWarningThresholdUser> list = this.list(queryWrapper);
        return list.stream().map(this::getEnvironmentWarningThresholdUserVO).collect(Collectors.toList());
    }

}




