package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
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.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecureSensitiveUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.person.PersonInfoAddRequest;
import com.ruoyi.web.domain.dto.person.PersonInfoEditRequest;
import com.ruoyi.web.domain.dto.person.PersonInfoListQueryRequest;
import com.ruoyi.web.domain.dto.person.PersonInfoQueryRequest;
import com.ruoyi.web.domain.entity.EventTypeAssignee;
import com.ruoyi.web.domain.entity.HouseInfo;
import com.ruoyi.web.domain.entity.HouseholdInfo;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.vo.PersonInfoVO;
import com.ruoyi.web.mapper.HouseInfoMapper;
import com.ruoyi.web.mapper.PersonInfoMapper;
import com.ruoyi.web.service.EventTypeAssigneeService;
import com.ruoyi.web.service.HouseholdInfoService;
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.*;
import java.util.stream.Collectors;

/**
 * 人员信息服务
 */
@Service
public class PersonInfoServiceImpl extends ServiceImpl<PersonInfoMapper, PersonInfo>
        implements PersonInfoService {

    @Autowired
    private HouseInfoMapper houseInfoMapper;

    @Autowired
    private HouseholdInfoService householdInfoService;

    @Resource
    private EventTypeAssigneeService eventTypeAssigneeService;

    @Override
    public Integer addPersonInfo(PersonInfoAddRequest personInfoAddRequest) {
        if (personInfoAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            PersonInfo personInfo = new PersonInfo();
            BeanUtil.copyProperties(personInfoAddRequest, personInfo);
            // 将人口标签 List 转为 String
            personInfo.setPopulationTags(JSONUtil.toJsonStr(personInfoAddRequest.getPopulationTags()));
            // 数据校验 todo
            validPersonInfo(personInfo, BusinessType.INSERT);
//            // 身份证加密
//            String idCard = personInfo.getIdCard();
//            personInfo.setIdCard(this.encryptIdCard(idCard));
            // 保存到数据库
            this.save(personInfo);
            return personInfo.getId();
        } catch (Exception e) {
            log.error("添加人员失败", e);
            throw new ServiceException("添加人员失败");
        }
    }

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

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

    @Override
    public void editPersonInfo(PersonInfoEditRequest personInfoEditRequest) {
        // 判断是否存在
        Integer id = personInfoEditRequest.getId();
        PersonInfo oldPersonInfo = this.getById(id);
        if (oldPersonInfo == null) {
            throw new ServiceException("没有找到人员");
        }
        PersonInfo personInfo = new PersonInfo();
        BeanUtil.copyProperties(personInfoEditRequest, personInfo);
        // 将人口标签 List 转为 String
        personInfo.setPopulationTags(JSONUtil.toJsonStr(personInfoEditRequest.getPopulationTags()));
        personInfo.setUpdateTime(new Date());
        // 数据校验
        validPersonInfo(personInfo, BusinessType.UPDATE);

        // 操作数据库
        boolean result = this.updateById(personInfo);
        if (!result) {
            throw new ServiceException("修改人员操作失败");
        }
    }

    /**
     * 校验人员
     *
     * @param personInfo
     */
    public void validPersonInfo(PersonInfo personInfo, BusinessType type) {
        if (ObjectUtil.isEmpty(personInfo)) {
            throw new ServiceException("数据为空");
        }
        Integer id = personInfo.getId();
        String realname = personInfo.getRealname();
        String idCard = personInfo.getIdCard();
        String ethnic = personInfo.getEthnic();
        Integer age = personInfo.getAge();
        Integer gender = personInfo.getGender();
        Date birthDate = personInfo.getBirthDate();
        Integer populationCategory = personInfo.getPopulationCategory();
        String phone = personInfo.getPhone();
        String populationTags = personInfo.getPopulationTags();
        String occupation = personInfo.getOccupation();
        String grid = personInfo.getGrid();
        String educationLevel = personInfo.getEducationLevel();
        Integer maritalStatus = personInfo.getMaritalStatus();
        String politicalStatus = personInfo.getPoliticalStatus();
        String religion = personInfo.getReligion();
        String photoUrl = personInfo.getPhotoUrl();
        Integer householdId = personInfo.getHouseholdId();
        String householdRelation = personInfo.getHouseholdRelation();
        String specialIdentity = personInfo.getSpecialIdentity();
        Date createTime = personInfo.getCreateTime();
        String createBy = personInfo.getCreateBy();
        Date updateTime = personInfo.getUpdateTime();
        String updateBy = personInfo.getUpdateBy();
        String delFlag = personInfo.getDelFlag();

        // 修改数据时，id 不能为空 todo
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(realname)) {
            throw new ServiceException("姓名不能为空");
        }
    }

    /**
     * 根据id获取人员包装类
     *
     * @param id
     * @return
     */
    @Override
    public PersonInfoVO getPersonInfoById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        PersonInfo personInfo = this.getById(id);
        return getPersonInfoVO(personInfo);
    }

    /**
     * 根据 系统用户id 获取人员包装类列表
     *
     * @param userIds
     * @return
     */
    @Override
    public List<PersonInfoVO> getPersonInfoVOListByUserIds(List<Integer> userIds) {
        if (ObjectUtil.isEmpty(userIds)) {
            throw new ServiceException("系统用户id不能为空或id异常");
        }
        // 1. 批量查询 PersonInfo
        QueryWrapper<PersonInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIds);
        List<PersonInfo> personInfoList = this.list(wrapper);

        // 2. 转换为 VO 列表
        return personInfoList.stream()
                .map(this::getPersonInfoVO)
                .collect(Collectors.toList());
    }


    /**
     * 分页获取人员列表
     *
     * @param personInfoQueryRequest
     * @return
     */
    @Override
    public Page<PersonInfoVO> getListPersonInfoByPage(PersonInfoQueryRequest personInfoQueryRequest) {
        long current = personInfoQueryRequest.getPageNum();
        long size = personInfoQueryRequest.getPageSize();
        Page<PersonInfo> personInfoPage = this.page(new Page<>(current, size),
                getQueryWrapper(personInfoQueryRequest));

        // 2. 补充关联数据
        Page<PersonInfoVO> resultPage = new Page<>();
        BeanUtils.copyProperties(personInfoPage, resultPage, "records");

        // 3. 处理每条记录
        List<PersonInfoVO> viewList = personInfoPage.getRecords().stream().map(personInfo -> {
            return getPersonInfoVO(personInfo);
        }).collect(Collectors.toList());
        resultPage.setRecords(viewList);
        return resultPage;
    }

    /**
     * 获取人员列表
     *
     * @param personInfoListQueryRequest
     * @return
     */
    @Override
    public List<PersonInfoVO> getPersonInfoVOList(PersonInfoListQueryRequest personInfoListQueryRequest) {

        QueryWrapper<PersonInfo> queryWrapper = new QueryWrapper<>();
        String realname = personInfoListQueryRequest.getRealname();
        String idCard = personInfoListQueryRequest.getIdCard();
        String phone = personInfoListQueryRequest.getPhone();

        // 姓名、身份证、电话 模糊查询
        queryWrapper.like(StrUtil.isNotBlank(realname), "realname", realname);
        queryWrapper.like(StrUtil.isNotBlank(idCard), "idCard", idCard);
        queryWrapper.like(StrUtil.isNotBlank(phone), "phone", phone);
        List<PersonInfo> list = this.list(queryWrapper);
        QueryWrapper<EventTypeAssignee> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT user_id");
        List<EventTypeAssignee> eventTypeAssigneeList = eventTypeAssigneeService.list(wrapper);
        // 3. 提取所有存在的 user_id（已去重）
        Set<Integer> existingUserIds = eventTypeAssigneeList.stream()
                .map(EventTypeAssignee::getUserId)
                .collect(Collectors.toSet());

        // 4. 处理每条记录
        return list.stream().map(personInfo->{
            PersonInfoVO personInfoVO = getPersonInfoVO(personInfo);
            personInfoVO.setLeader(existingUserIds.contains(personInfo.getUserId()));
            return personInfoVO;
        }).collect(Collectors.toList());
    }


    /**
     * 获取人员包装类
     *
     * @param personInfo
     * @return
     */
    @Override
    public PersonInfoVO getPersonInfoVO(PersonInfo personInfo) {
        if (ObjectUtil.isEmpty(personInfo)) {
            throw new ServiceException("请求参数不存在");
        }
        PersonInfoVO personInfoVO = new PersonInfoVO();
        BeanUtils.copyProperties(personInfo, personInfoVO);
//        // 获取身份证号 解密
//        String idCard = personInfoVO.getIdCard();
//        idCard = this.decryptIdCard(idCard);
//        personInfoVO.setIdCard(idCard);

        // 联表查询补充数据
        if (personInfo.getHouseholdId() != null) {
            // 查询户籍信息
//            HouseholdInfo household = householdInfoService.getById(personInfo.getHouseholdId());
//            if (household != null) {
                //户主姓名
//                int householdHeadId = personInfo.getHouseholdHeadId();
//                PersonInfo householdHead = this.getById(householdHeadId);
//                //String householdHead = household.getHouseholdHead();
//                if (householdHead != null) {
//                    // 户主姓名
//                    personInfoVO.setHouseHoldHead(householdHead.getRealname());
//                }
                // 查询房屋信息
//                if (StrUtil.isNotBlank(household.getHouseCode())) {
//                    HouseInfo house = houseInfoMapper.selectOne(
//                            new QueryWrapper<HouseInfo>()
//                                    .eq("house_code", household.getHouseCode())
//                                    .last("LIMIT 1"));
//                    if (house != null) {
//                        // 房屋编号
//                        personInfoVO.setHouseCode(house.getHouseCode());
//                        // 门牌号
//                        personInfoVO.setDoorplateNumber(house.getDoorplateNumber());
//                        // 房主姓名
//                        Long houseOwnerId = house.getHouseOwnerId();
//                        PersonInfo houseOwner;
//                        String houseOwnerName = null;
//                        if (houseOwnerId != null) {
//                            houseOwner = this.getById(houseOwnerId);
//                            houseOwnerName = houseOwner.getRealname();
//                        }
//                        personInfoVO.setHouseOwnerName(houseOwnerName);
//                    }
//                }
////            }
        }
        return personInfoVO;
    }

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

        // 从对象中取值
        Integer id = personInfoQueryRequest.getId();
        String realname = personInfoQueryRequest.getRealname();
        String ethnic = personInfoQueryRequest.getEthnic();
        String doorplateNumber = personInfoQueryRequest.getDoorplateNumber();
        String specialIdentity = personInfoQueryRequest.getSpecialIdentity();
        List<String> populationTags = personInfoQueryRequest.getPopulationTags();
        String sortField = personInfoQueryRequest.getSortField();
        String sortOrder = personInfoQueryRequest.getSortOrder();

        // 姓名、民族、房屋门牌号、特殊身份、人口标签
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.like(StrUtil.isNotBlank(realname), "realname", realname);
        queryWrapper.eq(StrUtil.isNotBlank(ethnic), "ethnic", ethnic);
        queryWrapper.eq(StrUtil.isNotBlank(specialIdentity), "special_identity", specialIdentity);

        // 门牌号查询人员列表
        if (StrUtil.isNotBlank(doorplateNumber)) {
            String subQuery = "SELECT hd.id FROM household_info hd " +
                              "JOIN house_info hi ON hd.house_code = hi.house_code " +
                              "WHERE hi.doorplate_number = '" + doorplateNumber + "'";
            queryWrapper.inSql("household_id", subQuery);
        }

        // 人口标签 JSON 数组查询
        if (CollUtil.isNotEmpty(populationTags)) {
            for (String tag : populationTags) {
                queryWrapper.like("population_tags", "\"" + tag + "\"");
            }
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }

    /**
     * 解密身份证
     *
     * @param idCard
     * @return
     */
    @Override
    public String decryptIdCard(String idCard) {
        try {
            idCard = SecureSensitiveUtils.decrypt(idCard, SecureSensitiveUtils.generateAesKey());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return idCard;
    }

    /**
     * 加密身份证
     *
     * @param idCard
     * @return
     */
    @Override
    public String encryptIdCard(String idCard) {
        try {
            idCard = SecureSensitiveUtils.encrypt(idCard, SecureSensitiveUtils.generateAesKey());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return idCard;
    }

    /**
     * 根据人口id列表 获取 系统用户 id列表
     *
     * @param personIds
     * @return
     */
    @Override
    public List<Integer> getUserIdListByPersonIds(List<Integer> personIds) {
        if (ObjectUtil.isEmpty(personIds)) {
            throw new ServiceException("参数为空");
        }
        // 2. 查询数据库获取user_id列表
        QueryWrapper<PersonInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_id")
                .in("id", personIds)
                .isNotNull("user_id");

        List<PersonInfo> personInfoList = this.list(queryWrapper);

        // 3. 提取user_id并去重
        return personInfoList.stream()
                .map(PersonInfo::getUserId)
                .filter(Objects::nonNull) // 过滤掉null值
                .distinct() // 去重
                .collect(Collectors.toList());
    }
}




