package com.zksy.base.service.impl;

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 com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.EquipmentMaintain;
import com.zksy.base.mapper.EquipmentBaseMapper;
import com.zksy.base.mapper.EquipmentMaintainMapper;
import com.zksy.base.service.EquipmentMaintainService;
import com.zksy.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class EquipmentMaintainServiceImpl extends ServiceImpl<EquipmentMaintainMapper, EquipmentMaintain>
        implements EquipmentMaintainService {

    @Autowired
    private EquipmentBaseMapper equipmentBaseMapper;

    @Override
    public Page<EquipmentMaintain> findByPage(long pageNum, long pageSize,
                                              String maintainId,String equipmentId,
                                              String maintainType,String maintainPerson) {
        Page<EquipmentMaintain> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<EquipmentMaintain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EquipmentMaintain::getMaintainId,maintainId)
                    .eq(EquipmentMaintain::getEquipmentId,equipmentId)
                    .eq(EquipmentMaintain::getMaintainType,maintainType)
                    .eq(EquipmentMaintain::getMaintainPerson,maintainPerson);
        return this.page(page,queryWrapper);
    }

    /**
     * 新增设备维护记录
     * @param entity
     * @return
     */
    @Override
    public boolean saveWithCheck(EquipmentMaintain entity) {
        //校验关联的设备是否存在
        String equipmentId = entity.getEquipmentId();
        if (equipmentBaseMapper.selectById(equipmentId) == null) {
            throw new ServiceException("关联的设备不存在：" + equipmentId);
        }
        //新增
        return this.save(entity);
    }

    /**
     * 批量新增设备维护记录
     * @param entityList
     * @return
     */
    @Override
    @Transactional
    public boolean saveBatchWithCheck(List<EquipmentMaintain> entityList) {
        //批量校验设备ID是否存在
        Set<String> equipmentIds = entityList.stream()
                .map(EquipmentMaintain::getEquipmentId)
                .collect(Collectors.toSet());
        List<String> existEquipmentIds = equipmentBaseMapper.selectBatchIds(equipmentIds).stream()
                .map(EquipmentBase::getEquipmentId)
                .collect(Collectors.toList());
        Set<String> invalidEquipmentIds = equipmentIds.stream()
                .filter(id -> !existEquipmentIds.contains(id))
                .collect(Collectors.toSet());

        if (!invalidEquipmentIds.isEmpty()) {
            throw new ServiceException("存在无效的设备ID：" + invalidEquipmentIds);
        }

        //校验
        for (EquipmentMaintain entity : entityList) {
            //校验关联的设备是否存在
            String equipmentId = entity.getEquipmentId();
            if (equipmentBaseMapper.selectById(equipmentId) == null) {
                throw new ServiceException("关联的设备不存在：" + equipmentId + "（维护记录ID：" + entity.getMaintainId() + "）");
            }

            //校验核心必填字段
//            if (entity.getMaintainPersonPhone() != null) {
//                String phoneStr = String.valueOf(entity.getMaintainPersonPhone());
//                if (phoneStr.length() != 11) {
//                    throw new ServiceException("维护人手机号格式错误（需11位）：" + phoneStr + "（维护记录ID：" + entity.getMaintainId() + "）");
//                }
//            }
        }

        //批量新增
        return this.saveBatch(entityList);
    }

    /**
     * 修改设备维护记录
     * @param entity
     * @return
     */
    @Override
    @Transactional
    public boolean updateWithCheck(EquipmentMaintain entity) {
        //是否存在
        String maintainId = entity.getMaintainId();
        EquipmentMaintain oldRecord = this.getById(maintainId);
        if (oldRecord == null) {
            throw new ServiceException("维护记录不存在：" + maintainId);
        }

        //修改设备ID，需校验新设备是否存在
        String newEquipmentId = entity.getEquipmentId();
        if (newEquipmentId != null && !newEquipmentId.equals(oldRecord.getEquipmentId())) {
            if (equipmentBaseMapper.selectById(newEquipmentId) == null) {
                throw new ServiceException("新关联的设备不存在：" + newEquipmentId);
            }
        }

//        //校验核心字段格式（可选）
//        if (entity.getMaintainPersonPhone() != null) {
//            String phoneStr = String.valueOf(entity.getMaintainPersonPhone());
//            if (phoneStr.length() != 11) {
//                throw new ServiceException("维护人手机号格式错误（需11位）：" + phoneStr);
//            }
//        }

        //更新
        return this.updateById(entity);
    }
}
