package com.gyee.wisdom.alarm.sharding.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyee.wisdom.alarm.sharding.entity.Alertrule2;
import com.gyee.wisdom.alarm.sharding.entity.Scadafault;
import com.gyee.wisdom.alarm.sharding.entity.Warning2;
import com.gyee.wisdom.alarm.sharding.logtool.LogService;
import com.gyee.wisdom.alarm.sharding.mapper.ScadafaultMapper;
import com.gyee.wisdom.alarm.sharding.mapper.Warning2Mapper;
import com.gyee.wisdom.alarm.sharding.util.SnowflakeGenerator;
import com.gyee.wisdom.alarm.sharding.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Warning2Service extends ServiceImpl<Warning2Mapper, Warning2> {
    @Autowired
    private Warning2Mapper warning2Mapper;

    @Autowired
    private LogService logService;

    @Autowired
    private RuleUpdateEventService eventService;

    public int saveAndUpdateWarning2(Warning2 warning2,String userName) {
        String modelId = warning2.getModelId();
        String[] s = modelId.split("_");
        if(s.length>1){
            warning2.setModelId(s[0]);
        }
        Warning2 oldData=null;
        int result = 0;
        if (StringUtils.isBlank(warning2.getId())) {
            String maxIdString = warning2Mapper.getMaxIdByModelId(warning2.getModelId());
            if(maxIdString == null || maxIdString.length() == 0){
                maxIdString = warning2.getModelId()+"_0";
            }
            String[] arr = maxIdString.split("_");

            int maxId = 0;
            try {
                maxId = Integer.valueOf(arr[1]);
            } catch (Exception ex) {
                maxId = 100000;
            } finally {
                warning2.setId(String.valueOf(warning2.getModelId() + "_" + (maxId + 1)));
                result = warning2Mapper.insert(warning2);
            }
        } else {
             oldData = warning2Mapper.selectById(warning2.getId());
            if (oldData != null) {
                result = warning2Mapper.updateById(warning2);
            }
        }
        if(result>0){
            eventService.saveEventWarning(warning2,oldData,userName);
        }
        return result;
    }

    public int deleteWarning2(Warning2 warning2) {
        return warning2Mapper.deleteById(warning2.getId());
    }

    public IPage<Warning2> pageQueryAll(Page page, String modelId, String name, String isLeaf) {
        return warning2Mapper.pageQueryAll(page, modelId, name, isLeaf);
    }
}
