package cn.iocoder.yudao.module.member.service.devicewarn;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.member.controller.admin.devicewarn.vo.DeviceWarnPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.devicewarn.vo.DeviceWarnSaveReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.devicewarn.DeviceWarnDO;
import cn.iocoder.yudao.module.member.dal.mysql.devicewarn.DeviceWarnMapper;
import cn.iocoder.yudao.module.member.util.MemberConstants;
import cn.iocoder.yudao.module.system.api.deviceInfo.DeviceInfoApi;
import cn.iocoder.yudao.module.system.api.deviceInfo.dto.DeviceInfoDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.DEVICE_WARN_NOT_EXISTS;

/**
 * 设备告警次数 Service 实现类
 *
 * @author 开发账号
 */
@Service
@Validated
public class DeviceWarnServiceImpl implements DeviceWarnService {

    @Resource
    private DeviceWarnMapper deviceWarnMapper;
    @Resource
    private DeviceInfoApi deviceInfoApi;


    @Override
    public Long createDeviceWarn(DeviceWarnSaveReqVO createReqVO) {
        // 插入
        DeviceWarnDO deviceWarn = BeanUtils.toBean(createReqVO, DeviceWarnDO.class);
        deviceWarnMapper.insert(deviceWarn);
        // 返回
        return deviceWarn.getId();
    }

    @Override
    public void updateDeviceWarn(DeviceWarnSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceWarnExists(updateReqVO.getId());
        // 更新
        DeviceWarnDO updateObj = BeanUtils.toBean(updateReqVO, DeviceWarnDO.class);
        deviceWarnMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceWarn(Long id) {
        // 校验存在
        validateDeviceWarnExists(id);
        // 删除
        deviceWarnMapper.deleteById(id);
    }

    private void validateDeviceWarnExists(Long id) {
        if (deviceWarnMapper.selectById(id) == null) {
            throw exception(DEVICE_WARN_NOT_EXISTS);
        }
    }

    @Override
    public DeviceWarnDO getDeviceWarn(Long id) {
        return deviceWarnMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceWarnDO> getDeviceWarnPage(DeviceWarnPageReqVO pageReqVO) {
        return deviceWarnMapper.selectPage(pageReqVO);
    }

    @Override
    public void addDeviceWarn(HttpServletRequest request) {
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern(MemberConstants.DATE_FORMAT));
        String deviceIp = request.getHeader("Authorization");
        DeviceInfoDto device = deviceInfoApi.getDevice(deviceIp);
        QueryWrapper<DeviceWarnDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_format(create_time,'%Y-%m-%d')", format)
                .eq("device_sn", deviceIp)
                .last(MemberConstants.LIMIT_ONE);
        DeviceWarnDO old = deviceWarnMapper.selectOne(queryWrapper);
        if (ObjUtil.isNotEmpty(old)) {
            old.setWarnNum(old.getWarnNum() + 1);
            deviceWarnMapper.updateById(old);
        } else {
            DeviceWarnDO deviceWarnDO = new DeviceWarnDO();
            deviceWarnDO.setDeviceSn(deviceIp).setWarnNum(1).setStoreId(device.getCarteenId());
            deviceWarnMapper.insert(deviceWarnDO);
        }
    }

    @Override
    public Long getWarn(Long storeId) {
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern(MemberConstants.DATE_FORMAT));
        QueryWrapper<DeviceWarnDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("sum(warn_num) as warnNum")
                .eq("date_format(create_time,'%Y-%m-%d')", format)
                .eq(storeId!=null,"store_id", storeId);
        List<Map<String, Object>> maps = deviceWarnMapper.selectMaps(queryWrapper);
        if(CollectionUtil.isNotEmpty(maps) && maps.get(0)!=null){
            return Long.valueOf(maps.get(0).get("warnNum").toString());
        }
        return 0L;
    }
}