package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.disaster.DisasterReliefAddRequest;
import com.ruoyi.web.domain.dto.disaster.DisasterReliefEditRequest;
import com.ruoyi.web.domain.dto.disaster.DisasterReliefQueryRequest;
import com.ruoyi.web.domain.entity.DisasterRelief;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.vo.DisasterReliefVO;
import com.ruoyi.web.mapper.DisasterReliefMapper;
import com.ruoyi.web.service.DisasterReliefService;
import com.ruoyi.web.service.PersonInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 灾情共度管理服务实现类
 */
@Service
public class DisasterReliefServiceImpl extends ServiceImpl<DisasterReliefMapper, DisasterRelief>
        implements DisasterReliefService {

    @Autowired
    private PersonInfoService personInfoService;

    @Override
    public Integer addDisasterRelief(DisasterReliefAddRequest disasterReliefAddRequest) {
        if (disasterReliefAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }

        try {
            // 1. 检查村民是否存在
            Integer personId = disasterReliefAddRequest.getPersonId();
            if (personId == null || personId <= 0) {
                throw new ServiceException("村民ID不能为空或无效");
            }

            PersonInfo personInfo = personInfoService.getById(personId);
            if (personInfo == null) {
                throw new ServiceException("未找到对应的村民信息");
            }

            // 2. 将请求对象转换为实体对象
            DisasterRelief disasterRelief = new DisasterRelief();
            BeanUtil.copyProperties(disasterReliefAddRequest, disasterRelief);

            // 3. 设置创建时间
            disasterRelief.setCreateTime(new Date());

            // 4. 数据校验
            validDisasterRelief(disasterRelief, BusinessType.INSERT);

            // 5. 保存到数据库
            this.save(disasterRelief);
            return disasterRelief.getId();
        } catch (Exception e) {
            log.error("添加灾情共度记录失败", e);
            throw new ServiceException("添加灾情共度记录失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteDisasterRelief(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("ID不能为空或ID异常");
        }

        try {
            // 分割ID字符串为列表
            java.util.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格式异常");
            }

            // 构建删除条件
            QueryWrapper<DisasterRelief> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", idList);

            // 执行删除（返回是否删除成功）
            return remove(queryWrapper);
        } catch (NumberFormatException e) {
            throw new ServiceException("ID格式错误，请确保所有ID都是数字");
        } catch (Exception e) {
            log.error("删除灾情共度记录失败", e);
            throw new ServiceException("删除灾情共度记录失败: " + e.getMessage());
        }
    }

    @Override
    public void editDisasterRelief(DisasterReliefEditRequest disasterReliefEditRequest) {
        // 判断请求是否为空
        if (disasterReliefEditRequest == null) {
            throw new ServiceException("请求参数为空");
        }

        try {
            // 判断记录是否存在
            Integer id = disasterReliefEditRequest.getId();
            DisasterRelief oldDisasterRelief = this.getById(id);
            if (oldDisasterRelief == null) {
                throw new ServiceException("没有找到对应的灾情共度记录");
            }

            // 检查村民是否存在
            Integer personId = disasterReliefEditRequest.getPersonId();
            if (personId != null && personId > 0) {
                PersonInfo personInfo = personInfoService.getById(personId);
                if (personInfo == null) {
                    throw new ServiceException("未找到对应的村民信息");
                }
            }

            // 将请求对象转换为实体对象
            DisasterRelief disasterRelief = new DisasterRelief();
            BeanUtil.copyProperties(disasterReliefEditRequest, disasterRelief);

            // 设置更新时间
            disasterRelief.setUpdateTime(new Date());

            // 数据校验
            validDisasterRelief(disasterRelief, BusinessType.UPDATE);

            // 更新数据库
            boolean result = this.updateById(disasterRelief);
            if (!result) {
                throw new ServiceException("修改灾情共度记录失败");
            }
        } catch (Exception e) {
            log.error("修改灾情共度记录失败", e);
            throw new ServiceException("修改灾情共度记录失败: " + e.getMessage());
        }
    }

    @Override
    public DisasterReliefVO getDisasterReliefById(int id) {
        if (id <= 0) {
            throw new ServiceException("ID不能为空或ID异常");
        }

        DisasterRelief disasterRelief = this.getById(id);
        if (disasterRelief == null) {
            throw new ServiceException("没有找到对应的灾情共度记录");
        }

        return getDisasterReliefVO(disasterRelief);
    }

    @Override
    public DisasterReliefVO getDisasterReliefVO(DisasterRelief disasterRelief) {
        if (ObjectUtil.isEmpty(disasterRelief)) {
            throw new ServiceException("请求参数不存在");
        }

        DisasterReliefVO disasterReliefVO = new DisasterReliefVO();
        BeanUtils.copyProperties(disasterRelief, disasterReliefVO);

        // 联表查询补充村民信息
        Integer personId = disasterRelief.getPersonId();
        if (personId != null && personId > 0) {
            PersonInfo personInfo = personInfoService.getById(personId);
            if (personInfo != null) {
                // 设置村民姓名
                disasterReliefVO.setName(personInfo.getRealname());
                // 设置村民身份证号
                //disasterReliefVO.setIdCard(personInfoService.decryptIdCard(personInfo.getIdCard()));
                disasterReliefVO.setIdCard(personInfo.getIdCard());
                // 设置村民联系方式
                disasterReliefVO.setPhone(personInfo.getPhone());
            }
        }

        return disasterReliefVO;
    }

    @Override
    public Page<DisasterReliefVO> getListDisasterReliefByPage(DisasterReliefQueryRequest disasterReliefQueryRequest) {
        // 获取分页参数
        long current = disasterReliefQueryRequest.getPageNum();
        long size = disasterReliefQueryRequest.getPageSize();

        // 查询数据
        Page<DisasterRelief> disasterReliefPage = this.page(new Page<>(current, size),
                getQueryWrapper(disasterReliefQueryRequest));

        // 创建结果分页对象
        Page<DisasterReliefVO> resultPage = new Page<>();
        BeanUtils.copyProperties(disasterReliefPage, resultPage, "records");

        // 处理每条记录，转换为VO对象并补充关联数据
        List<DisasterReliefVO> viewList = disasterReliefPage.getRecords().stream()
                .map(this::getDisasterReliefVO)
                .collect(Collectors.toList());

        resultPage.setRecords(viewList);
        return resultPage;
    }

    @Override
    public QueryWrapper<DisasterRelief> getQueryWrapper(DisasterReliefQueryRequest disasterReliefQueryRequest) {
        QueryWrapper<DisasterRelief> queryWrapper = new QueryWrapper<>();
        if (disasterReliefQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        Integer id = disasterReliefQueryRequest.getId();
        Integer personId = disasterReliefQueryRequest.getPersonId();
        String personName = disasterReliefQueryRequest.getPersonName();
        Date startDate = disasterReliefQueryRequest.getStartDate();
        Date endDate = disasterReliefQueryRequest.getEndDate();
        String location = disasterReliefQueryRequest.getLocation();
        String sortField = disasterReliefQueryRequest.getSortField();
        String sortOrder = disasterReliefQueryRequest.getSortOrder();

        // ID查询条件
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);

        // 村民ID查询条件
        queryWrapper.eq(ObjectUtil.isNotEmpty(personId), "person_id", personId);

        // 发生日期范围查询
        if (startDate != null) {
            queryWrapper.ge("date", startDate);
        }
        if (endDate != null) {
            queryWrapper.le("date", endDate);
        }

        // 如果有村民姓名查询条件，则需要联表查询
        if (StrUtil.isNotBlank(personName)) {
            // 通过子查询获取符合条件的村民ID
            String subQuery = "SELECT id FROM person_info WHERE realname LIKE '%" + personName + "%'";
            queryWrapper.inSql("person_id", subQuery);
        }

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

    /**
     * 校验灾情共度数据
     *
     * @param disasterRelief 灾情共度记录
     * @param type           业务操作类型
     */
    public void validDisasterRelief(DisasterRelief disasterRelief, BusinessType type) {
        if (ObjectUtil.isEmpty(disasterRelief)) {
            throw new ServiceException("数据为空");
        }

        // 基础校验
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(disasterRelief.getId())) {
            throw new ServiceException("ID不能为空");
        }

        // 必填项校验
        if (ObjectUtil.isEmpty(disasterRelief.getPersonId())) {
            throw new ServiceException("村民ID不能为空");
        }

        if (ObjectUtil.isEmpty(disasterRelief.getDate())) {
            throw new ServiceException("发生日期不能为空");
        }

        if (StrUtil.isBlank(disasterRelief.getLocation())) {
            throw new ServiceException("发生地点不能为空");
        }
    }
}




