package org.dromara.progress.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.progress.constant.PgsProgressCategoryConstant;
import org.dromara.progress.domain.PgsProgressCategoryTemplate;
import org.dromara.progress.domain.dto.progresscategorytemplate.PgsProgressCategoryTemplateCreateReq;
import org.dromara.progress.domain.dto.progresscategorytemplate.PgsProgressCategoryTemplateQueryReq;
import org.dromara.progress.domain.dto.progresscategorytemplate.PgsProgressCategoryTemplateUpdateReq;
import org.dromara.progress.domain.vo.progresscategorytemplate.PgsProgressCategoryTemplateVo;
import org.dromara.progress.mapper.PgsProgressCategoryTemplateMapper;
import org.dromara.progress.service.IPgsProgressCategoryTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * 进度类别模版Service业务层处理
 *
 * @author lcj
 * @date 2025-05-22
 */
@Service
public class PgsProgressCategoryTemplateServiceImpl extends ServiceImpl<PgsProgressCategoryTemplateMapper, PgsProgressCategoryTemplate>
    implements IPgsProgressCategoryTemplateService {

    /**
     * 查询进度类别模版
     *
     * @param id 主键
     * @return 进度类别模版
     */
    @Override
    public PgsProgressCategoryTemplateVo queryById(Long id) {
        PgsProgressCategoryTemplate progressCategoryTemplate = this.getById(id);
        if (progressCategoryTemplate == null) {
            throw new ServiceException("进度类别模版信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(progressCategoryTemplate);
    }

    /**
     * 分页查询进度类别模版
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 进度类别模版分页列表
     */
    @Override
    public TableDataInfo<PgsProgressCategoryTemplateVo> queryPageList(PgsProgressCategoryTemplateQueryReq req, PageQuery pageQuery) {
        Page<PgsProgressCategoryTemplate> progressCategoryTemplatePage = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(progressCategoryTemplatePage));
    }

    /**
     * 查询符合条件的进度类别模版列表
     *
     * @param req 查询条件
     * @return 进度类别模版列表
     */
    @Override
    public List<PgsProgressCategoryTemplateVo> queryList(PgsProgressCategoryTemplateQueryReq req) {
        List<PgsProgressCategoryTemplate> list = this.list(this.buildQueryWrapper(req));
        return list.stream().map(this::getVo).toList();
    }

    /**
     * 新增进度类别模版
     *
     * @param req 进度类别模版
     * @return 新增进度类别模版id
     */
    @Override
    public Long insertByBo(PgsProgressCategoryTemplateCreateReq req) {
        // 将实体类和 DTO 进行转换
        PgsProgressCategoryTemplate progressCategoryTemplate = new PgsProgressCategoryTemplate();
        BeanUtils.copyProperties(req, progressCategoryTemplate);
        // 数据校验
        validEntityBeforeSave(progressCategoryTemplate);
        // 写入数据库
        boolean result = this.save(progressCategoryTemplate);
        if (!result) {
            throw new ServiceException("新增进度类别模版失败，数据库异常", HttpStatus.ERROR);
        }
        return progressCategoryTemplate.getId();
    }

    /**
     * 修改进度类别模版
     *
     * @param req 进度类别模版
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PgsProgressCategoryTemplateUpdateReq req) {
        // 将实体类和 DTO 进行转换
        PgsProgressCategoryTemplate progressCategoryTemplate = new PgsProgressCategoryTemplate();
        BeanUtils.copyProperties(req, progressCategoryTemplate);
        PgsProgressCategoryTemplate oldProgressCategoryTemplate = this.getById(req.getId());
        if (oldProgressCategoryTemplate == null) {
            throw new ServiceException("修改进度类别模版失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 数据校验
        validEntityBeforeSave(progressCategoryTemplate);
        // 写入数据库
        boolean result = this.updateById(progressCategoryTemplate);
        if (!result) {
            throw new ServiceException("更新进度类别模版失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PgsProgressCategoryTemplate entity) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        Long pid = entity.getPid();
        if (projectId != null && projectId != 0) {
            if (this.getById(projectId) == null) {
                throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
            }
        }
        if (pid != null && pid != 0) {
            if (this.getById(pid) == null) {
                throw new ServiceException("对应进度类别模版不存在", HttpStatus.NOT_FOUND);
            }
        }
        // 名称唯一性校验
        LambdaQueryWrapper<PgsProgressCategoryTemplate> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PgsProgressCategoryTemplate::getName, entity.getName());
        if (projectId != null && projectId != 0) {
            lqw.eq(PgsProgressCategoryTemplate::getProjectId, entity.getProjectId());
        }
        if (pid != null && pid != 0) {
            lqw.eq(PgsProgressCategoryTemplate::getPid, entity.getPid());
        }
        if (entity.getId() != null) {
            // 排除自身
            lqw.ne(PgsProgressCategoryTemplate::getId, entity.getId());
        }
        if (this.count(lqw) > 0) {
            throw new ServiceException("已有同名进度类别模版", HttpStatus.CONFLICT);
        }
    }

    /**
     * 校验并批量删除进度类别模版信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取进度类别模版视图对象
     *
     * @param progressCategoryTemplate 进度类别模版对象
     * @return 进度类别模版视图对象
     */
    @Override
    public PgsProgressCategoryTemplateVo getVo(PgsProgressCategoryTemplate progressCategoryTemplate) {
        if (progressCategoryTemplate == null) {
            return null;
        }
        // 对象转封装类
        PgsProgressCategoryTemplateVo progressCategoryTemplateVo = new PgsProgressCategoryTemplateVo();
        BeanUtils.copyProperties(progressCategoryTemplate, progressCategoryTemplateVo);
        return progressCategoryTemplateVo;
    }

    /**
     * 获取进度类别模版查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<PgsProgressCategoryTemplate> buildQueryWrapper(PgsProgressCategoryTemplateQueryReq req) {
        LambdaQueryWrapper<PgsProgressCategoryTemplate> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        Long pid = req.getPid();
        String name = req.getName();
        String unitType = req.getUnitType();
        Long projectId = req.getProjectId();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(name), PgsProgressCategoryTemplate::getName, name);
        // 精确查询
        lqw.in(ObjectUtils.isNotEmpty(projectId), PgsProgressCategoryTemplate::getProjectId, projectId, PgsProgressCategoryConstant.PUBLIC_PROJECT_ID);
        lqw.eq(StringUtils.isNotBlank(unitType), PgsProgressCategoryTemplate::getUnitType, unitType);
        lqw.eq(ObjectUtils.isNotEmpty(pid), PgsProgressCategoryTemplate::getPid, pid);
        return lqw;
    }

    /**
     * 获取进度类别模版分页对象视图
     *
     * @param progressCategoryTemplatePage 进度类别模版分页对象
     * @return 进度类别模版分页对象视图
     */
    @Override
    public Page<PgsProgressCategoryTemplateVo> getVoPage(Page<PgsProgressCategoryTemplate> progressCategoryTemplatePage) {
        List<PgsProgressCategoryTemplate> progressCategoryTemplateList = progressCategoryTemplatePage.getRecords();
        Page<PgsProgressCategoryTemplateVo> progressCategoryTemplateVoPage = new Page<>(progressCategoryTemplatePage.getCurrent(), progressCategoryTemplatePage.getSize(), progressCategoryTemplatePage.getTotal());
        if (CollUtil.isEmpty(progressCategoryTemplateList)) {
            return progressCategoryTemplateVoPage;
        }
        // 对象列表 => 封装对象列表
        List<PgsProgressCategoryTemplateVo> progressCategoryTemplateVoList = progressCategoryTemplateList.stream().map(progressCategoryTemplate -> {
            // 对象转封装类
            PgsProgressCategoryTemplateVo progressCategoryTemplateVo = new PgsProgressCategoryTemplateVo();
            BeanUtils.copyProperties(progressCategoryTemplate, progressCategoryTemplateVo);
            return progressCategoryTemplateVo;
        }).toList();
        progressCategoryTemplateVoPage.setRecords(progressCategoryTemplateVoList);
        return progressCategoryTemplateVoPage;
    }
}
