package org.dromara.safety.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
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 jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.domain.vo.IdAndNameVO;
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.project.domain.BusConstructionUser;
import org.dromara.project.domain.BusContractor;
import org.dromara.project.domain.BusProjectTeam;
import org.dromara.project.service.IBusConstructionUserService;
import org.dromara.project.service.IBusContractorService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusProjectTeamService;
import org.dromara.safety.domain.BusTeamMeeting;
import org.dromara.safety.domain.req.teammeeting.TeamMeetingCreateReq;
import org.dromara.safety.domain.req.teammeeting.TeamMeetingQueryReq;
import org.dromara.safety.domain.req.teammeeting.TeamMeetingUpdateReq;
import org.dromara.safety.domain.vo.BusTeamMeetingVo;
import org.dromara.safety.mapper.BusTeamMeetingMapper;
import org.dromara.safety.service.IBusTeamMeetingService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 站班会Service业务层处理
 *
 * @author lcj
 * @date 2025-03-19
 */
@Service
public class BusTeamMeetingServiceImpl extends ServiceImpl<BusTeamMeetingMapper, BusTeamMeeting>
    implements IBusTeamMeetingService {

    @Resource
    private ISysOssService ossService;

    @Resource
    private IBusConstructionUserService constructionUserService;

    @Resource
    private IBusContractorService contractorService;

    @Resource
    private IBusProjectTeamService projectTeamService;

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询站班会
     *
     * @param id 主键
     * @return 站班会
     */
    @Override
    public BusTeamMeetingVo queryById(Long id) {
        BusTeamMeeting teamMeeting = this.getById(id);
        if (teamMeeting == null) {
            throw new ServiceException("站班会信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(teamMeeting);
    }

    /**
     * 分页查询站班会列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 站班会分页列表
     */
    @Override
    public TableDataInfo<BusTeamMeetingVo> queryPageList(TeamMeetingQueryReq req, PageQuery pageQuery) {
        Page<BusTeamMeeting> result = this.page(pageQuery.build(), this.buildQuery(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的站班会列表
     *
     * @param req 查询条件
     * @return 站班会列表
     */
    @Override
    public List<BusTeamMeetingVo> queryList(TeamMeetingQueryReq req) {
        List<BusTeamMeeting> list = this.list(this.buildQuery(req));
        // 对象列表 => 封装对象列表
        return list.stream().map(this::getVo).toList();
    }

    /**
     * 新增站班会
     *
     * @param req 站班会
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(TeamMeetingCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusTeamMeeting teamMeeting = new BusTeamMeeting();
        BeanUtils.copyProperties(req, teamMeeting);
        // 数据转换
        List<String> pictureList = req.getPictureList();
        String pictureStr = JSONUtil.toJsonStr(pictureList);
        teamMeeting.setPicture(pictureStr);
        List<String> participantIdList = req.getParticipantIdList();
        String participantIdStr = JSONUtil.toJsonStr(participantIdList);
        teamMeeting.setParticipantId(participantIdStr);
        // 数据校验
        validEntityBeforeSave(teamMeeting, true);
        // 写入数据库
        boolean save = this.save(teamMeeting);
        if (!save) {
            throw new ServiceException("新增站班会信息失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据
        return teamMeeting.getId();
    }

    /**
     * 修改站班会
     *
     * @param req 站班会
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TeamMeetingUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusTeamMeeting teamMeeting = new BusTeamMeeting();
        BeanUtils.copyProperties(req, teamMeeting);
        // 数据转换
        List<String> pictureList = req.getPictureList();
        String pictureStr = JSONUtil.toJsonStr(pictureList);
        teamMeeting.setPicture(pictureStr);
        List<String> participantIdList = req.getParticipantIdList();
        String participantIdStr = JSONUtil.toJsonStr(participantIdList);
        teamMeeting.setParticipantId(participantIdStr);
        // 数据校验
        validEntityBeforeSave(teamMeeting, false);
        // 判断是否存在
        BusTeamMeeting oldTeamMeeting = this.getById(teamMeeting.getId());
        if (oldTeamMeeting == null) {
            throw new ServiceException("修改站班会信息失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(teamMeeting);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusTeamMeeting entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        Long projectId = entity.getProjectId();
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && projectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 校验并批量删除站班会信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取站班会视图对象
     *
     * @param teamMeeting 站班会对象
     * @return 站班会视图对象
     */
    @Override
    public BusTeamMeetingVo getVo(BusTeamMeeting teamMeeting) {
        // 对象转封装类
        BusTeamMeetingVo teamMeetingVo = new BusTeamMeetingVo();
        if (teamMeeting == null) {
            return teamMeetingVo;
        }
        BeanUtils.copyProperties(teamMeeting, teamMeetingVo);
        // 查询对应分包公司
        Long contractorId = teamMeeting.getContractorId();
        if (contractorId != null) {
            // 仅查询id 和 name
            LambdaQueryWrapper<BusContractor> contractorLambdaQueryWrapper = Wrappers.lambdaQuery(BusContractor.class)
                .select(BusContractor::getId, BusContractor::getName)
                .eq(BusContractor::getId, contractorId);
            BusContractor contractor = contractorService.getOne(contractorLambdaQueryWrapper);
            teamMeetingVo.setContractor(IdAndNameVO.build(contractor.getId(), contractor.getName()));
        }
        // 查询对应班组
        Long teamId = teamMeeting.getTeamId();
        if (teamId != null) {
            LambdaQueryWrapper<BusProjectTeam> teamLambdaQueryWrapper = Wrappers.lambdaQuery(BusProjectTeam.class)
                .select(BusProjectTeam::getId, BusProjectTeam::getTeamName)
                .eq(BusProjectTeam::getId, teamId);
            BusProjectTeam projectTeam = projectTeamService.getOne(teamLambdaQueryWrapper);
            teamMeetingVo.setTeam(IdAndNameVO.build(projectTeam.getId(), projectTeam.getTeamName()));
        }
        // 查询对应参会用户
        String participantId = teamMeeting.getParticipantId();
        List<Long> participantIdList = JSONUtil.toList(participantId, Long.class);
        if (CollUtil.isNotEmpty(participantIdList)) {
            LambdaQueryWrapper<BusConstructionUser> constructionUserLambdaQueryWrapper = Wrappers.lambdaQuery(BusConstructionUser.class)
                .select(BusConstructionUser::getId, BusConstructionUser::getUserName)
                .in(BusConstructionUser::getId, participantIdList);
            List<BusConstructionUser> constructionUserList = constructionUserService.list(constructionUserLambdaQueryWrapper);
            List<IdAndNameVO> idAndNameVOList = constructionUserList.stream()
                .map(constructionUser -> IdAndNameVO.build(constructionUser.getId(), constructionUser.getUserName()))
                .toList();
            teamMeetingVo.setParticipantList(idAndNameVOList);
        }
        // 查询对应宣讲人
        Long compereId = teamMeeting.getCompereId();
        if (compereId != null) {
            LambdaQueryWrapper<BusConstructionUser> constructionUserLambdaQueryWrapper = Wrappers.lambdaQuery(BusConstructionUser.class)
                .select(BusConstructionUser::getId, BusConstructionUser::getUserName)
                .eq(BusConstructionUser::getId, compereId);
            BusConstructionUser constructionUser = constructionUserService.getOne(constructionUserLambdaQueryWrapper);
            teamMeetingVo.setCompere(IdAndNameVO.build(constructionUser.getId(), constructionUser.getUserName()));
        }
        // 查询对应图片url
        String picture = teamMeeting.getPicture();
        List<Long> pictureIdList = JSONUtil.toList(picture, Long.class);
        if (CollUtil.isNotEmpty(pictureIdList)) {
            List<SysOssVo> ossVoList = ossService.listByIds(pictureIdList);
            List<IdAndNameVO> pictureList = ossVoList.stream()
                .map(ossVo -> IdAndNameVO.build(ossVo.getOssId(), ossVo.getUrl())).toList();
            teamMeetingVo.setPictureUrl(pictureList);
        }
        return teamMeetingVo;
    }

    /**
     * 获取站班会查询条件封装
     *
     * @param req 站班会查询条件
     * @return 站班会查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusTeamMeeting> buildQuery(TeamMeetingQueryReq req) {
        LambdaQueryWrapper<BusTeamMeeting> lqw = Wrappers.lambdaQuery();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long projectId = req.getProjectId();
        Long teamId = req.getTeamId();
        Long contractorId = req.getContractorId();
        Date meetingDate = req.getMeetingDate();
        Long compereId = req.getCompereId();
        List<String> participantIdList = req.getParticipantIdList();
        String content = req.getContent();
        String remark = req.getRemark();
        // JSON 数组查询
        if (CollUtil.isNotEmpty(participantIdList)) {
            for (String participantId : participantIdList) {
                lqw.like(BusTeamMeeting::getParticipantId, "\"" + participantId + "\"");
            }
        }
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(content), BusTeamMeeting::getContent, content);
        lqw.like(StringUtils.isNotBlank(remark), BusTeamMeeting::getRemark, remark);
        // 精准查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusTeamMeeting::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusTeamMeeting::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(teamId), BusTeamMeeting::getTeamId, teamId);
        lqw.eq(ObjectUtils.isNotEmpty(contractorId), BusTeamMeeting::getContractorId, contractorId);
        lqw.eq(ObjectUtils.isNotEmpty(meetingDate), BusTeamMeeting::getMeetingDate, meetingDate);
        lqw.eq(ObjectUtils.isNotEmpty(compereId), BusTeamMeeting::getCompereId, compereId);
        return lqw;
    }

    /**
     * 获取站班会分页对象视图
     *
     * @param teamMeetingPage 站班会分页对象
     * @return 站班会分页对象视图
     */
    @Override
    public Page<BusTeamMeetingVo> getVoPage(Page<BusTeamMeeting> teamMeetingPage) {
        // 获取材料数据
        List<BusTeamMeeting> teamMeetingList = teamMeetingPage.getRecords();
        // 添加分页信息
        Page<BusTeamMeetingVo> teamMeetingVoPage = new Page<>(teamMeetingPage.getCurrent(), teamMeetingPage.getSize(), teamMeetingPage.getTotal());
        if (CollUtil.isEmpty(teamMeetingList)) {
            return teamMeetingVoPage;
        }
        // 对象列表 => 封装对象列表
        List<BusTeamMeetingVo> teamMeetingVoList = teamMeetingList.stream().map(this::getVo).toList();
        teamMeetingVoPage.setRecords(teamMeetingVoList);
        return teamMeetingVoPage;
    }
}
