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.web.domain.dto.VillageProfile.VillageProfileAddRequest;
import com.ruoyi.web.domain.dto.VillageProfile.VillageProfileEditRequest;
import com.ruoyi.web.domain.dto.VillageProfile.VillageProfileQueryRequest;
import com.ruoyi.web.domain.entity.VillageProfile;
import com.ruoyi.web.domain.vo.VillageProfileVO;
import com.ruoyi.web.mapper.VillageProfileMapper;
import com.ruoyi.web.service.PersonInfoService;
import com.ruoyi.web.service.VillageProfileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 村庄概况服务实现
 */
@Slf4j
@Service
public class VillageProfileServiceImpl extends ServiceImpl<VillageProfileMapper, VillageProfile>
        implements VillageProfileService {

    @Autowired
    private PersonInfoService personInfoService;

    @Override
    public Integer addVillageProfile(VillageProfileAddRequest villageProfileAddRequest) {
        if (villageProfileAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            VillageProfile villageProfile = new VillageProfile();
            BeanUtil.copyProperties(villageProfileAddRequest, villageProfile);
            // 数据校验
            validVillageProfile(villageProfile, BusinessType.INSERT);
            // 保存到数据库
            this.save(villageProfile);
            return villageProfile.getId();
        } catch (Exception e) {
            log.error("添加村庄概况失败", e);
            throw new ServiceException("添加村庄概况失败");
        }
    }

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

        // 分割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格式异常");
        }

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

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

    @Override
    public void editVillageProfile(VillageProfileEditRequest villageProfileEditRequest) {
        // 判断是否存在
        Integer id = villageProfileEditRequest.getId();
        VillageProfile oldVillageProfile = this.getById(id);
        if (oldVillageProfile == null) {
            throw new ServiceException("没有找到村庄概况信息");
        }
        
        VillageProfile villageProfile = new VillageProfile();
        BeanUtil.copyProperties(villageProfileEditRequest, villageProfile);
        villageProfile.setUpdateTime(new Date());
        // 数据校验
        validVillageProfile(villageProfile, BusinessType.UPDATE);
        
        // 操作数据库
        boolean result = this.updateById(villageProfile);
        if (!result) {
            throw new ServiceException("修改村庄概况操作失败");
        }
    }

    @Override
    public VillageProfileVO getVillageProfileById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        VillageProfile villageProfile = this.getById(id);
        if (villageProfile == null) {
            return null;
        }
        
        return convertToVillageProfileVO(villageProfile);
    }

    @Override
    public Page<VillageProfileVO> getListVillageProfileByPage(VillageProfileQueryRequest villageProfileQueryRequest) {
        long current = villageProfileQueryRequest.getPageNum();
        long size = villageProfileQueryRequest.getPageSize();
        
        // 分页查询村庄概况信息
        Page<VillageProfile> profilePage = this.page(new Page<>(current, size),
                getQueryWrapper(villageProfileQueryRequest));
        
        // 创建VO分页对象
        Page<VillageProfileVO> voPage = new Page<>(current, size, profilePage.getTotal());
        
        // 转换为VO列表
        List<VillageProfileVO> voList = new ArrayList<>();
        for (VillageProfile profile : profilePage.getRecords()) {
            voList.add(convertToVillageProfileVO(profile));
        }
        
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public QueryWrapper<VillageProfile> getQueryWrapper(VillageProfileQueryRequest villageProfileQueryRequest) {
        QueryWrapper<VillageProfile> queryWrapper = new QueryWrapper<>();
        if (villageProfileQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        String name = villageProfileQueryRequest.getName();
        String sortField = villageProfileQueryRequest.getSortField();
        String sortOrder = villageProfileQueryRequest.getSortOrder();

        // 构建查询条件
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField),  "ascend".equals(sortOrder), sortField);
        return queryWrapper;
    }

    /**
     * 校验村庄概况
     *
     * @param villageProfile 村庄概况
     * @param type 业务类型
     */
    private void validVillageProfile(VillageProfile villageProfile, BusinessType type) {
        if (ObjectUtil.isEmpty(villageProfile)) {
            throw new ServiceException("数据为空");
        }
        
        Integer id = villageProfile.getId();
        String name = villageProfile.getName();
        String region = villageProfile.getRegion();
        String introduction = villageProfile.getIntroduction();
        String images = villageProfile.getImages();

        // 添加时id无需校验，修改时id不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("村庄名称不能为空");
        }
        if (StrUtil.isBlank(region)) {
            throw new ServiceException("所属区域不能为空");
        }
        if (StrUtil.isBlank(introduction)) {
            throw new ServiceException("村庄简介不能为空");
        }
        if (StrUtil.isBlank(images)) {
            throw new ServiceException("村图片不能为空");
        }
    }

    /**
     * 将实体转换为VO，处理村民数量和区域信息
     */
    private VillageProfileVO convertToVillageProfileVO(VillageProfile profile) {
        VillageProfileVO vo = new VillageProfileVO();
        BeanUtil.copyProperties(profile, vo);

        // 村民数量
        int count = personInfoService.count();
        if (count>0){
            vo.setVillagerCount(count);
        }
        return vo;
    }
} 