package com.casic.missiles.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.casic.missiles.modular.system.dto.BusConfigDTO;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.modular.system.dto.DeviceTypeEnum;
import com.casic.missiles.modular.system.model.BusConfig;
import com.casic.missiles.modular.system.dao.BusConfigMapper;
import com.casic.missiles.modular.system.model.Device;
import com.casic.missiles.modular.system.redis.RedisPublisherUtil;
import com.casic.missiles.modular.system.rs.RedisCommon;
import com.casic.missiles.modular.system.service.IBusConfigService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.casic.missiles.modular.system.service.IDeviceRuleService;
import com.casic.missiles.modular.system.service.IDeviceService;
import com.casic.missiles.util.RegUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 * 设备配置表 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2019-05-16
 */
@Service
public class BusConfigServiceImpl extends ServiceImpl<BusConfigMapper, BusConfig> implements IBusConfigService {
    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private IDeviceService iDeviceService;
    @Autowired
    private IDeviceRuleService iDeviceRuleService;

    @Override
    public List<BusConfig> getListBydevId(Long devId) {
        EntityWrapper<BusConfig> busConfigEntityWrapper = new EntityWrapper<>();
        busConfigEntityWrapper.eq("DEVICE_ID", devId);
        return this.baseMapper.selectList(busConfigEntityWrapper);
    }

    public String getThresholdByDevId(BusConfigDTO busConfigDTO) {
        String limitValue = "0";//报警阈值
        limitValue = getWellDeepByDevId(busConfigDTO.getDeviceId());
        DecimalFormat df = new DecimalFormat("0.000");
        limitValue = df.format(Double.parseDouble(limitValue) *
                Double.valueOf(busConfigDTO.getPercent()) / 100);
        return limitValue;
    }

    @Override
    public List<Map<String, Object>> getConfigList(Page<BusConfigDTO> page,
                                                   String keywords,
                                                   String deptid,
                                                   DataScope dataScope) {
        return this.baseMapper.getConfigList(page, keywords, deptid, dataScope);

    }


    @Override
    public String getConcenCodeByDevId(Long devID) {
        return this.baseMapper.getConcenCodeByDevId(devID);
    }

    @Override
    public String getWellDeepByDevId(Long devID) {
        return this.baseMapper.getWellDeepByDevId(devID);
    }

    @Override
    public void addConfig(BusConfigDTO busConfigDTO) {
        List<BusConfig> busConfigList = getListBydevId(busConfigDTO.getDeviceId());
        busConfigList.forEach(busConfig -> {
            this.deleteById(busConfig.getId());
        });
        busConfigDTO.setThreshold(Float.valueOf(getThresholdByDevId(busConfigDTO)));
        BusConfig busConfig = new BusConfig(busConfigDTO);
        insert(busConfig);
        Device device=iDeviceService.selectById(busConfigDTO.getDeviceId());
        if(device!=null){
            iDeviceRuleService.updateRule(device.getDevcode(),busConfigDTO.getThreshold(),null);
        }
        String concentratorCode = redisCommon.sendMsg(DeviceTypeEnum.Liquid.toString(),
                busConfig.getDeviceId(), busConfig.getFramecontent(), busConfigDTO.getAttemptsMax());
        if (StringUtils.isNotBlank(concentratorCode)) {//发布消息订阅
            RedisPublisherUtil.getInstance().
                    publishMessage(concentratorCode);
        }
    }

    @Override
    public void addBatchConfig(List<BusConfigDTO> busConfigDTOList) {
        String concentratorCodeStr = "";
        for (BusConfigDTO busConfigDTO : busConfigDTOList) {
            List<BusConfig> busConfigList = getListBydevId(busConfigDTO.getDeviceId());
            for (BusConfig busConfig : busConfigList) {
                deleteById(busConfig.getId());
            }
            busConfigDTO.setThreshold(Float.valueOf(getThresholdByDevId(busConfigDTO)));
            BusConfig busConfig1 = new BusConfig(busConfigDTO);
            insert(busConfig1);
            Device device=iDeviceService.selectById(busConfigDTO.getDeviceId());
            if(device!=null){
                iDeviceRuleService.updateRule(device.getDevcode(),busConfigDTO.getThreshold(),null);
            }
            String concentratorCode = redisCommon.sendMsg(DeviceTypeEnum.Liquid.toString(),
                    busConfig1.getDeviceId(), busConfig1.getFramecontent(), busConfigDTO.getAttemptsMax());
            if (StringUtils.isNotBlank(concentratorCode)) {
                concentratorCodeStr += (concentratorCode + ",");
            }
        }
        if (StringUtils.isNotBlank(concentratorCodeStr)) {//发布消息订阅
            RedisPublisherUtil.getInstance().
                    publishMessage(concentratorCodeStr.substring(0, concentratorCodeStr.length() - 1));
        }
    }

    @Override
    public void updateConfig(BusConfigDTO busConfigDTO) {
        busConfigDTO.setThreshold(Float.valueOf(getThresholdByDevId(busConfigDTO)));
        BusConfig busConfig = selectById(busConfigDTO.getId());
        busConfig.setDeviceId(Long.valueOf(busConfigDTO.getDeviceId()));
        busConfig.setFramecontent(busConfigDTO.getThreshold() + "," + busConfigDTO.getInstallHeight() + ","
                + busConfigDTO.getRetryTimes() + "," + busConfigDTO.getPercent() + "," + busConfigDTO.getIp() + ","
                + busConfigDTO.getPort());
        busConfig.setStatus("0");
        busConfig.setAttemptsmax(Integer.valueOf(busConfigDTO.getAttemptsMax()));
        busConfig.setWritetime(new Date());
        updateById(busConfig);
        Device device=iDeviceService.selectById(busConfigDTO.getDeviceId());
        if(device!=null){
            iDeviceRuleService.updateRule(device.getDevcode(),busConfigDTO.getThreshold(),null);
        }
        String concentratorCode = redisCommon.sendMsg(DeviceTypeEnum.Liquid.toString(),
                busConfig.getDeviceId(), busConfig.getFramecontent(), busConfigDTO.getAttemptsMax());
        if (StringUtils.isNotBlank(concentratorCode)) {//发布消息订阅
            RedisPublisherUtil.getInstance().
                    publishMessage(concentratorCode);
        }
    }

    @Override
    public Map<String, Object> validate(List<BusConfigDTO> busConfigDTOList) {
        Map<String, Object> stringMap = new HashMap<>();
        try {
            for (int i = 0; i < busConfigDTOList.size(); i++) {
                if (!RegUtil.isNumOrLetter(busConfigDTOList.get(i).getDevcode())) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，设备编号必填且为字母或数字");
                    return stringMap;
                }else {//校验设备编号是否在系统中存在
                    Device device =iDeviceService.getDeviceByDevCode(
                            busConfigDTOList.get(i).getDevcode());
                    if(null==device)
                    {
                        stringMap.put("success", false);
                        stringMap.put("msg", "第" + (i + 2) + "行，设备编号在系统中不存在，请先导入设备");
                        return stringMap;
                    }else {
                        busConfigDTOList.get(i).setDeviceId(device.getId());
                    }
                }

                if (0 == busConfigDTOList.get(i).getPercent()) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，报警阈值必填且小数位最多保留2位");
                    return stringMap;

                } else if (!RegUtil.isDecimal2(String.valueOf(busConfigDTOList.get(i).getPercent()))) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，报警阈值必填且小数位最多保留2位");
                    return stringMap;
                }
                if (!RegUtil.isInteger(busConfigDTOList.get(i).getRetryTimes())) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，重传次数必填且为正整数");
                    return stringMap;
                }
                if (0.0 == busConfigDTOList.get(i).getInstallHeight()) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，安装高度必填且小数位最多保留2位");
                    return stringMap;
                } else if (!RegUtil.isDecimal2(String.valueOf(busConfigDTOList.get(i).getInstallHeight()))) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，安装高度必填且小数位最多保留2位");
                    return stringMap;
                }

                if (!RegUtil.isIp(busConfigDTOList.get(i).getIp())) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，IP填写不合格");
                    return stringMap;
                }
                if (!RegUtil.isPort(busConfigDTOList.get(i).getPort())) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，端口号填写不合格");
                    return stringMap;
                }
                if (!RegUtil.isInteger(busConfigDTOList.get(i).getAttemptsMax())) {
                    stringMap.put("success", false);
                    stringMap.put("msg", "第" + (i + 2) + "行，最大尝试次数必填且为正整数");
                    return stringMap;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            stringMap.put("success", false);
            stringMap.put("msg", "导入异常！");
        }
        stringMap.put("success", true);
        stringMap.put("msg", "导入成功");
        return stringMap;
    }

}
