package com.bonus.material.ma.service.impl;

import java.time.ZoneId;
import java.util.*;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.bonus.common.biz.domain.lease.LeaseApplyInfo;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.lease.domain.vo.LeaseApplyRequestVo;
import com.bonus.material.lease.domain.vo.LeaseOutVo;
import com.bonus.material.lease.mapper.LeaseApplyDetailsMapper;
import com.bonus.material.lease.mapper.LeaseApplyInfoMapper;
import com.bonus.material.ma.domain.MachineSynch;
import com.bonus.material.ma.domain.Type;
import com.bonus.material.ma.domain.vo.MachineVo;
import com.bonus.material.ma.domain.vo.SampleSync;
import com.bonus.material.purchase.config.RemoteConfig;
import com.bonus.material.scrap.domain.ScrapApplyDetails;
import com.bonus.material.scrap.mapper.ScrapApplyDetailsMapper;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.stereotype.Service;
import com.bonus.material.ma.mapper.MachineMapper;
import com.bonus.material.ma.domain.Machine;
import com.bonus.material.ma.service.IMachineService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;

import static com.bonus.common.core.web.domain.AjaxResult.error;
import static com.bonus.common.core.web.domain.AjaxResult.success;

/**
 * 机具设备管理Service业务层处理
 *
 * @author xsheng
 * @date 2024-09-27
 */
@Service
@Slf4j
public class MachineServiceImpl implements IMachineService
{
    @Resource
    private MachineMapper machineMapper;

    @Resource
    private RemoteConfig remoteConfig;

    @Resource
    private ScrapApplyDetailsMapper scrapApplyDetailsMapper;

    @Resource
    private LeaseApplyInfoMapper leaseApplyInfoMapper;

    @Resource
    private LeaseApplyDetailsMapper leaseApplyDetailsMapper;

    /**
     * 查询机具设备管理
     *
     * @param maId 机具设备管理主键
     * @return 机具设备管理
     */
    @Override
    public MachineVo selectMachineByMaId(Long maId)
    {
        MachineVo machineVo = machineMapper.selectMachineByMaId(maId);
        Map<String, String> machineStatus = remoteConfig.getDictValue("ma_machine_status");
        if (StringUtils.isNotBlank(machineVo.getMaStatus())) {
            machineVo.setStatusName(StringUtils.isBlank(machineStatus.get(machineVo.getMaStatus())) ? "" : machineStatus.get(machineVo.getMaStatus()));
        }
        return machineVo;
    }

    /**
     * 查询机具设备管理列表
     *
     * @param machine 机具设备管理
     * @return 机具设备管理
     */
    @Override
    public List<MachineVo> selectMachineList(Machine machine)
    {
        try {
            List<MachineVo> list = machineMapper.selectMachineList(machine);
            Map<String, String> machineStatus = remoteConfig.getDictValue("ma_machine_status");
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(machineVo -> {
                    if (StringUtils.isNotBlank(machineVo.getMaStatus())) {
                        machineVo.setStatusName(StringUtils.isBlank(machineStatus.get(machineVo.getMaStatus())) ? "" : machineStatus.get(machineVo.getMaStatus()));
                    }
                });
            }
            return list;
        } catch (Exception e){
            return new ArrayList<>();
        }

    }

    /**
     * 新增机具设备管理
     *
     * @param machine 机具设备管理
     * @return 结果
     */
    @Override
    public int insertMachine(Machine machine)
    {
        machine.setCreateTime(DateUtils.getNowDate());
        return machineMapper.insertMachine(machine);
    }

    /**
     * 修改机具设备管理
     *
     * @param machine 机具设备管理
     * @return 结果
     */
    @Override
    public AjaxResult updateMachine(Machine machine)
    {
        machine.setUpdateTime(DateUtils.getNowDate());
        int result = machineMapper.updateMachine(machine);
        if (result > 0) {
            return success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 批量删除机具设备管理
     *
     * @param maIds 需要删除的机具设备管理主键
     * @return 结果
     */
    @Override
    public int deleteMachineByMaIds(Long[] maIds)
    {
        return machineMapper.deleteMachineByMaIds(maIds);
    }

    /**
     * 删除机具设备管理信息
     *
     * @param maId 机具设备管理主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteMachineByMaId(Long maId)
    {
        int result = machineMapper.deleteMachineByMaId(maId);
        if (result > 0) {
            return success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 根据类型查询
     * @param type
     * @return
     */
    @Override
    public AjaxResult selectByTypeList(Type type) {
        List<Type> typeList = machineMapper.selectByTypeList(type);
        return success(typeList);
    }

    /**
     * todo 查询在库机具编号，存在数据拼接，盘点报废专用
     * @param type
     * @return
     */
    @Override
    public AjaxResult getMachineList(Type type) {
        List<Machine> typeList = machineMapper.getMachineList(type);
        if (type.getTaskId() != null && type.getTypeId() != null) {
            ScrapApplyDetails scrapApplyDetails = new ScrapApplyDetails();
            scrapApplyDetails.setTaskId(type.getTaskId());
            scrapApplyDetails.setTypeId(type.getTypeId());
            List<ScrapApplyDetails> list = scrapApplyDetailsMapper.getDetailsList(scrapApplyDetails);
            if (CollectionUtils.isNotEmpty(list)) {
                for (ScrapApplyDetails details : list) {
                    if (StringUtils.isNotBlank(details.getMaIds())) {
                        String[] maIds = details.getMaIds().split(",");
                        for (String maId : maIds) {
                            Machine machine = new Machine();
                            MachineVo machineVo = machineMapper.selectMachineByMaId(Long.parseLong(maId));
                            machine.setMaId(machineVo.getMaId());
                            machine.setMaCode(machineVo.getMaCode());
                            typeList.add(machine);
                        }
                    }
                }
            }
        }
        return success(typeList);
    }

    /**
     * 查询电子标签信息
     * @param machine
     * @return
     */
    @Override
    public AjaxResult getElectronicLabel(Machine machine) {
        List<Machine> list = new ArrayList<>();
        int type = 0;
        try {
            if (machine.getDevType()==1){
                //查询ws_ma_info,工器具
                list = machineMapper.getElectronicLabelByWsMaInfo(machine);
            } else {
                //查询ma_machine表，安全工器具
                list = machineMapper.getElectronicLabel(machine);
            }
            for (Machine dto : list){
                Date nextCheckTime = dto.getNextCheckTime();
                Date todayStart = new Date(); // 获取当前时间
                // 将 todayStart 设置为当天的开始时间（00:00:00）
                todayStart = Date.from(todayStart.toInstant().atZone(ZoneId.systemDefault())
                        .withHour(0).withMinute(0).withSecond(0).withNano(0)
                        .toInstant());
                if (nextCheckTime != null && nextCheckTime.before(todayStart)) {
                    type=1;
                    throw new RuntimeException("该工器具已临近下次检验时间，请及时退还至机具（物流）分公司！");
                }
            }

            if (CollectionUtils.isNotEmpty(list)) {
                for (Machine dto : list) {
                    // 根据typeId查询信息
                    Machine info = machineMapper.selectHouse(dto);
                    if (info != null) {
                        if ("机具库".equals(info.getOwnHouse())) {
                            dto.setIsJj(0);
                        } else {
                            dto.setIsJj(1);
                        }
                    }
                    // 获取领料单详情
                    List<LeaseOutVo> details = leaseApplyDetailsMapper.selectByMaId(dto.getMaId());
                    if (CollectionUtils.isNotEmpty(details)) {
                        Long id = details.get(0).getId();
                        dto.setId(id);
                    }
                }
            }
            return AjaxResult.success(list);
        } catch (Exception e){
            if (type==1){
                return AjaxResult.error("该工器具已临近下次检验时间，请及时退还至机具（物流）分公司！");
            } else {
                return AjaxResult.success(new ArrayList<>());
            }
        }
    }

    /**
     * 根据标签信息查询出库单
     * @param leaseApplyInfo
     * @return
     */
    @Override
    public LeaseApplyRequestVo getInfoByMaId(LeaseApplyInfo leaseApplyInfo) {
        try {
            LeaseApplyRequestVo leaseApplyRequestVo = new LeaseApplyRequestVo();
            // 根据maCode查询maId
            Long maId = machineMapper.selectMaId(leaseApplyInfo);
            // 获取领料单详情
            List<LeaseOutVo> details = leaseApplyDetailsMapper.selectByMaId(maId);
            if (CollectionUtils.isNotEmpty(details)) {
                leaseApplyRequestVo.setLeaseOutVoList(details);
                Long id = details.get(0).getId();
                leaseApplyInfo.setId(id);
            }
            LeaseApplyInfo optionalInfo = leaseApplyInfoMapper.selectLeaseApplyInfoById(leaseApplyInfo);
            if (optionalInfo != null) {
                leaseApplyRequestVo.setLeaseApplyInfo(optionalInfo);
            }
            return leaseApplyRequestVo;
        } catch (Exception e) {
            // 记录异常日志
            throw new RuntimeException("Failed to select lease apply info", e);
        }
    }

    /**
     * 电子标签编码查询
     * @param machine
     * @return
     */
    @Override
    public List<Machine> getByMaCode(Machine machine) {
        return machineMapper.getByMaCode(machine);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult synchReport(Machine machine) {
        try {
            String pdfUrl = machine.getPdf();
            String checkTime = machine.getCheckTimeSynch() + " 00:00:00";
            String nextCheckTime = machine.getNextCheckTimeSynch() + " 00:00:00";
            String reportName = machine.getReportName();
            String reportNum = machine.getReportNum();
            Long userId = SecurityUtils.getLoginUser().getUserid();
            machine.setUserId(userId);
            //往主表插入
            Machine machineTemp = new Machine();
            machineTemp.setReportNum(machine.getReportNum());
            machineTemp.setUserId(userId);

            machineMapper.insertInfo(machineTemp);
            int newId = Math.toIntExact(machineTemp.getId());
            List<SampleSync> samples = machine.getSamples();

            if(samples != null && !samples.isEmpty()){
                // 批量设置属性
                for(SampleSync sample : samples){
                    sample.setCheckTimeSynch(checkTime);
                    sample.setNextCheckTimeSynch(nextCheckTime);
                    sample.setPdf(pdfUrl);
                    sample.setReportName(reportName);
                    sample.setReportNum(reportNum);
                    sample.setSelfCode(sample.getSelfCode().trim());
                    sample.setTypeNameCode(sample.getSampleName() + "-" + sample.getSelfCode());
                    sample.setParentId(newId);
                }
                //找出大类ma_code
                List<SampleSync> bigList = machineMapper.getBigList(samples);

                //丢失、报废、不存在的编号都为异常，不合格
                //1.初始化分类列表
                List<SampleSync> lostList = new ArrayList<>();
                List<SampleSync> scrapList = new ArrayList<>();
                List<SampleSync> notExistList = new ArrayList<>();
                List<SampleSync> successList = new ArrayList<>(); // 原sueecssList修正拼写
                List<SampleSync> exceptionList = new ArrayList<>(); // 新增异常列表
                List<SampleSync> noSuccessList = new ArrayList<>();
                //2.构建bigList的typeNameCode映射表（优化查询效率）
                Map<String, List<SampleSync>> typeNameCodeMap = new HashMap<>();
                for (SampleSync bigItem : bigList) {
                    String key = bigItem.getTypeNameCode();
                    typeNameCodeMap.computeIfAbsent(key, k -> new ArrayList<>()).add(bigItem);
                }

                //3.遍历samples进行分类
                for (SampleSync sample : samples) {
                    String sampleTypeNameCode = sample.getTypeNameCode();
                    List<SampleSync> matchedBigItems = typeNameCodeMap.getOrDefault(sampleTypeNameCode, Collections.emptyList());

                    if (matchedBigItems.isEmpty()) {
                        // 无匹配项
                        sample.setResult("未发现该机具");
                        sample.setIsSuccess(0);
                        notExistList.add(sample);
                    } else if (matchedBigItems.size() > 1) {
                        // 匹配超过1个，存入异常列表
                        sample.setResult("该机具编码重复");
                        sample.setIsSuccess(0);
                        exceptionList.add(sample);
                    } else {
                        // 仅匹配1个，提取公共属性设置
                        SampleSync matchedItem = matchedBigItems.get(0);
                        sample.setModelName(matchedItem.getModelName());
                        sample.setTypeName(matchedItem.getTypeName());
                        Integer maStatus = matchedItem.getMaStatus();

                        // 预计算"不合格"状态
                        boolean isUnqualified = "不合格".equals(sample.getResult());

                        if (isUnqualified) {
                            // 优先处理不合格状态，减少嵌套判断
                            sample.setResult("不合格");
                            sample.setIsSuccess(0);
                            noSuccessList.add(sample);
                        } else if (maStatus != null) {
                            sample.setIsSuccess(0);
                            // 根据maStatus分类
                            if (maStatus == 6 || maStatus == 7 || maStatus == 8 || maStatus == 10) {
                                sample.setResult("该机具已报废");
                                scrapList.add(sample);
                            } else if (maStatus == 18) {
                                sample.setResult("该机具已丢失");
                                lostList.add(sample);
                            } else {
                                // 非报废/丢失状态，标记为成功
                                sample.setIsSuccess(1);
                                successList.add(sample);
                            }
                        } else {
                            // maStatus为空，视为未匹配
                            sample.setResult("未发现该机具");
                            sample.setIsSuccess(0);
                            notExistList.add(sample);
                        }
                    }
                }

                //对数据进行汇总
                List<SampleSync> allList = new ArrayList<>();
                allList.addAll(lostList);
                allList.addAll(scrapList);
                allList.addAll(notExistList);
                allList.addAll(successList);
                allList.addAll(exceptionList);
                allList.addAll(noSuccessList);

                // 使用批量更新
                if(successList != null && !successList.isEmpty()){
                    int numAll = machineMapper.batchUpdateSynchReport(successList);
                    //异常和合格的都插入到记录表
                    int num = machineMapper.batchInsertSynchDetails(allList);
                    if(numAll > 0){
                        return success("同步成功，更新了 " + numAll + " 条记录");
                    }else{
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return error("同步失败，暂无相关的机具编码");
                    }
                }else{
                    //异常和合格的都插入到记录表
                    int num = machineMapper.batchInsertSynchDetails(allList);
                    return error("同步失败，暂无相关的机具编码");
                }



            }
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return error("同步失败，暂无相关的机具编码");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.getMessage());
            return error("同步报告失败");
        }
    }

    @Override
    public int editAssetsCode(Machine machine)
    {
        machine.setCreateTime(DateUtils.getNowDate());
        return machineMapper.editAssetsCode(machine);
    }

    @Override
    public AjaxResult getHisByQrcode(Machine machine) {
        //1根据二维码查询基础信息
        Machine baseInfo = machineMapper.getInfoByQrcode(machine);
        if (baseInfo == null) {
            return AjaxResult.error("扫描二维码信息为空");
        }
        machine.setMaId(baseInfo.getMaId());
        //2根据二维码查询初次入库时间
        Machine inTime = machineMapper.getInTimeByQrcode(machine);
        //服务工程次数，检验次数
        Machine serviceNum = machineMapper.getServiceNumByQrcode(machine);
        //更换配件次数
        Machine checkNum = machineMapper.getCheckNumByQrcode(machine);
        //报废时间
        Machine scrapTime = machineMapper.getScrapTimeByQrcode(machine);
//        //3根据机具id查询领退工程
//        Machine leaseInfo = machineMapper.getLeaseInfoByQrcode(machine);

        // 根据maid查询领料任务
        LeaseApplyInfo leaseInfo = machineMapper.getLeaseParentId(machine);
        if (leaseInfo == null || leaseInfo.getParentId() == null){
            baseInfo.setLeaseTime(null);
            baseInfo.setLeaseUnit(null);
            baseInfo.setLeaseProject(null);

        }else{
            LeaseApplyInfo leaseDetail = machineMapper.getLeaseUnitAndProject(leaseInfo);
            baseInfo.setLeaseTime(String.valueOf(leaseInfo.getLeaseTime()));
            baseInfo.setLeaseUnit(leaseDetail.getUnitName());
            baseInfo.setLeaseProject(leaseDetail.getProjectName());
        }

        // 根据maid查询退料任务
        LeaseApplyInfo leaseInfoBack = machineMapper.getBackParentId(machine);
        if (leaseInfoBack == null || leaseInfoBack.getParentId() == null){
            baseInfo.setBackTime(null);
            baseInfo.setBackUnit(null);
            baseInfo.setBackProject(null);
        }else{
            LeaseApplyInfo leaseDetailBack = machineMapper.getBackUnitAndProject(leaseInfoBack);
            baseInfo.setBackTime(String.valueOf(leaseDetailBack.getLeaseTime()));
            baseInfo.setBackUnit(leaseDetailBack.getUnitName());
            baseInfo.setBackProject(leaseDetailBack.getProjectName());
        }


        if (inTime != null){
            Integer taskId = inTime.getTaskId();
            if(taskId != null){
                baseInfo.setInTime(inTime.getInTime()+"(新购)");
            }else{
                baseInfo.setInTime(inTime.getInTime());
            }

        }

        if(serviceNum != null){
            baseInfo.setServiceNum(serviceNum.getServiceNum());
        }else{
            baseInfo.setServiceNum(0);
        }

        if(checkNum != null){
            baseInfo.setCheckNum(checkNum.getCheckNum());
        }else{
            baseInfo.setCheckNum(0);
        }

        if (scrapTime != null){
            baseInfo.setScrapTime(scrapTime.getScrapTime());
        }else{
            baseInfo.setScrapTime("暂无");
        }

        return success(baseInfo);
    }

    @Override
    public AjaxResult getHisByCode(Machine machine) {
         List<Machine> result = new ArrayList<>();
         List<Machine> maList = machineMapper.getListByCode(machine);
         if (CollectionUtils.isNotEmpty(maList)){
             if(maList.size() == 1){
                 Machine baseInfo = maList.get(0);
                 machine.setMaId(baseInfo.getMaId());
                 machine.setMaCode(baseInfo.getMaCode());
                 //2根据二维码查询初次入库时间
                 Machine inTime = machineMapper.getInTimeByQrcode(machine);
                 //服务工程次数，检验次数
                 Machine serviceNum = machineMapper.getServiceNumByQrcode(machine);
                 //更换配件次数
                 Machine checkNum = machineMapper.getCheckNumByQrcode(machine);
                 //报废时间
                 Machine scrapTime = machineMapper.getScrapTimeByQrcode(machine);
                 //3根据机具id查询领退工程
                 Machine leaseInfo = machineMapper.getLeaseInfoByQrcode(machine);
                 if (inTime != null){
                     Integer taskId = inTime.getTaskId();
                     if(taskId != null){
                         baseInfo.setInTime(inTime.getInTime()+"(新购)");
                     }else{
                         baseInfo.setInTime(inTime.getInTime());
                     }

                 }

                 if(serviceNum != null){
                     baseInfo.setServiceNum(serviceNum.getServiceNum());
                 }else{
                     baseInfo.setServiceNum(0);
                 }

                 if(checkNum != null){
                     baseInfo.setCheckNum(checkNum.getCheckNum());
                 }else{
                     baseInfo.setCheckNum(0);
                 }

                 if (scrapTime != null){
                     baseInfo.setScrapTime(scrapTime.getScrapTime());
                 }else{
                     baseInfo.setScrapTime("暂无");
                 }

                 if(leaseInfo != null){
                     baseInfo.setLeaseTime(leaseInfo.getLeaseTime());
                     baseInfo.setLeaseUnit(leaseInfo.getLeaseUnit());
                     baseInfo.setLeaseProject(leaseInfo.getLeaseProject());
                     baseInfo.setBackTime(leaseInfo.getBackTime());
                     baseInfo.setBackUnit(leaseInfo.getBackUnit());
                     baseInfo.setBackProject(leaseInfo.getBackProject());
                 }
                 result.add(baseInfo);
                 return success(result);

             }else{
                 return success(maList);
             }
         }else{
             return error("暂无该设备信息");
         }

    }

    @Override
    public AjaxResult getHisByCodeNew(Machine machine) {
        try {
            List<Machine> result = new ArrayList<>();
            List<Machine> maList=new ArrayList<>();
            if (machine.getDevType()==0){
                maList = machineMapper.getHisByCodeNew(machine);
            } else if (machine.getDevType()==1){
                maList = machineMapper.getHisByCodeNewByWsMaInfo(machine);
            } else if (machine.getDevType()==2){
                maList = machineMapper.getListByCode(machine);
            }

            if (CollectionUtils.isNotEmpty(maList)){
                if(maList.size() == 1){
                    Machine baseInfo = maList.get(0);
                    if (baseInfo.getJiJuType()==2){
                        machine.setMaId(baseInfo.getMaId());
                        machine.setMaCode(baseInfo.getMaCode());
                        //2根据二维码查询初次入库时间
                        Machine inTime = machineMapper.getInTimeByQrcode(machine);
                        //服务工程次数，检验次数
                        Machine serviceNum = machineMapper.getServiceNumByQrcode(machine);
                        //更换配件次数
                        Machine checkNum = machineMapper.getCheckNumByQrcode(machine);
                        //报废时间
                        Machine scrapTime = machineMapper.getScrapTimeByQrcode(machine);
                        //3根据机具id查询领退工程
                        Machine leaseInfo = machineMapper.getLeaseInfoByQrcode(machine);
                        if (inTime != null){
                            Integer taskId = inTime.getTaskId();
                            if(taskId != null){
                                baseInfo.setInTime(inTime.getInTime()+"(新购)");
                            }else{
                                baseInfo.setInTime(inTime.getInTime());
                            }

                        }
                        if(serviceNum != null){
                            baseInfo.setServiceNum(serviceNum.getServiceNum());
                        }else{
                            baseInfo.setServiceNum(0);
                        }

                        if(checkNum != null){
                            baseInfo.setCheckNum(checkNum.getCheckNum());
                        }else{
                            baseInfo.setCheckNum(0);
                        }

                        if (scrapTime != null){
                            baseInfo.setScrapTime(scrapTime.getScrapTime());
                        }else{
                            baseInfo.setScrapTime("暂无");
                        }
                        if(leaseInfo != null){
                            baseInfo.setLeaseTime(leaseInfo.getLeaseTime());
                            baseInfo.setLeaseUnit(leaseInfo.getLeaseUnit());
                            baseInfo.setLeaseProject(leaseInfo.getLeaseProject());
                            baseInfo.setBackTime(leaseInfo.getBackTime());
                            baseInfo.setBackUnit(leaseInfo.getBackUnit());
                            baseInfo.setBackProject(leaseInfo.getBackProject());
                        }
                        result.add(baseInfo);
                        return success(result);
                    } else {
                        result.add(baseInfo);
                        return success(result);
                    }
                } else {
                    return success(maList);
                }
            }else{
                return error("暂无该设备信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("暂无该设备信息");
        }
    }

    @Override
    public AjaxResult editMachineStatus(Machine machine) {
        machine.setUpdateTime(DateUtils.getNowDate());
        int result = machineMapper.editMachineStatus(machine);
        if (result > 0) {
            return success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    @Override
    public List<Machine> getNewByMaCode(Machine machine) {
        return machineMapper.getNewByMaCode(machine);
    }

    @Override
    public List<Machine> findMaMsgById(Machine machine) {
        return machineMapper.findMaMsgById(machine);
    }

    @Override
    public AjaxResult addMaMachine(Machine machine) {
        try {
            //查询类型下编码是否存在
            int count = machineMapper.getCountByMaCode(machine);
            if (count > 0) {
                return AjaxResult.error("该规格类型下此编码已存在");
            }
            machine.setMaStatus("1");
            machine.setMaVender(machine.getSupplierId());
            int result = machineMapper.insertMachine(machine);
            if (result > 0) {
                return AjaxResult.success("入库成功");
            }
            return AjaxResult.error("添加盘点入库失败");
        } catch (Exception e) {
            return AjaxResult.error("添加盘点入库失败");
        }
    }

    /**
     * 编码铭牌信息
     * @param machine
     * @return
     */
    @Override
    public List<Machine> getInfoByMaCode(Machine machine) {
        List<Machine> infoByMaCode = machineMapper.getInfoByMaCode(machine);
        return infoByMaCode;
    }

    /**
     * 根据类型id获取编码
     * @param machine
     * @return
     */
    @Override
    public List<Machine> getInfoByTypeId(Machine machine) {
        return machineMapper.getInfoByTypeId(machine);
    }

    @Override
    public List<MachineSynch> selectSynchList(MachineSynch machine) {
        return machineMapper.selectSynchList(machine);
    }

    @Override
    public List<MachineSynch> selectSynchDetailList(MachineSynch machine) {
        return machineMapper.selectSynchDetailList(machine);
    }

    /**
     * 批量更新检验时间
     * @param info
     * @return
     */
    @Override
    public AjaxResult updateDate(Machine info) {
        try {
            if (info.getMaIds() != null && info.getMaIds().length > 0) {
                if (info.getThisCheckTime() != null && info.getNextCheckTime() != null) {
                    // 批量更新
                    int rows = machineMapper.updateCheckTimeBatch(
                            info.getMaIds(),
                            info.getThisCheckTime(),
                            info.getNextCheckTime()
                    );
                    return rows > 0 ? success("批量更新成功") : error("未更新任何数据");
                } else {
                    return error("检验时间不能为空");
                }
            } else {
                return error("设备ID不能为空");
            }
        } catch (Exception e) {
            log.error("批量更新检验时间失败", e);
            return error("检验时间更新失败");
        }
    }
}
