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.controller.admin.screen.vo.DeviceInfo;
import cn.iocoder.yudao.module.member.dal.dataobject.devicewarn.DeviceWarnNumDO;
import cn.iocoder.yudao.module.member.dal.mysql.devicewarn.DeviceWarnNumMapper;
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 DeviceWarnNumServiceImpl implements DeviceWarnNumService {

    @Resource
    private DeviceWarnNumMapper deviceWarnNumMapper;
    @Resource
    private DeviceInfoApi deviceInfoApi;


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

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

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

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

    @Override
    public DeviceWarnNumDO getDeviceWarn(Long id) {
        return deviceWarnNumMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceWarnNumDO> getDeviceWarnPage(DeviceWarnPageReqVO pageReqVO) {
        return deviceWarnNumMapper.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<DeviceWarnNumDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_format(create_time,'%Y-%m-%d')", format)
                .eq("device_sn", deviceIp)
                .last(MemberConstants.LIMIT_ONE);
        DeviceWarnNumDO old = deviceWarnNumMapper.selectOne(queryWrapper);
        if (ObjUtil.isNotEmpty(old)) {
            old.setWarnNum(old.getWarnNum() + 1);
            deviceWarnNumMapper.updateById(old);
        } else {
            DeviceWarnNumDO deviceWarnDO = new DeviceWarnNumDO();
            deviceWarnDO.setDeviceSn(deviceIp).setWarnNum(1).setStoreId(device.getCarteenId());
            deviceWarnNumMapper.insert(deviceWarnDO);
        }
    }

    @Override
    public Long getWarn(Long storeId) {
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern(MemberConstants.DATE_FORMAT));
        QueryWrapper<DeviceWarnNumDO> 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 = deviceWarnNumMapper.selectMaps(queryWrapper);
        if(CollectionUtil.isNotEmpty(maps) && maps.get(0)!=null){
            return Long.valueOf(maps.get(0).get("warnNum").toString());
        }
        return 0L;
    }

    @Override
    public List<DeviceInfo> getDeviceInfo(Long carteenId) {
        return deviceWarnNumMapper.getDeviceInfo(carteenId);
    }
}