package com.usky.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.BaseAlarm;
import com.usky.iot.domain.BaseAlarmType;
import com.usky.iot.domain.DmpProductInfo;
import com.usky.iot.mapper.BaseAlarmTypeMapper;
import com.usky.iot.service.BaseAlarmService;
import com.usky.iot.service.BaseAlarmTypeService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.iot.service.vo.BaseAlarmTypeRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 告警类型表 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-07-12
 */
@Service
public class BaseAlarmTypeServiceImpl extends AbstractCrudService<BaseAlarmTypeMapper, BaseAlarmType> implements BaseAlarmTypeService {
    @Autowired
    private BaseAlarmService baseAlarmService;

    @Override
    public void add(BaseAlarmType baseAlarmType){
        if(checkNameUnique(baseAlarmType)){
            throw new BusinessException("新增告警类型名称失败，"+baseAlarmType.getTypeName()+" 已经存在");
        }
        //Calendar car = Calendar.getInstance();
        //Date date = car.getTime();
        //baseAlarmType.setTypeCode(baseAlarmType.getTypeAbbrevia()+"-"+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(date));
        baseAlarmType.setCreateBy(SecurityUtils.getUsername());
        baseAlarmType.setCreateTime(LocalDateTime.now());
        baseAlarmType.setTenantId(SecurityUtils.getTenantId());
        this.save(baseAlarmType);
    }

    @Override
    public void update(BaseAlarmType baseAlarmType){
        if(checkNameUnique(baseAlarmType)){
            throw new BusinessException("修改告警类型名称失败，"+baseAlarmType.getTypeName()+" 已经存在");
        }
        baseAlarmType.setUpdateBy(SecurityUtils.getUsername());
        baseAlarmType.setUpdateTime(LocalDateTime.now());
        this.updateById(baseAlarmType);
    }

    @Override
    public void remove(Integer id){

        BaseAlarmType baseAlarmType = this.getById(id);
        Optional.ofNullable(baseAlarmType).orElseThrow(() -> new BusinessException("告警类型不存在"));

        LambdaQueryWrapper<BaseAlarm> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BaseAlarm::getAlarmType,baseAlarmType.getTypeCode());
        int count = baseAlarmService.count(queryWrapper);
        if(count > 0){
            throw new BusinessException("有告警信息使用该告警类型，不能删除");
        }

        baseAlarmType.setDeleteFlag(1);
        this.updateById(baseAlarmType);
    }

    @Override
    public CommonPage<BaseAlarmType> page(BaseAlarmTypeRequestVO requestVO){
        IPage<BaseAlarmType> page = new Page<>(requestVO.getCurrent(),requestVO.getSize());
        LambdaQueryWrapper<BaseAlarmType> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(requestVO.getTypeCode()),BaseAlarmType::getTypeCode,requestVO.getTypeCode())
                .like(StringUtils.isNotBlank(requestVO.getTypeName()),BaseAlarmType::getTypeName,requestVO.getTypeName())
                .eq(BaseAlarmType::getDeleteFlag,0)
                .orderByDesc(BaseAlarmType::getId);
        page  = this.page(page,queryWrapper);
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getSize(),page.getCurrent());

    }

    @Override
    public List<BaseAlarmType> tenantIdAlarmTypeList(){
        List<BaseAlarmType> list = new ArrayList<>();
        List<String> typeList = new ArrayList<>();
        List<BaseAlarm> list1 = baseMapper.getAlarmInfo(SecurityUtils.getTenantId());
        if(list1.size() > 0){
            for(int i=0;i<list1.size();i++){
                typeList.add(list1.get(i).getAlarmType());
            }
        }
        if(typeList.size()>0){
            LambdaQueryWrapper<BaseAlarmType> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(CollectionUtils.isNotEmpty(typeList),BaseAlarmType::getTypeCode,typeList)
                    .eq(BaseAlarmType::getDeleteFlag,0);
            list = this.list(queryWrapper);
        }

        return list;
    }

    @Override
    public boolean checkNameUnique(BaseAlarmType baseAlarmType) { //根据告警类型判断唯一
        Integer id = null == baseAlarmType.getId() ? -1 : baseAlarmType.getId();
        LambdaQueryWrapper<BaseAlarmType> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BaseAlarmType::getTypeName,baseAlarmType.getTypeName())
                .eq(BaseAlarmType::getDeleteFlag,0);
        BaseAlarmType one = this.getOne(queryWrapper);
        return null != one && !Objects.equals(one.getId(), id);
    }

}
