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.villageCommitteeRole.VillageCommitteeRoleUserAddRequest;
import com.ruoyi.web.domain.dto.villageCommitteeRole.VillageCommitteeRoleUserEditRequest;
import com.ruoyi.web.domain.dto.villageCommitteeRole.VillageCommitteeRoleUserQueryRequest;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.entity.VillageCommitteeRole;
import com.ruoyi.web.domain.entity.VillageCommitteeRoleUser;
import com.ruoyi.web.domain.vo.PersonInfoVO;
import com.ruoyi.web.domain.vo.VillageCommitteeRoleUserVO;
import com.ruoyi.web.mapper.VillageCommitteeRoleUserMapper;
import com.ruoyi.web.service.PersonInfoService;
import com.ruoyi.web.service.VillageCommitteeRoleService;
import com.ruoyi.web.service.VillageCommitteeRoleUserService;
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 VillageCommitteeRoleUserServiceImpl extends ServiceImpl<VillageCommitteeRoleUserMapper, VillageCommitteeRoleUser>
        implements VillageCommitteeRoleUserService {

    @Resource
    private VillageCommitteeRoleService villageCommitteeRoleService;

    @Resource
    private PersonInfoService personInfoService;

    @Override
    public Integer addVillageCommitteeRoleUser(VillageCommitteeRoleUserAddRequest villageCommitteeRoleUserAddRequest) {
        if (villageCommitteeRoleUserAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            VillageCommitteeRoleUser villageCommitteeRoleUser = new VillageCommitteeRoleUser();
            Integer personId = villageCommitteeRoleUserAddRequest.getPersonId();
            QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
            wrapper.select("user_id")
                    .eq("id", personId);
            PersonInfo one = personInfoService.getOne(wrapper);
            villageCommitteeRoleUser.setUserId(one.getUserId());
            villageCommitteeRoleUser.setRoleId(villageCommitteeRoleUserAddRequest.getRoleId());
            //数据校验
            Integer roleId = villageCommitteeRoleUser.getRoleId();
            QueryWrapper<VillageCommitteeRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", roleId);
            int count = villageCommitteeRoleService.count(queryWrapper);
            if (count <= 0) {
                throw new ServiceException("不存在该村委类型");
            }
            // 保存到数据库
            this.save(villageCommitteeRoleUser);
            return villageCommitteeRoleUser.getId();
        } catch (Exception e) {
            log.error("添加失败", e);
            throw new ServiceException("添加失败");
        }
    }

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

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

    @Override
    public void editVillageCommitteeRoleUser(VillageCommitteeRoleUserEditRequest villageCommitteeRoleUserEditRequest) {
        // 判断是否存在
        Integer id = villageCommitteeRoleUserEditRequest.getId();
        VillageCommitteeRoleUser oldVillageCommitteeRoleUser = this.getById(id);
        if (oldVillageCommitteeRoleUser == null) {
            throw new ServiceException("没有找到村委");
        }
        VillageCommitteeRoleUser villageCommitteeRoleUser = new VillageCommitteeRoleUser();
        Integer personId = villageCommitteeRoleUserEditRequest.getPersonId();
        QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
        wrapper.select("user_id")
                .eq("id", personId);
        PersonInfo one = personInfoService.getOne(wrapper);
        villageCommitteeRoleUser.setUserId(one.getUserId());
        villageCommitteeRoleUser.setRoleId(villageCommitteeRoleUserEditRequest.getRoleId());
        villageCommitteeRoleUser.setUpdateTime(new Date());
        // 数据校验
        Integer roleId = villageCommitteeRoleUser.getRoleId();
        QueryWrapper<VillageCommitteeRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        int count = villageCommitteeRoleService.count(queryWrapper);
        if (count <= 0) {
            throw new ServiceException("不存在该村委类型");
        }
        // 操作数据库
        boolean result = this.updateById(villageCommitteeRoleUser);
        if (!result) {
            throw new ServiceException("修改村委操作失败");
        }
    }


    @Override
    public VillageCommitteeRoleUserVO getVillageCommitteeRoleUserVOById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        VillageCommitteeRoleUser villageCommitteeRoleUser = this.getById(id);
        if (villageCommitteeRoleUser == null) {
            throw new ServiceException("未找到村委");
        }
        return getVillageCommitteeRoleUserVO(villageCommitteeRoleUser);
    }

    @Override
    public VillageCommitteeRoleUserVO getVillageCommitteeRoleUserVO(VillageCommitteeRoleUser villageCommitteeRoleUser) {
        if (ObjectUtil.isEmpty(villageCommitteeRoleUser)) {
            throw new ServiceException("请求参数不存在");
        }
        VillageCommitteeRoleUserVO villageCommitteeRoleUserVO = new VillageCommitteeRoleUserVO();
        BeanUtils.copyProperties(villageCommitteeRoleUser, villageCommitteeRoleUserVO);
        // 填充村委角色类型
        Integer roleId = villageCommitteeRoleUser.getRoleId();
        VillageCommitteeRole villageCommitteeRole = villageCommitteeRoleService.getById(roleId);
        villageCommitteeRoleUserVO.setRole(villageCommitteeRole.getType());
        // 填充村委信息
        Integer userId = villageCommitteeRoleUser.getUserId();
        QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        PersonInfo one = personInfoService.getOne(wrapper);
        PersonInfoVO personInfoVO = personInfoService.getPersonInfoVO(one);
        villageCommitteeRoleUserVO.setPersonInfo(personInfoVO);
        return villageCommitteeRoleUserVO;
    }


    @Override
    public List<VillageCommitteeRoleUserVO> getListVillageCommitteeRoleUserVO(VillageCommitteeRoleUserQueryRequest villageCommitteeRoleUserQueryRequest) {

        if (ObjectUtil.isEmpty(villageCommitteeRoleUserQueryRequest)) {
            throw new ServiceException("请求参数为空");
        }
        Integer id = villageCommitteeRoleUserQueryRequest.getId();
        Integer roleId = villageCommitteeRoleUserQueryRequest.getRoleId();
        QueryWrapper<VillageCommitteeRoleUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtil.isNotEmpty(roleId), "role_id", roleId)
                .eq(ObjectUtil.isNotEmpty(id), "id", id);
        List<VillageCommitteeRoleUser> list = this.list(queryWrapper);
        return list.stream().map(this::getVillageCommitteeRoleUserVO).collect(Collectors.toList());
    }
}




