package com.xhpc.charging.station.service;

import com.xhpc.charging.station.mapper.TimingTerminalDeactivateMapper;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.domain.TimingTerminalDeactivate;
import com.xhpc.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yuyang
 * @Date 2026-05-08 13:41
 */
@Service
public class TimingTerminalDeactivateServiceImpl implements  ITimingTerminalDeactivateService{

    @Resource
    private TimingTerminalDeactivateMapper deactivateMapper;
    @Resource
    private PowerPileService powerPileService;
    @Resource
    private RedisService redisService;


    @Override
    public TimingTerminalDeactivate selectTimingTerminalDeactivateById(Long id) {
        return deactivateMapper.getTimingTerminalDeactivateById(id);
    }

    @Override
    public List<TimingTerminalDeactivate> selectTimingTerminalDeactivateList(TimingTerminalDeactivate deactivate) {
        return deactivateMapper.selectDeactivateList(deactivate);
    }

    @Override
    public R insertTimingTerminalDeactivate(TimingTerminalDeactivate deactivate) {
        // 设置默认值
        if (deactivate.getStartType() == null) {
            deactivate.setStartType(0); // 未执行
        }
        if (deactivate.getStartStatus() == null) {
            deactivate.setStartStatus(1); // 默认停止
        }

        if (deactivate.getReason() == null || "".equals(deactivate.getReason())) {
            return R.fail(1001, "调整原因不能为空");
        }
        if (deactivate.getChargingStationId() == null || "".equals(deactivate.getChargingStationId())) {
            return R.fail(1001, "场站不能为空");
        }
        if (deactivate.getStartTimingTime() == null || "".equals(deactivate.getStartTimingTime())) {
            return R.fail(1001, "调整开始时间不能为空");
        }else{
            if(System.currentTimeMillis()>deactivate.getStartTimingTime().getTime()){
                return R.fail(1001, "调整开始时间不能小于现在时间");
            }
        }

        if (deactivate.getEndTimingTime() == null || "".equals(deactivate.getEndTimingTime())) {
            return R.fail(1001, "调整结束时间不能为空");
        }else{
            if(System.currentTimeMillis()>deactivate.getEndTimingTime().getTime()){
                return R.fail(1001, "调整结束时间不能小于现在时间");
            }

            if(deactivate.getEndTimingTime().getTime()<deactivate.getStartTimingTime().getTime()){
                return R.fail(1001, "调整结束时间不能小于调整开始时间");
            }
        }
        if(deactivate.getPileIds().length()==0){
            return R.fail(1001, "请选择桩");
        }
        deactivateMapper.addTimingTerminalDeactivate(deactivate);
        return R.ok();
    }

    @Override
    public R updateTimingTerminalDeactivate(TimingTerminalDeactivate deactivate) {

        // 设置默认值
        if (deactivate.getStartType() == null) {
            deactivate.setStartType(0); // 未执行
        }
        if (deactivate.getStartStatus() == null) {
            deactivate.setStartStatus(1); // 默认停止
        }

        if (deactivate.getReason() == null || "".equals(deactivate.getReason())) {
            return R.fail(1001, "调整原因不能为空");
        }
        if (deactivate.getChargingStationId() == null || "".equals(deactivate.getChargingStationId())) {
            return R.fail(1001, "场站不能为空");
        }
        if (deactivate.getStartTimingTime() == null || "".equals(deactivate.getStartTimingTime())) {
            return R.fail(1001, "调整开始时间不能为空");
        }else{
            if(System.currentTimeMillis()>deactivate.getStartTimingTime().getTime()){
                return R.fail(1001, "调整开始时间不能小于现在时间");
            }
        }

        if (deactivate.getEndTimingTime() == null || "".equals(deactivate.getEndTimingTime())) {
            return R.fail(1001, "调整结束时间不能为空");
        }else{
            if(System.currentTimeMillis()>deactivate.getEndTimingTime().getTime()){
                return R.fail(1001, "调整结束时间不能小于现在时间");
            }

            if(deactivate.getEndTimingTime().getTime()<deactivate.getStartTimingTime().getTime()){
                return R.fail(1001, "调整结束时间不能小于调整开始时间");
            }
        }
        if(deactivate.getPileIds().length()==0){
            return R.fail(1001, "请选择桩");
        }

        deactivateMapper.updateTimingTerminalDeactivate(deactivate);
        return R.ok();
    }

    @Override
    public int deleteTimingTerminalDeactivateByIds(List<Long> ids) {
        return deactivateMapper.deleteTimingTerminalDeactivate(null);
    }

    @Override
    public int deleteTimingTerminalDeactivateById(Long id) {
        return deactivateMapper.deleteTimingTerminalDeactivate(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeStartAdjustment() {
        // 查询到达开始时间且未执行的记录
        try{
            List<TimingTerminalDeactivate> listYu = deactivateMapper.getTimingTerminalDeactivateTime(1);

            for (int j = 0; j <listYu.size() ; j++) {

                TimingTerminalDeactivate timingTerminalDeactivate = listYu.get(j);
                if(timingTerminalDeactivate.getStartStatus()==1){

                    List<Map<String, Object>> list = deactivateMapper.getSerialNumberList(Arrays.asList(timingTerminalDeactivate.getPileIds().split(",")));
                    for (int i = 0; i <list.size() ; i++) {
                        Map<String, Object> map = list.get(i);
                        if(map.get("serialNumber") !=null){
                            String serialNumberOrderMap = map.get("serialNumber").toString();
                            Map<String, Object> cacheMap = redisService.getCacheMap("gun:" + serialNumberOrderMap.substring(0,16));
                            if(cacheMap !=null){
                                if(cacheMap.get("orderkey") !=null){
                                    String version ="0C";
                                    if(cacheMap.get("version") !=null){
                                        version =cacheMap.get("version").toString();
                                    }
                                    //同一个桩每道指令有500毫秒的保护期
                                    Thread.sleep(1500);
                                    System.out.println("===========serialNumberOrderMap=============="+serialNumberOrderMap+"====下发停止命令");
                                    powerPileService.stopCharging(serialNumberOrderMap, serialNumberOrderMap.substring(0,14), serialNumberOrderMap.substring(0,16), version);
                                }
                            }
                        }
                    }
                }
                deactivateMapper.updateXhpcTerminalAll(timingTerminalDeactivate.getStartStatus(),timingTerminalDeactivate.getPrompt(),Arrays.asList(timingTerminalDeactivate.getPileIds().split(",")));

                TimingTerminalDeactivate deactivate=new TimingTerminalDeactivate();
                deactivate.setTimingTerminalDeactivateId(timingTerminalDeactivate.getTimingTerminalDeactivateId());
                deactivate.setStartType(1);
                deactivateMapper.updateTimingTerminalDeactivate(deactivate);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeEndAdjustment() {
        try{
            // 查询到达结束时间且未执行的记录
            List<TimingTerminalDeactivate> listYu = deactivateMapper.getTimingTerminalDeactivateTime(2);

            for (int j = 0; j <listYu.size() ; j++) {

                TimingTerminalDeactivate timingTerminalDeactivate = listYu.get(j);
                if(timingTerminalDeactivate.getEndStatus()==1){
                    List<Map<String, Object>> list = deactivateMapper.getSerialNumberList(Arrays.asList(timingTerminalDeactivate.getPileIds().split(",")));
                    for (int i = 0; i <list.size() ; i++) {
                        Map<String, Object> map = list.get(i);
                        if(map.get("serialNumber") !=null){
                            String serialNumberOrderMap = map.get("serialNumber").toString();
                            Map<String, Object> cacheMap = redisService.getCacheMap("gun:" + serialNumberOrderMap.substring(0,16));
                            if(cacheMap !=null){
                                if(cacheMap.get("orderkey") !=null){
                                    String version ="0C";
                                    if(cacheMap.get("version") !=null){
                                        version =cacheMap.get("version").toString();
                                    }
                                    //同一个桩每道指令有500毫秒的保护期
                                    Thread.sleep(1500);
                                    powerPileService.stopCharging(serialNumberOrderMap, serialNumberOrderMap.substring(0,14), serialNumberOrderMap.substring(0,16), version);
                                }
                            }
                        }
                    }
                }
                deactivateMapper.updateXhpcTerminalAll(timingTerminalDeactivate.getEndStatus(),timingTerminalDeactivate.getPrompt(),Arrays.asList(timingTerminalDeactivate.getPileIds().split(",")));

                TimingTerminalDeactivate deactivate=new TimingTerminalDeactivate();
                deactivate.setTimingTerminalDeactivateId(timingTerminalDeactivate.getTimingTerminalDeactivateId());
                deactivate.setEndType(1);
                deactivateMapper.updateTimingTerminalDeactivate(deactivate);

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
