package com.usky.sas.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.sas.domain.SasEventTypeGroup;
import com.usky.sas.domain.SasSystemActivation;
import com.usky.sas.enums.SystemTypeCodeEnum;
import com.usky.sas.enums.EventLevelEnum;
import com.usky.sas.mapper.SasEventTypeGroupMapper;
import com.usky.sas.service.SasEventCodeService;
import com.usky.sas.service.SasEventTypeGroupService;
import com.usky.sas.service.SasSystemActivationService;
import com.usky.sas.service.vo.EventGroupInfo;
import com.usky.sas.service.vo.EventGroupPageRequest;
import com.usky.sas.service.vo.EventGroupSaveRequest;
import com.usky.sas.service.vo.SystemTypeCodeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class SasEventTypeGroupServiceImpl extends AbstractCrudService<SasEventTypeGroupMapper, SasEventTypeGroup>
        implements SasEventTypeGroupService {

    @Autowired
    private SasEventCodeService sasEventCodeService;

    @Autowired
    private SasSystemActivationService systemActivationService;

    @Override
    public CommonPage<EventGroupInfo> page(EventGroupPageRequest request) {
        IPage<SasEventTypeGroup> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<SasEventTypeGroup> wrapper = new LambdaQueryWrapper<>();
        if (request.getDeviceType() != null) {
            wrapper.eq(SasEventTypeGroup::getDeviceType, request.getDeviceType());
        }
        if (request.getName() != null && !request.getName().isEmpty()) {
            wrapper.like(SasEventTypeGroup::getName, request.getName());
        }
        wrapper.orderByDesc(SasEventTypeGroup::getCreateTime);
        page = this.page(page, wrapper);

        List<EventGroupInfo> records = page.getRecords().stream()
                .map(this::toEventGroupInfo)
                .collect(Collectors.toList());

        return new CommonPage<>(records, page.getTotal(), page.getCurrent(), page.getSize());
    }

    /**
     * 将事件组实体转为带设备类型名称、事件编码列表的 VO
     */
    private EventGroupInfo toEventGroupInfo(SasEventTypeGroup group) {
        EventGroupInfo info = new EventGroupInfo();
        info.setId(group.getId());
        info.setName(group.getName());
        info.setDeviceType(group.getDeviceType());
        info.setEventLevel(group.getEventLevel());
        info.setCreateTime(group.getCreateTime());
        info.setUpdateTime(group.getUpdateTime());
        info.setCanDel(group.getCanDel());

        Integer deviceType = group.getDeviceType();
        SystemTypeCodeEnum typeEnum = SystemTypeCodeEnum.getByCode(deviceType);
        if (typeEnum != null) {
            info.setDeviceTypeName(typeEnum.getMessage());
        }

        info.setEventLevelName(EventLevelEnum.getNameByCode(group.getEventLevel()));

        if (StrUtil.isNotBlank(group.getEventCodes())) {
            List<Integer> codes = Arrays.stream(group.getEventCodes().split(","))
                    .map(String::trim)
                    .filter(StrUtil::isNotBlank)
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
            if (!codes.isEmpty()) {
                info.setEventCodes(sasEventCodeService.getEventCodesByIds(deviceType, codes));
            }
        }

        return info;
    }

    @Override
    public String create(EventGroupSaveRequest request) {
        SasEventTypeGroup group = new SasEventTypeGroup();
        group.setId(UUID.randomUUID().toString());
        group.setName(request.getName());
        group.setDeviceType(request.getDeviceType());
        if (request.getEventCodes() != null) {
            group.setEventCodes(request.getEventCodes().stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(",")));
        }
        group.setEventLevel(request.getEventLevel());
        group.setCanDel(true);
        LocalDateTime now = LocalDateTime.now();
        group.setCreateTime(now);
        group.setUpdateTime(now);
        this.save(group);
        return group.getId();
    }

    @Override
    public void update(String id, EventGroupSaveRequest request) {
        SasEventTypeGroup group = this.getById(id);
        if (group == null) {
            return;
        }
        group.setName(request.getName());
        group.setDeviceType(request.getDeviceType());
        if (request.getEventCodes() != null) {
            group.setEventCodes(request.getEventCodes().stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(",")));
        }
        group.setEventLevel(request.getEventLevel());
        group.setUpdateTime(LocalDateTime.now());
        this.updateById(group);
    }

    @Override
    public void delete(String id) {
        SasEventTypeGroup group = this.getById(id);
        if (group == null) {
            return;
        }
        if (Boolean.FALSE.equals(group.getCanDel())) {
            return;
        }
        this.removeById(id);
    }

    @Override
    public List<SystemTypeCodeVO> getSystemTypeCodes() {
        SasSystemActivation activation = systemActivationService.currentActivation();
        if (activation == null || activation.getAuthorizationModule() == null
                || activation.getAuthorizationModule().trim().isEmpty()) {
            return java.util.Collections.emptyList();
        }
        String authorizationModule = activation.getAuthorizationModule();
        List<Integer> codes = Arrays.stream(authorizationModule.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        return codes.stream()
                .map(SystemTypeCodeEnum::getByCode)
                .filter(e -> e != null)
                .map(e -> new SystemTypeCodeVO(e.getCode(), e.getMessage()))
                .collect(Collectors.toList());
    }
}

