package com.xhpc.charging.station.service;

import com.xhpc.charging.station.mapper.XhpcTimingChargingPowerMapper;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.domain.XhpcTimingChargingPowerModel;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class XhpcTimingChargingPowerServiceImpl implements IXhpcTimingChargingPowerService {

    @Resource
    private XhpcTimingChargingPowerMapper xhpcTimingChargingPowerMapper;
    @Resource
    private TokenService tokenService;
    @Resource
    private PowerPileService powerPileService;
    @Autowired
    RedisService redisService;
    private final ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Override
    public List<Map<String, Object>> list(HttpServletRequest request, String tenantId, Long operatorId, String reason, Integer status, String startTime, String endTime, Long chargingStationId, String endSatrtTime, String endEndTime,Integer type) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        SysUser sysUser = loginUser.getSysUser();

        Long sysUserId = sysUser.getUserId();
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUserId)){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                return xhpcTimingChargingPowerMapper.list(operatorId,reason,status,startTime,endTime,chargingStationId,logOperatorId, 1,tenantId,endSatrtTime,endEndTime,type);
            }else{
                //查询赋值的场站
                return xhpcTimingChargingPowerMapper.list(operatorId,reason,status,startTime,endTime,chargingStationId,sysUserId, 2,tenantId,endSatrtTime,endEndTime,type);
            }
        }else{
            return xhpcTimingChargingPowerMapper.list(operatorId,reason,status,startTime,endTime,chargingStationId,sysUserId, 0,tenantId,endSatrtTime,endEndTime,type);
        }

    }

    @Override
    public R addXhpcTimingChargingPowerModel(HttpServletRequest request, XhpcTimingChargingPowerModel xhpcTimingChargingPowerModel) {

        LoginUser loginUser = tokenService.getLoginUser(request);
        if(loginUser ==null){
            return R.fail(1001, "登录信息为空");
        }
        if (xhpcTimingChargingPowerModel.getReason() == null || "".equals(xhpcTimingChargingPowerModel.getReason())) {
            return R.fail(1001, "调整原因不能为空");
        }
        if (xhpcTimingChargingPowerModel.getChargingStationId() == null || "".equals(xhpcTimingChargingPowerModel.getChargingStationId())) {
            return R.fail(1001, "场站不能为空");
        }
        if (xhpcTimingChargingPowerModel.getStartTimingTime() == null || "".equals(xhpcTimingChargingPowerModel.getStartTimingTime())) {
            return R.fail(1001, "调整开始时间不能为空");
        }else{
            if(System.currentTimeMillis()>xhpcTimingChargingPowerModel.getStartTimingTime().getTime()){
                return R.fail(1001, "调整开始时间不能小于现在时间");
            }
        }

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

            if(xhpcTimingChargingPowerModel.getEndTimingTime().getTime()<xhpcTimingChargingPowerModel.getStartTimingTime().getTime()){
                return R.fail(1001, "调整结束时间不能小于调整开始时间");
            }
        }

        if (xhpcTimingChargingPowerModel.getPowerNumber() == null) {
            return R.fail(1001, "调整开始桩功率百分比不能为空");
        }else {
            if(xhpcTimingChargingPowerModel.getPowerNumber()<1 || xhpcTimingChargingPowerModel.getPowerNumber()>100){
                return R.fail(1001, "调整开始桩功率百分比范围在1~100之间");
            }
        }

        if (xhpcTimingChargingPowerModel.getEndPowerNumber() == null) {
            return R.fail(1001, "调整结束桩功率百分比不能为空");
        }else {
            if(xhpcTimingChargingPowerModel.getEndPowerNumber()<1 || xhpcTimingChargingPowerModel.getEndPowerNumber()>100){
                return R.fail(1001, "调整结束桩功率百分比范围在1~100之间");
            }
        }
        if(xhpcTimingChargingPowerModel.getChargingPileIds().length==0){
            return R.fail(1001, "请选择桩");
        }
        Integer[] chargingPileIds = xhpcTimingChargingPowerModel.getChargingPileIds();
        String st ="";
        for (int i = 0; i <chargingPileIds.length ; i++) {
            if(i==0 && chargingPileIds.length>1){
                st =st+chargingPileIds[i];
            }else if(chargingPileIds.length==1){
                st =chargingPileIds[i]+"";
            }else{
                st =st+","+chargingPileIds[i];
            }
        }
        xhpcTimingChargingPowerModel.setPileIds(st);

        if(xhpcTimingChargingPowerModel.getTimingChargingPowerId() !=null){
            xhpcTimingChargingPowerMapper.updateXhpcTimingChargingPowerModel(xhpcTimingChargingPowerModel);
        }else{
            xhpcTimingChargingPowerMapper.insertXhpcTimingChargingPowerModel(xhpcTimingChargingPowerModel);
        }
        return R.ok();
    }

    @Override
    public R updateXhpcTimingChargingPowerModel(Long timingChargingPowerId) {
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser ==null){
            return R.ok();
        }
        //查询是否是未执行状态
        XhpcTimingChargingPowerModel xhpcTimingChargingPowerModel = xhpcTimingChargingPowerMapper.getXhpcTimingChargingPowerModelById(timingChargingPowerId,null);
        if(xhpcTimingChargingPowerModel ==null){
            return R.fail("数据不存在");
        }else if (xhpcTimingChargingPowerModel.getStatus()==0){
            xhpcTimingChargingPowerModel.setDelFlag(2);
            xhpcTimingChargingPowerMapper.updateXhpcTimingChargingPowerModel(xhpcTimingChargingPowerModel);
            return R.ok();
        }else if (xhpcTimingChargingPowerModel.getStatus()==1){
            return R.fail("该数据已执行，不能删除");
        }else {
            return R.fail("该数据执行错误，不能删除");
        }
    }

    @Override
    public R getXhpcTimingChargingPowerModelMessage(Long timingChargingPowerId) {

        Map<String, Object> map =new HashMap<>();
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser ==null){
            return R.ok(map);
        }
        //查询是否是未执行状态
        XhpcTimingChargingPowerModel xhpcTimingChargingPowerModelById = xhpcTimingChargingPowerMapper.getXhpcTimingChargingPowerModelById(timingChargingPowerId, loginUser.getTenantId());

        if(xhpcTimingChargingPowerModelById.getPileIds().length()>0){
            String pileIds = xhpcTimingChargingPowerModelById.getPileIds();
            String[] split = pileIds.split(",");
             Integer [] piles =new Integer [split.length];
            for (int i = 0; i <split.length ; i++) {
                String s = split[i];
                piles[i] = Integer.parseInt(s);
            }
            xhpcTimingChargingPowerModelById.setChargingPileIds(piles);
        }

        return R.ok(xhpcTimingChargingPowerModelById);

    }

    @Override
    public R getXhpcTimingChargingPowerModelCron() {

;        List<XhpcTimingChargingPowerModel> list = xhpcTimingChargingPowerMapper.getXhpcTimingChargingPowerModelCron();
        if(list !=null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                XhpcTimingChargingPowerModel xhpcTimingChargingPowerModel = list.get(i);
                String pileIds = xhpcTimingChargingPowerModel.getPileIds();
                String[] split = pileIds.split(",");
                for (int j = 0; j <split.length ; j++) {
                    String s = split[j];
                    Long aLong = Long.valueOf(s);

                    String xhpcChargingPile = xhpcTimingChargingPowerMapper.getXhpcChargingPile(aLong,xhpcTimingChargingPowerModel.getChargingStationId());
                    redisService.setCacheObject("pile:"+xhpcChargingPile+":powerNumber",xhpcTimingChargingPowerModel.getPowerNumber().toString());
                    R r =powerPileService.pileConfigSettings(xhpcChargingPile,xhpcTimingChargingPowerModel.getPowerNumber().toString());
                    if (r.getCode() != 200) {
                        executorService.execute(new Runnable() {
                            @Override
                            public void run() {
                                R r1 = powerPileService.pileConfigSettings(xhpcChargingPile, xhpcTimingChargingPowerModel.getPowerNumber().toString());
                                if (r1.getCode() == 200) {
                                    xhpcTimingChargingPowerMapper.updateXhpcChargingPile(aLong,xhpcTimingChargingPowerModel.getPowerNumber());
                                    xhpcTimingChargingPowerMapper.updateXhpcChargingPower(xhpcTimingChargingPowerModel.getTimingChargingPowerId(),1,null);
                                }
                            }
                        });
                    }else{
                        xhpcTimingChargingPowerMapper.updateXhpcChargingPile(aLong,xhpcTimingChargingPowerModel.getPowerNumber());
                        xhpcTimingChargingPowerMapper.updateXhpcChargingPower(xhpcTimingChargingPowerModel.getTimingChargingPowerId(),1,null);
                    }
                }
            }
        }

        List<XhpcTimingChargingPowerModel> mapList = xhpcTimingChargingPowerMapper.getXhpcEndTimingChargingPowerModelCron();
        if(mapList !=null && mapList.size()>0){
            for (int i = 0; i < mapList.size(); i++) {
                XhpcTimingChargingPowerModel xhpcTimingChargingPowerModel = mapList.get(i);
                String pileIds = xhpcTimingChargingPowerModel.getPileIds();

                String[] split = pileIds.split(",");
                for (int j = 0; j <split.length ; j++) {
                    String s = split[j];
                    Long aLong = Long.valueOf(s);
                    String xhpcChargingPile = xhpcTimingChargingPowerMapper.getXhpcChargingPile(aLong,xhpcTimingChargingPowerModel.getChargingStationId());
                    redisService.setCacheObject("pile:"+xhpcChargingPile+":powerNumber",xhpcTimingChargingPowerModel.getEndPowerNumber().toString());
                    R r =powerPileService.pileConfigSettings(xhpcChargingPile,xhpcTimingChargingPowerModel.getEndPowerNumber().toString());
                    if (r.getCode() != 200) {
                        executorService.execute(new Runnable() {
                            @Override
                            public void run() {
                                R r1 = powerPileService.pileConfigSettings(xhpcChargingPile, xhpcTimingChargingPowerModel.getEndPowerNumber().toString());
                                if (r1.getCode() == 200) {
                                    xhpcTimingChargingPowerMapper.updateXhpcChargingPile(aLong,xhpcTimingChargingPowerModel.getEndPowerNumber());
                                    xhpcTimingChargingPowerMapper.updateXhpcChargingPower(xhpcTimingChargingPowerModel.getTimingChargingPowerId(),null,1);
                                }
                            }
                        });
                    }else{
                        xhpcTimingChargingPowerMapper.updateXhpcChargingPile(aLong,xhpcTimingChargingPowerModel.getEndPowerNumber());
                        xhpcTimingChargingPowerMapper.updateXhpcChargingPower(xhpcTimingChargingPowerModel.getTimingChargingPowerId(),null,1);
                    }
                }

            }
        }
        return null;
    }
}
