package com.artfess.device.base.manager.impl;

import com.artfess.base.constants.CacheKeyConst;
import com.artfess.base.enums.EnableStatusEnum;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.device.base.dao.DeviceWarnConfDao;
import com.artfess.device.base.manager.DeviceWarnConfDetailsManager;
import com.artfess.device.base.manager.DeviceWarnConfManager;
import com.artfess.device.base.model.DeviceWarnConf;
import com.artfess.device.base.model.DeviceWarnConfDetails;
import com.artfess.redis.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 设备告警配置 服务实现类
 *
 * @author min.wu
 * @company 阿特菲斯信息技术有限公司
 * @since 2022-07-15
 */
@Service
public class DeviceWarnConfManagerImpl extends BaseManagerImpl<DeviceWarnConfDao, DeviceWarnConf> implements DeviceWarnConfManager {

    @Autowired
    private DeviceWarnConfDetailsManager detailsManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public PageList<DeviceWarnConf> query(QueryFilter<DeviceWarnConf> queryFilter) {
        PageBean pageBean = queryFilter.getPageBean();
        IPage<DeviceWarnConf> result = baseMapper.queryPage(convert2IPage(pageBean), convert2Wrapper(queryFilter, currentModelClass()));
        // 封装告警配置下的详情数据
        List<DeviceWarnConfDetails> detailsList = detailsManager.list();
        result.getRecords().forEach(r -> {
            List<DeviceWarnConfDetails> details = new ArrayList<>();
            detailsList.forEach(d -> {
                if (r.getId().equals(d.getDeviceWarnConfId())) {
                    details.add(d);
                }
            });
            r.setDetails(details);
        });
        return new PageList<>(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CacheKeyConst.SYS_WARN_CACHE, allEntries = true)
    public String createInfo(DeviceWarnConf t) {
        this.vaild(t);
        int i = this.baseMapper.insert(t);
        if (i > 0) {
            redisUtil.delLike(CacheKeyConst.SYS_WARN_CACHE + ":");
            processDetails(t.getId(), t.getDetails());
            return t.getId();
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CacheKeyConst.SYS_WARN_CACHE, allEntries = true)
    public String updateInfo(DeviceWarnConf t) {
        this.vaild(t);
        int i = this.baseMapper.updateById(t);
        if (i > 0) {
            redisUtil.delLike(CacheKeyConst.SYS_WARN_CACHE + ":");
            processDetails(t.getId(), t.getDetails());
            return t.getId();
        }
        return null;
    }

    @Override
    public DeviceWarnConf findById(String id) {
        DeviceWarnConf entity = getById(id);
        if (null == entity) {
            return null;
        }
        QueryWrapper<DeviceWarnConfDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_warn_conf_id_", id);
        List<DeviceWarnConfDetails> deviceWarnConfs = detailsManager.getBaseMapper().selectList(queryWrapper);
        entity.setDetails(deviceWarnConfs);
        return entity;
    }

    @Override
    public boolean modifyEnabled(DeviceWarnConf t) {

        DeviceWarnConf entity = getById(t.getId());
        if (null == entity) {
            return false;
        }

        entity.setStatus(EnableStatusEnum.Y.getType().equals(entity.getStatus()) ? EnableStatusEnum.N.getType() : EnableStatusEnum.Y.getType());
        entity.setUpdateTime(LocalDateTime.now());
        boolean b = this.saveOrUpdate(entity);
        return b;
    }

    private void processDetails(String id, List<DeviceWarnConfDetails> list) {

        QueryWrapper<DeviceWarnConfDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_warn_conf_id_", id);
        detailsManager.getBaseMapper().delete(queryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        list.forEach(details -> {
            details.setDeviceWarnConfId(id);
            detailsManager.getBaseMapper().insert(details);
        });
    }

    public void vaild(DeviceWarnConf t) {
        QueryWrapper<DeviceWarnConf> queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(t.getId())) {
            queryWrapper.ne("id_", t.getId());
        }
        queryWrapper.eq("warn_name_", t.getWarnName()).eq("product_conf_id_", t.getProductConfId());
        List<DeviceWarnConf> functions = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(functions)) {
            throw new IllegalArgumentException("预警名称已重复，请重新输入");
        }
    }
}
