package com.agri.system.service.impl;

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

import com.agri.common.exception.ServiceException;
import com.agri.common.utils.DateUtils;
import com.agri.common.utils.StringUtils;
import com.agri.system.domain.SysRollerParam;
import com.agri.system.domain.vo.AgriTermVo;
import com.agri.system.service.ISysRollerParamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.agri.system.mapper.SysAutoTermMapper;
import com.agri.system.domain.SysAutoTerm;
import com.agri.system.service.ISysAutoTermService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 卷膜运行条件Service业务层处理
 * 
 * @author lld
 * @date 2026-02-27
 */
@Service
public class SysAutoTermServiceImpl extends ServiceImpl<SysAutoTermMapper, SysAutoTerm> implements ISysAutoTermService 
{

    @Autowired
    private ISysRollerParamService rollerParamService;

    // 温度控制条件数量上限
    private static final int MAX_TERM_COUNT = 5;

    /**
     * 查询卷膜运行条件
     * 
     * @param id 卷膜运行条件主键
     * @return 卷膜运行条件
     */
    @Override
    public SysAutoTerm selectSysAutoTermById(String id)
    {
        return baseMapper.selectSysAutoTermById(id);
    }

    /**
     * 查询卷膜运行条件列表
     * 
     * @param sysAutoTerm 卷膜运行条件
     * @return 卷膜运行条件
     */
    @Override
    public List<SysAutoTerm> selectSysAutoTermList(SysAutoTerm sysAutoTerm)
    {
        return baseMapper.selectSysAutoTermList(sysAutoTerm);
    }

    /**
     * 新增卷膜运行条件
     * 
     * @param sysAutoTerm 卷膜运行条件
     * @return 结果
     */
    @Override
    public int insertSysAutoTerm(SysAutoTerm sysAutoTerm)
    {
        return baseMapper.insert(sysAutoTerm);
    }

    /**
     * 修改卷膜运行条件
     * 
     * @param sysAutoTerm 卷膜运行条件
     * @return 结果
     */
    @Override
    public int updateSysAutoTerm(SysAutoTerm sysAutoTerm)
    {
        sysAutoTerm.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateSysAutoTerm(sysAutoTerm);
    }

    /**
     * 批量删除卷膜运行条件
     * 
     * @param ids 需要删除的卷膜运行条件主键
     * @return 结果
     */
    @Override
    public int deleteSysAutoTermByIds(String[] ids)
    {
        return baseMapper.deleteSysAutoTermByIds(ids);
    }

    /**
     * 删除卷膜运行条件信息
     * 
     * @param id 卷膜运行条件主键
     * @return 结果
     */
    @Override
    public int deleteSysAutoTermById(String id)
    {
        return baseMapper.deleteSysAutoTermById(id);
    }


    @Transactional
    @Override
    public boolean saveAgriTerm(List<AgriTermVo> agriTerms) {

        Map<String, Object> map = new HashMap<>();
        map.put("imei", agriTerms.get(0).getConfig().getImei());
        boolean isDelTermSuc = super.removeByMap(map);
        boolean isDelParamSuc = rollerParamService.removeByMap(map);
        List<SysAutoTerm> autoTerms = new ArrayList<>();
        List<SysRollerParam> rollerParams = new ArrayList<>();
        for (AgriTermVo agriTerm : agriTerms) {
            autoTerms.addAll(agriTerm.getTerms());
            rollerParams.add(agriTerm.getConfig());
        }
        boolean isSaveTermSuccess = super.saveBatch(autoTerms);
        boolean isSaveRollerSuccess = rollerParamService.saveBatch(rollerParams);

        return isSaveTermSuccess && isSaveRollerSuccess;
    }

    @Override
    public String validate(List<AgriTermVo> agriTerms) {
        if (CollectionUtils.isEmpty(agriTerms)) {
            return "请设置自动化条件后重新保存重试！";
        }

        for (AgriTermVo vo : agriTerms) {
            SysRollerParam config = vo.getConfig();
            if (config == null) {
                return "参数设置失败，请下拉刷新后重试！";
            }

            String roller = config.getRoller();
            List<SysAutoTerm> terms = vo.getTerms();

            // ===== 按顺序校验，一步一判断，清晰直观 =====
            if (StringUtils.isBlank(config.getRefTempCode())) {
                return roller + "参考温度未设置，请点击相应页签左上角设置后重试！";
            }

            boolean hasLen = (config.getManualTotalLen() != null && config.getManualTotalLen().compareTo(BigDecimal.ZERO)>0)
                    || (config.getAutoTotalLen() != null && config.getAutoTotalLen().compareTo(BigDecimal.ZERO)>0);
            if (!hasLen) {
                return roller + "计算风口总长和手动设置风口长度至少填写一个！";
            }

            boolean isValidLen = (config.getManualTotalLen() != null && config.getManualTotalLen().compareTo(BigDecimal.valueOf(300))>0)
                    || (config.getAutoTotalLen() != null && config.getAutoTotalLen().compareTo(BigDecimal.valueOf(300))>0);
            if (isValidLen) {
                return roller + "风口长度设置不能大于300cm！";
            }
            if (config.getReservedLen() == null || config.getReservedLen().compareTo(BigDecimal.ZERO)<=0) {
                return roller + "预留风口长度未设置，请点击相应页签右上角设置后重试！";
            }

            if (CollectionUtils.isEmpty(terms)) {
                return roller + "温度控制未设置，请设置后重新尝试！";
            }

            if (terms.size() > 5) {
                return roller + "温度控制设置条数超过上限！请调整后重试";
            }

            for (SysAutoTerm term : terms) {
                if (term.getStartTime() == null || term.getEndTime() == null) {
                    return roller + "温度控制运行时间填写不完整，请检查填写后重新尝试！";
                }
                if (term.getStartTime().after(term.getEndTime())) {
                    return roller + "温度控制运行时间起不能大于止！";
                }
                if (term.getTemp() == null || term.getTemp().compareTo(BigDecimal.ZERO) <= 0) {
                    return roller + "温度控制适宜温度填写不完整！";
                }
                if (term.getVent() == null || term.getVent() <= 0) {
                    return roller + "温度控制风口开合大小填写不完整！";
                }
            }

            if (checkTimeConflict(terms)) {
                return roller + "温度控制运行时间存在冲突，请检查填写后重新尝试！";
            }
        }
        return "";
    }

    /**
     * 精简版：时间冲突校验（逻辑不变，代码更紧凑）
     */
    private static boolean checkTimeConflict(List<SysAutoTerm> terms) {
        if (terms.size() <= 1) return false;

        for (int i = 0; i < terms.size(); i++) {
            SysAutoTerm t1 = terms.get(i);
            for (int j = i + 1; j < terms.size(); j++) {
                SysAutoTerm t2 = terms.get(j);
                // 一行判断时间重叠，精简代码
                if (!(t1.getEndTime().before(t2.getStartTime()) || t1.getStartTime().after(t2.getEndTime()))) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<AgriTermVo> getAgriTerm(String imei) {

        List<AgriTermVo> agriTerms = new ArrayList<>();
        List<SysAutoTerm> autoTerms = super.lambdaQuery()
                .eq(SysAutoTerm::getImei, imei)
                .orderByAsc(SysAutoTerm::getRoller)
                .list();
        List<SysRollerParam> rollerParams = rollerParamService.lambdaQuery()
                .eq(SysRollerParam::getImei, imei)
                .orderByAsc(SysRollerParam::getRoller)
                .list();
        if (CollectionUtils.isEmpty(rollerParams)) {
            return agriTerms;
        }
        Map<String, List<SysAutoTerm>> rollerMap
                = autoTerms.stream().collect(Collectors.groupingBy(SysAutoTerm::getRoller));
        for (SysRollerParam rollerParam : rollerParams) {
            rollerParam.setRefTemp(rollerParam.getRefTempCode().replace("temp","温度"));
            AgriTermVo agriTerm = new AgriTermVo();
            agriTerm.setConfig(rollerParam);
            List<SysAutoTerm> terms = rollerMap.get(rollerParam.getRoller());
            if (CollectionUtils.isNotEmpty(terms)) {
                agriTerm.setTerms(terms);
            }
            agriTerms.add(agriTerm);
        }
        return agriTerms;
    }
}
