package com.pwt.system.service.impl;

import com.pwt.common.constant.CacheConstants;
import com.pwt.common.exception.job.TaskException;
import com.pwt.common.utils.CacheMap;
import com.pwt.common.utils.CloudPlatformService;
import com.pwt.common.utils.StringUtils;
import com.pwt.common.utils.spring.SpringUtils;
import com.pwt.quartz.domain.SysJob;
import com.pwt.quartz.service.ISysJobService;
import com.pwt.quartz.util.CronUtils;
import com.pwt.system.domain.PwtConfig;
import com.pwt.system.mapper.PwtConfigMapper;
import com.pwt.system.service.IPwtConfigService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * 系统配置Service业务层处理
 *
 * @author linyun
 * @date 2022-11-21
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class PwtConfigServiceImpl implements IPwtConfigService {
    @Autowired
    private PwtConfigMapper pwtConfigMapper;

    // 初始化参数
    @PostConstruct
    public void init() {
        PwtConfig config = pwtConfigMapper.selectPwtConfigById(1L);
        loadingConfig(config);
    }

    /**
     * 将参数加载到内存
     */
    private void loadingConfig(PwtConfig config) {
        CacheMap.put(getConfigKey("websiteEnabled"), config.getWebsiteEnabled());
        CacheMap.put(getConfigKey("systemName"), config.getSystemName());
        CacheMap.put(getConfigKey("systemIp"), config.getSystemIp());
        CacheMap.put(getConfigKey("systemPort"), config.getSystemPort());
        CacheMap.put(getConfigKey("adminExpireTime"), config.getAdminExpireTime());
        CacheMap.put(getConfigKey("lastBackupTime"), config.getLastBackupTime());
        CacheMap.put(getConfigKey("chargeSoc"), config.getChargeSoc());
        CacheMap.put(getConfigKey("cloudEnabled"), config.getCloudEnabled());
        CacheMap.put(getConfigKey("cloudAddress"), config.getCloudAddress());
        CacheMap.put(getConfigKey("cloudAccount"), config.getCloudAccount());
        CacheMap.put(getConfigKey("cloudPassword"), config.getCloudPassword());
        CacheMap.put(getConfigKey("agreementType"), config.getAgreementType());
        CacheMap.put(getConfigKey("vehicleCidr"), config.getVehicleCidr());
        CacheMap.put(getConfigKey("robotIp"), config.getRobotIp());
        CacheMap.put(getConfigKey("robotPort"), config.getRobotPort());
        CacheMap.put(getConfigKey("scannerIp"), config.getScannerIp());
        CacheMap.put(getConfigKey("scannerPort"), config.getScannerPort());
        CacheMap.put(getConfigKey("rfidIp"), config.getRfidIp());
        CacheMap.put(getConfigKey("rfidPort"), config.getRfidPort());
        CacheMap.put(getConfigKey("charger1Ip"), config.getCharger1Ip());
        CacheMap.put(getConfigKey("charger2Ip"), config.getCharger2Ip());
        CacheMap.put(getConfigKey("charger3Ip"), config.getCharger3Ip());
        CacheMap.put(getConfigKey("charger4Ip"), config.getCharger4Ip());
        CacheMap.put(getConfigKey("charger5Ip"), config.getCharger5Ip());
        CacheMap.put(getConfigKey("charger6Ip"), config.getCharger6Ip());
        CacheMap.put(getConfigKey("charger7Ip"), config.getCharger7Ip());
        CacheMap.put(getConfigKey("charger8Ip"), config.getCharger8Ip());
    }

    /**
     * 获取参数key前缀
     */
    public String getConfigKey(String key) {
        return CacheConstants.PWT_CONFIG_KEY + key;
    }

    /**
     * 查询系统配置
     *
     * @param id 系统配置主键
     * @return 系统配置
     */
    @Override
    public PwtConfig selectPwtConfigById(Long id) {
        return pwtConfigMapper.selectPwtConfigById(id);
    }

    /**
     * 查询系统配置列表
     *
     * @param pwtConfig 系统配置
     * @return 系统配置
     */
    @Override
    public List<PwtConfig> selectPwtConfigList(PwtConfig pwtConfig) {
        return pwtConfigMapper.selectPwtConfigList(pwtConfig);
    }

    /**
     * 修改系统配置
     *
     * @param pwtConfig 系统配置
     * @return 结果
     */
    @Override
    public PwtConfig updatePwtConfig(PwtConfig pwtConfig) {
        paramConvert(pwtConfig);
        chargeTask(pwtConfig);
        PwtConfig con = pwtConfigMapper.selectPwtConfigById(pwtConfig.getId());
        // 检测站点开关状态如果更改,则调用云平台站点开关状态同步
        if (pwtConfig.getWebsiteEnabled() != null && !pwtConfig.getWebsiteEnabled().equals(con.getWebsiteEnabled())) {
            String result = CloudPlatformService.status(pwtConfig.getWebsiteEnabled());
            log.info("站点开关同步结果:{}", result);
        }
        int row = pwtConfigMapper.updatePwtConfig(pwtConfig);
        if (row > 0) {
            PwtConfig config = pwtConfigMapper.selectPwtConfigById(pwtConfig.getId());
            // 修改数据重新加载到内存
            loadingConfig(config);
            return config;
        }
        return null;
    }


    /**
     * 配置是否自动换仓
     *
     * @param isAutoChangeWarehouse
     */
    @Override
    public void changeAutoChangeWarehouse(Long id, boolean isAutoChangeWarehouse) {
        pwtConfigMapper.changeAutoChangeWarehouse(id, isAutoChangeWarehouse);
    }

    @Override
    public Boolean getIsAutoChangeWarehouse(Long id) {
        return pwtConfigMapper.getIsAutoChangeWarehouse(id);
    }

    /**
     * 定时充电
     *
     * @param pwtConfig 配置对象
     */
    private void chargeTask(PwtConfig pwtConfig) {
        ISysJobService sysJobService = SpringUtils.getBean(ISysJobService.class);
        List<SysJob> jobList = sysJobService.selectJobList(new SysJob());
        try {
            if (pwtConfig.getCharger1Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger1Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger1")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
            if (pwtConfig.getCharger2Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger2Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger2")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
            if (pwtConfig.getCharger3Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger3Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger3")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
            if (pwtConfig.getCharger4Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger4Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger4")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
            if (pwtConfig.getCharger5Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger5Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger5")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
            if (pwtConfig.getCharger6Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger6Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger6")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
            if (pwtConfig.getCharger7Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger7Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger7")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
            if (pwtConfig.getCharger8Time() != null) {
                String cron = CronUtils.formatDateByPattern(pwtConfig.getCharger8Time());
                SysJob sysJob = jobList.stream().filter(j -> j.getInvokeTarget() != null && j.getInvokeTarget().equals("ryTask.charger8")).findFirst().orElse(null);
                if (sysJob != null) {
                    sysJob.setCronExpression(cron);
                    sysJobService.updateJob(sysJob);
                }
            }
        } catch (SchedulerException | TaskException e) {
            e.printStackTrace();
        }
    }

    /**
     * 页面参数转换
     *
     * @param pwtConfig 配置对象
     */
    private void paramConvert(PwtConfig pwtConfig) {
        // 站控
        if (StringUtils.isNotBlank(pwtConfig.getSystemIp())) {
            List<String> systemList = split(pwtConfig.getSystemIp());
            pwtConfig.setSystemIp(systemList.get(0));
            pwtConfig.setSystemPort(Integer.parseInt(systemList.get(1)));
        }
        // 扫码器
        if (StringUtils.isNotBlank(pwtConfig.getScannerIp())) {
            List<String> scannerList = split(pwtConfig.getScannerIp());
            pwtConfig.setScannerIp(scannerList.get(0));
            pwtConfig.setScannerPort(Integer.parseInt(scannerList.get(1)));
        }
        // rfid
        if (StringUtils.isNotBlank(pwtConfig.getRfidIp())) {
            List<String> rfidList = split(pwtConfig.getRfidIp());
            pwtConfig.setRfidIp(rfidList.get(0));
            pwtConfig.setRfidPort(Integer.parseInt(rfidList.get(1)));
        }
        // robot
        if (StringUtils.isNotBlank(pwtConfig.getRobotIp())) {
            List<String> robotList = split(pwtConfig.getRobotIp());
            pwtConfig.setRobotIp(robotList.get(0));
            pwtConfig.setRfidPort(Integer.parseInt(robotList.get(1)));
        }
        // charger1
        if (StringUtils.isNotBlank(pwtConfig.getCharger1Ip())) {
            List<String> charger1List = split(pwtConfig.getCharger1Ip());
            pwtConfig.setCharger1Ip(charger1List.get(0));
            pwtConfig.setCharger1Port(Integer.parseInt(charger1List.get(1)));
        }
        // charger2
        if (StringUtils.isNotBlank(pwtConfig.getCharger2Ip())) {
            List<String> charger2List = split(pwtConfig.getCharger2Ip());
            pwtConfig.setCharger2Ip(charger2List.get(0));
            pwtConfig.setCharger2Port(Integer.parseInt(charger2List.get(1)));
        }
        // charger3
        if (StringUtils.isNotBlank(pwtConfig.getCharger3Ip())) {
            List<String> charger3List = split(pwtConfig.getCharger3Ip());
            pwtConfig.setCharger3Ip(charger3List.get(0));
            pwtConfig.setCharger3Port(Integer.parseInt(charger3List.get(1)));
        }
        // charger4
        if (StringUtils.isNotBlank(pwtConfig.getCharger4Ip())) {
            List<String> charger4List = split(pwtConfig.getCharger4Ip());
            pwtConfig.setCharger4Ip(charger4List.get(0));
            pwtConfig.setCharger4Port(Integer.parseInt(charger4List.get(1)));
        }
        // charger5
        if (StringUtils.isNotBlank(pwtConfig.getCharger5Ip())) {
            List<String> charger5List = split(pwtConfig.getCharger5Ip());
            pwtConfig.setCharger5Ip(charger5List.get(0));
            pwtConfig.setCharger5Port(Integer.parseInt(charger5List.get(1)));
        }
        // charger6
        if (StringUtils.isNotBlank(pwtConfig.getCharger6Ip())) {
            List<String> charger6List = split(pwtConfig.getCharger6Ip());
            pwtConfig.setCharger6Ip(charger6List.get(0));
            pwtConfig.setCharger6Port(Integer.parseInt(charger6List.get(1)));
        }
        // charger7
        if (StringUtils.isNotBlank(pwtConfig.getCharger7Ip())) {
            List<String> charger7List = split(pwtConfig.getCharger7Ip());
            pwtConfig.setCharger7Ip(charger7List.get(0));
            pwtConfig.setCharger7Port(Integer.parseInt(charger7List.get(1)));
        }
        // charger8
        if (StringUtils.isNotBlank(pwtConfig.getCharger8Ip())) {
            List<String> charger8List = split(pwtConfig.getCharger8Ip());
            pwtConfig.setCharger8Ip(charger8List.get(0));
            pwtConfig.setCharger8Port(Integer.parseInt(charger8List.get(1)));
        }
    }

    private List<String> split(String parameter) {
        return Arrays.asList(parameter.split(":"));
    }

}
