package com.maintain.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.maintain.business.domain.ErpRepairForm;
import com.maintain.business.domain.ErpRepairFormProject;
import com.maintain.business.domain.ErpRepairFormProjectDispatch;
import com.maintain.business.domain.ErpUser;
import com.maintain.business.domain.bo.ErpRepairFormProjectBatchBo;
import com.maintain.business.domain.bo.ErpRepairFormProjectBo;
import com.maintain.business.domain.vo.ErpMaintainProjectVo;
import com.maintain.business.domain.vo.ErpRepairFormProjectDispatchVo;
import com.maintain.business.domain.vo.ErpRepairFormProjectVo;
import com.maintain.business.domain.vo.ErpUserVo;
import com.maintain.business.mapper.ErpMaintainProjectMapper;
import com.maintain.business.mapper.ErpRepairFormProjectDispatchMapper;
import com.maintain.business.mapper.ErpUserMapper;
import com.maintain.common.utils.StringUtils;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.maintain.business.mapper.ErpRepairFormProjectMapper;
import com.maintain.business.service.IErpRepairFormProjectService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 报修单-维修项目\检验项目Service业务层处理
 *
 * @author liushuai
 * @date 2025-04-01
 */
@RequiredArgsConstructor
@Service
public class ErpRepairFormProjectServiceImpl implements IErpRepairFormProjectService {

    private final ErpRepairFormProjectMapper baseMapper;
    private final ErpMaintainProjectMapper maintainProjectMapper;
    private final ErpRepairFormProjectDispatchMapper projectDispatchMapper;
    private final ErpUserMapper userMapper;

    /**
     * 查询报修单-维修项目\检验项目
     */
    @Override
    public ErpRepairFormProjectVo queryById(Long id){
        ErpRepairFormProjectVo repairFormProjectVo = baseMapper.selectVoById(id);
        LambdaQueryWrapper<ErpRepairFormProjectDispatch> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpRepairFormProjectDispatch::getRepairFormId, id);
        List<ErpRepairFormProjectDispatchVo> dispatchVos = projectDispatchMapper.selectVoList(lqw);
        if (!dispatchVos.isEmpty()) {
            repairFormProjectVo.setProjectDispatchVoList(dispatchVos);
        }
        return repairFormProjectVo;
    }

    /**
     * 查询报修单-维修项目\检验项目列表
     */
    @Override
    public TableDataInfo<ErpRepairFormProjectVo> queryPageList(ErpRepairFormProjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpRepairFormProject> lqw = buildQueryWrapper(bo);
        Page<ErpRepairFormProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询报修单-维修项目\检验项目列表
     */
    @Override
    public List<ErpRepairFormProjectVo> queryList(ErpRepairFormProjectBo bo) {
        LambdaQueryWrapper<ErpRepairFormProject> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }


    private LambdaQueryWrapper<ErpRepairFormProject> buildQueryWrapper(ErpRepairFormProjectBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpRepairFormProject> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getRepairFormId() != null, ErpRepairFormProject::getRepairFormId, bo.getRepairFormId());
        lqw.eq(bo.getTypeId() != null, ErpRepairFormProject::getTypeId, bo.getTypeId());
        lqw.like(StringUtils.isNotBlank(bo.getTypeName()), ErpRepairFormProject::getTypeName, bo.getTypeName());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectCode()), ErpRepairFormProject::getProjectCode, bo.getProjectCode());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), ErpRepairFormProject::getProjectName, bo.getProjectName());
        lqw.eq(bo.getStandardManHour() != null, ErpRepairFormProject::getStandardManHour, bo.getStandardManHour());
        lqw.eq(bo.getStandardPrice() != null, ErpRepairFormProject::getStandardPrice, bo.getStandardPrice());
        lqw.eq(bo.getWarrantyPeriod() != null, ErpRepairFormProject::getWarrantyPeriod, bo.getWarrantyPeriod());
        lqw.eq(StringUtils.isNotBlank(bo.getTechnicalSpecification()), ErpRepairFormProject::getTechnicalSpecification, bo.getTechnicalSpecification());
        lqw.eq(bo.getActualTime() != null, ErpRepairFormProject::getActualTime, bo.getActualTime());
        lqw.eq(bo.getIsDispatch() != null, ErpRepairFormProject::getIsDispatch, bo.getIsDispatch());
        lqw.eq(bo.getExamineUserId() != null, ErpRepairFormProject::getExamineUserId, bo.getExamineUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getExamineUserCode()), ErpRepairFormProject::getExamineUserCode, bo.getExamineUserCode());
        lqw.like(StringUtils.isNotBlank(bo.getExamineUserName()), ErpRepairFormProject::getExamineUserName, bo.getExamineUserName());
        lqw.eq(bo.getExamineTime() != null, ErpRepairFormProject::getExamineTime, bo.getExamineTime());
        return lqw;
    }

    /**
     * 批量新增维修项目
     * @param bo
     * @return
     */
    @Override
    public Boolean insertBatchByBo(ErpRepairFormProjectBatchBo bo) {
        List<ErpRepairFormProject> collect = bo.getMaintainIdList().stream().map(item -> {
            ErpMaintainProjectVo maintainProjectVo = maintainProjectMapper.selectVoById(item);
            ErpRepairFormProject formProject = BeanUtil.toBean(maintainProjectVo, ErpRepairFormProject.class);
            formProject.setId(null);
            formProject.setMaintainId(maintainProjectVo.getId());
            formProject.setRepairFormId(bo.getRepairFormId());
            return formProject;
        }).collect(Collectors.toList());
        return baseMapper.insertBatch(collect);
    }

    /**
     * 新增报修单-维修项目\检验项目
     */
    @Override
    public Boolean insertByBo(ErpRepairFormProjectBo bo) {
        ErpMaintainProjectVo projectVo = maintainProjectMapper.selectVoById(bo.getMaintainId());
        if (ObjectUtils.isEmpty(projectVo)) {
            throw new RuntimeException("维修项目不存在，请刷新后重试");
        }
        ErpRepairFormProject add = BeanUtil.toBean(projectVo, ErpRepairFormProject.class);
        add.setId(null);
        add.setMaintainId(bo.getMaintainId());
        add.setRepairFormId(bo.getRepairFormId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改报修单-维修项目\检验项目
     */
    @Override
    public Boolean updateByBo(ErpRepairFormProjectBo bo) {
//        ErpRepairFormProject update = BeanUtil.toBean(bo, ErpRepairFormProject.class);
        ErpRepairFormProject repairFormProject = baseMapper.selectById(bo.getId());
        // 检验人员不为空，则说明是项目检验
        if (bo.getExamineUserId() != null) {
            ErpUserVo userVo = userMapper.selectVoById(bo.getExamineUserId());
            repairFormProject.setExamineUserCode(userVo.getJobNumber());
            repairFormProject.setExamineUserName(userVo.getName());
            repairFormProject.setExamineTime(bo.getExamineTime());
        }
        validEntityBeforeSave(repairFormProject);
        return baseMapper.updateById(repairFormProject) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpRepairFormProject entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除报修单-维修项目\检验项目
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        boolean flag = baseMapper.deleteBatchIds(ids) > 0;
        if (flag) {
            LambdaQueryWrapper<ErpRepairFormProjectDispatch> deleteWrapper = Wrappers.lambdaQuery();
            deleteWrapper.in(ErpRepairFormProjectDispatch::getRepairFormProjectId, ids);
            projectDispatchMapper.delete(deleteWrapper);
        }
        return flag;
    }
}
