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.projects.ProjectsAddRequest;
import com.ruoyi.web.domain.dto.projects.ProjectsEditRequest;
import com.ruoyi.web.domain.dto.projects.ProjectsQueryRequest;
import com.ruoyi.web.domain.entity.Projects;
import com.ruoyi.web.domain.vo.ProjectsVO;
import com.ruoyi.web.mapper.ProjectsMapper;
import com.ruoyi.web.service.ProjectsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * 项目服务
 */
@Service
public class ProjectsServiceImpl extends ServiceImpl<ProjectsMapper, Projects>
        implements ProjectsService {

    /**
     * 添加
     *
     * @param projectsAddRequest
     * @return
     */
    @Override
    public Integer addProjects(ProjectsAddRequest projectsAddRequest) {
        if (projectsAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            // 转换为实体对象
            Projects projects = new Projects();
            BeanUtil.copyProperties(projectsAddRequest, projects);
            //数据校验
            validProjects(projects, BusinessType.INSERT);

            // 保存到数据库
            this.save(projects);
            return projects.getId();
        } catch (Exception e) {
            log.error("添加项目失败", e);
            throw new ServiceException("添加项目失败");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteProjects(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<Projects> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

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

    }

    /**
     * 编辑
     *
     * @param projectsEditRequest
     */
    @Override
    public void editProjects(ProjectsEditRequest projectsEditRequest) {
        // 判断是否存在
        Integer id = projectsEditRequest.getId();
        Projects oldProjects = this.getById(id);
        if (oldProjects == null) {
            throw new ServiceException("没有找到项目");
        }
        Projects projects = new Projects();
        BeanUtil.copyProperties(projectsEditRequest, projects);
        projects.setUpdateTime(new Date());
        // 数据校验
        validProjects(projects, BusinessType.UPDATE);
        // 如果有实际建成日期 更新项目进度
        if (ObjectUtil.isNotNull(projects.getActualCompletionDate())) {
            if (projects.getActualCompletionDate().after(new Date())) {
                throw new ServiceException("实际建成日期不能是未来日期");
            }
            projects.setProgress(1);
        }
        // 操作数据库
        boolean result = this.updateById(projects);
        if (!result) {
            throw new ServiceException("修改项目操作失败");
        }
    }

    /**
     * 建成
     *
     * @param id
     * @param date
     * @return
     */
    @Override
    public boolean completedProjects(int id, Date date) {
        Projects projects = this.getById(id);
        if (projects == null) {
            throw new ServiceException("没有找到项目");
        }
        // 如果有实际建成日期 更新项目进度
        if (ObjectUtil.isNotNull(date)) {
            if (date.after(new Date())) {
                throw new ServiceException("实际建成日期不能是未来日期");
            }
            projects.setActualCompletionDate(date);
            projects.setProgress(1);
        }
        boolean result = this.updateById(projects);
        if (!result) {
            throw new ServiceException("操作失败");
        }
        return true;
    }

    /**
     * 校验数据
     *
     * @param projects
     */
    public void validProjects(Projects projects, BusinessType type) {
        if (ObjectUtil.isEmpty(projects)) {
            throw new ServiceException("数据为空");
        }
        // 从对象中取值
        Integer id = projects.getId();
        String projectName = projects.getProjectName();
        String projectDescription = projects.getProjectDescription();
        BigDecimal investmentAmount = projects.getInvestmentAmount();
        Date startDate = projects.getStartDate();
        Date estimatedCompletionDate = projects.getEstimatedCompletionDate();
        Date actualCompletionDate = projects.getActualCompletionDate();
        Integer progress = projects.getProgress();

        // 添加id无需校验，修改时，id 不能为空
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(projectName)) {
            throw new ServiceException("项目名称不能为空");
        }
        if (ObjectUtil.isEmpty(investmentAmount)) {
            throw new ServiceException("投资金额不能为空");
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public ProjectsVO getProjectsById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        Projects projects = this.getById(id);
        return getProjectsVO(projects);
    }

    /**
     * 获取项目包装类
     *
     * @param projects
     * @return
     */
    @Override
    public ProjectsVO getProjectsVO(Projects projects) {
        if (ObjectUtil.isEmpty(projects)) {
            throw new ServiceException("请求参数不存在");
        }
        ProjectsVO projectsVO = new ProjectsVO();
        BeanUtils.copyProperties(projects, projectsVO);
        return projectsVO;
    }

    /**
     * 分页获取项目列表
     *
     * @param projectsQueryRequest
     * @return
     */
    @Override
    public Page<ProjectsVO> getListProjectsByPage(ProjectsQueryRequest projectsQueryRequest) {
        long current = projectsQueryRequest.getPageNum();
        long size = projectsQueryRequest.getPageSize();
        Page<Projects> page = this.page(new Page<>(current, size),
                getQueryWrapper(projectsQueryRequest));
        Page<ProjectsVO> projectsVOPage = new Page<>();
        BeanUtils.copyProperties(page, projectsVOPage, "records");
        List<ProjectsVO> voList = page.getRecords().stream()
                .map(projects -> {
                    ProjectsVO vo = new ProjectsVO();
                    BeanUtils.copyProperties(projects, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        projectsVOPage.setRecords(voList);
        return projectsVOPage;
    }

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

        // 从对象中取值
        Integer id = projectsQueryRequest.getId();
        String projectName = projectsQueryRequest.getProjectName();
        String projectDescription = projectsQueryRequest.getProjectDescription();
        Integer progress = projectsQueryRequest.getProgress();
        String sortField = projectsQueryRequest.getSortField();
        String sortOrder = projectsQueryRequest.getSortOrder();

        // 项目名称、项目描述 项目进度
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(projectName), "project_name", projectName);
        queryWrapper.like(StringUtils.isNotBlank(projectDescription), "project_description", projectDescription);
        queryWrapper.eq(ObjectUtil.isNotEmpty(progress), "progress", progress);

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




