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.government.GovernmentInfoAddRequest;
import com.ruoyi.web.domain.dto.government.GovernmentInfoEditRequest;
import com.ruoyi.web.domain.dto.government.GovernmentInfoQueryRequest;
import com.ruoyi.web.domain.entity.GovernmentInfo;
import com.ruoyi.web.domain.enums.GovernmentInfoEnum;
import com.ruoyi.web.domain.vo.GovernmentInfoVO;
import com.ruoyi.web.mapper.GovernmentInfoMapper;
import com.ruoyi.web.service.GovernmentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 *
 */
@Service
public class GovernmentInfoServiceImpl extends ServiceImpl<GovernmentInfoMapper, GovernmentInfo>
    implements GovernmentInfoService {
    @Autowired
    private ISysUserService userService;

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

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

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

    @Override
    public void editGovernmentInfo(GovernmentInfoEditRequest governmentInfoEditRequest) {
        // 判断是否存在
        Integer id = governmentInfoEditRequest.getId();
        GovernmentInfo oldGovernmentInfo = this.getById(id);
        if (oldGovernmentInfo == null) {
            throw new ServiceException("没有找到政务信息");
        }
        GovernmentInfo governmentInfo = new GovernmentInfo();
        BeanUtil.copyProperties(governmentInfoEditRequest, governmentInfo);
        governmentInfo.setUpdateTime(new Date());

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

        // 数据校验
        validGovernmentInfo(governmentInfo, BusinessType.UPDATE);
        // 操作数据库
        boolean result = this.updateById(governmentInfo);
        if (!result) {
            throw new ServiceException("修改政务信息操作失败");
        }
    }

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

    /**
     * 下架
     *
     * @param id
     * @return
     */
    @Override
    public boolean removeGovernmentInfo(int id) {
        if (id <= 0) {
            throw new ServiceException("参数错误");
        }
        GovernmentInfo governmentInfo = this.getById(id);
        if (governmentInfo == null) {
            throw new ServiceException("没有找到政务信息");
        }
        Integer status = governmentInfo.getStatus();
        if (status.equals(GovernmentInfoEnum.PUBLISHED.getValue())) {
            governmentInfo.setStatus(GovernmentInfoEnum.REMOVED.getValue());
        } else {
            throw new ServiceException("发布的才能下架");
        }
        this.updateById(governmentInfo);
        return true;
    }


    /**
     * 校验政务信息
     *
     * @param governmentInfo
     */
    public void validGovernmentInfo(GovernmentInfo governmentInfo, BusinessType type) {
        if (ObjectUtil.isEmpty(governmentInfo)) {
            throw new ServiceException("数据为空");
        }
        Integer id = governmentInfo.getId();
        String title = governmentInfo.getTitle();
        String tag = governmentInfo.getTag();
        String serviceType = governmentInfo.getType();
        String content = governmentInfo.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 GovernmentInfoVO getGovernmentInfoById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        GovernmentInfo governmentInfo = this.getById(id);
        if (governmentInfo == null) {
            return null;
        }
        return getGovernmentInfoVO(governmentInfo);
    }

    @Override
    public Page<GovernmentInfoVO> getListGovernmentInfoByPage(GovernmentInfoQueryRequest governmentInfoQueryRequest) {
        long current = governmentInfoQueryRequest.getPageNum();
        long size = governmentInfoQueryRequest.getPageSize();
        Page<GovernmentInfo> servicePage = this.page(new Page<>(current, size),
                getQueryWrapper(governmentInfoQueryRequest));

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

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

        voPage.setRecords(voList);
        return voPage;
    }

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

        // 如果有发布人ID，获取发布人信息
        Integer issuerId = governmentInfo.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<GovernmentInfo> getQueryWrapper(GovernmentInfoQueryRequest governmentInfoQueryRequest) {
        QueryWrapper<GovernmentInfo> queryWrapper = new QueryWrapper<>();
        if (governmentInfoQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        String tag = governmentInfoQueryRequest.getTag();
        String keyword = governmentInfoQueryRequest.getKeyword();
        Date startTime = governmentInfoQueryRequest.getStartTime();
        Date endTime = governmentInfoQueryRequest.getEndTime();
        Integer status = governmentInfoQueryRequest.getStatus();
        String sortField = governmentInfoQueryRequest.getSortField();
        String sortOrder = governmentInfoQueryRequest.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;
    }

    @Override
    public Page<GovernmentInfoVO> pageFaBu(GovernmentInfoQueryRequest governmentInfoQueryRequest) {
        long current = governmentInfoQueryRequest.getPageNum();
        long size = governmentInfoQueryRequest.getPageSize();
        Page<GovernmentInfo> servicePage = this.page(new Page<>(current, size),
                getQueryWrapper(governmentInfoQueryRequest));

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

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

        voPage.setRecords(voList);
        return voPage;
    }
}




