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.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.dto.VillageService.VillageServiceAddRequest;
import com.ruoyi.web.domain.dto.VillageService.VillageServiceEditRequest;
import com.ruoyi.web.domain.dto.VillageService.VillageServiceQueryRequest;
import com.ruoyi.web.domain.entity.VillageService;
import com.ruoyi.web.domain.enums.VillageServiceEnum;
import com.ruoyi.web.domain.vo.VillageServiceVO;
import com.ruoyi.web.mapper.VillageServiceMapper;
import com.ruoyi.web.service.VillageServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class VillageServiceServiceImpl extends ServiceImpl<VillageServiceMapper, VillageService>
        implements VillageServiceService {

    @Autowired
    private ISysUserService userService;

    @Override
    public Integer addVillageService(VillageServiceAddRequest villageServiceAddRequest) {
        if (villageServiceAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            VillageService villageService = new VillageService();
            BeanUtil.copyProperties(villageServiceAddRequest, villageService);
            //数据校验
            validVillageService(villageService, BusinessType.INSERT);
            Integer status = villageService.getStatus();
            if (status.equals(VillageServiceEnum.PUBLISHED.getValue())) {
                // 填充发布日期和发布人
                villageService.setDate(new Date()); // 设置发布日期为当前时间
                Long userId = SecurityUtils.getUserId();
                villageService.setIssuerId(userId.intValue());// 设置发布人ID
                villageService.setStatus(VillageServiceEnum.PUBLISHED.getValue());
            }
            // 保存到数据库
            this.save(villageService);
            return villageService.getId();
        } catch (Exception e) {
            log.error("添加服务与支持失败", e);
            throw new ServiceException("添加服务与支持失败");
        }
    }

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

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

    @Override
    public void editVillageService(VillageServiceEditRequest villageServiceEditRequest) {
        // 判断是否存在
        Integer id = villageServiceEditRequest.getId();
        VillageService oldVillageService = this.getById(id);
        if (oldVillageService == null) {
            throw new ServiceException("没有找到服务与支持");
        }
        VillageService villageService = new VillageService();
        BeanUtil.copyProperties(villageServiceEditRequest, villageService);
        villageService.setUpdateTime(new Date());

        //如果修改状态为 发布 时，填充 发布日期 和 发布人
        if (VillageServiceEnum.PUBLISHED.getValue() == villageService.getStatus()) {
            // 填充发布日期和发布人
            villageService.setDate(new Date()); // 设置发布日期为当前时间
            Long userId = SecurityUtils.getUserId();
            villageService.setIssuerId(userId.intValue());// 设置发布人ID
        }

        // 数据校验
        validVillageService(villageService, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(villageService);
        if (!result) {
            throw new ServiceException("修改服务与支持操作失败");
        }
    }

    /**
     * 发布
     *
     * @param id
     * @return
     */
    @Override
    public boolean publishVillageService(int id) {
        if (id <= 0) {
            throw new ServiceException("参数错误");
        }
        VillageService villageService = this.getById(id);
        if (villageService == null) {
            throw new ServiceException("没有找到服务与支持");
        }
        Integer status = villageService.getStatus();
        if (status.equals(VillageServiceEnum.NON_PUBLISHED.getValue())) {
            // 填充发布日期和发布人
            villageService.setDate(new Date()); // 设置发布日期为当前时间
            Long userId = SecurityUtils.getUserId();
            villageService.setIssuerId(userId.intValue());// 设置发布人ID
            villageService.setStatus(VillageServiceEnum.PUBLISHED.getValue());
            this.updateById(villageService);
        } else {
            throw new ServiceException("只有未发布的才能发布");
        }
        return true;
    }

    /**
     * 下架
     *
     * @param id
     * @return
     */
    @Override
    public boolean removeVillageService(int id) {
        if (id <= 0) {
            throw new ServiceException("参数错误");
        }
        VillageService villageService = this.getById(id);
        if (villageService == null) {
            throw new ServiceException("没有找到服务与支持");
        }
        Integer status = villageService.getStatus();
        if (status.equals(VillageServiceEnum.PUBLISHED.getValue())) {
            villageService.setStatus(VillageServiceEnum.REMOVED.getValue());
        } else {
            throw new ServiceException("发布的才能下架");
        }
        this.updateById(villageService);
        return true;
    }


    /**
     * 校验服务与支持
     *
     * @param villageService
     */
    public void validVillageService(VillageService villageService, BusinessType type) {
        if (ObjectUtil.isEmpty(villageService)) {
            throw new ServiceException("数据为空");
        }
        Integer id = villageService.getId();
        String title = villageService.getTitle();
        String tag = villageService.getTag();
        String serviceType = villageService.getType();
        String content = villageService.getContent();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(title)) {
            throw new ServiceException("标题不能为空");
        }
        if (StrUtil.isBlank(tag)) {
            throw new ServiceException("标签不能为空");
        }
        if (StrUtil.isBlank(serviceType)) {
            throw new ServiceException("类型不能为空");
        }
        if (StrUtil.isBlank(content)) {
            throw new ServiceException("内容不能为空");
        }
    }


    @Override
    public VillageServiceVO getVillageServiceById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        VillageService villageService = this.getById(id);
        if (villageService == null) {
            return null;
        }
        return getVillageServiceVO(villageService);
    }

    @Override
    public Page<VillageServiceVO> getListVillageServiceByPage(VillageServiceQueryRequest villageServiceQueryRequest) {
        long current = villageServiceQueryRequest.getPageNum();
        long size = villageServiceQueryRequest.getPageSize();
        Page<VillageService> servicePage = this.page(new Page<>(current, size),
                getQueryWrapper(villageServiceQueryRequest));

        // 创建VO分页对象
        Page<VillageServiceVO> voPage = new Page<>(current, size, servicePage.getTotal());

        // 转换为VO列表
        List<VillageServiceVO> voList = new ArrayList<>();
        for (VillageService service : servicePage.getRecords()) {
            voList.add(getVillageServiceVO(service));
        }

        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 将实体转换为VO，并填充发布人信息
     */
    @Override
    public VillageServiceVO getVillageServiceVO(VillageService villageService) {
        VillageServiceVO vo = new VillageServiceVO();
        BeanUtil.copyProperties(villageService, vo);

        // 如果有发布人ID，获取发布人信息
        Integer issuerId = villageService.getIssuerId();
        if (issuerId != null) {
            try {
                SysUser user = userService.selectUserById(issuerId.longValue());
                if (user != null) {
                    Map<String, String> issuer = new HashMap<>();
                    issuer.put("nickName", user.getNickName());
                    // 填充其他信息
                    vo.setIssuer(issuer);
                }
            } catch (Exception e) {
                log.error("获取发布人信息失败", e);
                throw new ServiceException("获取发布人信息失败");
            }
        }

        return vo;
    }

    @Override
    public QueryWrapper<VillageService> getQueryWrapper(VillageServiceQueryRequest villageServiceQueryRequest) {
        QueryWrapper<VillageService> queryWrapper = new QueryWrapper<>();
        if (villageServiceQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        String tag = villageServiceQueryRequest.getTag();
        String keyword = villageServiceQueryRequest.getKeyword();
        Date startTime = villageServiceQueryRequest.getStartTime();
        Date endTime = villageServiceQueryRequest.getEndTime();
        Integer status = villageServiceQueryRequest.getStatus();
        String sortField = villageServiceQueryRequest.getSortField();
        String sortOrder = villageServiceQueryRequest.getSortOrder();

        queryWrapper.eq(ObjectUtil.isNotEmpty(status), "status", status)
                .eq(StrUtil.isNotEmpty(tag), "tag", tag);

        // 如果关键字不为空，添加模糊查询条件  标题或内容
        if (StrUtil.isNotBlank(keyword)) {
            queryWrapper.like("title", keyword)
                    .or()
                    .like("content", keyword);
        }
        // 日期范围查询（优先判断范围）
        if (startTime != null && endTime != null) {
            queryWrapper.between("date", startTime, endTime);
        } else if (startTime != null) {
            queryWrapper.ge("date", startTime); // >= 开始日期
        } else if (endTime != null) {
            queryWrapper.le("date", endTime);   // <= 结束日期
        }

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




