package com.xzzn.ems.service.impl;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzzn.common.enums.StrategyStatus;
import com.xzzn.common.utils.DateUtils;
import com.xzzn.common.utils.StringUtils;
import com.xzzn.common.utils.bean.BeanUtils;
import com.xzzn.ems.domain.EmsStrategy;
import com.xzzn.ems.domain.EmsStrategyTemp;
import com.xzzn.ems.domain.EmsStrategyTempTimeConfig;
import com.xzzn.ems.domain.vo.StrategyTempConfigRequest;
import com.xzzn.ems.domain.vo.SyncStrategyTempVo;
import com.xzzn.ems.mapper.EmsStrategyCurveMapper;
import com.xzzn.ems.mapper.EmsStrategyMapper;
import com.xzzn.ems.mapper.EmsStrategyTempMapper;
import com.xzzn.ems.mapper.EmsStrategyTimeConfigMapper;
import com.xzzn.ems.service.IEmsStrategyTempService;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 模板Service业务层处理
 *
 * @author xzzn
 * @date 2025-07-11
 */
@Service
public class EmsStrategyTempServiceImpl implements IEmsStrategyTempService
{
    private static final String PREFIX= "Temp";
    @Autowired
    private EmsStrategyTempMapper emsStrategyTempMapper;
    @Autowired
    private EmsStrategyTimeConfigMapper emsStrategyTimeConfigMapper;
    @Autowired
    private EmsStrategyCurveMapper emsStrategyCurveMapper;
    @Autowired
    private EmsStrategyMapper emsStrategyMapper;

    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 查询模板列表
     *
     * @param templateId 模板
     * @return 模板
     */
    @Override
    public List<EmsStrategyTemp> selectEmsStrategyTempList(String templateId)
    {
        return emsStrategyTempMapper.selectStrategyTempByTempId(templateId);
    }

    /**
     * 新增模板和时间配置
     * @param requestVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addNewTempAndTimeConfig(StrategyTempConfigRequest requestVo) {
        // 随机生产模板id格式：Temp+时间戳
        String templateId = requestVo.getTemplateId();
        if (StringUtils.isEmpty(templateId)) {
            templateId = PREFIX + DateUtils.dateTimeNow();
        }

        EmsStrategyTemp publicTemp = new EmsStrategyTemp();
        BeanUtils.copyProperties(requestVo, publicTemp);
        publicTemp.setTemplateId(templateId);
        publicTemp.setCreateTime(DateUtils.getNowDate());

        List<EmsStrategyTempTimeConfig> timeList = requestVo.getTimeConfigList();
        if (timeList != null && !timeList.isEmpty())  {
            for (EmsStrategyTempTimeConfig timeConfig : timeList) {
                EmsStrategyTemp temp = new EmsStrategyTemp();
                BeanUtils.copyProperties(publicTemp, temp);
                // 时间设置
                temp.setStartTime(timeConfig.getStartTime());
                temp.setEndTime(timeConfig.getEndTime());
                temp.setChargeDischargePower(timeConfig.getChargeDischargePower());
                // 每个时间段可独立配置SOC上下限；为空时兼容旧的模板级配置
                temp.setSdcDown(timeConfig.getSdcDown() != null ? timeConfig.getSdcDown() : publicTemp.getSdcDown());
                temp.setSdcUp(timeConfig.getSdcUp() != null ? timeConfig.getSdcUp() : publicTemp.getSdcUp());
                temp.setChargeStatus(timeConfig.getChargeStatus());
                emsStrategyTempMapper.insertEmsStrategyTemp(temp);
            }
        } else {// 无时间配置只配置模板基本信息
                emsStrategyTempMapper.insertEmsStrategyTemp(publicTemp);
        }
        return true;
    }

    /**
     * 修改模板
     *
     * @param requestVo 模板
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEmsStrategyTemp(StrategyTempConfigRequest requestVo)
    {
        String templateId = requestVo.getTemplateId();
        // 无发匹配原数据
        // 全删
        emsStrategyTempMapper.deleteTempByTempId(templateId);

        // 根据模版id 删除推送的曲线图数据
        emsStrategyCurveMapper.physicalDeleteByTemplateId(templateId);
        // 设置该模版的时间配置为待下发
        emsStrategyTimeConfigMapper.updateTimeConfigWaitingPost(templateId);
        // 重新新增
        addNewTempAndTimeConfig(requestVo);

        return true;
    }

    @Override
    public List<Map<String,String>> getTempNameList(Long strategyId, String siteId) {
        return emsStrategyTempMapper.getTempNameList(strategyId, siteId);
    }


    @Override
    public int deleteStrategyTempById(String templateId) {
        // 先更新配置该模板的月份数据
        emsStrategyTimeConfigMapper.cleanTemplateId(templateId);
        // 根据模版id 删除推送的曲线图数据
        emsStrategyCurveMapper.physicalDeleteByTemplateId(templateId);

        return emsStrategyTempMapper.deleteTempByTempId(templateId);
    }

    @Override
    public void dealStrategyTempData(String content, String operateType) throws JsonProcessingException {
        if (StringUtils.isEmpty(content)) {
            return;
        }
        String siteId = "";
        EmsStrategyTemp temp = new EmsStrategyTemp();
        switch (operateType) {
            case "INSERT":
                SyncStrategyTempVo syncVo = JSON.parseObject(content, SyncStrategyTempVo.class);
                //转换开始和结束时间
                convertStringToDate(content, syncVo);
                BeanUtils.copyProperties(syncVo, temp);
                // 先校验策略是否存在，不存在则插入
                dealStrategyData(temp, syncVo);
                // 新增策略运行数据
                emsStrategyTempMapper.insertEmsStrategyTemp(temp);
                break;
            case "DELETE":
                JsonNode jsonNode = objectMapper.readTree(content);
                String tempId = jsonNode.get("templateId").asText();
                // 删除模版
                deleteStrategyTempById(tempId);
                break;
            default:
                // 未知操作类型-不同步
                break;
        }
    }

    private void convertStringToDate(String content, SyncStrategyTempVo syncVo) throws JsonProcessingException {
        JsonNode rootNode = objectMapper.readTree(content);
        String startTime = rootNode.path("startTime").asText();
        String endTime = rootNode.path("endTime").asText();
        if (startTime != null && !"null".equals(startTime)) {
            syncVo.setStartTime(parseTimeStringToDate(startTime));
        }
        if (endTime != null && !"null".equals(endTime)) {
            syncVo.setEndTime(parseTimeStringToDate(endTime));
        }
    }

    private Date parseTimeStringToDate(String timeStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        LocalTime time = LocalTime.parse(timeStr, formatter);
        LocalDateTime dateTime = LocalDateTime.of(LocalDate.now(), time);
        return Date.from(dateTime.atZone(ZoneId.of("Asia/Shanghai")).toInstant());
    }

    private void dealStrategyData(EmsStrategyTemp temp, SyncStrategyTempVo syncVo) {
        // 主策略
        String mainStrategyName =  syncVo.getStrategyName();
        EmsStrategy strategy = emsStrategyMapper.getStrategyByName(mainStrategyName);
        if (strategy != null) {
            temp.setStrategyId(strategy.getId());
        } else {
            strategy = createStrategyEntity(mainStrategyName,   syncVo.getStrategyType());
            emsStrategyMapper.insertEmsStrategy(strategy);
            temp.setStrategyId(strategy.getId());
        }
    }

    private EmsStrategy createStrategyEntity(String strategyName, Long type) {
        EmsStrategy strategy = new EmsStrategy();
        strategy.setStrategyType(type);
        strategy.setStrategyName(strategyName);
        strategy.setStatus(StrategyStatus.RUNNING.getCode());
        strategy.setCreateTime(DateUtils.getNowDate());
        return  strategy;
    }
}
