package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
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 jakarta.annotation.Resource;
import org.dromara.common.core.constant.CommonConstant;
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.core.utils.sql.SqlUtil;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.project.domain.BusProject;
import org.dromara.project.domain.BusUserProjectRelevancy;
import org.dromara.project.domain.req.project.ProjectCreateReq;
import org.dromara.project.domain.req.project.ProjectQueryReq;
import org.dromara.project.domain.req.project.ProjectUpdateReq;
import org.dromara.project.domain.vo.BusProjectVo;
import org.dromara.project.mapper.BusProjectMapper;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusUserProjectRelevancyService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

/**
 * 项目Service业务层处理
 *
 * @author lcj
 * @date 2025-03-04
 */
@Service
public class BusProjectServiceImpl extends ServiceImpl<BusProjectMapper, BusProject>
    implements IBusProjectService {

    @Resource
    private BusProjectMapper baseMapper;

    @Lazy
    @Resource
    private IBusUserProjectRelevancyService userProjectRelevancyService;

    /**
     * 查询项目
     *
     * @param id 主键
     * @return 项目
     */
    @Override
    public BusProjectVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询项目列表
     *
     * @param req 查询条件
     * @return 项目分页列表
     */
    @Override
    public Page<BusProjectVo> queryPageList(ProjectQueryReq req) {
        long current = req.getCurrent();
        long size = req.getPageSize();
        // 查询数据库
        Page<BusProject> result = this.page(new Page<>(current, size), this.getQueryWrapper(req));
        return this.getVoPage(result);
    }

    /**
     * 查询符合条件的项目列表
     *
     * @param req 查询条件
     * @return 项目列表
     */
    @Override
    public List<BusProjectVo> queryList(ProjectQueryReq req) {
        QueryWrapper<BusProject> queryWrapper = this.getQueryWrapper(req);
        return baseMapper.selectVoList(queryWrapper);
    }

    /**
     * 新增项目
     *
     * @param dto 项目
     * @return 新项目 id
     */
    @Override
    public Long insertByBo(ProjectCreateReq dto) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(dto, project);
        // 数据校验
        validEntityBeforeSave(project);
        // 写入数据库
        boolean save = this.save(project);
        if (!save) {
            throw new ServiceException("新增项目失败，数据库异常", HttpStatus.ERROR);
        }
        Long projectId = project.getId();
        Long userId = LoginHelper.getUserId();
        // 同步保存用户与项目关联
        BusUserProjectRelevancy userProjectRelevancy = new BusUserProjectRelevancy();
        userProjectRelevancy.setUserId(userId);
        userProjectRelevancy.setProjectId(projectId);
        boolean saveRelevancy = userProjectRelevancyService.save(userProjectRelevancy);
        if (!saveRelevancy) {
            throw new ServiceException("新增用户与项目关联失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据 projectId
        return projectId;
    }

    /**
     * 修改项目
     *
     * @param req 项目
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProjectUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(req, project);
        // 数据校验
        validEntityBeforeSave(project);
        // 权限校验
        validPermission(project);
        // 判断是否存在
        BusProject oldProject = this.getById(project.getId());
        if (oldProject == null) {
            throw new ServiceException("修改项目失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(project);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProject entity) {
        // TODO 做一些数据校验,如唯一约束
        String projectName = entity.getProjectName();
        if (StringUtils.isBlank(projectName)) {
            throw new ServiceException("项目名称不能为空", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 权限判断
     */
    private void validPermission(BusProject entity) {
        Long entityId = entity.getId();
        // 获取当前登录用户
        Long userId = LoginHelper.getUserId();
        // 判断是否存在项目与登录用户关联
        QueryWrapper<BusUserProjectRelevancy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", entityId);
        queryWrapper.eq("user_id", userId);
        if (userProjectRelevancyService.count(queryWrapper) <= 0) {
            throw new ServiceException("当前用户无权限操作", HttpStatus.FORBIDDEN);
        }
    }

    /**
     * 校验并批量删除项目信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验

        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 获取项目视图对象
     *
     * @param project 项目对象
     * @return 项目视图对象
     */
    @Override
    public BusProjectVo getProjectVo(BusProject project) {
        if (project == null) {
            return null;
        }
        // 对象转封装类
        BusProjectVo projectVo = new BusProjectVo();
        BeanUtils.copyProperties(project, projectVo);
        return projectVo;
    }

    /**
     * 获取项目查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public QueryWrapper<BusProject> getQueryWrapper(ProjectQueryReq req) {
        QueryWrapper<BusProject> queryWrapper = new QueryWrapper<>();
        if (req == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = req.getId();
        String projectName = req.getProjectName();
        String shortName = req.getShortName();
        Long pId = req.getPId();
        Long status = req.getStatus();
        String remark = req.getRemark();
        String type = req.getType();
        Long isType = req.getIsType();
        String projectSite = req.getProjectSite();
        String principal = req.getPrincipal();
        String principalPhone = req.getPrincipalPhone();
        String actual = req.getActual();
        String plan = req.getPlan();
        String onStreamTime = req.getOnStreamTime();
        String punchRange = req.getPunchRange();
        Long designTotal = req.getDesignTotal();
        Long showHidden = req.getShowHidden();
        String sortField = req.getSortField();
        String sortOrder = req.getSortOrder();
        String underlineSortField = StrUtil.toUnderlineCase(sortField);
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(projectName), "project_name", projectName);
        queryWrapper.like(StringUtils.isNotBlank(shortName), "short_name", shortName);
        queryWrapper.like(StringUtils.isNotBlank(remark), "remark", remark);
        queryWrapper.like(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.like(StringUtils.isNotBlank(projectSite), "project_site", projectSite);
        queryWrapper.like(StringUtils.isNotBlank(principal), "principal", principal);
        queryWrapper.like(StringUtils.isNotBlank(principalPhone), "principal_phone", principalPhone);
        queryWrapper.like(StringUtils.isNotBlank(actual), "actual", actual);
        queryWrapper.like(StringUtils.isNotBlank(plan), "plan", plan);
        queryWrapper.like(StringUtils.isNotBlank(onStreamTime), "on_stream_time", onStreamTime);
        queryWrapper.like(StringUtils.isNotBlank(punchRange), "punch_range", punchRange);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(pId), "p_id", pId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(isType), "is_type", isType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(designTotal), "design_total", designTotal);
        queryWrapper.eq(ObjectUtils.isNotEmpty(showHidden), "show_hidden", showHidden);
        // 排序规则
        queryWrapper.orderBy(SqlUtil.validSortField(sortField),
            sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
            underlineSortField);
        return queryWrapper;
    }


    @Override
    public Page<BusProjectVo> getVoPage(Page<BusProject> projectPage) {
        List<BusProject> projectList = projectPage.getRecords();
        Page<BusProjectVo> projectVoPage = new Page<>(projectPage.getCurrent(), projectPage.getSize(), projectPage.getTotal());
        if (CollUtil.isEmpty(projectList)) {
            return projectVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusProjectVo> projectVoList = projectList.stream().map(this::getProjectVo).toList();
        projectVoPage.setRecords(projectVoList);
        return projectVoPage;
    }

}
