package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.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.BusDailyPieceItem;
import org.dromara.project.domain.BusProjectTeam;
import org.dromara.project.domain.BusWorkerDailyReport;
import org.dromara.project.domain.dto.workerdailyreport.BusWorkerDailyReportQueryReq;
import org.dromara.project.domain.vo.dailypieceitem.BusDailyPieceItemVo;
import org.dromara.project.domain.vo.workerdailyreport.BusWorkerDailyReportVo;
import org.dromara.project.mapper.BusWorkerDailyReportMapper;
import org.dromara.project.service.IBusDailyPieceItemService;
import org.dromara.project.service.IBusProjectTeamService;
import org.dromara.project.service.IBusWorkerDailyReportService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * 施工人员日报Service业务层处理
 *
 * @author lcj
 * @date 2025-04-09
 */
@Service
public class BusWorkerDailyReportServiceImpl extends ServiceImpl<BusWorkerDailyReportMapper, BusWorkerDailyReport>
    implements IBusWorkerDailyReportService {

    @Resource
    private IBusDailyPieceItemService dailyPieceItemService;

    @Resource
    private IBusProjectTeamService projectTeamService;

    @Resource
    private ISysOssService ossService;

    /**
     * 查询施工人员日报
     *
     * @param id 主键
     * @return 施工人员日报
     */
    @Override
    public BusWorkerDailyReportVo queryById(Long id) {
        BusWorkerDailyReport workerDailyReport = this.getById(id);
        if (workerDailyReport == null) {
            throw new ServiceException("施工人员日报信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(workerDailyReport);
    }

    /**
     * 分页查询施工人员日报列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 施工人员日报分页列表
     */
    @Override
    public TableDataInfo<BusWorkerDailyReportVo> queryPageList(BusWorkerDailyReportQueryReq req, PageQuery pageQuery) {
        LambdaQueryWrapper<BusWorkerDailyReport> lqw = this.buildQueryWrapper(req);
        Page<BusWorkerDailyReport> result = this.page(pageQuery.build(), lqw);
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的施工人员日报列表
     *
     * @param req 查询条件
     * @return 施工人员日报列表
     */
    @Override
    public List<BusWorkerDailyReportVo> queryList(BusWorkerDailyReportQueryReq req) {
        LambdaQueryWrapper<BusWorkerDailyReport> lqw = buildQueryWrapper(req);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 校验并批量删除施工人员日报信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 获取施工人员日报列表视图对象
     *
     * @param workerDailyReport 施工人员日报列表对象
     * @return 施工人员日报列表视图对象
     */
    @Override
    public BusWorkerDailyReportVo getVo(BusWorkerDailyReport workerDailyReport) {
        // 对象转封装类
        BusWorkerDailyReportVo workerDailyReportVo = new BusWorkerDailyReportVo();
        if (workerDailyReport == null) {
            return workerDailyReportVo;
        }
        BeanUtils.copyProperties(workerDailyReport, workerDailyReportVo);
        // 获取日报计件详情信息
        List<BusDailyPieceItem> dailyPieceItemList = dailyPieceItemService.lambdaQuery()
            .eq(BusDailyPieceItem::getReportId, workerDailyReport.getId()).list();
        workerDailyReportVo.setDailyPieceItemVoList(dailyPieceItemService.getListVo(dailyPieceItemList));
        // 获取班组详情信息
        workerDailyReportVo.setTeamName(projectTeamService.getById(workerDailyReport.getTeamId()).getTeamName());
        // 获取图片信息
        String file = workerDailyReport.getFile();
        if (StringUtils.isNotEmpty(file)) {
            List<Long> picList = Arrays.stream(file.split(","))
                .map(Long::parseLong)
                .toList();
            List<SysOssVo> pictureList = ossService.listByIds(picList);
            workerDailyReportVo.setFileList(pictureList.stream().map(SysOssVo::getUrl).toList());
        }
        return workerDailyReportVo;
    }

    /**
     * 获取施工人员日报列表查询条件封装
     *
     * @param req 施工人员日报列表查询条件
     * @return 施工人员日报列表查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusWorkerDailyReport> buildQueryWrapper(BusWorkerDailyReportQueryReq req) {
        LambdaQueryWrapper<BusWorkerDailyReport> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long projectId = req.getProjectId();
        Long teamId = req.getTeamId();
        Long userId = req.getUserId();
        String userName = req.getUserName();
        Date reportDate = req.getReportDate();
        Long isResubmit = req.getIsResubmit();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(userName), BusWorkerDailyReport::getUserName, userName);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusWorkerDailyReport::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusWorkerDailyReport::getProjectId, projectId);
        lqw.eq(ObjectUtils.isNotEmpty(teamId), BusWorkerDailyReport::getTeamId, teamId);
        lqw.eq(ObjectUtils.isNotEmpty(userId), BusWorkerDailyReport::getUserId, userId);
        lqw.eq(ObjectUtils.isNotEmpty(reportDate), BusWorkerDailyReport::getReportDate, reportDate);
        lqw.eq(ObjectUtils.isNotEmpty(isResubmit), BusWorkerDailyReport::getIsResubmit, isResubmit);
        return lqw;
    }

    /**
     * 获取施工人员日报列表分页对象视图
     *
     * @param workerDailyReportPage 施工人员日报列表分页对象
     * @return 施工人员日报列表分页对象视图
     */
    @Override
    public Page<BusWorkerDailyReportVo> getVoPage(Page<BusWorkerDailyReport> workerDailyReportPage) {
        // 对象列表 => 封装对象列表
        List<BusWorkerDailyReport> workerDailyReportList = workerDailyReportPage.getRecords();
        Page<BusWorkerDailyReportVo> workerDailyReportVoPage = new Page<>(
            workerDailyReportPage.getCurrent(),
            workerDailyReportPage.getSize(),
            workerDailyReportPage.getTotal());
        if (CollUtil.isEmpty(workerDailyReportList)) {
            return workerDailyReportVoPage;
        }
        // 获取日报计件详情信息
        List<Long> idList = workerDailyReportList.stream().map(BusWorkerDailyReport::getId).toList();
        Map<Long, List<BusDailyPieceItem>> reportIdDailyPieceItemMap = dailyPieceItemService.lambdaQuery()
            .in(BusDailyPieceItem::getReportId, idList).list()
            .stream().collect(Collectors.groupingBy(BusDailyPieceItem::getReportId));
        // 获取班组详情信息
        List<Long> teamIdList = workerDailyReportList.stream().map(BusWorkerDailyReport::getTeamId).toList();
        Map<Long, List<BusProjectTeam>> teamIdProjectTeamMap = projectTeamService.lambdaQuery()
            .in(BusProjectTeam::getId, teamIdList).list()
            .stream().collect(Collectors.groupingBy(BusProjectTeam::getId));
        // 封装对象
        List<BusWorkerDailyReportVo> workerDailyReportVoList = workerDailyReportList.stream().map(workerDailyReport -> {
            BusWorkerDailyReportVo workerDailyReportVo = new BusWorkerDailyReportVo();
            BeanUtils.copyProperties(workerDailyReport, workerDailyReportVo);
            Long id = workerDailyReport.getId();
            // 获取日报计件详情信息
            List<BusDailyPieceItemVo> dailyPieceItemVoList = new ArrayList<>();
            if (reportIdDailyPieceItemMap.containsKey(id)) {
                List<BusDailyPieceItem> dailyPieceItemList = reportIdDailyPieceItemMap.get(id);
                dailyPieceItemVoList = dailyPieceItemService.getListVo(dailyPieceItemList);
            }
            workerDailyReportVo.setDailyPieceItemVoList(dailyPieceItemVoList);
            // 获取班组详情信息
            String teamName = null;
            if (teamIdProjectTeamMap.containsKey(workerDailyReport.getTeamId())) {
                BusProjectTeam projectTeam = teamIdProjectTeamMap.get(workerDailyReport.getTeamId()).get(0);
                teamName = projectTeam.getTeamName();
            }
            workerDailyReportVo.setTeamName(teamName);
            return workerDailyReportVo;
        }).toList();
        workerDailyReportVoPage.setRecords(workerDailyReportVoList);
        return workerDailyReportVoPage;
    }

}
