package com.maintain.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.maintain.business.domain.*;
import com.maintain.business.domain.bo.ErpMalfunctionProjectBo;
import com.maintain.business.domain.vo.ErpMalfunctionProjectVo;
import com.maintain.business.domain.vo.ErpRepairFormProjectVo;
import com.maintain.business.mapper.*;
import com.maintain.common.exception.ServiceException;
import com.maintain.common.pinyin.PinyinUtils;
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.domain.bo.ErpMaintainProjectBo;
import com.maintain.business.domain.vo.ErpMaintainProjectVo;
import com.maintain.business.service.IErpMaintainProjectService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 维修项目Service业务层处理
 *
 * @author liushuai
 * @date 2025-03-28
 */
@RequiredArgsConstructor
@Service
public class ErpMaintainProjectServiceImpl implements IErpMaintainProjectService {

    private final ErpMaintainProjectMapper baseMapper;
    private final ErpProjectTypeMapper projectTypeMapper;
    private final ErpMalfunctionProjectMapper malfunctionProjectMapper;
    private final ErpMaintainMalfunctionMapper maintainMalfunctionMapper;
    private final ErpRepairFormProjectMapper repairFormProjectMapper;


    /**
     * 查询维修项目
     */
    @Override
    public ErpMaintainProjectVo queryById(Long id){
        ErpMaintainProjectVo projectVo = baseMapper.selectVoById(id);
        // 获取维修项目与故障项目关联数据
        LambdaQueryWrapper<ErpMaintainMalfunction> malfunctionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        malfunctionLambdaQueryWrapper.eq(ErpMaintainMalfunction::getMaintainId, id);
        List<ErpMaintainMalfunction> malfunctionList = maintainMalfunctionMapper.selectList(malfunctionLambdaQueryWrapper);
        List<Long> malfunctionIdList = malfunctionList.stream().map(ErpMaintainMalfunction::getMalfunctionId).collect(Collectors.toList());
        // 根据故障项目ID列表获取故障项目列表
        if (!malfunctionIdList.isEmpty()) {
            LambdaQueryWrapper<ErpMalfunctionProject> malfunctionProjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            malfunctionProjectLambdaQueryWrapper.in(ErpMalfunctionProject::getId, malfunctionIdList);
            List<ErpMalfunctionProjectVo> malfunctionProjectVoList = malfunctionProjectMapper.selectVoList(malfunctionProjectLambdaQueryWrapper);
            projectVo.setMalfunctionProjectList(malfunctionProjectVoList);
        }
        return projectVo;
    }

    /**
     * 查询维修项目列表
     */
    @Override
    public TableDataInfo<ErpMaintainProjectVo> queryPageList(ErpMaintainProjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpMaintainProject> lqw = buildQueryWrapper(bo);
        Page<ErpMaintainProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询维修项目列表
     */
    @Override
    public List<ErpMaintainProjectVo> queryList(ErpMaintainProjectBo bo) {
        LambdaQueryWrapper<ErpMaintainProject> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpMaintainProject> buildQueryWrapper(ErpMaintainProjectBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpMaintainProject> lqw = Wrappers.lambdaQuery();
        lqw.notIn(bo.getNotInIdList() != null, ErpMaintainProject::getId, bo.getNotInIdList());
        lqw.eq(bo.getTypeId() != null, ErpMaintainProject::getTypeId, bo.getTypeId());
        lqw.like(StringUtils.isNotBlank(bo.getTypeName()), ErpMaintainProject::getTypeName, bo.getTypeName());
        lqw.like(StringUtils.isNotBlank(bo.getProjectCode()), ErpMaintainProject::getProjectCode, bo.getProjectCode());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), ErpMaintainProject::getProjectName, bo.getProjectName());
        lqw.eq(bo.getStandardManHour() != null, ErpMaintainProject::getStandardManHour, bo.getStandardManHour());
        lqw.eq(bo.getStandardPrice() != null, ErpMaintainProject::getStandardPrice, bo.getStandardPrice());
        lqw.eq(bo.getWarrantyPeriod() != null, ErpMaintainProject::getWarrantyPeriod, bo.getWarrantyPeriod());
        lqw.eq(StringUtils.isNotBlank(bo.getTechnicalSpecification()), ErpMaintainProject::getTechnicalSpecification, bo.getTechnicalSpecification());
        lqw.eq(bo.getState() != null, ErpMaintainProject::getState, bo.getState());
        lqw.eq(bo.getIsDelete() != null, ErpMaintainProject::getIsDelete, bo.getIsDelete());
        return lqw;
    }

    /**
     * 新增维修项目
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(ErpMaintainProjectBo bo) {
        ErpMaintainProject add = BeanUtil.toBean(bo, ErpMaintainProject.class);
        validEntityBeforeSave(add);
        int randomNum = (int)(Math.random() * 90000) + 10000;
        add.setProjectCode(PinyinUtils.getFirstLetters(add.getProjectName()) + randomNum);
        ErpProjectType projectType = projectTypeMapper.selectById(add.getTypeId());
        add.setTypeName(projectType.getTypeName());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 保存故障项目
            List<ErpMalfunctionProjectBo> projectBoList = bo.getMalfunctionProjectList();
            List<ErpMaintainMalfunction> collect = projectBoList.stream().map(item -> {
                ErpMaintainMalfunction maintainMalfunction = new ErpMaintainMalfunction();
                maintainMalfunction.setMaintainId(add.getId());
                maintainMalfunction.setMaintainName(add.getProjectName());
                maintainMalfunction.setMalfunctionId(item.getId());
                maintainMalfunction.setMalfunctionName(item.getMalfunctionName());
                return maintainMalfunction;
            }).collect(Collectors.toList());
            maintainMalfunctionMapper.insertBatch(collect);
        }
        return flag;
    }

    /**
     * 修改维修项目
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(ErpMaintainProjectBo bo) {
        ErpMaintainProject update = BeanUtil.toBean(bo, ErpMaintainProject.class);
        validEntityBeforeSave(update);
        ErpProjectType projectType = projectTypeMapper.selectById(update.getTypeId());
        update.setTypeName(projectType.getTypeName());
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 删除原有故障项目绑定
            LambdaQueryWrapper<ErpMaintainMalfunction> malfunctionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            malfunctionLambdaQueryWrapper.eq(ErpMaintainMalfunction::getMaintainId, update.getId());
            maintainMalfunctionMapper.delete(malfunctionLambdaQueryWrapper);
            // 新增维修项目与故障项目的绑定关系
            List<ErpMalfunctionProjectBo> projectBoList = bo.getMalfunctionProjectList();
            List<ErpMaintainMalfunction> collect = projectBoList.stream().map(item -> {
                ErpMaintainMalfunction maintainMalfunction = new ErpMaintainMalfunction();
                maintainMalfunction.setMaintainId(update.getId());
                maintainMalfunction.setMaintainName(update.getProjectName());
                maintainMalfunction.setMalfunctionId(item.getId());
                maintainMalfunction.setMalfunctionName(item.getMalfunctionName());
                return maintainMalfunction;
            }).collect(Collectors.toList());
            // 批量保存
            maintainMalfunctionMapper.insertBatch(collect);
        }
        return flag;
    }

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

    /**
     * 批量删除维修项目
     */
    @Transactional
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            List<ErpRepairFormProjectVo> projectVos = repairFormProjectMapper.selectVoList(new LambdaQueryWrapper<ErpRepairFormProject>().in(ErpRepairFormProject::getMaintainId, ids));
            if (!projectVos.isEmpty()) {
                Set<String> collect = projectVos.stream().map(ErpRepairFormProjectVo::getProjectName).collect(Collectors.toSet());
                throw new ServiceException("删除失败，维修项目 "+collect+" 已被使用！");
            }
        }
        maintainMalfunctionMapper.delete(new LambdaQueryWrapper<ErpMaintainMalfunction>().in(ErpMaintainMalfunction::getMaintainId, ids));
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
