package org.jeecg.modules.regular.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import javafx.scene.paint.Material;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.jeecg.common.api.dto.TreeDataDto;
import org.jeecg.modules.device.entity.BuDeviceType;
import org.jeecg.modules.device.mapper.BuDeviceTypeMapper;
import org.jeecg.modules.regular.entity.*;
import org.jeecg.modules.regular.mapper.*;
import org.jeecg.modules.regular.service.IRegularService;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description: 检修规程
 * @Author: jeecg-boot
 * @Date:   2025-01-16
 * @Version: V1.0
 */
@Service
@AllArgsConstructor
public class RegularServiceImpl extends ServiceImpl<RegularMapper, Regular> implements IRegularService {
    private final BuDeviceTypeMapper deviceTypeMapper;
    private final RegularToolsMapper regularToolsMapper;
    private final RegularMaterialMapper regularMaterialMapper;
    private final RegularDetailMapper regularDetailMapper;
    private final RegularInputMapper regularInputMapper;
    private ISysDictItemService dictItemService;
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(Regular entity) {
         if(super.save(entity)){
             List<RegularTools> tools = entity.getTools().stream().map(item -> {
                 RegularTools tool = new RegularTools();
                 tool.setRegular(entity.getId());
                 tool.setCount(Integer.parseInt(item.getCount()));
                 tool.setToolId(item.getId());
                 tool.setSpecification(item.getSpecification());
                 tool.setUnit(item.getUnit());
                 return tool;
             }).toList();
             for (RegularTools tool : tools) {
                 if (regularToolsMapper.insert(tool) <= 0) {
                     throw new RuntimeException();
                 }
             }

             List<RegularMaterial> materials = entity.getMaterials().stream().map(item -> {
                 RegularMaterial material = new RegularMaterial();
                 material.setRegular(entity.getId());
                 material.setCount(Double.parseDouble(item.getCount()));
                 material.setMaterialId(item.getId());
                 material.setSpecification(item.getSpecification());
                 material.setUnit(item.getUnit());
                 return material;
             }).toList();
             for (RegularMaterial material : materials) {
                 if (regularMaterialMapper.insert(material) <= 0) {
                     throw new RuntimeException();
                 }
             }

             return true;
         }
         return false;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean updateById(Regular entity) {
        if(super.updateById(entity)){
            List<RegularTools> tools = entity.getTools().stream().map(item -> {
                RegularTools tool = new RegularTools();
                tool.setRegular(entity.getId());
                tool.setCount(Integer.parseInt(item.getCount()));
                tool.setToolId(item.getId());
                tool.setSpecification(item.getSpecification());
                tool.setUnit(item.getUnit());
                return tool;
            }).toList();
            regularToolsMapper.delete(new LambdaQueryWrapper<RegularTools>()
                    .eq(RegularTools::getRegular, entity.getId()));
            for (RegularTools tool : tools) {
                if (regularToolsMapper.insert(tool) <= 0) {
                    throw new RuntimeException();
                }
            }

            List<RegularMaterial> materials = entity.getMaterials().stream().map(item -> {
                RegularMaterial material = new RegularMaterial();
                material.setRegular(entity.getId());
                material.setCount(Double.parseDouble(item.getCount()));
                material.setMaterialId(item.getId());
                material.setSpecification(item.getSpecification());
                material.setUnit(item.getUnit());
                return material;
            }).toList();
            regularMaterialMapper.delete(new LambdaQueryWrapper<RegularMaterial>().eq(RegularMaterial::getRegular, entity.getId()));
            for (RegularMaterial material : materials) {
                if (regularMaterialMapper.insert(material) <= 0) {
                    throw new RuntimeException();
                }
            }

            return true;
        }
        return false;
    }

    @Override
    public List<TreeDataDto> queryRegularMap() {
        List<Regular> regularList = baseMapper.selectList(null);
        // 获取所有设备ID
        Set<String> deviceTypeIds = regularList.stream()
                .map(Regular::getDeviceTypeId)
                .collect(Collectors.toSet());
        // 一次性查询所有设备信息
        List<BuDeviceType> deviceTypeList = deviceTypeMapper.selectBatchIds(deviceTypeIds);
        // 获取检修规程类型字典
        Map<String, String> regulerDictMap = dictItemService.selectItemsByDictCode("repair_range");

        // 将 Regular 列表转换为 Map，以设备 ID 为键，规程列表为值
        Map<String, List<TreeDataDto>> regularMap = regularList.stream()
                .collect(Collectors.groupingBy(Regular::getDeviceTypeId,
                        Collectors.mapping(regular -> {
                            TreeDataDto dto = new TreeDataDto();
                            dto.setKey(regular.getId());
                            dto.setValue(regular.getId());
                            dto.setTitle(regulerDictMap.get(regular.getRapairRange().toString()));
                            return dto;
                        }, Collectors.toList())));

        return deviceTypeList.stream()
                .map(deviceType -> {
                    TreeDataDto dto = new TreeDataDto();
                    dto.setKey(deviceType.getId());
                    dto.setValue(deviceType.getId());
                    dto.setTitle(deviceType.getTypeName()+"("+deviceType.getTypeCode()+")");
                    dto.setChildren(regularMap.getOrDefault(deviceType.getId(), new ArrayList<>()));
                    return dto;
                }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(String regularId) {
        // 删除对应修程的工具配置
        regularToolsMapper.delete(new LambdaQueryWrapper<RegularTools>().eq(RegularTools::getRegular, regularId));
        // 删除对应修程的物料配置
        regularMaterialMapper.delete(new LambdaQueryWrapper<RegularMaterial>().eq(RegularMaterial::getRegular, regularId));
        // 查找有测量项的detailId，并删除规程下的测量项配置
        List<String> detailIds = regularDetailMapper.selectList(
                Wrappers.<RegularDetail>lambdaQuery().select(RegularDetail::getId)
                        .eq(RegularDetail::getRegularId, regularId).eq(RegularDetail::getMeasure, "1")
        ).stream().map(RegularDetail::getId).collect(Collectors.toList());
        if(!detailIds.isEmpty()){
            regularInputMapper.delete(new LambdaQueryWrapper<RegularInput>().eq(RegularInput::getDetailId,detailIds));
        }
        // 删除对应修程的修程详情
        regularDetailMapper.delete(new LambdaQueryWrapper<RegularDetail>().eq(RegularDetail::getRegularId,regularId));
        // 删除对应修程
        return baseMapper.deleteById(regularId)>0;
    }
}
